[WinEH] Move WinEHFuncInfo from MachineModuleInfo to MachineFunction
[oota-llvm.git] / lib / Target / X86 / X86ISelLowering.cpp
1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "X86ISelLowering.h"
16 #include "Utils/X86ShuffleDecode.h"
17 #include "X86CallingConv.h"
18 #include "X86FrameLowering.h"
19 #include "X86InstrBuilder.h"
20 #include "X86MachineFunctionInfo.h"
21 #include "X86TargetMachine.h"
22 #include "X86TargetObjectFile.h"
23 #include "llvm/ADT/SmallBitVector.h"
24 #include "llvm/ADT/SmallSet.h"
25 #include "llvm/ADT/Statistic.h"
26 #include "llvm/ADT/StringExtras.h"
27 #include "llvm/ADT/StringSwitch.h"
28 #include "llvm/Analysis/LibCallSemantics.h"
29 #include "llvm/CodeGen/IntrinsicLowering.h"
30 #include "llvm/CodeGen/MachineFrameInfo.h"
31 #include "llvm/CodeGen/MachineFunction.h"
32 #include "llvm/CodeGen/MachineInstrBuilder.h"
33 #include "llvm/CodeGen/MachineJumpTableInfo.h"
34 #include "llvm/CodeGen/MachineModuleInfo.h"
35 #include "llvm/CodeGen/MachineRegisterInfo.h"
36 #include "llvm/CodeGen/WinEHFuncInfo.h"
37 #include "llvm/IR/CallSite.h"
38 #include "llvm/IR/CallingConv.h"
39 #include "llvm/IR/Constants.h"
40 #include "llvm/IR/DerivedTypes.h"
41 #include "llvm/IR/Function.h"
42 #include "llvm/IR/GlobalAlias.h"
43 #include "llvm/IR/GlobalVariable.h"
44 #include "llvm/IR/Instructions.h"
45 #include "llvm/IR/Intrinsics.h"
46 #include "llvm/MC/MCAsmInfo.h"
47 #include "llvm/MC/MCContext.h"
48 #include "llvm/MC/MCExpr.h"
49 #include "llvm/MC/MCSymbol.h"
50 #include "llvm/Support/CommandLine.h"
51 #include "llvm/Support/Debug.h"
52 #include "llvm/Support/ErrorHandling.h"
53 #include "llvm/Support/MathExtras.h"
54 #include "llvm/Target/TargetOptions.h"
55 #include "X86IntrinsicsInfo.h"
56 #include <bitset>
57 #include <numeric>
58 #include <cctype>
59 using namespace llvm;
60
61 #define DEBUG_TYPE "x86-isel"
62
63 STATISTIC(NumTailCalls, "Number of tail calls");
64
65 static cl::opt<bool> ExperimentalVectorWideningLegalization(
66     "x86-experimental-vector-widening-legalization", cl::init(false),
67     cl::desc("Enable an experimental vector type legalization through widening "
68              "rather than promotion."),
69     cl::Hidden);
70
71 X86TargetLowering::X86TargetLowering(const X86TargetMachine &TM,
72                                      const X86Subtarget &STI)
73     : TargetLowering(TM), Subtarget(&STI) {
74   X86ScalarSSEf64 = Subtarget->hasSSE2();
75   X86ScalarSSEf32 = Subtarget->hasSSE1();
76   MVT PtrVT = MVT::getIntegerVT(8 * TM.getPointerSize());
77
78   // Set up the TargetLowering object.
79
80   // X86 is weird. It always uses i8 for shift amounts and setcc results.
81   setBooleanContents(ZeroOrOneBooleanContent);
82   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
83   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
84
85   // For 64-bit, since we have so many registers, use the ILP scheduler.
86   // For 32-bit, use the register pressure specific scheduling.
87   // For Atom, always use ILP scheduling.
88   if (Subtarget->isAtom())
89     setSchedulingPreference(Sched::ILP);
90   else if (Subtarget->is64Bit())
91     setSchedulingPreference(Sched::ILP);
92   else
93     setSchedulingPreference(Sched::RegPressure);
94   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
95   setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
96
97   // Bypass expensive divides on Atom when compiling with O2.
98   if (TM.getOptLevel() >= CodeGenOpt::Default) {
99     if (Subtarget->hasSlowDivide32())
100       addBypassSlowDiv(32, 8);
101     if (Subtarget->hasSlowDivide64() && Subtarget->is64Bit())
102       addBypassSlowDiv(64, 16);
103   }
104
105   if (Subtarget->isTargetKnownWindowsMSVC()) {
106     // Setup Windows compiler runtime calls.
107     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
108     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
109     setLibcallName(RTLIB::SREM_I64, "_allrem");
110     setLibcallName(RTLIB::UREM_I64, "_aullrem");
111     setLibcallName(RTLIB::MUL_I64, "_allmul");
112     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
113     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
114     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
115     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
116     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
117   }
118
119   if (Subtarget->isTargetDarwin()) {
120     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
121     setUseUnderscoreSetJmp(false);
122     setUseUnderscoreLongJmp(false);
123   } else if (Subtarget->isTargetWindowsGNU()) {
124     // MS runtime is weird: it exports _setjmp, but longjmp!
125     setUseUnderscoreSetJmp(true);
126     setUseUnderscoreLongJmp(false);
127   } else {
128     setUseUnderscoreSetJmp(true);
129     setUseUnderscoreLongJmp(true);
130   }
131
132   // Set up the register classes.
133   addRegisterClass(MVT::i8, &X86::GR8RegClass);
134   addRegisterClass(MVT::i16, &X86::GR16RegClass);
135   addRegisterClass(MVT::i32, &X86::GR32RegClass);
136   if (Subtarget->is64Bit())
137     addRegisterClass(MVT::i64, &X86::GR64RegClass);
138
139   for (MVT VT : MVT::integer_valuetypes())
140     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
141
142   // We don't accept any truncstore of integer registers.
143   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
144   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
145   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
146   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
147   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
148   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
149
150   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
151
152   // SETOEQ and SETUNE require checking two conditions.
153   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
154   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
155   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
156   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
157   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
158   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
159
160   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
161   // operation.
162   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
163   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
164   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
165
166   if (Subtarget->is64Bit()) {
167     if (!Subtarget->useSoftFloat() && Subtarget->hasAVX512())
168       // f32/f64 are legal, f80 is custom.
169       setOperationAction(ISD::UINT_TO_FP   , MVT::i32  , Custom);
170     else
171       setOperationAction(ISD::UINT_TO_FP   , MVT::i32  , Promote);
172     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
173   } else if (!Subtarget->useSoftFloat()) {
174     // We have an algorithm for SSE2->double, and we turn this into a
175     // 64-bit FILD followed by conditional FADD for other targets.
176     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
177     // We have an algorithm for SSE2, and we turn this into a 64-bit
178     // FILD or VCVTUSI2SS/SD for other targets.
179     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
180   }
181
182   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
183   // this operation.
184   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
185   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
186
187   if (!Subtarget->useSoftFloat()) {
188     // SSE has no i16 to fp conversion, only i32
189     if (X86ScalarSSEf32) {
190       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
191       // f32 and f64 cases are Legal, f80 case is not
192       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
193     } else {
194       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
195       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
196     }
197   } else {
198     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
199     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
200   }
201
202   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
203   // this operation.
204   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
205   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
206
207   if (!Subtarget->useSoftFloat()) {
208     // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
209     // are Legal, f80 is custom lowered.
210     setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
211     setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
212
213     if (X86ScalarSSEf32) {
214       setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
215       // f32 and f64 cases are Legal, f80 case is not
216       setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
217     } else {
218       setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
219       setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
220     }
221   } else {
222     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
223     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Expand);
224     setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Expand);
225   }
226
227   // Handle FP_TO_UINT by promoting the destination to a larger signed
228   // conversion.
229   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
230   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
231   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
232
233   if (Subtarget->is64Bit()) {
234     if (!Subtarget->useSoftFloat() && Subtarget->hasAVX512()) {
235       // FP_TO_UINT-i32/i64 is legal for f32/f64, but custom for f80.
236       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
237       setOperationAction(ISD::FP_TO_UINT   , MVT::i64  , Custom);
238     } else {
239       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Promote);
240       setOperationAction(ISD::FP_TO_UINT   , MVT::i64  , Expand);
241     }
242   } else if (!Subtarget->useSoftFloat()) {
243     // Since AVX is a superset of SSE3, only check for SSE here.
244     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
245       // Expand FP_TO_UINT into a select.
246       // FIXME: We would like to use a Custom expander here eventually to do
247       // the optimal thing for SSE vs. the default expansion in the legalizer.
248       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
249     else
250       // With AVX512 we can use vcvts[ds]2usi for f32/f64->i32, f80 is custom.
251       // With SSE3 we can use fisttpll to convert to a signed i64; without
252       // SSE, we're stuck with a fistpll.
253       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
254
255     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
256   }
257
258   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
259   if (!X86ScalarSSEf64) {
260     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
261     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
262     if (Subtarget->is64Bit()) {
263       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
264       // Without SSE, i64->f64 goes through memory.
265       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
266     }
267   }
268
269   // Scalar integer divide and remainder are lowered to use operations that
270   // produce two results, to match the available instructions. This exposes
271   // the two-result form to trivial CSE, which is able to combine x/y and x%y
272   // into a single instruction.
273   //
274   // Scalar integer multiply-high is also lowered to use two-result
275   // operations, to match the available instructions. However, plain multiply
276   // (low) operations are left as Legal, as there are single-result
277   // instructions for this in x86. Using the two-result multiply instructions
278   // when both high and low results are needed must be arranged by dagcombine.
279   for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
280     setOperationAction(ISD::MULHS, VT, Expand);
281     setOperationAction(ISD::MULHU, VT, Expand);
282     setOperationAction(ISD::SDIV, VT, Expand);
283     setOperationAction(ISD::UDIV, VT, Expand);
284     setOperationAction(ISD::SREM, VT, Expand);
285     setOperationAction(ISD::UREM, VT, Expand);
286
287     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
288     setOperationAction(ISD::ADDC, VT, Custom);
289     setOperationAction(ISD::ADDE, VT, Custom);
290     setOperationAction(ISD::SUBC, VT, Custom);
291     setOperationAction(ISD::SUBE, VT, Custom);
292   }
293
294   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
295   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
296   setOperationAction(ISD::BR_CC            , MVT::f32,   Expand);
297   setOperationAction(ISD::BR_CC            , MVT::f64,   Expand);
298   setOperationAction(ISD::BR_CC            , MVT::f80,   Expand);
299   setOperationAction(ISD::BR_CC            , MVT::i8,    Expand);
300   setOperationAction(ISD::BR_CC            , MVT::i16,   Expand);
301   setOperationAction(ISD::BR_CC            , MVT::i32,   Expand);
302   setOperationAction(ISD::BR_CC            , MVT::i64,   Expand);
303   setOperationAction(ISD::SELECT_CC        , MVT::f32,   Expand);
304   setOperationAction(ISD::SELECT_CC        , MVT::f64,   Expand);
305   setOperationAction(ISD::SELECT_CC        , MVT::f80,   Expand);
306   setOperationAction(ISD::SELECT_CC        , MVT::i8,    Expand);
307   setOperationAction(ISD::SELECT_CC        , MVT::i16,   Expand);
308   setOperationAction(ISD::SELECT_CC        , MVT::i32,   Expand);
309   setOperationAction(ISD::SELECT_CC        , MVT::i64,   Expand);
310   if (Subtarget->is64Bit())
311     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
312   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
313   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
314   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
315   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
316
317   if (Subtarget->is32Bit() && Subtarget->isTargetKnownWindowsMSVC()) {
318     // On 32 bit MSVC, `fmodf(f32)` is not defined - only `fmod(f64)`
319     // is. We should promote the value to 64-bits to solve this.
320     // This is what the CRT headers do - `fmodf` is an inline header
321     // function casting to f64 and calling `fmod`.
322     setOperationAction(ISD::FREM           , MVT::f32  , Promote);
323   } else {
324     setOperationAction(ISD::FREM           , MVT::f32  , Expand);
325   }
326
327   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
328   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
329   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
330
331   // Promote the i8 variants and force them on up to i32 which has a shorter
332   // encoding.
333   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
334   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
335   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
336   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
337   if (Subtarget->hasBMI()) {
338     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
339     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
340     if (Subtarget->is64Bit())
341       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
342   } else {
343     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
344     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
345     if (Subtarget->is64Bit())
346       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
347   }
348
349   if (Subtarget->hasLZCNT()) {
350     // When promoting the i8 variants, force them to i32 for a shorter
351     // encoding.
352     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
353     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
354     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
355     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
356     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
357     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
358     if (Subtarget->is64Bit())
359       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
360   } else {
361     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
362     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
363     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
364     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
365     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
366     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
367     if (Subtarget->is64Bit()) {
368       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
369       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
370     }
371   }
372
373   // Special handling for half-precision floating point conversions.
374   // If we don't have F16C support, then lower half float conversions
375   // into library calls.
376   if (Subtarget->useSoftFloat() || !Subtarget->hasF16C()) {
377     setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
378     setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
379   }
380
381   // There's never any support for operations beyond MVT::f32.
382   setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
383   setOperationAction(ISD::FP16_TO_FP, MVT::f80, Expand);
384   setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
385   setOperationAction(ISD::FP_TO_FP16, MVT::f80, Expand);
386
387   setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
388   setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
389   setLoadExtAction(ISD::EXTLOAD, MVT::f80, MVT::f16, Expand);
390   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
391   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
392   setTruncStoreAction(MVT::f80, MVT::f16, Expand);
393
394   if (Subtarget->hasPOPCNT()) {
395     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
396   } else {
397     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
398     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
399     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
400     if (Subtarget->is64Bit())
401       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
402   }
403
404   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
405
406   if (!Subtarget->hasMOVBE())
407     setOperationAction(ISD::BSWAP          , MVT::i16  , Expand);
408
409   // These should be promoted to a larger select which is supported.
410   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
411   // X86 wants to expand cmov itself.
412   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
413   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
414   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
415   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
416   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
417   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
418   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
419   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
420   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
421   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
422   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
423   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
424   if (Subtarget->is64Bit()) {
425     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
426     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
427   }
428   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
429   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
430   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
431   // support continuation, user-level threading, and etc.. As a result, no
432   // other SjLj exception interfaces are implemented and please don't build
433   // your own exception handling based on them.
434   // LLVM/Clang supports zero-cost DWARF exception handling.
435   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
436   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
437
438   // Darwin ABI issue.
439   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
440   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
441   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
442   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
443   if (Subtarget->is64Bit())
444     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
445   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
446   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
447   if (Subtarget->is64Bit()) {
448     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
449     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
450     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
451     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
452     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
453   }
454   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
455   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
456   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
457   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
458   if (Subtarget->is64Bit()) {
459     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
460     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
461     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
462   }
463
464   if (Subtarget->hasSSE1())
465     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
466
467   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
468
469   // Expand certain atomics
470   for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
471     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
472     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
473     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
474   }
475
476   if (Subtarget->hasCmpxchg16b()) {
477     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
478   }
479
480   // FIXME - use subtarget debug flags
481   if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetELF() &&
482       !Subtarget->isTargetCygMing() && !Subtarget->isTargetWin64()) {
483     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
484   }
485
486   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
487   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
488
489   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
490   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
491
492   setOperationAction(ISD::TRAP, MVT::Other, Legal);
493   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
494
495   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
496   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
497   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
498   if (Subtarget->is64Bit()) {
499     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
500     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
501   } else {
502     // TargetInfo::CharPtrBuiltinVaList
503     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
504     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
505   }
506
507   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
508   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
509
510   setOperationAction(ISD::DYNAMIC_STACKALLOC, PtrVT, Custom);
511
512   // GC_TRANSITION_START and GC_TRANSITION_END need custom lowering.
513   setOperationAction(ISD::GC_TRANSITION_START, MVT::Other, Custom);
514   setOperationAction(ISD::GC_TRANSITION_END, MVT::Other, Custom);
515
516   if (!Subtarget->useSoftFloat() && X86ScalarSSEf64) {
517     // f32 and f64 use SSE.
518     // Set up the FP register classes.
519     addRegisterClass(MVT::f32, &X86::FR32RegClass);
520     addRegisterClass(MVT::f64, &X86::FR64RegClass);
521
522     // Use ANDPD to simulate FABS.
523     setOperationAction(ISD::FABS , MVT::f64, Custom);
524     setOperationAction(ISD::FABS , MVT::f32, Custom);
525
526     // Use XORP to simulate FNEG.
527     setOperationAction(ISD::FNEG , MVT::f64, Custom);
528     setOperationAction(ISD::FNEG , MVT::f32, Custom);
529
530     // Use ANDPD and ORPD to simulate FCOPYSIGN.
531     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
532     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
533
534     // Lower this to FGETSIGNx86 plus an AND.
535     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
536     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
537
538     // We don't support sin/cos/fmod
539     setOperationAction(ISD::FSIN   , MVT::f64, Expand);
540     setOperationAction(ISD::FCOS   , MVT::f64, Expand);
541     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
542     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
543     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
544     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
545
546     // Expand FP immediates into loads from the stack, except for the special
547     // cases we handle.
548     addLegalFPImmediate(APFloat(+0.0)); // xorpd
549     addLegalFPImmediate(APFloat(+0.0f)); // xorps
550   } else if (!Subtarget->useSoftFloat() && X86ScalarSSEf32) {
551     // Use SSE for f32, x87 for f64.
552     // Set up the FP register classes.
553     addRegisterClass(MVT::f32, &X86::FR32RegClass);
554     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
555
556     // Use ANDPS to simulate FABS.
557     setOperationAction(ISD::FABS , MVT::f32, Custom);
558
559     // Use XORP to simulate FNEG.
560     setOperationAction(ISD::FNEG , MVT::f32, Custom);
561
562     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
563
564     // Use ANDPS and ORPS to simulate FCOPYSIGN.
565     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
566     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
567
568     // We don't support sin/cos/fmod
569     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
570     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
571     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
572
573     // Special cases we handle for FP constants.
574     addLegalFPImmediate(APFloat(+0.0f)); // xorps
575     addLegalFPImmediate(APFloat(+0.0)); // FLD0
576     addLegalFPImmediate(APFloat(+1.0)); // FLD1
577     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
578     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
579
580     if (!TM.Options.UnsafeFPMath) {
581       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
582       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
583       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
584     }
585   } else if (!Subtarget->useSoftFloat()) {
586     // f32 and f64 in x87.
587     // Set up the FP register classes.
588     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
589     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
590
591     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
592     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
593     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
594     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
595
596     if (!TM.Options.UnsafeFPMath) {
597       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
598       setOperationAction(ISD::FSIN   , MVT::f32, Expand);
599       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
600       setOperationAction(ISD::FCOS   , MVT::f32, Expand);
601       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
602       setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
603     }
604     addLegalFPImmediate(APFloat(+0.0)); // FLD0
605     addLegalFPImmediate(APFloat(+1.0)); // FLD1
606     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
607     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
608     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
609     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
610     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
611     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
612   }
613
614   // We don't support FMA.
615   setOperationAction(ISD::FMA, MVT::f64, Expand);
616   setOperationAction(ISD::FMA, MVT::f32, Expand);
617
618   // Long double always uses X87.
619   if (!Subtarget->useSoftFloat()) {
620     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
621     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
622     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
623     {
624       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
625       addLegalFPImmediate(TmpFlt);  // FLD0
626       TmpFlt.changeSign();
627       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
628
629       bool ignored;
630       APFloat TmpFlt2(+1.0);
631       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
632                       &ignored);
633       addLegalFPImmediate(TmpFlt2);  // FLD1
634       TmpFlt2.changeSign();
635       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
636     }
637
638     if (!TM.Options.UnsafeFPMath) {
639       setOperationAction(ISD::FSIN   , MVT::f80, Expand);
640       setOperationAction(ISD::FCOS   , MVT::f80, Expand);
641       setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
642     }
643
644     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
645     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
646     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
647     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
648     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
649     setOperationAction(ISD::FMA, MVT::f80, Expand);
650   }
651
652   // Always use a library call for pow.
653   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
654   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
655   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
656
657   setOperationAction(ISD::FLOG, MVT::f80, Expand);
658   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
659   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
660   setOperationAction(ISD::FEXP, MVT::f80, Expand);
661   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
662   setOperationAction(ISD::FMINNUM, MVT::f80, Expand);
663   setOperationAction(ISD::FMAXNUM, MVT::f80, Expand);
664
665   // First set operation action for all vector types to either promote
666   // (for widening) or expand (for scalarization). Then we will selectively
667   // turn on ones that can be effectively codegen'd.
668   for (MVT VT : MVT::vector_valuetypes()) {
669     setOperationAction(ISD::ADD , VT, Expand);
670     setOperationAction(ISD::SUB , VT, Expand);
671     setOperationAction(ISD::FADD, VT, Expand);
672     setOperationAction(ISD::FNEG, VT, Expand);
673     setOperationAction(ISD::FSUB, VT, Expand);
674     setOperationAction(ISD::MUL , VT, Expand);
675     setOperationAction(ISD::FMUL, VT, Expand);
676     setOperationAction(ISD::SDIV, VT, Expand);
677     setOperationAction(ISD::UDIV, VT, Expand);
678     setOperationAction(ISD::FDIV, VT, Expand);
679     setOperationAction(ISD::SREM, VT, Expand);
680     setOperationAction(ISD::UREM, VT, Expand);
681     setOperationAction(ISD::LOAD, VT, Expand);
682     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
683     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
684     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
685     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
686     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
687     setOperationAction(ISD::FABS, VT, Expand);
688     setOperationAction(ISD::FSIN, VT, Expand);
689     setOperationAction(ISD::FSINCOS, VT, Expand);
690     setOperationAction(ISD::FCOS, VT, Expand);
691     setOperationAction(ISD::FSINCOS, VT, Expand);
692     setOperationAction(ISD::FREM, VT, Expand);
693     setOperationAction(ISD::FMA,  VT, Expand);
694     setOperationAction(ISD::FPOWI, VT, Expand);
695     setOperationAction(ISD::FSQRT, VT, Expand);
696     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
697     setOperationAction(ISD::FFLOOR, VT, Expand);
698     setOperationAction(ISD::FCEIL, VT, Expand);
699     setOperationAction(ISD::FTRUNC, VT, Expand);
700     setOperationAction(ISD::FRINT, VT, Expand);
701     setOperationAction(ISD::FNEARBYINT, VT, Expand);
702     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
703     setOperationAction(ISD::MULHS, VT, Expand);
704     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
705     setOperationAction(ISD::MULHU, VT, Expand);
706     setOperationAction(ISD::SDIVREM, VT, Expand);
707     setOperationAction(ISD::UDIVREM, VT, Expand);
708     setOperationAction(ISD::FPOW, VT, Expand);
709     setOperationAction(ISD::CTPOP, VT, Expand);
710     setOperationAction(ISD::CTTZ, VT, Expand);
711     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
712     setOperationAction(ISD::CTLZ, VT, Expand);
713     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
714     setOperationAction(ISD::SHL, VT, Expand);
715     setOperationAction(ISD::SRA, VT, Expand);
716     setOperationAction(ISD::SRL, VT, Expand);
717     setOperationAction(ISD::ROTL, VT, Expand);
718     setOperationAction(ISD::ROTR, VT, Expand);
719     setOperationAction(ISD::BSWAP, VT, Expand);
720     setOperationAction(ISD::SETCC, VT, Expand);
721     setOperationAction(ISD::FLOG, VT, Expand);
722     setOperationAction(ISD::FLOG2, VT, Expand);
723     setOperationAction(ISD::FLOG10, VT, Expand);
724     setOperationAction(ISD::FEXP, VT, Expand);
725     setOperationAction(ISD::FEXP2, VT, Expand);
726     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
727     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
728     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
729     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
730     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
731     setOperationAction(ISD::TRUNCATE, VT, Expand);
732     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
733     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
734     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
735     setOperationAction(ISD::VSELECT, VT, Expand);
736     setOperationAction(ISD::SELECT_CC, VT, Expand);
737     for (MVT InnerVT : MVT::vector_valuetypes()) {
738       setTruncStoreAction(InnerVT, VT, Expand);
739
740       setLoadExtAction(ISD::SEXTLOAD, InnerVT, VT, Expand);
741       setLoadExtAction(ISD::ZEXTLOAD, InnerVT, VT, Expand);
742
743       // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like
744       // types, we have to deal with them whether we ask for Expansion or not.
745       // Setting Expand causes its own optimisation problems though, so leave
746       // them legal.
747       if (VT.getVectorElementType() == MVT::i1)
748         setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
749
750       // EXTLOAD for MVT::f16 vectors is not legal because f16 vectors are
751       // split/scalarized right now.
752       if (VT.getVectorElementType() == MVT::f16)
753         setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
754     }
755   }
756
757   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
758   // with -msoft-float, disable use of MMX as well.
759   if (!Subtarget->useSoftFloat() && Subtarget->hasMMX()) {
760     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
761     // No operations on x86mmx supported, everything uses intrinsics.
762   }
763
764   // MMX-sized vectors (other than x86mmx) are expected to be expanded
765   // into smaller operations.
766   for (MVT MMXTy : {MVT::v8i8, MVT::v4i16, MVT::v2i32, MVT::v1i64}) {
767     setOperationAction(ISD::MULHS,              MMXTy,      Expand);
768     setOperationAction(ISD::AND,                MMXTy,      Expand);
769     setOperationAction(ISD::OR,                 MMXTy,      Expand);
770     setOperationAction(ISD::XOR,                MMXTy,      Expand);
771     setOperationAction(ISD::SCALAR_TO_VECTOR,   MMXTy,      Expand);
772     setOperationAction(ISD::SELECT,             MMXTy,      Expand);
773     setOperationAction(ISD::BITCAST,            MMXTy,      Expand);
774   }
775   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
776
777   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE1()) {
778     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
779
780     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
781     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
782     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
783     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
784     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
785     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
786     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
787     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
788     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
789     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
790     setOperationAction(ISD::VSELECT,            MVT::v4f32, Custom);
791     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
792     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
793     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Custom);
794   }
795
796   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE2()) {
797     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
798
799     // FIXME: Unfortunately, -soft-float and -no-implicit-float mean XMM
800     // registers cannot be used even for integer operations.
801     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
802     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
803     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
804     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
805
806     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
807     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
808     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
809     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
810     setOperationAction(ISD::MUL,                MVT::v16i8, Custom);
811     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
812     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
813     setOperationAction(ISD::UMUL_LOHI,          MVT::v4i32, Custom);
814     setOperationAction(ISD::SMUL_LOHI,          MVT::v4i32, Custom);
815     setOperationAction(ISD::MULHU,              MVT::v8i16, Legal);
816     setOperationAction(ISD::MULHS,              MVT::v8i16, Legal);
817     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
818     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
819     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
820     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
821     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
822     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
823     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
824     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
825     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
826     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
827     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
828     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
829
830     setOperationAction(ISD::SMAX,               MVT::v8i16, Legal);
831     setOperationAction(ISD::UMAX,               MVT::v16i8, Legal);
832     setOperationAction(ISD::SMIN,               MVT::v8i16, Legal);
833     setOperationAction(ISD::UMIN,               MVT::v16i8, Legal);
834
835     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
836     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
837     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
838     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
839
840     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
841     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
842     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
843     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
844     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
845
846     setOperationAction(ISD::CTPOP,              MVT::v16i8, Custom);
847     setOperationAction(ISD::CTPOP,              MVT::v8i16, Custom);
848     setOperationAction(ISD::CTPOP,              MVT::v4i32, Custom);
849     setOperationAction(ISD::CTPOP,              MVT::v2i64, Custom);
850
851     setOperationAction(ISD::CTTZ,               MVT::v16i8, Custom);
852     setOperationAction(ISD::CTTZ,               MVT::v8i16, Custom);
853     setOperationAction(ISD::CTTZ,               MVT::v4i32, Custom);
854     // ISD::CTTZ v2i64 - scalarization is faster.
855     setOperationAction(ISD::CTTZ_ZERO_UNDEF,    MVT::v16i8, Custom);
856     setOperationAction(ISD::CTTZ_ZERO_UNDEF,    MVT::v8i16, Custom);
857     setOperationAction(ISD::CTTZ_ZERO_UNDEF,    MVT::v4i32, Custom);
858     // ISD::CTTZ_ZERO_UNDEF v2i64 - scalarization is faster.
859
860     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
861     for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) {
862       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
863       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
864       setOperationAction(ISD::VSELECT,            VT, Custom);
865       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
866     }
867
868     // We support custom legalizing of sext and anyext loads for specific
869     // memory vector types which we can load as a scalar (or sequence of
870     // scalars) and extend in-register to a legal 128-bit vector type. For sext
871     // loads these must work with a single scalar load.
872     for (MVT VT : MVT::integer_vector_valuetypes()) {
873       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i8, Custom);
874       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i16, Custom);
875       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v8i8, Custom);
876       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i8, Custom);
877       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i16, Custom);
878       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i32, Custom);
879       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i8, Custom);
880       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i16, Custom);
881       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8i8, Custom);
882     }
883
884     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
885     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
886     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
887     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
888     setOperationAction(ISD::VSELECT,            MVT::v2f64, Custom);
889     setOperationAction(ISD::VSELECT,            MVT::v2i64, Custom);
890     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
891     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
892
893     if (Subtarget->is64Bit()) {
894       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
895       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
896     }
897
898     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
899     for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) {
900       setOperationAction(ISD::AND,    VT, Promote);
901       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
902       setOperationAction(ISD::OR,     VT, Promote);
903       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
904       setOperationAction(ISD::XOR,    VT, Promote);
905       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
906       setOperationAction(ISD::LOAD,   VT, Promote);
907       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
908       setOperationAction(ISD::SELECT, VT, Promote);
909       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
910     }
911
912     // Custom lower v2i64 and v2f64 selects.
913     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
914     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
915     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
916     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
917
918     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
919     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
920
921     setOperationAction(ISD::SINT_TO_FP,         MVT::v2i32, Custom);
922
923     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
924     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
925     // As there is no 64-bit GPR available, we need build a special custom
926     // sequence to convert from v2i32 to v2f32.
927     if (!Subtarget->is64Bit())
928       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
929
930     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
931     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
932
933     for (MVT VT : MVT::fp_vector_valuetypes())
934       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2f32, Legal);
935
936     setOperationAction(ISD::BITCAST,            MVT::v2i32, Custom);
937     setOperationAction(ISD::BITCAST,            MVT::v4i16, Custom);
938     setOperationAction(ISD::BITCAST,            MVT::v8i8,  Custom);
939   }
940
941   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE41()) {
942     for (MVT RoundedTy : {MVT::f32, MVT::f64, MVT::v4f32, MVT::v2f64}) {
943       setOperationAction(ISD::FFLOOR,           RoundedTy,  Legal);
944       setOperationAction(ISD::FCEIL,            RoundedTy,  Legal);
945       setOperationAction(ISD::FTRUNC,           RoundedTy,  Legal);
946       setOperationAction(ISD::FRINT,            RoundedTy,  Legal);
947       setOperationAction(ISD::FNEARBYINT,       RoundedTy,  Legal);
948     }
949
950     setOperationAction(ISD::SMAX,               MVT::v16i8, Legal);
951     setOperationAction(ISD::SMAX,               MVT::v4i32, Legal);
952     setOperationAction(ISD::UMAX,               MVT::v8i16, Legal);
953     setOperationAction(ISD::UMAX,               MVT::v4i32, Legal);
954     setOperationAction(ISD::SMIN,               MVT::v16i8, Legal);
955     setOperationAction(ISD::SMIN,               MVT::v4i32, Legal);
956     setOperationAction(ISD::UMIN,               MVT::v8i16, Legal);
957     setOperationAction(ISD::UMIN,               MVT::v4i32, Legal);
958
959     // FIXME: Do we need to handle scalar-to-vector here?
960     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
961
962     // We directly match byte blends in the backend as they match the VSELECT
963     // condition form.
964     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
965
966     // SSE41 brings specific instructions for doing vector sign extend even in
967     // cases where we don't have SRA.
968     for (MVT VT : MVT::integer_vector_valuetypes()) {
969       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i8, Custom);
970       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i16, Custom);
971       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i32, Custom);
972     }
973
974     // SSE41 also has vector sign/zero extending loads, PMOV[SZ]X
975     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i16, MVT::v8i8,  Legal);
976     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i8,  Legal);
977     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i8,  Legal);
978     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
979     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
980     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
981
982     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i16, MVT::v8i8,  Legal);
983     setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i8,  Legal);
984     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i8,  Legal);
985     setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
986     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
987     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
988
989     // i8 and i16 vectors are custom because the source register and source
990     // source memory operand types are not the same width.  f32 vectors are
991     // custom since the immediate controlling the insert encodes additional
992     // information.
993     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
994     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
995     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
996     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
997
998     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
999     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1000     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1001     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1002
1003     // FIXME: these should be Legal, but that's only for the case where
1004     // the index is constant.  For now custom expand to deal with that.
1005     if (Subtarget->is64Bit()) {
1006       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1007       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1008     }
1009   }
1010
1011   if (Subtarget->hasSSE2()) {
1012     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v2i64, Custom);
1013     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v4i32, Custom);
1014     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v8i16, Custom);
1015
1016     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1017     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1018
1019     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1020     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1021
1022     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1023     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1024
1025     // In the customized shift lowering, the legal cases in AVX2 will be
1026     // recognized.
1027     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1028     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1029
1030     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1031     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1032
1033     setOperationAction(ISD::SRA,               MVT::v2i64, Custom);
1034     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1035   }
1036
1037   if (Subtarget->hasXOP()) {
1038     setOperationAction(ISD::ROTL,              MVT::v16i8, Custom);
1039     setOperationAction(ISD::ROTL,              MVT::v8i16, Custom);
1040     setOperationAction(ISD::ROTL,              MVT::v4i32, Custom);
1041     setOperationAction(ISD::ROTL,              MVT::v2i64, Custom);
1042     setOperationAction(ISD::ROTL,              MVT::v32i8, Custom);
1043     setOperationAction(ISD::ROTL,              MVT::v16i16, Custom);
1044     setOperationAction(ISD::ROTL,              MVT::v8i32, Custom);
1045     setOperationAction(ISD::ROTL,              MVT::v4i64, Custom);
1046   }
1047
1048   if (!Subtarget->useSoftFloat() && Subtarget->hasFp256()) {
1049     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1050     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1051     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1052     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1053     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1054     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1055
1056     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1057     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1058     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1059
1060     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1061     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1062     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1063     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1064     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1065     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1066     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1067     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1068     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1069     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1070     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1071     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1072
1073     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1074     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1075     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1076     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1077     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1078     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1079     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1080     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1081     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1082     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1083     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1084     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1085
1086     // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1087     // even though v8i16 is a legal type.
1088     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Promote);
1089     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i16, Promote);
1090     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1091
1092     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1093     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1094     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1095
1096     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1097     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1098
1099     for (MVT VT : MVT::fp_vector_valuetypes())
1100       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4f32, Legal);
1101
1102     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1103     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1104
1105     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1106     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1107
1108     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1109     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1110
1111     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1112     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1113     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1114     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1115
1116     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1117     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1118     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1119
1120     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1121     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1122     setOperationAction(ISD::SIGN_EXTEND,       MVT::v16i16, Custom);
1123     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1124     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1125     setOperationAction(ISD::ZERO_EXTEND,       MVT::v16i16, Custom);
1126     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1127     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1128     setOperationAction(ISD::ANY_EXTEND,        MVT::v16i16, Custom);
1129     setOperationAction(ISD::TRUNCATE,          MVT::v16i8, Custom);
1130     setOperationAction(ISD::TRUNCATE,          MVT::v8i16, Custom);
1131     setOperationAction(ISD::TRUNCATE,          MVT::v4i32, Custom);
1132
1133     setOperationAction(ISD::CTPOP,             MVT::v32i8, Custom);
1134     setOperationAction(ISD::CTPOP,             MVT::v16i16, Custom);
1135     setOperationAction(ISD::CTPOP,             MVT::v8i32, Custom);
1136     setOperationAction(ISD::CTPOP,             MVT::v4i64, Custom);
1137
1138     setOperationAction(ISD::CTTZ,              MVT::v32i8, Custom);
1139     setOperationAction(ISD::CTTZ,              MVT::v16i16, Custom);
1140     setOperationAction(ISD::CTTZ,              MVT::v8i32, Custom);
1141     setOperationAction(ISD::CTTZ,              MVT::v4i64, Custom);
1142     setOperationAction(ISD::CTTZ_ZERO_UNDEF,   MVT::v32i8, Custom);
1143     setOperationAction(ISD::CTTZ_ZERO_UNDEF,   MVT::v16i16, Custom);
1144     setOperationAction(ISD::CTTZ_ZERO_UNDEF,   MVT::v8i32, Custom);
1145     setOperationAction(ISD::CTTZ_ZERO_UNDEF,   MVT::v4i64, Custom);
1146
1147     if (Subtarget->hasFMA() || Subtarget->hasFMA4() || Subtarget->hasAVX512()) {
1148       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1149       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1150       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1151       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1152       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1153       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1154     }
1155
1156     if (Subtarget->hasInt256()) {
1157       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1158       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1159       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1160       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1161
1162       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1163       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1164       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1165       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1166
1167       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1168       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1169       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1170       setOperationAction(ISD::MUL,             MVT::v32i8, Custom);
1171
1172       setOperationAction(ISD::UMUL_LOHI,       MVT::v8i32, Custom);
1173       setOperationAction(ISD::SMUL_LOHI,       MVT::v8i32, Custom);
1174       setOperationAction(ISD::MULHU,           MVT::v16i16, Legal);
1175       setOperationAction(ISD::MULHS,           MVT::v16i16, Legal);
1176
1177       setOperationAction(ISD::SMAX,            MVT::v32i8,  Legal);
1178       setOperationAction(ISD::SMAX,            MVT::v16i16, Legal);
1179       setOperationAction(ISD::SMAX,            MVT::v8i32,  Legal);
1180       setOperationAction(ISD::UMAX,            MVT::v32i8,  Legal);
1181       setOperationAction(ISD::UMAX,            MVT::v16i16, Legal);
1182       setOperationAction(ISD::UMAX,            MVT::v8i32,  Legal);
1183       setOperationAction(ISD::SMIN,            MVT::v32i8,  Legal);
1184       setOperationAction(ISD::SMIN,            MVT::v16i16, Legal);
1185       setOperationAction(ISD::SMIN,            MVT::v8i32,  Legal);
1186       setOperationAction(ISD::UMIN,            MVT::v32i8,  Legal);
1187       setOperationAction(ISD::UMIN,            MVT::v16i16, Legal);
1188       setOperationAction(ISD::UMIN,            MVT::v8i32,  Legal);
1189
1190       // The custom lowering for UINT_TO_FP for v8i32 becomes interesting
1191       // when we have a 256bit-wide blend with immediate.
1192       setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Custom);
1193
1194       // AVX2 also has wider vector sign/zero extending loads, VPMOV[SZ]X
1195       setLoadExtAction(ISD::SEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1196       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32,  MVT::v8i8,  Legal);
1197       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i8,  Legal);
1198       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32,  MVT::v8i16, Legal);
1199       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i16, Legal);
1200       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i32, Legal);
1201
1202       setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1203       setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32,  MVT::v8i8,  Legal);
1204       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i8,  Legal);
1205       setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32,  MVT::v8i16, Legal);
1206       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i16, Legal);
1207       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i32, Legal);
1208     } else {
1209       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1210       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1211       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1212       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1213
1214       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1215       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1216       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1217       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1218
1219       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1220       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1221       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1222       setOperationAction(ISD::MUL,             MVT::v32i8, Custom);
1223
1224       setOperationAction(ISD::SMAX,            MVT::v32i8,  Custom);
1225       setOperationAction(ISD::SMAX,            MVT::v16i16, Custom);
1226       setOperationAction(ISD::SMAX,            MVT::v8i32,  Custom);
1227       setOperationAction(ISD::UMAX,            MVT::v32i8,  Custom);
1228       setOperationAction(ISD::UMAX,            MVT::v16i16, Custom);
1229       setOperationAction(ISD::UMAX,            MVT::v8i32,  Custom);
1230       setOperationAction(ISD::SMIN,            MVT::v32i8,  Custom);
1231       setOperationAction(ISD::SMIN,            MVT::v16i16, Custom);
1232       setOperationAction(ISD::SMIN,            MVT::v8i32,  Custom);
1233       setOperationAction(ISD::UMIN,            MVT::v32i8,  Custom);
1234       setOperationAction(ISD::UMIN,            MVT::v16i16, Custom);
1235       setOperationAction(ISD::UMIN,            MVT::v8i32,  Custom);
1236     }
1237
1238     // In the customized shift lowering, the legal cases in AVX2 will be
1239     // recognized.
1240     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1241     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1242
1243     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1244     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1245
1246     setOperationAction(ISD::SRA,               MVT::v4i64, Custom);
1247     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1248
1249     // Custom lower several nodes for 256-bit types.
1250     for (MVT VT : MVT::vector_valuetypes()) {
1251       if (VT.getScalarSizeInBits() >= 32) {
1252         setOperationAction(ISD::MLOAD,  VT, Legal);
1253         setOperationAction(ISD::MSTORE, VT, Legal);
1254       }
1255       // Extract subvector is special because the value type
1256       // (result) is 128-bit but the source is 256-bit wide.
1257       if (VT.is128BitVector()) {
1258         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1259       }
1260       // Do not attempt to custom lower other non-256-bit vectors
1261       if (!VT.is256BitVector())
1262         continue;
1263
1264       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1265       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1266       setOperationAction(ISD::VSELECT,            VT, Custom);
1267       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1268       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1269       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1270       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1271       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1272     }
1273
1274     if (Subtarget->hasInt256())
1275       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1276
1277     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1278     for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32 }) {
1279       setOperationAction(ISD::AND,    VT, Promote);
1280       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1281       setOperationAction(ISD::OR,     VT, Promote);
1282       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1283       setOperationAction(ISD::XOR,    VT, Promote);
1284       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1285       setOperationAction(ISD::LOAD,   VT, Promote);
1286       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1287       setOperationAction(ISD::SELECT, VT, Promote);
1288       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1289     }
1290   }
1291
1292   if (!Subtarget->useSoftFloat() && Subtarget->hasAVX512()) {
1293     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1294     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1295     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1296     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1297
1298     addRegisterClass(MVT::i1,     &X86::VK1RegClass);
1299     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1300     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1301
1302     for (MVT VT : MVT::fp_vector_valuetypes())
1303       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8f32, Legal);
1304
1305     setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i32, MVT::v16i8, Legal);
1306     setLoadExtAction(ISD::SEXTLOAD, MVT::v16i32, MVT::v16i8, Legal);
1307     setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i32, MVT::v16i16, Legal);
1308     setLoadExtAction(ISD::SEXTLOAD, MVT::v16i32, MVT::v16i16, Legal);
1309     setLoadExtAction(ISD::ZEXTLOAD, MVT::v32i16, MVT::v32i8, Legal);
1310     setLoadExtAction(ISD::SEXTLOAD, MVT::v32i16, MVT::v32i8, Legal);
1311     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i8,  Legal);
1312     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i8,  Legal);
1313     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i16,  Legal);
1314     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i16,  Legal);
1315     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i32,  Legal);
1316     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i32,  Legal);
1317
1318     setOperationAction(ISD::BR_CC,              MVT::i1,    Expand);
1319     setOperationAction(ISD::SETCC,              MVT::i1,    Custom);
1320     setOperationAction(ISD::SELECT_CC,          MVT::i1,    Expand);
1321     setOperationAction(ISD::XOR,                MVT::i1,    Legal);
1322     setOperationAction(ISD::OR,                 MVT::i1,    Legal);
1323     setOperationAction(ISD::AND,                MVT::i1,    Legal);
1324     setOperationAction(ISD::SUB,                MVT::i1,    Custom);
1325     setOperationAction(ISD::ADD,                MVT::i1,    Custom);
1326     setOperationAction(ISD::MUL,                MVT::i1,    Custom);
1327     setOperationAction(ISD::LOAD,               MVT::v16f32, Legal);
1328     setOperationAction(ISD::LOAD,               MVT::v8f64, Legal);
1329     setOperationAction(ISD::LOAD,               MVT::v8i64, Legal);
1330     setOperationAction(ISD::LOAD,               MVT::v16i32, Legal);
1331     setOperationAction(ISD::LOAD,               MVT::v16i1, Legal);
1332
1333     setOperationAction(ISD::FADD,               MVT::v16f32, Legal);
1334     setOperationAction(ISD::FSUB,               MVT::v16f32, Legal);
1335     setOperationAction(ISD::FMUL,               MVT::v16f32, Legal);
1336     setOperationAction(ISD::FDIV,               MVT::v16f32, Legal);
1337     setOperationAction(ISD::FSQRT,              MVT::v16f32, Legal);
1338     setOperationAction(ISD::FNEG,               MVT::v16f32, Custom);
1339
1340     setOperationAction(ISD::FADD,               MVT::v8f64, Legal);
1341     setOperationAction(ISD::FSUB,               MVT::v8f64, Legal);
1342     setOperationAction(ISD::FMUL,               MVT::v8f64, Legal);
1343     setOperationAction(ISD::FDIV,               MVT::v8f64, Legal);
1344     setOperationAction(ISD::FSQRT,              MVT::v8f64, Legal);
1345     setOperationAction(ISD::FNEG,               MVT::v8f64, Custom);
1346     setOperationAction(ISD::FMA,                MVT::v8f64, Legal);
1347     setOperationAction(ISD::FMA,                MVT::v16f32, Legal);
1348
1349     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1350     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1351     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1352     setOperationAction(ISD::FP_TO_UINT,         MVT::v4i32, Legal);
1353     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1354     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i1,   Custom);
1355     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i1,  Custom);
1356     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i8,  Promote);
1357     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i16, Promote);
1358     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1359     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1360     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Legal);
1361     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i8, Custom);
1362     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i16, Custom);
1363     setOperationAction(ISD::FP_ROUND,           MVT::v8f32, Legal);
1364     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Legal);
1365
1366     setTruncStoreAction(MVT::v8i64,   MVT::v8i8,   Legal);
1367     setTruncStoreAction(MVT::v8i64,   MVT::v8i16,  Legal);
1368     setTruncStoreAction(MVT::v8i64,   MVT::v8i32,  Legal);
1369     setTruncStoreAction(MVT::v16i32,  MVT::v16i8,  Legal);
1370     setTruncStoreAction(MVT::v16i32,  MVT::v16i16, Legal);
1371     if (Subtarget->hasVLX()){
1372       setTruncStoreAction(MVT::v4i64, MVT::v4i8,  Legal);
1373       setTruncStoreAction(MVT::v4i64, MVT::v4i16, Legal);
1374       setTruncStoreAction(MVT::v4i64, MVT::v4i32, Legal);
1375       setTruncStoreAction(MVT::v8i32, MVT::v8i8,  Legal);
1376       setTruncStoreAction(MVT::v8i32, MVT::v8i16, Legal);
1377
1378       setTruncStoreAction(MVT::v2i64, MVT::v2i8,  Legal);
1379       setTruncStoreAction(MVT::v2i64, MVT::v2i16, Legal);
1380       setTruncStoreAction(MVT::v2i64, MVT::v2i32, Legal);
1381       setTruncStoreAction(MVT::v4i32, MVT::v4i8,  Legal);
1382       setTruncStoreAction(MVT::v4i32, MVT::v4i16, Legal);
1383     }
1384     setOperationAction(ISD::TRUNCATE,           MVT::i1, Custom);
1385     setOperationAction(ISD::TRUNCATE,           MVT::v16i8, Custom);
1386     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1387     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v8i1,  Custom);
1388     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v16i1, Custom);
1389     if (Subtarget->hasDQI()) {
1390       setOperationAction(ISD::TRUNCATE,         MVT::v2i1, Custom);
1391       setOperationAction(ISD::TRUNCATE,         MVT::v4i1, Custom);
1392
1393       setOperationAction(ISD::SINT_TO_FP,       MVT::v8i64, Legal);
1394       setOperationAction(ISD::UINT_TO_FP,       MVT::v8i64, Legal);
1395       setOperationAction(ISD::FP_TO_SINT,       MVT::v8i64, Legal);
1396       setOperationAction(ISD::FP_TO_UINT,       MVT::v8i64, Legal);
1397       if (Subtarget->hasVLX()) {
1398         setOperationAction(ISD::SINT_TO_FP,    MVT::v4i64, Legal);
1399         setOperationAction(ISD::SINT_TO_FP,    MVT::v2i64, Legal);
1400         setOperationAction(ISD::UINT_TO_FP,    MVT::v4i64, Legal);
1401         setOperationAction(ISD::UINT_TO_FP,    MVT::v2i64, Legal);
1402         setOperationAction(ISD::FP_TO_SINT,    MVT::v4i64, Legal);
1403         setOperationAction(ISD::FP_TO_SINT,    MVT::v2i64, Legal);
1404         setOperationAction(ISD::FP_TO_UINT,    MVT::v4i64, Legal);
1405         setOperationAction(ISD::FP_TO_UINT,    MVT::v2i64, Legal);
1406       }
1407     }
1408     if (Subtarget->hasVLX()) {
1409       setOperationAction(ISD::SINT_TO_FP,       MVT::v8i32, Legal);
1410       setOperationAction(ISD::UINT_TO_FP,       MVT::v8i32, Legal);
1411       setOperationAction(ISD::FP_TO_SINT,       MVT::v8i32, Legal);
1412       setOperationAction(ISD::FP_TO_UINT,       MVT::v8i32, Legal);
1413       setOperationAction(ISD::SINT_TO_FP,       MVT::v4i32, Legal);
1414       setOperationAction(ISD::UINT_TO_FP,       MVT::v4i32, Legal);
1415       setOperationAction(ISD::FP_TO_SINT,       MVT::v4i32, Legal);
1416       setOperationAction(ISD::FP_TO_UINT,       MVT::v4i32, Legal);
1417     }
1418     setOperationAction(ISD::TRUNCATE,           MVT::v8i1, Custom);
1419     setOperationAction(ISD::TRUNCATE,           MVT::v16i1, Custom);
1420     setOperationAction(ISD::TRUNCATE,           MVT::v16i16, Custom);
1421     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1422     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1423     setOperationAction(ISD::ANY_EXTEND,         MVT::v16i32, Custom);
1424     setOperationAction(ISD::ANY_EXTEND,         MVT::v8i64, Custom);
1425     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1426     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1427     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i8, Custom);
1428     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i16, Custom);
1429     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i16, Custom);
1430     if (Subtarget->hasDQI()) {
1431       setOperationAction(ISD::SIGN_EXTEND,        MVT::v4i32, Custom);
1432       setOperationAction(ISD::SIGN_EXTEND,        MVT::v2i64, Custom);
1433     }
1434     setOperationAction(ISD::FFLOOR,             MVT::v16f32, Legal);
1435     setOperationAction(ISD::FFLOOR,             MVT::v8f64, Legal);
1436     setOperationAction(ISD::FCEIL,              MVT::v16f32, Legal);
1437     setOperationAction(ISD::FCEIL,              MVT::v8f64, Legal);
1438     setOperationAction(ISD::FTRUNC,             MVT::v16f32, Legal);
1439     setOperationAction(ISD::FTRUNC,             MVT::v8f64, Legal);
1440     setOperationAction(ISD::FRINT,              MVT::v16f32, Legal);
1441     setOperationAction(ISD::FRINT,              MVT::v8f64, Legal);
1442     setOperationAction(ISD::FNEARBYINT,         MVT::v16f32, Legal);
1443     setOperationAction(ISD::FNEARBYINT,         MVT::v8f64, Legal);
1444
1445     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1446     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1447     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1448     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1449     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i1, Legal);
1450
1451     setOperationAction(ISD::SETCC,              MVT::v16i1, Custom);
1452     setOperationAction(ISD::SETCC,              MVT::v8i1, Custom);
1453
1454     setOperationAction(ISD::MUL,              MVT::v8i64, Custom);
1455
1456     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1,  Custom);
1457     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1458     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i1, Custom);
1459     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i1, Custom);
1460     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i1, Custom);
1461     setOperationAction(ISD::BUILD_VECTOR,       MVT::v16i1, Custom);
1462     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1463     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1464     setOperationAction(ISD::SELECT,             MVT::v16f32, Custom);
1465     setOperationAction(ISD::SELECT,             MVT::v16i1, Custom);
1466     setOperationAction(ISD::SELECT,             MVT::v8i1,  Custom);
1467
1468     setOperationAction(ISD::SMAX,               MVT::v16i32, Legal);
1469     setOperationAction(ISD::SMAX,               MVT::v8i64, Legal);
1470     setOperationAction(ISD::UMAX,               MVT::v16i32, Legal);
1471     setOperationAction(ISD::UMAX,               MVT::v8i64, Legal);
1472     setOperationAction(ISD::SMIN,               MVT::v16i32, Legal);
1473     setOperationAction(ISD::SMIN,               MVT::v8i64, Legal);
1474     setOperationAction(ISD::UMIN,               MVT::v16i32, Legal);
1475     setOperationAction(ISD::UMIN,               MVT::v8i64, Legal);
1476
1477     setOperationAction(ISD::ADD,                MVT::v8i64, Legal);
1478     setOperationAction(ISD::ADD,                MVT::v16i32, Legal);
1479
1480     setOperationAction(ISD::SUB,                MVT::v8i64, Legal);
1481     setOperationAction(ISD::SUB,                MVT::v16i32, Legal);
1482
1483     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1484
1485     setOperationAction(ISD::SRL,                MVT::v8i64, Custom);
1486     setOperationAction(ISD::SRL,                MVT::v16i32, Custom);
1487
1488     setOperationAction(ISD::SHL,                MVT::v8i64, Custom);
1489     setOperationAction(ISD::SHL,                MVT::v16i32, Custom);
1490
1491     setOperationAction(ISD::SRA,                MVT::v8i64, Custom);
1492     setOperationAction(ISD::SRA,                MVT::v16i32, Custom);
1493
1494     setOperationAction(ISD::AND,                MVT::v8i64, Legal);
1495     setOperationAction(ISD::OR,                 MVT::v8i64, Legal);
1496     setOperationAction(ISD::XOR,                MVT::v8i64, Legal);
1497     setOperationAction(ISD::AND,                MVT::v16i32, Legal);
1498     setOperationAction(ISD::OR,                 MVT::v16i32, Legal);
1499     setOperationAction(ISD::XOR,                MVT::v16i32, Legal);
1500
1501     if (Subtarget->hasCDI()) {
1502       setOperationAction(ISD::CTLZ,             MVT::v8i64,  Legal);
1503       setOperationAction(ISD::CTLZ,             MVT::v16i32, Legal);
1504       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v8i64,  Legal);
1505       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v16i32, Legal);
1506
1507       setOperationAction(ISD::CTLZ,             MVT::v8i16,  Custom);
1508       setOperationAction(ISD::CTLZ,             MVT::v16i8,  Custom);
1509       setOperationAction(ISD::CTLZ,             MVT::v16i16, Custom);
1510       setOperationAction(ISD::CTLZ,             MVT::v32i8,  Custom);
1511       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v8i16,  Custom);
1512       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v16i8,  Custom);
1513       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v16i16, Custom);
1514       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v32i8,  Custom);
1515
1516       setOperationAction(ISD::CTTZ_ZERO_UNDEF,  MVT::v8i64,  Custom);
1517       setOperationAction(ISD::CTTZ_ZERO_UNDEF,  MVT::v16i32, Custom);
1518
1519       if (Subtarget->hasVLX()) {
1520         setOperationAction(ISD::CTLZ,             MVT::v4i64, Legal);
1521         setOperationAction(ISD::CTLZ,             MVT::v8i32, Legal);
1522         setOperationAction(ISD::CTLZ,             MVT::v2i64, Legal);
1523         setOperationAction(ISD::CTLZ,             MVT::v4i32, Legal);
1524         setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v4i64, Legal);
1525         setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v8i32, Legal);
1526         setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v2i64, Legal);
1527         setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v4i32, Legal);
1528
1529         setOperationAction(ISD::CTTZ_ZERO_UNDEF,  MVT::v4i64, Custom);
1530         setOperationAction(ISD::CTTZ_ZERO_UNDEF,  MVT::v8i32, Custom);
1531         setOperationAction(ISD::CTTZ_ZERO_UNDEF,  MVT::v2i64, Custom);
1532         setOperationAction(ISD::CTTZ_ZERO_UNDEF,  MVT::v4i32, Custom);
1533       } else {
1534         setOperationAction(ISD::CTLZ,             MVT::v4i64, Custom);
1535         setOperationAction(ISD::CTLZ,             MVT::v8i32, Custom);
1536         setOperationAction(ISD::CTLZ,             MVT::v2i64, Custom);
1537         setOperationAction(ISD::CTLZ,             MVT::v4i32, Custom);
1538         setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v4i64, Custom);
1539         setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v8i32, Custom);
1540         setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v2i64, Custom);
1541         setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v4i32, Custom);
1542       }
1543     } // Subtarget->hasCDI()
1544
1545     if (Subtarget->hasDQI()) {
1546       setOperationAction(ISD::MUL,             MVT::v2i64, Legal);
1547       setOperationAction(ISD::MUL,             MVT::v4i64, Legal);
1548       setOperationAction(ISD::MUL,             MVT::v8i64, Legal);
1549     }
1550     // Custom lower several nodes.
1551     for (MVT VT : MVT::vector_valuetypes()) {
1552       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1553       if (EltSize == 1) {
1554         setOperationAction(ISD::AND, VT, Legal);
1555         setOperationAction(ISD::OR,  VT, Legal);
1556         setOperationAction(ISD::XOR,  VT, Legal);
1557       }
1558       if (EltSize >= 32 && VT.getSizeInBits() <= 512) {
1559         setOperationAction(ISD::MGATHER,  VT, Custom);
1560         setOperationAction(ISD::MSCATTER, VT, Custom);
1561       }
1562       // Extract subvector is special because the value type
1563       // (result) is 256/128-bit but the source is 512-bit wide.
1564       if (VT.is128BitVector() || VT.is256BitVector()) {
1565         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1566       }
1567       if (VT.getVectorElementType() == MVT::i1)
1568         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1569
1570       // Do not attempt to custom lower other non-512-bit vectors
1571       if (!VT.is512BitVector())
1572         continue;
1573
1574       if (EltSize >= 32) {
1575         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1576         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1577         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1578         setOperationAction(ISD::VSELECT,             VT, Legal);
1579         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1580         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1581         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1582         setOperationAction(ISD::MLOAD,               VT, Legal);
1583         setOperationAction(ISD::MSTORE,              VT, Legal);
1584       }
1585     }
1586     for (auto VT : { MVT::v64i8, MVT::v32i16, MVT::v16i32 }) {
1587       setOperationAction(ISD::SELECT, VT, Promote);
1588       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1589     }
1590   }// has  AVX-512
1591
1592   if (!Subtarget->useSoftFloat() && Subtarget->hasBWI()) {
1593     addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1594     addRegisterClass(MVT::v64i8,  &X86::VR512RegClass);
1595
1596     addRegisterClass(MVT::v32i1,  &X86::VK32RegClass);
1597     addRegisterClass(MVT::v64i1,  &X86::VK64RegClass);
1598
1599     setOperationAction(ISD::LOAD,               MVT::v32i16, Legal);
1600     setOperationAction(ISD::LOAD,               MVT::v64i8, Legal);
1601     setOperationAction(ISD::SETCC,              MVT::v32i1, Custom);
1602     setOperationAction(ISD::SETCC,              MVT::v64i1, Custom);
1603     setOperationAction(ISD::ADD,                MVT::v32i16, Legal);
1604     setOperationAction(ISD::ADD,                MVT::v64i8, Legal);
1605     setOperationAction(ISD::SUB,                MVT::v32i16, Legal);
1606     setOperationAction(ISD::SUB,                MVT::v64i8, Legal);
1607     setOperationAction(ISD::MUL,                MVT::v32i16, Legal);
1608     setOperationAction(ISD::MULHS,              MVT::v32i16, Legal);
1609     setOperationAction(ISD::MULHU,              MVT::v32i16, Legal);
1610     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v32i1, Legal);
1611     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v64i1, Legal);
1612     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v32i16, Custom);
1613     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v64i8, Custom);
1614     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v32i1, Custom);
1615     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v64i1, Custom);
1616     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v32i16, Custom);
1617     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v64i8, Custom);
1618     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v32i16, Custom);
1619     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v64i8, Custom);
1620     setOperationAction(ISD::SELECT,             MVT::v32i1, Custom);
1621     setOperationAction(ISD::SELECT,             MVT::v64i1, Custom);
1622     setOperationAction(ISD::SIGN_EXTEND,        MVT::v32i8, Custom);
1623     setOperationAction(ISD::ZERO_EXTEND,        MVT::v32i8, Custom);
1624     setOperationAction(ISD::SIGN_EXTEND,        MVT::v32i16, Custom);
1625     setOperationAction(ISD::ZERO_EXTEND,        MVT::v32i16, Custom);
1626     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v32i16, Custom);
1627     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v64i8, Custom);
1628     setOperationAction(ISD::SIGN_EXTEND,        MVT::v64i8, Custom);
1629     setOperationAction(ISD::ZERO_EXTEND,        MVT::v64i8, Custom);
1630     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v32i1, Custom);
1631     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v64i1, Custom);
1632     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v32i16, Custom);
1633     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v64i8, Custom);
1634     setOperationAction(ISD::VSELECT,            MVT::v32i16, Legal);
1635     setOperationAction(ISD::VSELECT,            MVT::v64i8, Legal);
1636     setOperationAction(ISD::TRUNCATE,           MVT::v32i1, Custom);
1637     setOperationAction(ISD::TRUNCATE,           MVT::v64i1, Custom);
1638     setOperationAction(ISD::TRUNCATE,           MVT::v32i8, Custom);
1639     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v32i1, Custom);
1640     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v64i1, Custom);
1641
1642     setOperationAction(ISD::SMAX,               MVT::v64i8, Legal);
1643     setOperationAction(ISD::SMAX,               MVT::v32i16, Legal);
1644     setOperationAction(ISD::UMAX,               MVT::v64i8, Legal);
1645     setOperationAction(ISD::UMAX,               MVT::v32i16, Legal);
1646     setOperationAction(ISD::SMIN,               MVT::v64i8, Legal);
1647     setOperationAction(ISD::SMIN,               MVT::v32i16, Legal);
1648     setOperationAction(ISD::UMIN,               MVT::v64i8, Legal);
1649     setOperationAction(ISD::UMIN,               MVT::v32i16, Legal);
1650
1651     setTruncStoreAction(MVT::v32i16,  MVT::v32i8, Legal);
1652     setTruncStoreAction(MVT::v16i16,  MVT::v16i8, Legal);
1653     if (Subtarget->hasVLX())
1654       setTruncStoreAction(MVT::v8i16,   MVT::v8i8,  Legal);
1655
1656     if (Subtarget->hasCDI()) {
1657       setOperationAction(ISD::CTLZ,            MVT::v32i16, Custom);
1658       setOperationAction(ISD::CTLZ,            MVT::v64i8,  Custom);
1659       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v32i16, Custom);
1660       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v64i8,  Custom);
1661     }
1662
1663     for (auto VT : { MVT::v64i8, MVT::v32i16 }) {
1664       setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1665       setOperationAction(ISD::VSELECT,             VT, Legal);
1666     }
1667   }
1668
1669   if (!Subtarget->useSoftFloat() && Subtarget->hasVLX()) {
1670     addRegisterClass(MVT::v4i1,   &X86::VK4RegClass);
1671     addRegisterClass(MVT::v2i1,   &X86::VK2RegClass);
1672
1673     setOperationAction(ISD::SETCC,              MVT::v4i1, Custom);
1674     setOperationAction(ISD::SETCC,              MVT::v2i1, Custom);
1675     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i1, Custom);
1676     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1, Custom);
1677     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v8i1, Custom);
1678     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v4i1, Custom);
1679     setOperationAction(ISD::SELECT,             MVT::v4i1, Custom);
1680     setOperationAction(ISD::SELECT,             MVT::v2i1, Custom);
1681     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4i1, Custom);
1682     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i1, Custom);
1683     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i1, Custom);
1684     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4i1, Custom);
1685
1686     setOperationAction(ISD::AND,                MVT::v8i32, Legal);
1687     setOperationAction(ISD::OR,                 MVT::v8i32, Legal);
1688     setOperationAction(ISD::XOR,                MVT::v8i32, Legal);
1689     setOperationAction(ISD::AND,                MVT::v4i32, Legal);
1690     setOperationAction(ISD::OR,                 MVT::v4i32, Legal);
1691     setOperationAction(ISD::XOR,                MVT::v4i32, Legal);
1692     setOperationAction(ISD::SRA,                MVT::v2i64, Custom);
1693     setOperationAction(ISD::SRA,                MVT::v4i64, Custom);
1694
1695     setOperationAction(ISD::SMAX,               MVT::v2i64, Legal);
1696     setOperationAction(ISD::SMAX,               MVT::v4i64, Legal);
1697     setOperationAction(ISD::UMAX,               MVT::v2i64, Legal);
1698     setOperationAction(ISD::UMAX,               MVT::v4i64, Legal);
1699     setOperationAction(ISD::SMIN,               MVT::v2i64, Legal);
1700     setOperationAction(ISD::SMIN,               MVT::v4i64, Legal);
1701     setOperationAction(ISD::UMIN,               MVT::v2i64, Legal);
1702     setOperationAction(ISD::UMIN,               MVT::v4i64, Legal);
1703   }
1704
1705   // We want to custom lower some of our intrinsics.
1706   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1707   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1708   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1709   if (!Subtarget->is64Bit())
1710     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1711
1712   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1713   // handle type legalization for these operations here.
1714   //
1715   // FIXME: We really should do custom legalization for addition and
1716   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1717   // than generic legalization for 64-bit multiplication-with-overflow, though.
1718   for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
1719     if (VT == MVT::i64 && !Subtarget->is64Bit())
1720       continue;
1721     // Add/Sub/Mul with overflow operations are custom lowered.
1722     setOperationAction(ISD::SADDO, VT, Custom);
1723     setOperationAction(ISD::UADDO, VT, Custom);
1724     setOperationAction(ISD::SSUBO, VT, Custom);
1725     setOperationAction(ISD::USUBO, VT, Custom);
1726     setOperationAction(ISD::SMULO, VT, Custom);
1727     setOperationAction(ISD::UMULO, VT, Custom);
1728   }
1729
1730   if (!Subtarget->is64Bit()) {
1731     // These libcalls are not available in 32-bit.
1732     setLibcallName(RTLIB::SHL_I128, nullptr);
1733     setLibcallName(RTLIB::SRL_I128, nullptr);
1734     setLibcallName(RTLIB::SRA_I128, nullptr);
1735   }
1736
1737   // Combine sin / cos into one node or libcall if possible.
1738   if (Subtarget->hasSinCos()) {
1739     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1740     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1741     if (Subtarget->isTargetDarwin()) {
1742       // For MacOSX, we don't want the normal expansion of a libcall to sincos.
1743       // We want to issue a libcall to __sincos_stret to avoid memory traffic.
1744       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1745       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1746     }
1747   }
1748
1749   if (Subtarget->isTargetWin64()) {
1750     setOperationAction(ISD::SDIV, MVT::i128, Custom);
1751     setOperationAction(ISD::UDIV, MVT::i128, Custom);
1752     setOperationAction(ISD::SREM, MVT::i128, Custom);
1753     setOperationAction(ISD::UREM, MVT::i128, Custom);
1754     setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1755     setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1756   }
1757
1758   // We have target-specific dag combine patterns for the following nodes:
1759   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1760   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1761   setTargetDAGCombine(ISD::BITCAST);
1762   setTargetDAGCombine(ISD::VSELECT);
1763   setTargetDAGCombine(ISD::SELECT);
1764   setTargetDAGCombine(ISD::SHL);
1765   setTargetDAGCombine(ISD::SRA);
1766   setTargetDAGCombine(ISD::SRL);
1767   setTargetDAGCombine(ISD::OR);
1768   setTargetDAGCombine(ISD::AND);
1769   setTargetDAGCombine(ISD::ADD);
1770   setTargetDAGCombine(ISD::FADD);
1771   setTargetDAGCombine(ISD::FSUB);
1772   setTargetDAGCombine(ISD::FMA);
1773   setTargetDAGCombine(ISD::SUB);
1774   setTargetDAGCombine(ISD::LOAD);
1775   setTargetDAGCombine(ISD::MLOAD);
1776   setTargetDAGCombine(ISD::STORE);
1777   setTargetDAGCombine(ISD::MSTORE);
1778   setTargetDAGCombine(ISD::ZERO_EXTEND);
1779   setTargetDAGCombine(ISD::ANY_EXTEND);
1780   setTargetDAGCombine(ISD::SIGN_EXTEND);
1781   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1782   setTargetDAGCombine(ISD::SINT_TO_FP);
1783   setTargetDAGCombine(ISD::UINT_TO_FP);
1784   setTargetDAGCombine(ISD::SETCC);
1785   setTargetDAGCombine(ISD::BUILD_VECTOR);
1786   setTargetDAGCombine(ISD::MUL);
1787   setTargetDAGCombine(ISD::XOR);
1788
1789   computeRegisterProperties(Subtarget->getRegisterInfo());
1790
1791   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1792   MaxStoresPerMemsetOptSize = 8;
1793   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1794   MaxStoresPerMemcpyOptSize = 4;
1795   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1796   MaxStoresPerMemmoveOptSize = 4;
1797   setPrefLoopAlignment(4); // 2^4 bytes.
1798
1799   // A predictable cmov does not hurt on an in-order CPU.
1800   // FIXME: Use a CPU attribute to trigger this, not a CPU model.
1801   PredictableSelectIsExpensive = !Subtarget->isAtom();
1802   EnableExtLdPromotion = true;
1803   setPrefFunctionAlignment(4); // 2^4 bytes.
1804
1805   verifyIntrinsicTables();
1806 }
1807
1808 // This has so far only been implemented for 64-bit MachO.
1809 bool X86TargetLowering::useLoadStackGuardNode() const {
1810   return Subtarget->isTargetMachO() && Subtarget->is64Bit();
1811 }
1812
1813 TargetLoweringBase::LegalizeTypeAction
1814 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1815   if (ExperimentalVectorWideningLegalization &&
1816       VT.getVectorNumElements() != 1 &&
1817       VT.getVectorElementType().getSimpleVT() != MVT::i1)
1818     return TypeWidenVector;
1819
1820   return TargetLoweringBase::getPreferredVectorAction(VT);
1821 }
1822
1823 EVT X86TargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1824                                           EVT VT) const {
1825   if (!VT.isVector())
1826     return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1827
1828   if (VT.isSimple()) {
1829     MVT VVT = VT.getSimpleVT();
1830     const unsigned NumElts = VVT.getVectorNumElements();
1831     const MVT EltVT = VVT.getVectorElementType();
1832     if (VVT.is512BitVector()) {
1833       if (Subtarget->hasAVX512())
1834         if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1835             EltVT == MVT::f32 || EltVT == MVT::f64)
1836           switch(NumElts) {
1837           case  8: return MVT::v8i1;
1838           case 16: return MVT::v16i1;
1839         }
1840       if (Subtarget->hasBWI())
1841         if (EltVT == MVT::i8 || EltVT == MVT::i16)
1842           switch(NumElts) {
1843           case 32: return MVT::v32i1;
1844           case 64: return MVT::v64i1;
1845         }
1846     }
1847
1848     if (VVT.is256BitVector() || VVT.is128BitVector()) {
1849       if (Subtarget->hasVLX())
1850         if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1851             EltVT == MVT::f32 || EltVT == MVT::f64)
1852           switch(NumElts) {
1853           case 2: return MVT::v2i1;
1854           case 4: return MVT::v4i1;
1855           case 8: return MVT::v8i1;
1856         }
1857       if (Subtarget->hasBWI() && Subtarget->hasVLX())
1858         if (EltVT == MVT::i8 || EltVT == MVT::i16)
1859           switch(NumElts) {
1860           case  8: return MVT::v8i1;
1861           case 16: return MVT::v16i1;
1862           case 32: return MVT::v32i1;
1863         }
1864     }
1865   }
1866
1867   return VT.changeVectorElementTypeToInteger();
1868 }
1869
1870 /// Helper for getByValTypeAlignment to determine
1871 /// the desired ByVal argument alignment.
1872 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1873   if (MaxAlign == 16)
1874     return;
1875   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1876     if (VTy->getBitWidth() == 128)
1877       MaxAlign = 16;
1878   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1879     unsigned EltAlign = 0;
1880     getMaxByValAlign(ATy->getElementType(), EltAlign);
1881     if (EltAlign > MaxAlign)
1882       MaxAlign = EltAlign;
1883   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1884     for (auto *EltTy : STy->elements()) {
1885       unsigned EltAlign = 0;
1886       getMaxByValAlign(EltTy, EltAlign);
1887       if (EltAlign > MaxAlign)
1888         MaxAlign = EltAlign;
1889       if (MaxAlign == 16)
1890         break;
1891     }
1892   }
1893 }
1894
1895 /// Return the desired alignment for ByVal aggregate
1896 /// function arguments in the caller parameter area. For X86, aggregates
1897 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1898 /// are at 4-byte boundaries.
1899 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty,
1900                                                   const DataLayout &DL) const {
1901   if (Subtarget->is64Bit()) {
1902     // Max of 8 and alignment of type.
1903     unsigned TyAlign = DL.getABITypeAlignment(Ty);
1904     if (TyAlign > 8)
1905       return TyAlign;
1906     return 8;
1907   }
1908
1909   unsigned Align = 4;
1910   if (Subtarget->hasSSE1())
1911     getMaxByValAlign(Ty, Align);
1912   return Align;
1913 }
1914
1915 /// Returns the target specific optimal type for load
1916 /// and store operations as a result of memset, memcpy, and memmove
1917 /// lowering. If DstAlign is zero that means it's safe to destination
1918 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1919 /// means there isn't a need to check it against alignment requirement,
1920 /// probably because the source does not need to be loaded. If 'IsMemset' is
1921 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1922 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1923 /// source is constant so it does not need to be loaded.
1924 /// It returns EVT::Other if the type should be determined using generic
1925 /// target-independent logic.
1926 EVT
1927 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1928                                        unsigned DstAlign, unsigned SrcAlign,
1929                                        bool IsMemset, bool ZeroMemset,
1930                                        bool MemcpyStrSrc,
1931                                        MachineFunction &MF) const {
1932   const Function *F = MF.getFunction();
1933   if ((!IsMemset || ZeroMemset) &&
1934       !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1935     if (Size >= 16 &&
1936         (!Subtarget->isUnalignedMem16Slow() ||
1937          ((DstAlign == 0 || DstAlign >= 16) &&
1938           (SrcAlign == 0 || SrcAlign >= 16)))) {
1939       if (Size >= 32) {
1940         // FIXME: Check if unaligned 32-byte accesses are slow.
1941         if (Subtarget->hasInt256())
1942           return MVT::v8i32;
1943         if (Subtarget->hasFp256())
1944           return MVT::v8f32;
1945       }
1946       if (Subtarget->hasSSE2())
1947         return MVT::v4i32;
1948       if (Subtarget->hasSSE1())
1949         return MVT::v4f32;
1950     } else if (!MemcpyStrSrc && Size >= 8 &&
1951                !Subtarget->is64Bit() &&
1952                Subtarget->hasSSE2()) {
1953       // Do not use f64 to lower memcpy if source is string constant. It's
1954       // better to use i32 to avoid the loads.
1955       return MVT::f64;
1956     }
1957   }
1958   // This is a compromise. If we reach here, unaligned accesses may be slow on
1959   // this target. However, creating smaller, aligned accesses could be even
1960   // slower and would certainly be a lot more code.
1961   if (Subtarget->is64Bit() && Size >= 8)
1962     return MVT::i64;
1963   return MVT::i32;
1964 }
1965
1966 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1967   if (VT == MVT::f32)
1968     return X86ScalarSSEf32;
1969   else if (VT == MVT::f64)
1970     return X86ScalarSSEf64;
1971   return true;
1972 }
1973
1974 bool
1975 X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1976                                                   unsigned,
1977                                                   unsigned,
1978                                                   bool *Fast) const {
1979   if (Fast) {
1980     switch (VT.getSizeInBits()) {
1981     default:
1982       // 8-byte and under are always assumed to be fast.
1983       *Fast = true;
1984       break;
1985     case 128:
1986       *Fast = !Subtarget->isUnalignedMem16Slow();
1987       break;
1988     case 256:
1989       *Fast = !Subtarget->isUnalignedMem32Slow();
1990       break;
1991     // TODO: What about AVX-512 (512-bit) accesses?
1992     }
1993   }
1994   // Misaligned accesses of any size are always allowed.
1995   return true;
1996 }
1997
1998 /// Return the entry encoding for a jump table in the
1999 /// current function.  The returned value is a member of the
2000 /// MachineJumpTableInfo::JTEntryKind enum.
2001 unsigned X86TargetLowering::getJumpTableEncoding() const {
2002   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
2003   // symbol.
2004   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2005       Subtarget->isPICStyleGOT())
2006     return MachineJumpTableInfo::EK_Custom32;
2007
2008   // Otherwise, use the normal jump table encoding heuristics.
2009   return TargetLowering::getJumpTableEncoding();
2010 }
2011
2012 bool X86TargetLowering::useSoftFloat() const {
2013   return Subtarget->useSoftFloat();
2014 }
2015
2016 const MCExpr *
2017 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
2018                                              const MachineBasicBlock *MBB,
2019                                              unsigned uid,MCContext &Ctx) const{
2020   assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
2021          Subtarget->isPICStyleGOT());
2022   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
2023   // entries.
2024   return MCSymbolRefExpr::create(MBB->getSymbol(),
2025                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
2026 }
2027
2028 /// Returns relocation base for the given PIC jumptable.
2029 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
2030                                                     SelectionDAG &DAG) const {
2031   if (!Subtarget->is64Bit())
2032     // This doesn't have SDLoc associated with it, but is not really the
2033     // same as a Register.
2034     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
2035                        getPointerTy(DAG.getDataLayout()));
2036   return Table;
2037 }
2038
2039 /// This returns the relocation base for the given PIC jumptable,
2040 /// the same as getPICJumpTableRelocBase, but as an MCExpr.
2041 const MCExpr *X86TargetLowering::
2042 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
2043                              MCContext &Ctx) const {
2044   // X86-64 uses RIP relative addressing based on the jump table label.
2045   if (Subtarget->isPICStyleRIPRel())
2046     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2047
2048   // Otherwise, the reference is relative to the PIC base.
2049   return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
2050 }
2051
2052 std::pair<const TargetRegisterClass *, uint8_t>
2053 X86TargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
2054                                            MVT VT) const {
2055   const TargetRegisterClass *RRC = nullptr;
2056   uint8_t Cost = 1;
2057   switch (VT.SimpleTy) {
2058   default:
2059     return TargetLowering::findRepresentativeClass(TRI, VT);
2060   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
2061     RRC = Subtarget->is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
2062     break;
2063   case MVT::x86mmx:
2064     RRC = &X86::VR64RegClass;
2065     break;
2066   case MVT::f32: case MVT::f64:
2067   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
2068   case MVT::v4f32: case MVT::v2f64:
2069   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
2070   case MVT::v4f64:
2071     RRC = &X86::VR128RegClass;
2072     break;
2073   }
2074   return std::make_pair(RRC, Cost);
2075 }
2076
2077 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
2078                                                unsigned &Offset) const {
2079   if (!Subtarget->isTargetLinux())
2080     return false;
2081
2082   if (Subtarget->is64Bit()) {
2083     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
2084     Offset = 0x28;
2085     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
2086       AddressSpace = 256;
2087     else
2088       AddressSpace = 257;
2089   } else {
2090     // %gs:0x14 on i386
2091     Offset = 0x14;
2092     AddressSpace = 256;
2093   }
2094   return true;
2095 }
2096
2097 Value *X86TargetLowering::getSafeStackPointerLocation(IRBuilder<> &IRB) const {
2098   if (!Subtarget->isTargetAndroid())
2099     return TargetLowering::getSafeStackPointerLocation(IRB);
2100
2101   // Android provides a fixed TLS slot for the SafeStack pointer. See the
2102   // definition of TLS_SLOT_SAFESTACK in
2103   // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
2104   unsigned AddressSpace, Offset;
2105   if (Subtarget->is64Bit()) {
2106     // %fs:0x48, unless we're using a Kernel code model, in which case it's %gs:
2107     Offset = 0x48;
2108     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
2109       AddressSpace = 256;
2110     else
2111       AddressSpace = 257;
2112   } else {
2113     // %gs:0x24 on i386
2114     Offset = 0x24;
2115     AddressSpace = 256;
2116   }
2117
2118   return ConstantExpr::getIntToPtr(
2119       ConstantInt::get(Type::getInt32Ty(IRB.getContext()), Offset),
2120       Type::getInt8PtrTy(IRB.getContext())->getPointerTo(AddressSpace));
2121 }
2122
2123 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
2124                                             unsigned DestAS) const {
2125   assert(SrcAS != DestAS && "Expected different address spaces!");
2126
2127   return SrcAS < 256 && DestAS < 256;
2128 }
2129
2130 //===----------------------------------------------------------------------===//
2131 //               Return Value Calling Convention Implementation
2132 //===----------------------------------------------------------------------===//
2133
2134 #include "X86GenCallingConv.inc"
2135
2136 bool X86TargetLowering::CanLowerReturn(
2137     CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
2138     const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
2139   SmallVector<CCValAssign, 16> RVLocs;
2140   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2141   return CCInfo.CheckReturn(Outs, RetCC_X86);
2142 }
2143
2144 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
2145   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
2146   return ScratchRegs;
2147 }
2148
2149 SDValue
2150 X86TargetLowering::LowerReturn(SDValue Chain,
2151                                CallingConv::ID CallConv, bool isVarArg,
2152                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2153                                const SmallVectorImpl<SDValue> &OutVals,
2154                                SDLoc dl, SelectionDAG &DAG) const {
2155   MachineFunction &MF = DAG.getMachineFunction();
2156   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2157
2158   SmallVector<CCValAssign, 16> RVLocs;
2159   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
2160   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
2161
2162   SDValue Flag;
2163   SmallVector<SDValue, 6> RetOps;
2164   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2165   // Operand #1 = Bytes To Pop
2166   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(), dl,
2167                    MVT::i16));
2168
2169   // Copy the result values into the output registers.
2170   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2171     CCValAssign &VA = RVLocs[i];
2172     assert(VA.isRegLoc() && "Can only return in registers!");
2173     SDValue ValToCopy = OutVals[i];
2174     EVT ValVT = ValToCopy.getValueType();
2175
2176     // Promote values to the appropriate types.
2177     if (VA.getLocInfo() == CCValAssign::SExt)
2178       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2179     else if (VA.getLocInfo() == CCValAssign::ZExt)
2180       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
2181     else if (VA.getLocInfo() == CCValAssign::AExt) {
2182       if (ValVT.isVector() && ValVT.getVectorElementType() == MVT::i1)
2183         ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2184       else
2185         ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
2186     }
2187     else if (VA.getLocInfo() == CCValAssign::BCvt)
2188       ValToCopy = DAG.getBitcast(VA.getLocVT(), ValToCopy);
2189
2190     assert(VA.getLocInfo() != CCValAssign::FPExt &&
2191            "Unexpected FP-extend for return value.");
2192
2193     // If this is x86-64, and we disabled SSE, we can't return FP values,
2194     // or SSE or MMX vectors.
2195     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
2196          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
2197           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
2198       report_fatal_error("SSE register return with SSE disabled");
2199     }
2200     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
2201     // llvm-gcc has never done it right and no one has noticed, so this
2202     // should be OK for now.
2203     if (ValVT == MVT::f64 &&
2204         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
2205       report_fatal_error("SSE2 register return with SSE2 disabled");
2206
2207     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
2208     // the RET instruction and handled by the FP Stackifier.
2209     if (VA.getLocReg() == X86::FP0 ||
2210         VA.getLocReg() == X86::FP1) {
2211       // If this is a copy from an xmm register to ST(0), use an FPExtend to
2212       // change the value to the FP stack register class.
2213       if (isScalarFPTypeInSSEReg(VA.getValVT()))
2214         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
2215       RetOps.push_back(ValToCopy);
2216       // Don't emit a copytoreg.
2217       continue;
2218     }
2219
2220     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
2221     // which is returned in RAX / RDX.
2222     if (Subtarget->is64Bit()) {
2223       if (ValVT == MVT::x86mmx) {
2224         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
2225           ValToCopy = DAG.getBitcast(MVT::i64, ValToCopy);
2226           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
2227                                   ValToCopy);
2228           // If we don't have SSE2 available, convert to v4f32 so the generated
2229           // register is legal.
2230           if (!Subtarget->hasSSE2())
2231             ValToCopy = DAG.getBitcast(MVT::v4f32, ValToCopy);
2232         }
2233       }
2234     }
2235
2236     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
2237     Flag = Chain.getValue(1);
2238     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2239   }
2240
2241   // All x86 ABIs require that for returning structs by value we copy
2242   // the sret argument into %rax/%eax (depending on ABI) for the return.
2243   // We saved the argument into a virtual register in the entry block,
2244   // so now we copy the value out and into %rax/%eax.
2245   //
2246   // Checking Function.hasStructRetAttr() here is insufficient because the IR
2247   // may not have an explicit sret argument. If FuncInfo.CanLowerReturn is
2248   // false, then an sret argument may be implicitly inserted in the SelDAG. In
2249   // either case FuncInfo->setSRetReturnReg() will have been called.
2250   if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
2251     SDValue Val = DAG.getCopyFromReg(Chain, dl, SRetReg,
2252                                      getPointerTy(MF.getDataLayout()));
2253
2254     unsigned RetValReg
2255         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
2256           X86::RAX : X86::EAX;
2257     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2258     Flag = Chain.getValue(1);
2259
2260     // RAX/EAX now acts like a return value.
2261     RetOps.push_back(
2262         DAG.getRegister(RetValReg, getPointerTy(DAG.getDataLayout())));
2263   }
2264
2265   RetOps[0] = Chain;  // Update chain.
2266
2267   // Add the flag if we have it.
2268   if (Flag.getNode())
2269     RetOps.push_back(Flag);
2270
2271   return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
2272 }
2273
2274 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2275   if (N->getNumValues() != 1)
2276     return false;
2277   if (!N->hasNUsesOfValue(1, 0))
2278     return false;
2279
2280   SDValue TCChain = Chain;
2281   SDNode *Copy = *N->use_begin();
2282   if (Copy->getOpcode() == ISD::CopyToReg) {
2283     // If the copy has a glue operand, we conservatively assume it isn't safe to
2284     // perform a tail call.
2285     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2286       return false;
2287     TCChain = Copy->getOperand(0);
2288   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2289     return false;
2290
2291   bool HasRet = false;
2292   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2293        UI != UE; ++UI) {
2294     if (UI->getOpcode() != X86ISD::RET_FLAG)
2295       return false;
2296     // If we are returning more than one value, we can definitely
2297     // not make a tail call see PR19530
2298     if (UI->getNumOperands() > 4)
2299       return false;
2300     if (UI->getNumOperands() == 4 &&
2301         UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2302       return false;
2303     HasRet = true;
2304   }
2305
2306   if (!HasRet)
2307     return false;
2308
2309   Chain = TCChain;
2310   return true;
2311 }
2312
2313 EVT
2314 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
2315                                             ISD::NodeType ExtendKind) const {
2316   MVT ReturnMVT;
2317   // TODO: Is this also valid on 32-bit?
2318   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2319     ReturnMVT = MVT::i8;
2320   else
2321     ReturnMVT = MVT::i32;
2322
2323   EVT MinVT = getRegisterType(Context, ReturnMVT);
2324   return VT.bitsLT(MinVT) ? MinVT : VT;
2325 }
2326
2327 /// Lower the result values of a call into the
2328 /// appropriate copies out of appropriate physical registers.
2329 ///
2330 SDValue
2331 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2332                                    CallingConv::ID CallConv, bool isVarArg,
2333                                    const SmallVectorImpl<ISD::InputArg> &Ins,
2334                                    SDLoc dl, SelectionDAG &DAG,
2335                                    SmallVectorImpl<SDValue> &InVals) const {
2336
2337   // Assign locations to each value returned by this call.
2338   SmallVector<CCValAssign, 16> RVLocs;
2339   bool Is64Bit = Subtarget->is64Bit();
2340   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2341                  *DAG.getContext());
2342   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2343
2344   // Copy all of the result registers out of their specified physreg.
2345   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2346     CCValAssign &VA = RVLocs[i];
2347     EVT CopyVT = VA.getLocVT();
2348
2349     // If this is x86-64, and we disabled SSE, we can't return FP values
2350     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2351         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2352       report_fatal_error("SSE register return with SSE disabled");
2353     }
2354
2355     // If we prefer to use the value in xmm registers, copy it out as f80 and
2356     // use a truncate to move it from fp stack reg to xmm reg.
2357     bool RoundAfterCopy = false;
2358     if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2359         isScalarFPTypeInSSEReg(VA.getValVT())) {
2360       CopyVT = MVT::f80;
2361       RoundAfterCopy = (CopyVT != VA.getLocVT());
2362     }
2363
2364     Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2365                                CopyVT, InFlag).getValue(1);
2366     SDValue Val = Chain.getValue(0);
2367
2368     if (RoundAfterCopy)
2369       Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2370                         // This truncation won't change the value.
2371                         DAG.getIntPtrConstant(1, dl));
2372
2373     if (VA.isExtInLoc() && VA.getValVT().getScalarType() == MVT::i1)
2374       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
2375
2376     InFlag = Chain.getValue(2);
2377     InVals.push_back(Val);
2378   }
2379
2380   return Chain;
2381 }
2382
2383 //===----------------------------------------------------------------------===//
2384 //                C & StdCall & Fast Calling Convention implementation
2385 //===----------------------------------------------------------------------===//
2386 //  StdCall calling convention seems to be standard for many Windows' API
2387 //  routines and around. It differs from C calling convention just a little:
2388 //  callee should clean up the stack, not caller. Symbols should be also
2389 //  decorated in some fancy way :) It doesn't support any vector arguments.
2390 //  For info on fast calling convention see Fast Calling Convention (tail call)
2391 //  implementation LowerX86_32FastCCCallTo.
2392
2393 /// CallIsStructReturn - Determines whether a call uses struct return
2394 /// semantics.
2395 enum StructReturnType {
2396   NotStructReturn,
2397   RegStructReturn,
2398   StackStructReturn
2399 };
2400 static StructReturnType
2401 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2402   if (Outs.empty())
2403     return NotStructReturn;
2404
2405   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2406   if (!Flags.isSRet())
2407     return NotStructReturn;
2408   if (Flags.isInReg())
2409     return RegStructReturn;
2410   return StackStructReturn;
2411 }
2412
2413 /// Determines whether a function uses struct return semantics.
2414 static StructReturnType
2415 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2416   if (Ins.empty())
2417     return NotStructReturn;
2418
2419   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2420   if (!Flags.isSRet())
2421     return NotStructReturn;
2422   if (Flags.isInReg())
2423     return RegStructReturn;
2424   return StackStructReturn;
2425 }
2426
2427 /// Make a copy of an aggregate at address specified by "Src" to address
2428 /// "Dst" with size and alignment information specified by the specific
2429 /// parameter attribute. The copy will be passed as a byval function parameter.
2430 static SDValue
2431 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2432                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2433                           SDLoc dl) {
2434   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
2435
2436   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2437                        /*isVolatile*/false, /*AlwaysInline=*/true,
2438                        /*isTailCall*/false,
2439                        MachinePointerInfo(), MachinePointerInfo());
2440 }
2441
2442 /// Return true if the calling convention is one that we can guarantee TCO for.
2443 static bool canGuaranteeTCO(CallingConv::ID CC) {
2444   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2445           CC == CallingConv::HiPE || CC == CallingConv::HHVM);
2446 }
2447
2448 /// Return true if we might ever do TCO for calls with this calling convention.
2449 static bool mayTailCallThisCC(CallingConv::ID CC) {
2450   switch (CC) {
2451   // C calling conventions:
2452   case CallingConv::C:
2453   case CallingConv::X86_64_Win64:
2454   case CallingConv::X86_64_SysV:
2455   // Callee pop conventions:
2456   case CallingConv::X86_ThisCall:
2457   case CallingConv::X86_StdCall:
2458   case CallingConv::X86_VectorCall:
2459   case CallingConv::X86_FastCall:
2460     return true;
2461   default:
2462     return canGuaranteeTCO(CC);
2463   }
2464 }
2465
2466 /// Return true if the function is being made into a tailcall target by
2467 /// changing its ABI.
2468 static bool shouldGuaranteeTCO(CallingConv::ID CC, bool GuaranteedTailCallOpt) {
2469   return GuaranteedTailCallOpt && canGuaranteeTCO(CC);
2470 }
2471
2472 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2473   auto Attr =
2474       CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2475   if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2476     return false;
2477
2478   CallSite CS(CI);
2479   CallingConv::ID CalleeCC = CS.getCallingConv();
2480   if (!mayTailCallThisCC(CalleeCC))
2481     return false;
2482
2483   return true;
2484 }
2485
2486 SDValue
2487 X86TargetLowering::LowerMemArgument(SDValue Chain,
2488                                     CallingConv::ID CallConv,
2489                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2490                                     SDLoc dl, SelectionDAG &DAG,
2491                                     const CCValAssign &VA,
2492                                     MachineFrameInfo *MFI,
2493                                     unsigned i) const {
2494   // Create the nodes corresponding to a load from this parameter slot.
2495   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2496   bool AlwaysUseMutable = shouldGuaranteeTCO(
2497       CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2498   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2499   EVT ValVT;
2500
2501   // If value is passed by pointer we have address passed instead of the value
2502   // itself.
2503   bool ExtendedInMem = VA.isExtInLoc() &&
2504     VA.getValVT().getScalarType() == MVT::i1;
2505
2506   if (VA.getLocInfo() == CCValAssign::Indirect || ExtendedInMem)
2507     ValVT = VA.getLocVT();
2508   else
2509     ValVT = VA.getValVT();
2510
2511   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2512   // changed with more analysis.
2513   // In case of tail call optimization mark all arguments mutable. Since they
2514   // could be overwritten by lowering of arguments in case of a tail call.
2515   if (Flags.isByVal()) {
2516     unsigned Bytes = Flags.getByValSize();
2517     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2518     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2519     return DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2520   } else {
2521     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2522                                     VA.getLocMemOffset(), isImmutable);
2523     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2524     SDValue Val = DAG.getLoad(
2525         ValVT, dl, Chain, FIN,
2526         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), false,
2527         false, false, 0);
2528     return ExtendedInMem ?
2529       DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val) : Val;
2530   }
2531 }
2532
2533 // FIXME: Get this from tablegen.
2534 static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
2535                                                 const X86Subtarget *Subtarget) {
2536   assert(Subtarget->is64Bit());
2537
2538   if (Subtarget->isCallingConvWin64(CallConv)) {
2539     static const MCPhysReg GPR64ArgRegsWin64[] = {
2540       X86::RCX, X86::RDX, X86::R8,  X86::R9
2541     };
2542     return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
2543   }
2544
2545   static const MCPhysReg GPR64ArgRegs64Bit[] = {
2546     X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2547   };
2548   return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
2549 }
2550
2551 // FIXME: Get this from tablegen.
2552 static ArrayRef<MCPhysReg> get64BitArgumentXMMs(MachineFunction &MF,
2553                                                 CallingConv::ID CallConv,
2554                                                 const X86Subtarget *Subtarget) {
2555   assert(Subtarget->is64Bit());
2556   if (Subtarget->isCallingConvWin64(CallConv)) {
2557     // The XMM registers which might contain var arg parameters are shadowed
2558     // in their paired GPR.  So we only need to save the GPR to their home
2559     // slots.
2560     // TODO: __vectorcall will change this.
2561     return None;
2562   }
2563
2564   const Function *Fn = MF.getFunction();
2565   bool NoImplicitFloatOps = Fn->hasFnAttribute(Attribute::NoImplicitFloat);
2566   bool isSoftFloat = Subtarget->useSoftFloat();
2567   assert(!(isSoftFloat && NoImplicitFloatOps) &&
2568          "SSE register cannot be used when SSE is disabled!");
2569   if (isSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
2570     // Kernel mode asks for SSE to be disabled, so there are no XMM argument
2571     // registers.
2572     return None;
2573
2574   static const MCPhysReg XMMArgRegs64Bit[] = {
2575     X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2576     X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2577   };
2578   return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
2579 }
2580
2581 SDValue X86TargetLowering::LowerFormalArguments(
2582     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2583     const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc dl, SelectionDAG &DAG,
2584     SmallVectorImpl<SDValue> &InVals) const {
2585   MachineFunction &MF = DAG.getMachineFunction();
2586   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2587   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
2588
2589   const Function* Fn = MF.getFunction();
2590   if (Fn->hasExternalLinkage() &&
2591       Subtarget->isTargetCygMing() &&
2592       Fn->getName() == "main")
2593     FuncInfo->setForceFramePointer(true);
2594
2595   MachineFrameInfo *MFI = MF.getFrameInfo();
2596   bool Is64Bit = Subtarget->is64Bit();
2597   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2598
2599   assert(!(isVarArg && canGuaranteeTCO(CallConv)) &&
2600          "Var args not supported with calling convention fastcc, ghc or hipe");
2601
2602   // Assign locations to all of the incoming arguments.
2603   SmallVector<CCValAssign, 16> ArgLocs;
2604   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2605
2606   // Allocate shadow area for Win64
2607   if (IsWin64)
2608     CCInfo.AllocateStack(32, 8);
2609
2610   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2611
2612   unsigned LastVal = ~0U;
2613   SDValue ArgValue;
2614   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2615     CCValAssign &VA = ArgLocs[i];
2616     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2617     // places.
2618     assert(VA.getValNo() != LastVal &&
2619            "Don't support value assigned to multiple locs yet");
2620     (void)LastVal;
2621     LastVal = VA.getValNo();
2622
2623     if (VA.isRegLoc()) {
2624       EVT RegVT = VA.getLocVT();
2625       const TargetRegisterClass *RC;
2626       if (RegVT == MVT::i32)
2627         RC = &X86::GR32RegClass;
2628       else if (Is64Bit && RegVT == MVT::i64)
2629         RC = &X86::GR64RegClass;
2630       else if (RegVT == MVT::f32)
2631         RC = &X86::FR32RegClass;
2632       else if (RegVT == MVT::f64)
2633         RC = &X86::FR64RegClass;
2634       else if (RegVT.is512BitVector())
2635         RC = &X86::VR512RegClass;
2636       else if (RegVT.is256BitVector())
2637         RC = &X86::VR256RegClass;
2638       else if (RegVT.is128BitVector())
2639         RC = &X86::VR128RegClass;
2640       else if (RegVT == MVT::x86mmx)
2641         RC = &X86::VR64RegClass;
2642       else if (RegVT == MVT::i1)
2643         RC = &X86::VK1RegClass;
2644       else if (RegVT == MVT::v8i1)
2645         RC = &X86::VK8RegClass;
2646       else if (RegVT == MVT::v16i1)
2647         RC = &X86::VK16RegClass;
2648       else if (RegVT == MVT::v32i1)
2649         RC = &X86::VK32RegClass;
2650       else if (RegVT == MVT::v64i1)
2651         RC = &X86::VK64RegClass;
2652       else
2653         llvm_unreachable("Unknown argument type!");
2654
2655       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2656       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2657
2658       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2659       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2660       // right size.
2661       if (VA.getLocInfo() == CCValAssign::SExt)
2662         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2663                                DAG.getValueType(VA.getValVT()));
2664       else if (VA.getLocInfo() == CCValAssign::ZExt)
2665         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2666                                DAG.getValueType(VA.getValVT()));
2667       else if (VA.getLocInfo() == CCValAssign::BCvt)
2668         ArgValue = DAG.getBitcast(VA.getValVT(), ArgValue);
2669
2670       if (VA.isExtInLoc()) {
2671         // Handle MMX values passed in XMM regs.
2672         if (RegVT.isVector() && VA.getValVT().getScalarType() != MVT::i1)
2673           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2674         else
2675           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2676       }
2677     } else {
2678       assert(VA.isMemLoc());
2679       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2680     }
2681
2682     // If value is passed via pointer - do a load.
2683     if (VA.getLocInfo() == CCValAssign::Indirect)
2684       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2685                              MachinePointerInfo(), false, false, false, 0);
2686
2687     InVals.push_back(ArgValue);
2688   }
2689
2690   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2691     // All x86 ABIs require that for returning structs by value we copy the
2692     // sret argument into %rax/%eax (depending on ABI) for the return. Save
2693     // the argument into a virtual register so that we can access it from the
2694     // return points.
2695     if (Ins[i].Flags.isSRet()) {
2696       unsigned Reg = FuncInfo->getSRetReturnReg();
2697       if (!Reg) {
2698         MVT PtrTy = getPointerTy(DAG.getDataLayout());
2699         Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2700         FuncInfo->setSRetReturnReg(Reg);
2701       }
2702       SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2703       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2704       break;
2705     }
2706   }
2707
2708   unsigned StackSize = CCInfo.getNextStackOffset();
2709   // Align stack specially for tail calls.
2710   if (shouldGuaranteeTCO(CallConv,
2711                          MF.getTarget().Options.GuaranteedTailCallOpt))
2712     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2713
2714   // If the function takes variable number of arguments, make a frame index for
2715   // the start of the first vararg value... for expansion of llvm.va_start. We
2716   // can skip this if there are no va_start calls.
2717   if (MFI->hasVAStart() &&
2718       (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2719                    CallConv != CallingConv::X86_ThisCall))) {
2720     FuncInfo->setVarArgsFrameIndex(
2721         MFI->CreateFixedObject(1, StackSize, true));
2722   }
2723
2724   // Figure out if XMM registers are in use.
2725   assert(!(Subtarget->useSoftFloat() &&
2726            Fn->hasFnAttribute(Attribute::NoImplicitFloat)) &&
2727          "SSE register cannot be used when SSE is disabled!");
2728
2729   // 64-bit calling conventions support varargs and register parameters, so we
2730   // have to do extra work to spill them in the prologue.
2731   if (Is64Bit && isVarArg && MFI->hasVAStart()) {
2732     // Find the first unallocated argument registers.
2733     ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
2734     ArrayRef<MCPhysReg> ArgXMMs = get64BitArgumentXMMs(MF, CallConv, Subtarget);
2735     unsigned NumIntRegs = CCInfo.getFirstUnallocated(ArgGPRs);
2736     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(ArgXMMs);
2737     assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2738            "SSE register cannot be used when SSE is disabled!");
2739
2740     // Gather all the live in physical registers.
2741     SmallVector<SDValue, 6> LiveGPRs;
2742     SmallVector<SDValue, 8> LiveXMMRegs;
2743     SDValue ALVal;
2744     for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
2745       unsigned GPR = MF.addLiveIn(Reg, &X86::GR64RegClass);
2746       LiveGPRs.push_back(
2747           DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64));
2748     }
2749     if (!ArgXMMs.empty()) {
2750       unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2751       ALVal = DAG.getCopyFromReg(Chain, dl, AL, MVT::i8);
2752       for (MCPhysReg Reg : ArgXMMs.slice(NumXMMRegs)) {
2753         unsigned XMMReg = MF.addLiveIn(Reg, &X86::VR128RegClass);
2754         LiveXMMRegs.push_back(
2755             DAG.getCopyFromReg(Chain, dl, XMMReg, MVT::v4f32));
2756       }
2757     }
2758
2759     if (IsWin64) {
2760       // Get to the caller-allocated home save location.  Add 8 to account
2761       // for the return address.
2762       int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2763       FuncInfo->setRegSaveFrameIndex(
2764           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2765       // Fixup to set vararg frame on shadow area (4 x i64).
2766       if (NumIntRegs < 4)
2767         FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2768     } else {
2769       // For X86-64, if there are vararg parameters that are passed via
2770       // registers, then we must store them to their spots on the stack so
2771       // they may be loaded by deferencing the result of va_next.
2772       FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2773       FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
2774       FuncInfo->setRegSaveFrameIndex(MFI->CreateStackObject(
2775           ArgGPRs.size() * 8 + ArgXMMs.size() * 16, 16, false));
2776     }
2777
2778     // Store the integer parameter registers.
2779     SmallVector<SDValue, 8> MemOps;
2780     SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2781                                       getPointerTy(DAG.getDataLayout()));
2782     unsigned Offset = FuncInfo->getVarArgsGPOffset();
2783     for (SDValue Val : LiveGPRs) {
2784       SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2785                                 RSFIN, DAG.getIntPtrConstant(Offset, dl));
2786       SDValue Store =
2787           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2788                        MachinePointerInfo::getFixedStack(
2789                            DAG.getMachineFunction(),
2790                            FuncInfo->getRegSaveFrameIndex(), Offset),
2791                        false, false, 0);
2792       MemOps.push_back(Store);
2793       Offset += 8;
2794     }
2795
2796     if (!ArgXMMs.empty() && NumXMMRegs != ArgXMMs.size()) {
2797       // Now store the XMM (fp + vector) parameter registers.
2798       SmallVector<SDValue, 12> SaveXMMOps;
2799       SaveXMMOps.push_back(Chain);
2800       SaveXMMOps.push_back(ALVal);
2801       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2802                              FuncInfo->getRegSaveFrameIndex(), dl));
2803       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2804                              FuncInfo->getVarArgsFPOffset(), dl));
2805       SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
2806                         LiveXMMRegs.end());
2807       MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2808                                    MVT::Other, SaveXMMOps));
2809     }
2810
2811     if (!MemOps.empty())
2812       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2813   }
2814
2815   if (isVarArg && MFI->hasMustTailInVarArgFunc()) {
2816     // Find the largest legal vector type.
2817     MVT VecVT = MVT::Other;
2818     // FIXME: Only some x86_32 calling conventions support AVX512.
2819     if (Subtarget->hasAVX512() &&
2820         (Is64Bit || (CallConv == CallingConv::X86_VectorCall ||
2821                      CallConv == CallingConv::Intel_OCL_BI)))
2822       VecVT = MVT::v16f32;
2823     else if (Subtarget->hasAVX())
2824       VecVT = MVT::v8f32;
2825     else if (Subtarget->hasSSE2())
2826       VecVT = MVT::v4f32;
2827
2828     // We forward some GPRs and some vector types.
2829     SmallVector<MVT, 2> RegParmTypes;
2830     MVT IntVT = Is64Bit ? MVT::i64 : MVT::i32;
2831     RegParmTypes.push_back(IntVT);
2832     if (VecVT != MVT::Other)
2833       RegParmTypes.push_back(VecVT);
2834
2835     // Compute the set of forwarded registers. The rest are scratch.
2836     SmallVectorImpl<ForwardedRegister> &Forwards =
2837         FuncInfo->getForwardedMustTailRegParms();
2838     CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, CC_X86);
2839
2840     // Conservatively forward AL on x86_64, since it might be used for varargs.
2841     if (Is64Bit && !CCInfo.isAllocated(X86::AL)) {
2842       unsigned ALVReg = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2843       Forwards.push_back(ForwardedRegister(ALVReg, X86::AL, MVT::i8));
2844     }
2845
2846     // Copy all forwards from physical to virtual registers.
2847     for (ForwardedRegister &F : Forwards) {
2848       // FIXME: Can we use a less constrained schedule?
2849       SDValue RegVal = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2850       F.VReg = MF.getRegInfo().createVirtualRegister(getRegClassFor(F.VT));
2851       Chain = DAG.getCopyToReg(Chain, dl, F.VReg, RegVal);
2852     }
2853   }
2854
2855   // Some CCs need callee pop.
2856   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2857                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2858     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2859   } else {
2860     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2861     // If this is an sret function, the return should pop the hidden pointer.
2862     if (!Is64Bit && !canGuaranteeTCO(CallConv) &&
2863         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2864         argsAreStructReturn(Ins) == StackStructReturn)
2865       FuncInfo->setBytesToPopOnReturn(4);
2866   }
2867
2868   if (!Is64Bit) {
2869     // RegSaveFrameIndex is X86-64 only.
2870     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2871     if (CallConv == CallingConv::X86_FastCall ||
2872         CallConv == CallingConv::X86_ThisCall)
2873       // fastcc functions can't have varargs.
2874       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2875   }
2876
2877   FuncInfo->setArgumentStackSize(StackSize);
2878
2879   if (WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo()) {
2880     EHPersonality Personality = classifyEHPersonality(Fn->getPersonalityFn());
2881     if (Personality == EHPersonality::CoreCLR) {
2882       assert(Is64Bit);
2883       // TODO: Add a mechanism to frame lowering that will allow us to indicate
2884       // that we'd prefer this slot be allocated towards the bottom of the frame
2885       // (i.e. near the stack pointer after allocating the frame).  Every
2886       // funclet needs a copy of this slot in its (mostly empty) frame, and the
2887       // offset from the bottom of this and each funclet's frame must be the
2888       // same, so the size of funclets' (mostly empty) frames is dictated by
2889       // how far this slot is from the bottom (since they allocate just enough
2890       // space to accomodate holding this slot at the correct offset).
2891       int PSPSymFI = MFI->CreateStackObject(8, 8, /*isSS=*/false);
2892       EHInfo->PSPSymFrameIdx = PSPSymFI;
2893     }
2894   }
2895
2896   return Chain;
2897 }
2898
2899 SDValue
2900 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2901                                     SDValue StackPtr, SDValue Arg,
2902                                     SDLoc dl, SelectionDAG &DAG,
2903                                     const CCValAssign &VA,
2904                                     ISD::ArgFlagsTy Flags) const {
2905   unsigned LocMemOffset = VA.getLocMemOffset();
2906   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
2907   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2908                        StackPtr, PtrOff);
2909   if (Flags.isByVal())
2910     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2911
2912   return DAG.getStore(
2913       Chain, dl, Arg, PtrOff,
2914       MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset),
2915       false, false, 0);
2916 }
2917
2918 /// Emit a load of return address if tail call
2919 /// optimization is performed and it is required.
2920 SDValue
2921 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2922                                            SDValue &OutRetAddr, SDValue Chain,
2923                                            bool IsTailCall, bool Is64Bit,
2924                                            int FPDiff, SDLoc dl) const {
2925   // Adjust the Return address stack slot.
2926   EVT VT = getPointerTy(DAG.getDataLayout());
2927   OutRetAddr = getReturnAddressFrameIndex(DAG);
2928
2929   // Load the "old" Return address.
2930   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2931                            false, false, false, 0);
2932   return SDValue(OutRetAddr.getNode(), 1);
2933 }
2934
2935 /// Emit a store of the return address if tail call
2936 /// optimization is performed and it is required (FPDiff!=0).
2937 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2938                                         SDValue Chain, SDValue RetAddrFrIdx,
2939                                         EVT PtrVT, unsigned SlotSize,
2940                                         int FPDiff, SDLoc dl) {
2941   // Store the return address to the appropriate stack slot.
2942   if (!FPDiff) return Chain;
2943   // Calculate the new stack slot for the return address.
2944   int NewReturnAddrFI =
2945     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2946                                          false);
2947   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2948   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2949                        MachinePointerInfo::getFixedStack(
2950                            DAG.getMachineFunction(), NewReturnAddrFI),
2951                        false, false, 0);
2952   return Chain;
2953 }
2954
2955 /// Returns a vector_shuffle mask for an movs{s|d}, movd
2956 /// operation of specified width.
2957 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
2958                        SDValue V2) {
2959   unsigned NumElems = VT.getVectorNumElements();
2960   SmallVector<int, 8> Mask;
2961   Mask.push_back(NumElems);
2962   for (unsigned i = 1; i != NumElems; ++i)
2963     Mask.push_back(i);
2964   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
2965 }
2966
2967 SDValue
2968 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2969                              SmallVectorImpl<SDValue> &InVals) const {
2970   SelectionDAG &DAG                     = CLI.DAG;
2971   SDLoc &dl                             = CLI.DL;
2972   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2973   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2974   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2975   SDValue Chain                         = CLI.Chain;
2976   SDValue Callee                        = CLI.Callee;
2977   CallingConv::ID CallConv              = CLI.CallConv;
2978   bool &isTailCall                      = CLI.IsTailCall;
2979   bool isVarArg                         = CLI.IsVarArg;
2980
2981   MachineFunction &MF = DAG.getMachineFunction();
2982   bool Is64Bit        = Subtarget->is64Bit();
2983   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2984   StructReturnType SR = callIsStructReturn(Outs);
2985   bool IsSibcall      = false;
2986   X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2987   auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls");
2988
2989   if (Attr.getValueAsString() == "true")
2990     isTailCall = false;
2991
2992   if (Subtarget->isPICStyleGOT() &&
2993       !MF.getTarget().Options.GuaranteedTailCallOpt) {
2994     // If we are using a GOT, disable tail calls to external symbols with
2995     // default visibility. Tail calling such a symbol requires using a GOT
2996     // relocation, which forces early binding of the symbol. This breaks code
2997     // that require lazy function symbol resolution. Using musttail or
2998     // GuaranteedTailCallOpt will override this.
2999     GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
3000     if (!G || (!G->getGlobal()->hasLocalLinkage() &&
3001                G->getGlobal()->hasDefaultVisibility()))
3002       isTailCall = false;
3003   }
3004
3005   bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
3006   if (IsMustTail) {
3007     // Force this to be a tail call.  The verifier rules are enough to ensure
3008     // that we can lower this successfully without moving the return address
3009     // around.
3010     isTailCall = true;
3011   } else if (isTailCall) {
3012     // Check if it's really possible to do a tail call.
3013     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
3014                     isVarArg, SR != NotStructReturn,
3015                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
3016                     Outs, OutVals, Ins, DAG);
3017
3018     // Sibcalls are automatically detected tailcalls which do not require
3019     // ABI changes.
3020     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
3021       IsSibcall = true;
3022
3023     if (isTailCall)
3024       ++NumTailCalls;
3025   }
3026
3027   assert(!(isVarArg && canGuaranteeTCO(CallConv)) &&
3028          "Var args not supported with calling convention fastcc, ghc or hipe");
3029
3030   // Analyze operands of the call, assigning locations to each operand.
3031   SmallVector<CCValAssign, 16> ArgLocs;
3032   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
3033
3034   // Allocate shadow area for Win64
3035   if (IsWin64)
3036     CCInfo.AllocateStack(32, 8);
3037
3038   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3039
3040   // Get a count of how many bytes are to be pushed on the stack.
3041   unsigned NumBytes = CCInfo.getAlignedCallFrameSize();
3042   if (IsSibcall)
3043     // This is a sibcall. The memory operands are available in caller's
3044     // own caller's stack.
3045     NumBytes = 0;
3046   else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
3047            canGuaranteeTCO(CallConv))
3048     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
3049
3050   int FPDiff = 0;
3051   if (isTailCall && !IsSibcall && !IsMustTail) {
3052     // Lower arguments at fp - stackoffset + fpdiff.
3053     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
3054
3055     FPDiff = NumBytesCallerPushed - NumBytes;
3056
3057     // Set the delta of movement of the returnaddr stackslot.
3058     // But only set if delta is greater than previous delta.
3059     if (FPDiff < X86Info->getTCReturnAddrDelta())
3060       X86Info->setTCReturnAddrDelta(FPDiff);
3061   }
3062
3063   unsigned NumBytesToPush = NumBytes;
3064   unsigned NumBytesToPop = NumBytes;
3065
3066   // If we have an inalloca argument, all stack space has already been allocated
3067   // for us and be right at the top of the stack.  We don't support multiple
3068   // arguments passed in memory when using inalloca.
3069   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
3070     NumBytesToPush = 0;
3071     if (!ArgLocs.back().isMemLoc())
3072       report_fatal_error("cannot use inalloca attribute on a register "
3073                          "parameter");
3074     if (ArgLocs.back().getLocMemOffset() != 0)
3075       report_fatal_error("any parameter with the inalloca attribute must be "
3076                          "the only memory argument");
3077   }
3078
3079   if (!IsSibcall)
3080     Chain = DAG.getCALLSEQ_START(
3081         Chain, DAG.getIntPtrConstant(NumBytesToPush, dl, true), dl);
3082
3083   SDValue RetAddrFrIdx;
3084   // Load return address for tail calls.
3085   if (isTailCall && FPDiff)
3086     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
3087                                     Is64Bit, FPDiff, dl);
3088
3089   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3090   SmallVector<SDValue, 8> MemOpChains;
3091   SDValue StackPtr;
3092
3093   // Walk the register/memloc assignments, inserting copies/loads.  In the case
3094   // of tail call optimization arguments are handle later.
3095   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3096   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3097     // Skip inalloca arguments, they have already been written.
3098     ISD::ArgFlagsTy Flags = Outs[i].Flags;
3099     if (Flags.isInAlloca())
3100       continue;
3101
3102     CCValAssign &VA = ArgLocs[i];
3103     EVT RegVT = VA.getLocVT();
3104     SDValue Arg = OutVals[i];
3105     bool isByVal = Flags.isByVal();
3106
3107     // Promote the value if needed.
3108     switch (VA.getLocInfo()) {
3109     default: llvm_unreachable("Unknown loc info!");
3110     case CCValAssign::Full: break;
3111     case CCValAssign::SExt:
3112       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
3113       break;
3114     case CCValAssign::ZExt:
3115       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
3116       break;
3117     case CCValAssign::AExt:
3118       if (Arg.getValueType().isVector() &&
3119           Arg.getValueType().getVectorElementType() == MVT::i1)
3120         Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
3121       else if (RegVT.is128BitVector()) {
3122         // Special case: passing MMX values in XMM registers.
3123         Arg = DAG.getBitcast(MVT::i64, Arg);
3124         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
3125         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
3126       } else
3127         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
3128       break;
3129     case CCValAssign::BCvt:
3130       Arg = DAG.getBitcast(RegVT, Arg);
3131       break;
3132     case CCValAssign::Indirect: {
3133       // Store the argument.
3134       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
3135       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
3136       Chain = DAG.getStore(
3137           Chain, dl, Arg, SpillSlot,
3138           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3139           false, false, 0);
3140       Arg = SpillSlot;
3141       break;
3142     }
3143     }
3144
3145     if (VA.isRegLoc()) {
3146       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3147       if (isVarArg && IsWin64) {
3148         // Win64 ABI requires argument XMM reg to be copied to the corresponding
3149         // shadow reg if callee is a varargs function.
3150         unsigned ShadowReg = 0;
3151         switch (VA.getLocReg()) {
3152         case X86::XMM0: ShadowReg = X86::RCX; break;
3153         case X86::XMM1: ShadowReg = X86::RDX; break;
3154         case X86::XMM2: ShadowReg = X86::R8; break;
3155         case X86::XMM3: ShadowReg = X86::R9; break;
3156         }
3157         if (ShadowReg)
3158           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
3159       }
3160     } else if (!IsSibcall && (!isTailCall || isByVal)) {
3161       assert(VA.isMemLoc());
3162       if (!StackPtr.getNode())
3163         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3164                                       getPointerTy(DAG.getDataLayout()));
3165       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
3166                                              dl, DAG, VA, Flags));
3167     }
3168   }
3169
3170   if (!MemOpChains.empty())
3171     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
3172
3173   if (Subtarget->isPICStyleGOT()) {
3174     // ELF / PIC requires GOT in the EBX register before function calls via PLT
3175     // GOT pointer.
3176     if (!isTailCall) {
3177       RegsToPass.push_back(std::make_pair(
3178           unsigned(X86::EBX), DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
3179                                           getPointerTy(DAG.getDataLayout()))));
3180     } else {
3181       // If we are tail calling and generating PIC/GOT style code load the
3182       // address of the callee into ECX. The value in ecx is used as target of
3183       // the tail jump. This is done to circumvent the ebx/callee-saved problem
3184       // for tail calls on PIC/GOT architectures. Normally we would just put the
3185       // address of GOT into ebx and then call target@PLT. But for tail calls
3186       // ebx would be restored (since ebx is callee saved) before jumping to the
3187       // target@PLT.
3188
3189       // Note: The actual moving to ECX is done further down.
3190       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
3191       if (G && !G->getGlobal()->hasLocalLinkage() &&
3192           G->getGlobal()->hasDefaultVisibility())
3193         Callee = LowerGlobalAddress(Callee, DAG);
3194       else if (isa<ExternalSymbolSDNode>(Callee))
3195         Callee = LowerExternalSymbol(Callee, DAG);
3196     }
3197   }
3198
3199   if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail) {
3200     // From AMD64 ABI document:
3201     // For calls that may call functions that use varargs or stdargs
3202     // (prototype-less calls or calls to functions containing ellipsis (...) in
3203     // the declaration) %al is used as hidden argument to specify the number
3204     // of SSE registers used. The contents of %al do not need to match exactly
3205     // the number of registers, but must be an ubound on the number of SSE
3206     // registers used and is in the range 0 - 8 inclusive.
3207
3208     // Count the number of XMM registers allocated.
3209     static const MCPhysReg XMMArgRegs[] = {
3210       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3211       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
3212     };
3213     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
3214     assert((Subtarget->hasSSE1() || !NumXMMRegs)
3215            && "SSE registers cannot be used when SSE is disabled");
3216
3217     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
3218                                         DAG.getConstant(NumXMMRegs, dl,
3219                                                         MVT::i8)));
3220   }
3221
3222   if (isVarArg && IsMustTail) {
3223     const auto &Forwards = X86Info->getForwardedMustTailRegParms();
3224     for (const auto &F : Forwards) {
3225       SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
3226       RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
3227     }
3228   }
3229
3230   // For tail calls lower the arguments to the 'real' stack slots.  Sibcalls
3231   // don't need this because the eligibility check rejects calls that require
3232   // shuffling arguments passed in memory.
3233   if (!IsSibcall && isTailCall) {
3234     // Force all the incoming stack arguments to be loaded from the stack
3235     // before any new outgoing arguments are stored to the stack, because the
3236     // outgoing stack slots may alias the incoming argument stack slots, and
3237     // the alias isn't otherwise explicit. This is slightly more conservative
3238     // than necessary, because it means that each store effectively depends
3239     // on every argument instead of just those arguments it would clobber.
3240     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
3241
3242     SmallVector<SDValue, 8> MemOpChains2;
3243     SDValue FIN;
3244     int FI = 0;
3245     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3246       CCValAssign &VA = ArgLocs[i];
3247       if (VA.isRegLoc())
3248         continue;
3249       assert(VA.isMemLoc());
3250       SDValue Arg = OutVals[i];
3251       ISD::ArgFlagsTy Flags = Outs[i].Flags;
3252       // Skip inalloca arguments.  They don't require any work.
3253       if (Flags.isInAlloca())
3254         continue;
3255       // Create frame index.
3256       int32_t Offset = VA.getLocMemOffset()+FPDiff;
3257       uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
3258       FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3259       FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3260
3261       if (Flags.isByVal()) {
3262         // Copy relative to framepointer.
3263         SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset(), dl);
3264         if (!StackPtr.getNode())
3265           StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3266                                         getPointerTy(DAG.getDataLayout()));
3267         Source = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
3268                              StackPtr, Source);
3269
3270         MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
3271                                                          ArgChain,
3272                                                          Flags, DAG, dl));
3273       } else {
3274         // Store relative to framepointer.
3275         MemOpChains2.push_back(DAG.getStore(
3276             ArgChain, dl, Arg, FIN,
3277             MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3278             false, false, 0));
3279       }
3280     }
3281
3282     if (!MemOpChains2.empty())
3283       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3284
3285     // Store the return address to the appropriate stack slot.
3286     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
3287                                      getPointerTy(DAG.getDataLayout()),
3288                                      RegInfo->getSlotSize(), FPDiff, dl);
3289   }
3290
3291   // Build a sequence of copy-to-reg nodes chained together with token chain
3292   // and flag operands which copy the outgoing args into registers.
3293   SDValue InFlag;
3294   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3295     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3296                              RegsToPass[i].second, InFlag);
3297     InFlag = Chain.getValue(1);
3298   }
3299
3300   if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
3301     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
3302     // In the 64-bit large code model, we have to make all calls
3303     // through a register, since the call instruction's 32-bit
3304     // pc-relative offset may not be large enough to hold the whole
3305     // address.
3306   } else if (Callee->getOpcode() == ISD::GlobalAddress) {
3307     // If the callee is a GlobalAddress node (quite common, every direct call
3308     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
3309     // it.
3310     GlobalAddressSDNode* G = cast<GlobalAddressSDNode>(Callee);
3311
3312     // We should use extra load for direct calls to dllimported functions in
3313     // non-JIT mode.
3314     const GlobalValue *GV = G->getGlobal();
3315     if (!GV->hasDLLImportStorageClass()) {
3316       unsigned char OpFlags = 0;
3317       bool ExtraLoad = false;
3318       unsigned WrapperKind = ISD::DELETED_NODE;
3319
3320       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
3321       // external symbols most go through the PLT in PIC mode.  If the symbol
3322       // has hidden or protected visibility, or if it is static or local, then
3323       // we don't need to use the PLT - we can directly call it.
3324       if (Subtarget->isTargetELF() &&
3325           DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
3326           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
3327         OpFlags = X86II::MO_PLT;
3328       } else if (Subtarget->isPICStyleStubAny() &&
3329                  !GV->isStrongDefinitionForLinker() &&
3330                  (!Subtarget->getTargetTriple().isMacOSX() ||
3331                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3332         // PC-relative references to external symbols should go through $stub,
3333         // unless we're building with the leopard linker or later, which
3334         // automatically synthesizes these stubs.
3335         OpFlags = X86II::MO_DARWIN_STUB;
3336       } else if (Subtarget->isPICStyleRIPRel() && isa<Function>(GV) &&
3337                  cast<Function>(GV)->hasFnAttribute(Attribute::NonLazyBind)) {
3338         // If the function is marked as non-lazy, generate an indirect call
3339         // which loads from the GOT directly. This avoids runtime overhead
3340         // at the cost of eager binding (and one extra byte of encoding).
3341         OpFlags = X86II::MO_GOTPCREL;
3342         WrapperKind = X86ISD::WrapperRIP;
3343         ExtraLoad = true;
3344       }
3345
3346       Callee = DAG.getTargetGlobalAddress(
3347           GV, dl, getPointerTy(DAG.getDataLayout()), G->getOffset(), OpFlags);
3348
3349       // Add a wrapper if needed.
3350       if (WrapperKind != ISD::DELETED_NODE)
3351         Callee = DAG.getNode(X86ISD::WrapperRIP, dl,
3352                              getPointerTy(DAG.getDataLayout()), Callee);
3353       // Add extra indirection if needed.
3354       if (ExtraLoad)
3355         Callee = DAG.getLoad(
3356             getPointerTy(DAG.getDataLayout()), dl, DAG.getEntryNode(), Callee,
3357             MachinePointerInfo::getGOT(DAG.getMachineFunction()), false, false,
3358             false, 0);
3359     }
3360   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3361     unsigned char OpFlags = 0;
3362
3363     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
3364     // external symbols should go through the PLT.
3365     if (Subtarget->isTargetELF() &&
3366         DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
3367       OpFlags = X86II::MO_PLT;
3368     } else if (Subtarget->isPICStyleStubAny() &&
3369                (!Subtarget->getTargetTriple().isMacOSX() ||
3370                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3371       // PC-relative references to external symbols should go through $stub,
3372       // unless we're building with the leopard linker or later, which
3373       // automatically synthesizes these stubs.
3374       OpFlags = X86II::MO_DARWIN_STUB;
3375     }
3376
3377     Callee = DAG.getTargetExternalSymbol(
3378         S->getSymbol(), getPointerTy(DAG.getDataLayout()), OpFlags);
3379   } else if (Subtarget->isTarget64BitILP32() &&
3380              Callee->getValueType(0) == MVT::i32) {
3381     // Zero-extend the 32-bit Callee address into a 64-bit according to x32 ABI
3382     Callee = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Callee);
3383   }
3384
3385   // Returns a chain & a flag for retval copy to use.
3386   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3387   SmallVector<SDValue, 8> Ops;
3388
3389   if (!IsSibcall && isTailCall) {
3390     Chain = DAG.getCALLSEQ_END(Chain,
3391                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3392                                DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
3393     InFlag = Chain.getValue(1);
3394   }
3395
3396   Ops.push_back(Chain);
3397   Ops.push_back(Callee);
3398
3399   if (isTailCall)
3400     Ops.push_back(DAG.getConstant(FPDiff, dl, MVT::i32));
3401
3402   // Add argument registers to the end of the list so that they are known live
3403   // into the call.
3404   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3405     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3406                                   RegsToPass[i].second.getValueType()));
3407
3408   // Add a register mask operand representing the call-preserved registers.
3409   const uint32_t *Mask = RegInfo->getCallPreservedMask(MF, CallConv);
3410   assert(Mask && "Missing call preserved mask for calling convention");
3411
3412   // If this is an invoke in a 32-bit function using a funclet-based
3413   // personality, assume the function clobbers all registers. If an exception
3414   // is thrown, the runtime will not restore CSRs.
3415   // FIXME: Model this more precisely so that we can register allocate across
3416   // the normal edge and spill and fill across the exceptional edge.
3417   if (!Is64Bit && CLI.CS && CLI.CS->isInvoke()) {
3418     const Function *CallerFn = MF.getFunction();
3419     EHPersonality Pers =
3420         CallerFn->hasPersonalityFn()
3421             ? classifyEHPersonality(CallerFn->getPersonalityFn())
3422             : EHPersonality::Unknown;
3423     if (isFuncletEHPersonality(Pers))
3424       Mask = RegInfo->getNoPreservedMask();
3425   }
3426
3427   Ops.push_back(DAG.getRegisterMask(Mask));
3428
3429   if (InFlag.getNode())
3430     Ops.push_back(InFlag);
3431
3432   if (isTailCall) {
3433     // We used to do:
3434     //// If this is the first return lowered for this function, add the regs
3435     //// to the liveout set for the function.
3436     // This isn't right, although it's probably harmless on x86; liveouts
3437     // should be computed from returns not tail calls.  Consider a void
3438     // function making a tail call to a function returning int.
3439     MF.getFrameInfo()->setHasTailCall();
3440     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3441   }
3442
3443   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3444   InFlag = Chain.getValue(1);
3445
3446   // Create the CALLSEQ_END node.
3447   unsigned NumBytesForCalleeToPop;
3448   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3449                        DAG.getTarget().Options.GuaranteedTailCallOpt))
3450     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
3451   else if (!Is64Bit && !canGuaranteeTCO(CallConv) &&
3452            !Subtarget->getTargetTriple().isOSMSVCRT() &&
3453            SR == StackStructReturn)
3454     // If this is a call to a struct-return function, the callee
3455     // pops the hidden struct pointer, so we have to push it back.
3456     // This is common for Darwin/X86, Linux & Mingw32 targets.
3457     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3458     NumBytesForCalleeToPop = 4;
3459   else
3460     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
3461
3462   // Returns a flag for retval copy to use.
3463   if (!IsSibcall) {
3464     Chain = DAG.getCALLSEQ_END(Chain,
3465                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3466                                DAG.getIntPtrConstant(NumBytesForCalleeToPop, dl,
3467                                                      true),
3468                                InFlag, dl);
3469     InFlag = Chain.getValue(1);
3470   }
3471
3472   // Handle result values, copying them out of physregs into vregs that we
3473   // return.
3474   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3475                          Ins, dl, DAG, InVals);
3476 }
3477
3478 //===----------------------------------------------------------------------===//
3479 //                Fast Calling Convention (tail call) implementation
3480 //===----------------------------------------------------------------------===//
3481
3482 //  Like std call, callee cleans arguments, convention except that ECX is
3483 //  reserved for storing the tail called function address. Only 2 registers are
3484 //  free for argument passing (inreg). Tail call optimization is performed
3485 //  provided:
3486 //                * tailcallopt is enabled
3487 //                * caller/callee are fastcc
3488 //  On X86_64 architecture with GOT-style position independent code only local
3489 //  (within module) calls are supported at the moment.
3490 //  To keep the stack aligned according to platform abi the function
3491 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
3492 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3493 //  If a tail called function callee has more arguments than the caller the
3494 //  caller needs to make sure that there is room to move the RETADDR to. This is
3495 //  achieved by reserving an area the size of the argument delta right after the
3496 //  original RETADDR, but before the saved framepointer or the spilled registers
3497 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3498 //  stack layout:
3499 //    arg1
3500 //    arg2
3501 //    RETADDR
3502 //    [ new RETADDR
3503 //      move area ]
3504 //    (possible EBP)
3505 //    ESI
3506 //    EDI
3507 //    local1 ..
3508
3509 /// Make the stack size align e.g 16n + 12 aligned for a 16-byte align
3510 /// requirement.
3511 unsigned
3512 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3513                                                SelectionDAG& DAG) const {
3514   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3515   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
3516   unsigned StackAlignment = TFI.getStackAlignment();
3517   uint64_t AlignMask = StackAlignment - 1;
3518   int64_t Offset = StackSize;
3519   unsigned SlotSize = RegInfo->getSlotSize();
3520   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3521     // Number smaller than 12 so just add the difference.
3522     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3523   } else {
3524     // Mask out lower bits, add stackalignment once plus the 12 bytes.
3525     Offset = ((~AlignMask) & Offset) + StackAlignment +
3526       (StackAlignment-SlotSize);
3527   }
3528   return Offset;
3529 }
3530
3531 /// Return true if the given stack call argument is already available in the
3532 /// same position (relatively) of the caller's incoming argument stack.
3533 static
3534 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3535                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3536                          const X86InstrInfo *TII) {
3537   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3538   int FI = INT_MAX;
3539   if (Arg.getOpcode() == ISD::CopyFromReg) {
3540     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3541     if (!TargetRegisterInfo::isVirtualRegister(VR))
3542       return false;
3543     MachineInstr *Def = MRI->getVRegDef(VR);
3544     if (!Def)
3545       return false;
3546     if (!Flags.isByVal()) {
3547       if (!TII->isLoadFromStackSlot(Def, FI))
3548         return false;
3549     } else {
3550       unsigned Opcode = Def->getOpcode();
3551       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r ||
3552            Opcode == X86::LEA64_32r) &&
3553           Def->getOperand(1).isFI()) {
3554         FI = Def->getOperand(1).getIndex();
3555         Bytes = Flags.getByValSize();
3556       } else
3557         return false;
3558     }
3559   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3560     if (Flags.isByVal())
3561       // ByVal argument is passed in as a pointer but it's now being
3562       // dereferenced. e.g.
3563       // define @foo(%struct.X* %A) {
3564       //   tail call @bar(%struct.X* byval %A)
3565       // }
3566       return false;
3567     SDValue Ptr = Ld->getBasePtr();
3568     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3569     if (!FINode)
3570       return false;
3571     FI = FINode->getIndex();
3572   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3573     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3574     FI = FINode->getIndex();
3575     Bytes = Flags.getByValSize();
3576   } else
3577     return false;
3578
3579   assert(FI != INT_MAX);
3580   if (!MFI->isFixedObjectIndex(FI))
3581     return false;
3582   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3583 }
3584
3585 /// Check whether the call is eligible for tail call optimization. Targets
3586 /// that want to do tail call optimization should implement this function.
3587 bool X86TargetLowering::IsEligibleForTailCallOptimization(
3588     SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
3589     bool isCalleeStructRet, bool isCallerStructRet, Type *RetTy,
3590     const SmallVectorImpl<ISD::OutputArg> &Outs,
3591     const SmallVectorImpl<SDValue> &OutVals,
3592     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
3593   if (!mayTailCallThisCC(CalleeCC))
3594     return false;
3595
3596   // If -tailcallopt is specified, make fastcc functions tail-callable.
3597   MachineFunction &MF = DAG.getMachineFunction();
3598   const Function *CallerF = MF.getFunction();
3599
3600   // If the function return type is x86_fp80 and the callee return type is not,
3601   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3602   // perform a tailcall optimization here.
3603   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3604     return false;
3605
3606   CallingConv::ID CallerCC = CallerF->getCallingConv();
3607   bool CCMatch = CallerCC == CalleeCC;
3608   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3609   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3610
3611   // Win64 functions have extra shadow space for argument homing. Don't do the
3612   // sibcall if the caller and callee have mismatched expectations for this
3613   // space.
3614   if (IsCalleeWin64 != IsCallerWin64)
3615     return false;
3616
3617   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3618     if (canGuaranteeTCO(CalleeCC) && CCMatch)
3619       return true;
3620     return false;
3621   }
3622
3623   // Look for obvious safe cases to perform tail call optimization that do not
3624   // require ABI changes. This is what gcc calls sibcall.
3625
3626   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3627   // emit a special epilogue.
3628   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3629   if (RegInfo->needsStackRealignment(MF))
3630     return false;
3631
3632   // Also avoid sibcall optimization if either caller or callee uses struct
3633   // return semantics.
3634   if (isCalleeStructRet || isCallerStructRet)
3635     return false;
3636
3637   // Do not sibcall optimize vararg calls unless all arguments are passed via
3638   // registers.
3639   if (isVarArg && !Outs.empty()) {
3640     // Optimizing for varargs on Win64 is unlikely to be safe without
3641     // additional testing.
3642     if (IsCalleeWin64 || IsCallerWin64)
3643       return false;
3644
3645     SmallVector<CCValAssign, 16> ArgLocs;
3646     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3647                    *DAG.getContext());
3648
3649     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3650     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3651       if (!ArgLocs[i].isRegLoc())
3652         return false;
3653   }
3654
3655   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3656   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3657   // this into a sibcall.
3658   bool Unused = false;
3659   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3660     if (!Ins[i].Used) {
3661       Unused = true;
3662       break;
3663     }
3664   }
3665   if (Unused) {
3666     SmallVector<CCValAssign, 16> RVLocs;
3667     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), RVLocs,
3668                    *DAG.getContext());
3669     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3670     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3671       CCValAssign &VA = RVLocs[i];
3672       if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3673         return false;
3674     }
3675   }
3676
3677   // If the calling conventions do not match, then we'd better make sure the
3678   // results are returned in the same way as what the caller expects.
3679   if (!CCMatch) {
3680     SmallVector<CCValAssign, 16> RVLocs1;
3681     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
3682                     *DAG.getContext());
3683     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3684
3685     SmallVector<CCValAssign, 16> RVLocs2;
3686     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
3687                     *DAG.getContext());
3688     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3689
3690     if (RVLocs1.size() != RVLocs2.size())
3691       return false;
3692     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3693       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3694         return false;
3695       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3696         return false;
3697       if (RVLocs1[i].isRegLoc()) {
3698         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3699           return false;
3700       } else {
3701         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3702           return false;
3703       }
3704     }
3705   }
3706
3707   unsigned StackArgsSize = 0;
3708
3709   // If the callee takes no arguments then go on to check the results of the
3710   // call.
3711   if (!Outs.empty()) {
3712     // Check if stack adjustment is needed. For now, do not do this if any
3713     // argument is passed on the stack.
3714     SmallVector<CCValAssign, 16> ArgLocs;
3715     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3716                    *DAG.getContext());
3717
3718     // Allocate shadow area for Win64
3719     if (IsCalleeWin64)
3720       CCInfo.AllocateStack(32, 8);
3721
3722     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3723     StackArgsSize = CCInfo.getNextStackOffset();
3724
3725     if (CCInfo.getNextStackOffset()) {
3726       // Check if the arguments are already laid out in the right way as
3727       // the caller's fixed stack objects.
3728       MachineFrameInfo *MFI = MF.getFrameInfo();
3729       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3730       const X86InstrInfo *TII = Subtarget->getInstrInfo();
3731       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3732         CCValAssign &VA = ArgLocs[i];
3733         SDValue Arg = OutVals[i];
3734         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3735         if (VA.getLocInfo() == CCValAssign::Indirect)
3736           return false;
3737         if (!VA.isRegLoc()) {
3738           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3739                                    MFI, MRI, TII))
3740             return false;
3741         }
3742       }
3743     }
3744
3745     // If the tailcall address may be in a register, then make sure it's
3746     // possible to register allocate for it. In 32-bit, the call address can
3747     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3748     // callee-saved registers are restored. These happen to be the same
3749     // registers used to pass 'inreg' arguments so watch out for those.
3750     if (!Subtarget->is64Bit() &&
3751         ((!isa<GlobalAddressSDNode>(Callee) &&
3752           !isa<ExternalSymbolSDNode>(Callee)) ||
3753          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3754       unsigned NumInRegs = 0;
3755       // In PIC we need an extra register to formulate the address computation
3756       // for the callee.
3757       unsigned MaxInRegs =
3758         (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3759
3760       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3761         CCValAssign &VA = ArgLocs[i];
3762         if (!VA.isRegLoc())
3763           continue;
3764         unsigned Reg = VA.getLocReg();
3765         switch (Reg) {
3766         default: break;
3767         case X86::EAX: case X86::EDX: case X86::ECX:
3768           if (++NumInRegs == MaxInRegs)
3769             return false;
3770           break;
3771         }
3772       }
3773     }
3774   }
3775
3776   bool CalleeWillPop =
3777       X86::isCalleePop(CalleeCC, Subtarget->is64Bit(), isVarArg,
3778                        MF.getTarget().Options.GuaranteedTailCallOpt);
3779
3780   if (unsigned BytesToPop =
3781           MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn()) {
3782     // If we have bytes to pop, the callee must pop them.
3783     bool CalleePopMatches = CalleeWillPop && BytesToPop == StackArgsSize;
3784     if (!CalleePopMatches)
3785       return false;
3786   } else if (CalleeWillPop && StackArgsSize > 0) {
3787     // If we don't have bytes to pop, make sure the callee doesn't pop any.
3788     return false;
3789   }
3790
3791   return true;
3792 }
3793
3794 FastISel *
3795 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3796                                   const TargetLibraryInfo *libInfo) const {
3797   return X86::createFastISel(funcInfo, libInfo);
3798 }
3799
3800 //===----------------------------------------------------------------------===//
3801 //                           Other Lowering Hooks
3802 //===----------------------------------------------------------------------===//
3803
3804 static bool MayFoldLoad(SDValue Op) {
3805   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3806 }
3807
3808 static bool MayFoldIntoStore(SDValue Op) {
3809   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3810 }
3811
3812 static bool isTargetShuffle(unsigned Opcode) {
3813   switch(Opcode) {
3814   default: return false;
3815   case X86ISD::BLENDI:
3816   case X86ISD::PSHUFB:
3817   case X86ISD::PSHUFD:
3818   case X86ISD::PSHUFHW:
3819   case X86ISD::PSHUFLW:
3820   case X86ISD::SHUFP:
3821   case X86ISD::PALIGNR:
3822   case X86ISD::MOVLHPS:
3823   case X86ISD::MOVLHPD:
3824   case X86ISD::MOVHLPS:
3825   case X86ISD::MOVLPS:
3826   case X86ISD::MOVLPD:
3827   case X86ISD::MOVSHDUP:
3828   case X86ISD::MOVSLDUP:
3829   case X86ISD::MOVDDUP:
3830   case X86ISD::MOVSS:
3831   case X86ISD::MOVSD:
3832   case X86ISD::UNPCKL:
3833   case X86ISD::UNPCKH:
3834   case X86ISD::VPERMILPI:
3835   case X86ISD::VPERM2X128:
3836   case X86ISD::VPERMI:
3837   case X86ISD::VPERMV:
3838   case X86ISD::VPERMV3:
3839     return true;
3840   }
3841 }
3842
3843 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, MVT VT,
3844                                     SDValue V1, unsigned TargetMask,
3845                                     SelectionDAG &DAG) {
3846   switch(Opc) {
3847   default: llvm_unreachable("Unknown x86 shuffle node");
3848   case X86ISD::PSHUFD:
3849   case X86ISD::PSHUFHW:
3850   case X86ISD::PSHUFLW:
3851   case X86ISD::VPERMILPI:
3852   case X86ISD::VPERMI:
3853     return DAG.getNode(Opc, dl, VT, V1,
3854                        DAG.getConstant(TargetMask, dl, MVT::i8));
3855   }
3856 }
3857
3858 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, MVT VT,
3859                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3860   switch(Opc) {
3861   default: llvm_unreachable("Unknown x86 shuffle node");
3862   case X86ISD::MOVLHPS:
3863   case X86ISD::MOVLHPD:
3864   case X86ISD::MOVHLPS:
3865   case X86ISD::MOVLPS:
3866   case X86ISD::MOVLPD:
3867   case X86ISD::MOVSS:
3868   case X86ISD::MOVSD:
3869   case X86ISD::UNPCKL:
3870   case X86ISD::UNPCKH:
3871     return DAG.getNode(Opc, dl, VT, V1, V2);
3872   }
3873 }
3874
3875 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3876   MachineFunction &MF = DAG.getMachineFunction();
3877   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3878   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3879   int ReturnAddrIndex = FuncInfo->getRAIndex();
3880
3881   if (ReturnAddrIndex == 0) {
3882     // Set up a frame object for the return address.
3883     unsigned SlotSize = RegInfo->getSlotSize();
3884     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3885                                                            -(int64_t)SlotSize,
3886                                                            false);
3887     FuncInfo->setRAIndex(ReturnAddrIndex);
3888   }
3889
3890   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy(DAG.getDataLayout()));
3891 }
3892
3893 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3894                                        bool hasSymbolicDisplacement) {
3895   // Offset should fit into 32 bit immediate field.
3896   if (!isInt<32>(Offset))
3897     return false;
3898
3899   // If we don't have a symbolic displacement - we don't have any extra
3900   // restrictions.
3901   if (!hasSymbolicDisplacement)
3902     return true;
3903
3904   // FIXME: Some tweaks might be needed for medium code model.
3905   if (M != CodeModel::Small && M != CodeModel::Kernel)
3906     return false;
3907
3908   // For small code model we assume that latest object is 16MB before end of 31
3909   // bits boundary. We may also accept pretty large negative constants knowing
3910   // that all objects are in the positive half of address space.
3911   if (M == CodeModel::Small && Offset < 16*1024*1024)
3912     return true;
3913
3914   // For kernel code model we know that all object resist in the negative half
3915   // of 32bits address space. We may not accept negative offsets, since they may
3916   // be just off and we may accept pretty large positive ones.
3917   if (M == CodeModel::Kernel && Offset >= 0)
3918     return true;
3919
3920   return false;
3921 }
3922
3923 /// Determines whether the callee is required to pop its own arguments.
3924 /// Callee pop is necessary to support tail calls.
3925 bool X86::isCalleePop(CallingConv::ID CallingConv,
3926                       bool is64Bit, bool IsVarArg, bool GuaranteeTCO) {
3927   // If GuaranteeTCO is true, we force some calls to be callee pop so that we
3928   // can guarantee TCO.
3929   if (!IsVarArg && shouldGuaranteeTCO(CallingConv, GuaranteeTCO))
3930     return true;
3931
3932   switch (CallingConv) {
3933   default:
3934     return false;
3935   case CallingConv::X86_StdCall:
3936   case CallingConv::X86_FastCall:
3937   case CallingConv::X86_ThisCall:
3938   case CallingConv::X86_VectorCall:
3939     return !is64Bit;
3940   }
3941 }
3942
3943 /// \brief Return true if the condition is an unsigned comparison operation.
3944 static bool isX86CCUnsigned(unsigned X86CC) {
3945   switch (X86CC) {
3946   default: llvm_unreachable("Invalid integer condition!");
3947   case X86::COND_E:     return true;
3948   case X86::COND_G:     return false;
3949   case X86::COND_GE:    return false;
3950   case X86::COND_L:     return false;
3951   case X86::COND_LE:    return false;
3952   case X86::COND_NE:    return true;
3953   case X86::COND_B:     return true;
3954   case X86::COND_A:     return true;
3955   case X86::COND_BE:    return true;
3956   case X86::COND_AE:    return true;
3957   }
3958 }
3959
3960 /// Do a one-to-one translation of a ISD::CondCode to the X86-specific
3961 /// condition code, returning the condition code and the LHS/RHS of the
3962 /// comparison to make.
3963 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, SDLoc DL, bool isFP,
3964                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3965   if (!isFP) {
3966     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3967       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3968         // X > -1   -> X == 0, jump !sign.
3969         RHS = DAG.getConstant(0, DL, RHS.getValueType());
3970         return X86::COND_NS;
3971       }
3972       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3973         // X < 0   -> X == 0, jump on sign.
3974         return X86::COND_S;
3975       }
3976       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3977         // X < 1   -> X <= 0
3978         RHS = DAG.getConstant(0, DL, RHS.getValueType());
3979         return X86::COND_LE;
3980       }
3981     }
3982
3983     switch (SetCCOpcode) {
3984     default: llvm_unreachable("Invalid integer condition!");
3985     case ISD::SETEQ:  return X86::COND_E;
3986     case ISD::SETGT:  return X86::COND_G;
3987     case ISD::SETGE:  return X86::COND_GE;
3988     case ISD::SETLT:  return X86::COND_L;
3989     case ISD::SETLE:  return X86::COND_LE;
3990     case ISD::SETNE:  return X86::COND_NE;
3991     case ISD::SETULT: return X86::COND_B;
3992     case ISD::SETUGT: return X86::COND_A;
3993     case ISD::SETULE: return X86::COND_BE;
3994     case ISD::SETUGE: return X86::COND_AE;
3995     }
3996   }
3997
3998   // First determine if it is required or is profitable to flip the operands.
3999
4000   // If LHS is a foldable load, but RHS is not, flip the condition.
4001   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
4002       !ISD::isNON_EXTLoad(RHS.getNode())) {
4003     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
4004     std::swap(LHS, RHS);
4005   }
4006
4007   switch (SetCCOpcode) {
4008   default: break;
4009   case ISD::SETOLT:
4010   case ISD::SETOLE:
4011   case ISD::SETUGT:
4012   case ISD::SETUGE:
4013     std::swap(LHS, RHS);
4014     break;
4015   }
4016
4017   // On a floating point condition, the flags are set as follows:
4018   // ZF  PF  CF   op
4019   //  0 | 0 | 0 | X > Y
4020   //  0 | 0 | 1 | X < Y
4021   //  1 | 0 | 0 | X == Y
4022   //  1 | 1 | 1 | unordered
4023   switch (SetCCOpcode) {
4024   default: llvm_unreachable("Condcode should be pre-legalized away");
4025   case ISD::SETUEQ:
4026   case ISD::SETEQ:   return X86::COND_E;
4027   case ISD::SETOLT:              // flipped
4028   case ISD::SETOGT:
4029   case ISD::SETGT:   return X86::COND_A;
4030   case ISD::SETOLE:              // flipped
4031   case ISD::SETOGE:
4032   case ISD::SETGE:   return X86::COND_AE;
4033   case ISD::SETUGT:              // flipped
4034   case ISD::SETULT:
4035   case ISD::SETLT:   return X86::COND_B;
4036   case ISD::SETUGE:              // flipped
4037   case ISD::SETULE:
4038   case ISD::SETLE:   return X86::COND_BE;
4039   case ISD::SETONE:
4040   case ISD::SETNE:   return X86::COND_NE;
4041   case ISD::SETUO:   return X86::COND_P;
4042   case ISD::SETO:    return X86::COND_NP;
4043   case ISD::SETOEQ:
4044   case ISD::SETUNE:  return X86::COND_INVALID;
4045   }
4046 }
4047
4048 /// Is there a floating point cmov for the specific X86 condition code?
4049 /// Current x86 isa includes the following FP cmov instructions:
4050 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
4051 static bool hasFPCMov(unsigned X86CC) {
4052   switch (X86CC) {
4053   default:
4054     return false;
4055   case X86::COND_B:
4056   case X86::COND_BE:
4057   case X86::COND_E:
4058   case X86::COND_P:
4059   case X86::COND_A:
4060   case X86::COND_AE:
4061   case X86::COND_NE:
4062   case X86::COND_NP:
4063     return true;
4064   }
4065 }
4066
4067 /// Returns true if the target can instruction select the
4068 /// specified FP immediate natively. If false, the legalizer will
4069 /// materialize the FP immediate as a load from a constant pool.
4070 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
4071   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
4072     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
4073       return true;
4074   }
4075   return false;
4076 }
4077
4078 bool X86TargetLowering::shouldReduceLoadWidth(SDNode *Load,
4079                                               ISD::LoadExtType ExtTy,
4080                                               EVT NewVT) const {
4081   // "ELF Handling for Thread-Local Storage" specifies that R_X86_64_GOTTPOFF
4082   // relocation target a movq or addq instruction: don't let the load shrink.
4083   SDValue BasePtr = cast<LoadSDNode>(Load)->getBasePtr();
4084   if (BasePtr.getOpcode() == X86ISD::WrapperRIP)
4085     if (const auto *GA = dyn_cast<GlobalAddressSDNode>(BasePtr.getOperand(0)))
4086       return GA->getTargetFlags() != X86II::MO_GOTTPOFF;
4087   return true;
4088 }
4089
4090 /// \brief Returns true if it is beneficial to convert a load of a constant
4091 /// to just the constant itself.
4092 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
4093                                                           Type *Ty) const {
4094   assert(Ty->isIntegerTy());
4095
4096   unsigned BitSize = Ty->getPrimitiveSizeInBits();
4097   if (BitSize == 0 || BitSize > 64)
4098     return false;
4099   return true;
4100 }
4101
4102 bool X86TargetLowering::isExtractSubvectorCheap(EVT ResVT,
4103                                                 unsigned Index) const {
4104   if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
4105     return false;
4106
4107   return (Index == 0 || Index == ResVT.getVectorNumElements());
4108 }
4109
4110 bool X86TargetLowering::isCheapToSpeculateCttz() const {
4111   // Speculate cttz only if we can directly use TZCNT.
4112   return Subtarget->hasBMI();
4113 }
4114
4115 bool X86TargetLowering::isCheapToSpeculateCtlz() const {
4116   // Speculate ctlz only if we can directly use LZCNT.
4117   return Subtarget->hasLZCNT();
4118 }
4119
4120 /// Return true if every element in Mask, beginning
4121 /// from position Pos and ending in Pos+Size is undef.
4122 static bool isUndefInRange(ArrayRef<int> Mask, unsigned Pos, unsigned Size) {
4123   for (unsigned i = Pos, e = Pos + Size; i != e; ++i)
4124     if (0 <= Mask[i])
4125       return false;
4126   return true;
4127 }
4128
4129 /// Return true if Val is undef or if its value falls within the
4130 /// specified range (L, H].
4131 static bool isUndefOrInRange(int Val, int Low, int Hi) {
4132   return (Val < 0) || (Val >= Low && Val < Hi);
4133 }
4134
4135 /// Val is either less than zero (undef) or equal to the specified value.
4136 static bool isUndefOrEqual(int Val, int CmpVal) {
4137   return (Val < 0 || Val == CmpVal);
4138 }
4139
4140 /// Return true if every element in Mask, beginning
4141 /// from position Pos and ending in Pos+Size, falls within the specified
4142 /// sequential range (Low, Low+Size]. or is undef.
4143 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
4144                                        unsigned Pos, unsigned Size, int Low) {
4145   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
4146     if (!isUndefOrEqual(Mask[i], Low))
4147       return false;
4148   return true;
4149 }
4150
4151 /// Return true if the specified EXTRACT_SUBVECTOR operand specifies a vector
4152 /// extract that is suitable for instruction that extract 128 or 256 bit vectors
4153 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4154   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4155   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4156     return false;
4157
4158   // The index should be aligned on a vecWidth-bit boundary.
4159   uint64_t Index =
4160     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4161
4162   MVT VT = N->getSimpleValueType(0);
4163   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4164   bool Result = (Index * ElSize) % vecWidth == 0;
4165
4166   return Result;
4167 }
4168
4169 /// Return true if the specified INSERT_SUBVECTOR
4170 /// operand specifies a subvector insert that is suitable for input to
4171 /// insertion of 128 or 256-bit subvectors
4172 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4173   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4174   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4175     return false;
4176   // The index should be aligned on a vecWidth-bit boundary.
4177   uint64_t Index =
4178     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4179
4180   MVT VT = N->getSimpleValueType(0);
4181   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4182   bool Result = (Index * ElSize) % vecWidth == 0;
4183
4184   return Result;
4185 }
4186
4187 bool X86::isVINSERT128Index(SDNode *N) {
4188   return isVINSERTIndex(N, 128);
4189 }
4190
4191 bool X86::isVINSERT256Index(SDNode *N) {
4192   return isVINSERTIndex(N, 256);
4193 }
4194
4195 bool X86::isVEXTRACT128Index(SDNode *N) {
4196   return isVEXTRACTIndex(N, 128);
4197 }
4198
4199 bool X86::isVEXTRACT256Index(SDNode *N) {
4200   return isVEXTRACTIndex(N, 256);
4201 }
4202
4203 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4204   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4205   assert(isa<ConstantSDNode>(N->getOperand(1).getNode()) &&
4206          "Illegal extract subvector for VEXTRACT");
4207
4208   uint64_t Index =
4209     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4210
4211   MVT VecVT = N->getOperand(0).getSimpleValueType();
4212   MVT ElVT = VecVT.getVectorElementType();
4213
4214   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4215   return Index / NumElemsPerChunk;
4216 }
4217
4218 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4219   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4220   assert(isa<ConstantSDNode>(N->getOperand(2).getNode()) &&
4221          "Illegal insert subvector for VINSERT");
4222
4223   uint64_t Index =
4224     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4225
4226   MVT VecVT = N->getSimpleValueType(0);
4227   MVT ElVT = VecVT.getVectorElementType();
4228
4229   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4230   return Index / NumElemsPerChunk;
4231 }
4232
4233 /// Return the appropriate immediate to extract the specified
4234 /// EXTRACT_SUBVECTOR index with VEXTRACTF128 and VINSERTI128 instructions.
4235 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4236   return getExtractVEXTRACTImmediate(N, 128);
4237 }
4238
4239 /// Return the appropriate immediate to extract the specified
4240 /// EXTRACT_SUBVECTOR index with VEXTRACTF64x4 and VINSERTI64x4 instructions.
4241 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4242   return getExtractVEXTRACTImmediate(N, 256);
4243 }
4244
4245 /// Return the appropriate immediate to insert at the specified
4246 /// INSERT_SUBVECTOR index with VINSERTF128 and VINSERTI128 instructions.
4247 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4248   return getInsertVINSERTImmediate(N, 128);
4249 }
4250
4251 /// Return the appropriate immediate to insert at the specified
4252 /// INSERT_SUBVECTOR index with VINSERTF46x4 and VINSERTI64x4 instructions.
4253 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4254   return getInsertVINSERTImmediate(N, 256);
4255 }
4256
4257 /// Returns true if V is a constant integer zero.
4258 static bool isZero(SDValue V) {
4259   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4260   return C && C->isNullValue();
4261 }
4262
4263 /// Returns true if Elt is a constant zero or a floating point constant +0.0.
4264 bool X86::isZeroNode(SDValue Elt) {
4265   if (isZero(Elt))
4266     return true;
4267   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4268     return CFP->getValueAPF().isPosZero();
4269   return false;
4270 }
4271
4272 // Build a vector of constants
4273 // Use an UNDEF node if MaskElt == -1.
4274 // Spilt 64-bit constants in the 32-bit mode.
4275 static SDValue getConstVector(ArrayRef<int> Values, MVT VT,
4276                               SelectionDAG &DAG,
4277                               SDLoc dl, bool IsMask = false) {
4278
4279   SmallVector<SDValue, 32>  Ops;
4280   bool Split = false;
4281
4282   MVT ConstVecVT = VT;
4283   unsigned NumElts = VT.getVectorNumElements();
4284   bool In64BitMode = DAG.getTargetLoweringInfo().isTypeLegal(MVT::i64);
4285   if (!In64BitMode && VT.getVectorElementType() == MVT::i64) {
4286     ConstVecVT = MVT::getVectorVT(MVT::i32, NumElts * 2);
4287     Split = true;
4288   }
4289
4290   MVT EltVT = ConstVecVT.getVectorElementType();
4291   for (unsigned i = 0; i < NumElts; ++i) {
4292     bool IsUndef = Values[i] < 0 && IsMask;
4293     SDValue OpNode = IsUndef ? DAG.getUNDEF(EltVT) :
4294       DAG.getConstant(Values[i], dl, EltVT);
4295     Ops.push_back(OpNode);
4296     if (Split)
4297       Ops.push_back(IsUndef ? DAG.getUNDEF(EltVT) :
4298                     DAG.getConstant(0, dl, EltVT));
4299   }
4300   SDValue ConstsNode = DAG.getNode(ISD::BUILD_VECTOR, dl, ConstVecVT, Ops);
4301   if (Split)
4302     ConstsNode = DAG.getBitcast(VT, ConstsNode);
4303   return ConstsNode;
4304 }
4305
4306 /// Returns a vector of specified type with all zero elements.
4307 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4308                              SelectionDAG &DAG, SDLoc dl) {
4309   assert(VT.isVector() && "Expected a vector type");
4310
4311   // Always build SSE zero vectors as <4 x i32> bitcasted
4312   // to their dest type. This ensures they get CSE'd.
4313   SDValue Vec;
4314   if (VT.is128BitVector()) {  // SSE
4315     if (Subtarget->hasSSE2()) {  // SSE2
4316       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4317       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4318     } else { // SSE1
4319       SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4320       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4321     }
4322   } else if (VT.is256BitVector()) { // AVX
4323     if (Subtarget->hasInt256()) { // AVX2
4324       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4325       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4326       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4327     } else {
4328       // 256-bit logic and arithmetic instructions in AVX are all
4329       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4330       SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4331       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4332       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4333     }
4334   } else if (VT.is512BitVector()) { // AVX-512
4335       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4336       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4337                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4338       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4339   } else if (VT.getVectorElementType() == MVT::i1) {
4340
4341     assert((Subtarget->hasBWI() || VT.getVectorNumElements() <= 16)
4342             && "Unexpected vector type");
4343     assert((Subtarget->hasVLX() || VT.getVectorNumElements() >= 8)
4344             && "Unexpected vector type");
4345     SDValue Cst = DAG.getConstant(0, dl, MVT::i1);
4346     SmallVector<SDValue, 64> Ops(VT.getVectorNumElements(), Cst);
4347     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4348   } else
4349     llvm_unreachable("Unexpected vector type");
4350
4351   return DAG.getBitcast(VT, Vec);
4352 }
4353
4354 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
4355                                 SelectionDAG &DAG, SDLoc dl,
4356                                 unsigned vectorWidth) {
4357   assert((vectorWidth == 128 || vectorWidth == 256) &&
4358          "Unsupported vector width");
4359   EVT VT = Vec.getValueType();
4360   EVT ElVT = VT.getVectorElementType();
4361   unsigned Factor = VT.getSizeInBits()/vectorWidth;
4362   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
4363                                   VT.getVectorNumElements()/Factor);
4364
4365   // Extract from UNDEF is UNDEF.
4366   if (Vec.getOpcode() == ISD::UNDEF)
4367     return DAG.getUNDEF(ResultVT);
4368
4369   // Extract the relevant vectorWidth bits.  Generate an EXTRACT_SUBVECTOR
4370   unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
4371   assert(isPowerOf2_32(ElemsPerChunk) && "Elements per chunk not power of 2");
4372
4373   // This is the index of the first element of the vectorWidth-bit chunk
4374   // we want. Since ElemsPerChunk is a power of 2 just need to clear bits.
4375   IdxVal &= ~(ElemsPerChunk - 1);
4376
4377   // If the input is a buildvector just emit a smaller one.
4378   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
4379     return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
4380                        makeArrayRef(Vec->op_begin() + IdxVal, ElemsPerChunk));
4381
4382   SDValue VecIdx = DAG.getIntPtrConstant(IdxVal, dl);
4383   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec, VecIdx);
4384 }
4385
4386 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
4387 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
4388 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
4389 /// instructions or a simple subregister reference. Idx is an index in the
4390 /// 128 bits we want.  It need not be aligned to a 128-bit boundary.  That makes
4391 /// lowering EXTRACT_VECTOR_ELT operations easier.
4392 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
4393                                    SelectionDAG &DAG, SDLoc dl) {
4394   assert((Vec.getValueType().is256BitVector() ||
4395           Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
4396   return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
4397 }
4398
4399 /// Generate a DAG to grab 256-bits from a 512-bit vector.
4400 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
4401                                    SelectionDAG &DAG, SDLoc dl) {
4402   assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
4403   return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
4404 }
4405
4406 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
4407                                unsigned IdxVal, SelectionDAG &DAG,
4408                                SDLoc dl, unsigned vectorWidth) {
4409   assert((vectorWidth == 128 || vectorWidth == 256) &&
4410          "Unsupported vector width");
4411   // Inserting UNDEF is Result
4412   if (Vec.getOpcode() == ISD::UNDEF)
4413     return Result;
4414   EVT VT = Vec.getValueType();
4415   EVT ElVT = VT.getVectorElementType();
4416   EVT ResultVT = Result.getValueType();
4417
4418   // Insert the relevant vectorWidth bits.
4419   unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
4420   assert(isPowerOf2_32(ElemsPerChunk) && "Elements per chunk not power of 2");
4421
4422   // This is the index of the first element of the vectorWidth-bit chunk
4423   // we want. Since ElemsPerChunk is a power of 2 just need to clear bits.
4424   IdxVal &= ~(ElemsPerChunk - 1);
4425
4426   SDValue VecIdx = DAG.getIntPtrConstant(IdxVal, dl);
4427   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec, VecIdx);
4428 }
4429
4430 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
4431 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
4432 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
4433 /// simple superregister reference.  Idx is an index in the 128 bits
4434 /// we want.  It need not be aligned to a 128-bit boundary.  That makes
4435 /// lowering INSERT_VECTOR_ELT operations easier.
4436 static SDValue Insert128BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4437                                   SelectionDAG &DAG, SDLoc dl) {
4438   assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
4439
4440   // For insertion into the zero index (low half) of a 256-bit vector, it is
4441   // more efficient to generate a blend with immediate instead of an insert*128.
4442   // We are still creating an INSERT_SUBVECTOR below with an undef node to
4443   // extend the subvector to the size of the result vector. Make sure that
4444   // we are not recursing on that node by checking for undef here.
4445   if (IdxVal == 0 && Result.getValueType().is256BitVector() &&
4446       Result.getOpcode() != ISD::UNDEF) {
4447     EVT ResultVT = Result.getValueType();
4448     SDValue ZeroIndex = DAG.getIntPtrConstant(0, dl);
4449     SDValue Undef = DAG.getUNDEF(ResultVT);
4450     SDValue Vec256 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Undef,
4451                                  Vec, ZeroIndex);
4452
4453     // The blend instruction, and therefore its mask, depend on the data type.
4454     MVT ScalarType = ResultVT.getVectorElementType().getSimpleVT();
4455     if (ScalarType.isFloatingPoint()) {
4456       // Choose either vblendps (float) or vblendpd (double).
4457       unsigned ScalarSize = ScalarType.getSizeInBits();
4458       assert((ScalarSize == 64 || ScalarSize == 32) && "Unknown float type");
4459       unsigned MaskVal = (ScalarSize == 64) ? 0x03 : 0x0f;
4460       SDValue Mask = DAG.getConstant(MaskVal, dl, MVT::i8);
4461       return DAG.getNode(X86ISD::BLENDI, dl, ResultVT, Result, Vec256, Mask);
4462     }
4463
4464     const X86Subtarget &Subtarget =
4465     static_cast<const X86Subtarget &>(DAG.getSubtarget());
4466
4467     // AVX2 is needed for 256-bit integer blend support.
4468     // Integers must be cast to 32-bit because there is only vpblendd;
4469     // vpblendw can't be used for this because it has a handicapped mask.
4470
4471     // If we don't have AVX2, then cast to float. Using a wrong domain blend
4472     // is still more efficient than using the wrong domain vinsertf128 that
4473     // will be created by InsertSubVector().
4474     MVT CastVT = Subtarget.hasAVX2() ? MVT::v8i32 : MVT::v8f32;
4475
4476     SDValue Mask = DAG.getConstant(0x0f, dl, MVT::i8);
4477     Vec256 = DAG.getBitcast(CastVT, Vec256);
4478     Vec256 = DAG.getNode(X86ISD::BLENDI, dl, CastVT, Result, Vec256, Mask);
4479     return DAG.getBitcast(ResultVT, Vec256);
4480   }
4481
4482   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
4483 }
4484
4485 static SDValue Insert256BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4486                                   SelectionDAG &DAG, SDLoc dl) {
4487   assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
4488   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
4489 }
4490
4491 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
4492 /// instructions. This is used because creating CONCAT_VECTOR nodes of
4493 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
4494 /// large BUILD_VECTORS.
4495 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
4496                                    unsigned NumElems, SelectionDAG &DAG,
4497                                    SDLoc dl) {
4498   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4499   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
4500 }
4501
4502 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
4503                                    unsigned NumElems, SelectionDAG &DAG,
4504                                    SDLoc dl) {
4505   SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4506   return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
4507 }
4508
4509 /// Returns a vector of specified type with all bits set.
4510 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4511 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4512 /// Then bitcast to their original type, ensuring they get CSE'd.
4513 static SDValue getOnesVector(EVT VT, const X86Subtarget *Subtarget,
4514                              SelectionDAG &DAG, SDLoc dl) {
4515   assert(VT.isVector() && "Expected a vector type");
4516
4517   SDValue Cst = DAG.getConstant(~0U, dl, MVT::i32);
4518   SDValue Vec;
4519   if (VT.is512BitVector()) {
4520     SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4521                       Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4522     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4523   } else if (VT.is256BitVector()) {
4524     if (Subtarget->hasInt256()) { // AVX2
4525       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4526       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4527     } else { // AVX
4528       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4529       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4530     }
4531   } else if (VT.is128BitVector()) {
4532     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4533   } else
4534     llvm_unreachable("Unexpected vector type");
4535
4536   return DAG.getBitcast(VT, Vec);
4537 }
4538
4539 /// Returns a vector_shuffle node for an unpackl operation.
4540 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4541                           SDValue V2) {
4542   unsigned NumElems = VT.getVectorNumElements();
4543   SmallVector<int, 8> Mask;
4544   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4545     Mask.push_back(i);
4546     Mask.push_back(i + NumElems);
4547   }
4548   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4549 }
4550
4551 /// Returns a vector_shuffle node for an unpackh operation.
4552 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4553                           SDValue V2) {
4554   unsigned NumElems = VT.getVectorNumElements();
4555   SmallVector<int, 8> Mask;
4556   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4557     Mask.push_back(i + Half);
4558     Mask.push_back(i + NumElems + Half);
4559   }
4560   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4561 }
4562
4563 /// Return a vector_shuffle of the specified vector of zero or undef vector.
4564 /// This produces a shuffle where the low element of V2 is swizzled into the
4565 /// zero/undef vector, landing at element Idx.
4566 /// This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4567 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4568                                            bool IsZero,
4569                                            const X86Subtarget *Subtarget,
4570                                            SelectionDAG &DAG) {
4571   MVT VT = V2.getSimpleValueType();
4572   SDValue V1 = IsZero
4573     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
4574   unsigned NumElems = VT.getVectorNumElements();
4575   SmallVector<int, 16> MaskVec;
4576   for (unsigned i = 0; i != NumElems; ++i)
4577     // If this is the insertion idx, put the low elt of V2 here.
4578     MaskVec.push_back(i == Idx ? NumElems : i);
4579   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
4580 }
4581
4582 /// Calculates the shuffle mask corresponding to the target-specific opcode.
4583 /// Returns true if the Mask could be calculated. Sets IsUnary to true if only
4584 /// uses one source. Note that this will set IsUnary for shuffles which use a
4585 /// single input multiple times, and in those cases it will
4586 /// adjust the mask to only have indices within that single input.
4587 /// FIXME: Add support for Decode*Mask functions that return SM_SentinelZero.
4588 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4589                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
4590   unsigned NumElems = VT.getVectorNumElements();
4591   SDValue ImmN;
4592
4593   IsUnary = false;
4594   bool IsFakeUnary = false;
4595   switch(N->getOpcode()) {
4596   case X86ISD::BLENDI:
4597     ImmN = N->getOperand(N->getNumOperands()-1);
4598     DecodeBLENDMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4599     break;
4600   case X86ISD::SHUFP:
4601     ImmN = N->getOperand(N->getNumOperands()-1);
4602     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4603     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4604     break;
4605   case X86ISD::UNPCKH:
4606     DecodeUNPCKHMask(VT, Mask);
4607     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4608     break;
4609   case X86ISD::UNPCKL:
4610     DecodeUNPCKLMask(VT, Mask);
4611     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4612     break;
4613   case X86ISD::MOVHLPS:
4614     DecodeMOVHLPSMask(NumElems, Mask);
4615     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4616     break;
4617   case X86ISD::MOVLHPS:
4618     DecodeMOVLHPSMask(NumElems, Mask);
4619     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4620     break;
4621   case X86ISD::PALIGNR:
4622     ImmN = N->getOperand(N->getNumOperands()-1);
4623     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4624     break;
4625   case X86ISD::PSHUFD:
4626   case X86ISD::VPERMILPI:
4627     ImmN = N->getOperand(N->getNumOperands()-1);
4628     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4629     IsUnary = true;
4630     break;
4631   case X86ISD::PSHUFHW:
4632     ImmN = N->getOperand(N->getNumOperands()-1);
4633     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4634     IsUnary = true;
4635     break;
4636   case X86ISD::PSHUFLW:
4637     ImmN = N->getOperand(N->getNumOperands()-1);
4638     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4639     IsUnary = true;
4640     break;
4641   case X86ISD::PSHUFB: {
4642     IsUnary = true;
4643     SDValue MaskNode = N->getOperand(1);
4644     while (MaskNode->getOpcode() == ISD::BITCAST)
4645       MaskNode = MaskNode->getOperand(0);
4646
4647     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4648       // If we have a build-vector, then things are easy.
4649       MVT VT = MaskNode.getSimpleValueType();
4650       assert(VT.isVector() &&
4651              "Can't produce a non-vector with a build_vector!");
4652       if (!VT.isInteger())
4653         return false;
4654
4655       int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
4656
4657       SmallVector<uint64_t, 32> RawMask;
4658       for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
4659         SDValue Op = MaskNode->getOperand(i);
4660         if (Op->getOpcode() == ISD::UNDEF) {
4661           RawMask.push_back((uint64_t)SM_SentinelUndef);
4662           continue;
4663         }
4664         auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4665         if (!CN)
4666           return false;
4667         APInt MaskElement = CN->getAPIntValue();
4668
4669         // We now have to decode the element which could be any integer size and
4670         // extract each byte of it.
4671         for (int j = 0; j < NumBytesPerElement; ++j) {
4672           // Note that this is x86 and so always little endian: the low byte is
4673           // the first byte of the mask.
4674           RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
4675           MaskElement = MaskElement.lshr(8);
4676         }
4677       }
4678       DecodePSHUFBMask(RawMask, Mask);
4679       break;
4680     }
4681
4682     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4683     if (!MaskLoad)
4684       return false;
4685
4686     SDValue Ptr = MaskLoad->getBasePtr();
4687     if (Ptr->getOpcode() == X86ISD::Wrapper ||
4688         Ptr->getOpcode() == X86ISD::WrapperRIP)
4689       Ptr = Ptr->getOperand(0);
4690
4691     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4692     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4693       return false;
4694
4695     if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
4696       DecodePSHUFBMask(C, Mask);
4697       if (Mask.empty())
4698         return false;
4699       break;
4700     }
4701
4702     return false;
4703   }
4704   case X86ISD::VPERMI:
4705     ImmN = N->getOperand(N->getNumOperands()-1);
4706     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4707     IsUnary = true;
4708     break;
4709   case X86ISD::MOVSS:
4710   case X86ISD::MOVSD:
4711     DecodeScalarMoveMask(VT, /* IsLoad */ false, Mask);
4712     break;
4713   case X86ISD::VPERM2X128:
4714     ImmN = N->getOperand(N->getNumOperands()-1);
4715     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4716     if (Mask.empty()) return false;
4717     // Mask only contains negative index if an element is zero.
4718     if (std::any_of(Mask.begin(), Mask.end(),
4719                     [](int M){ return M == SM_SentinelZero; }))
4720       return false;
4721     break;
4722   case X86ISD::MOVSLDUP:
4723     DecodeMOVSLDUPMask(VT, Mask);
4724     IsUnary = true;
4725     break;
4726   case X86ISD::MOVSHDUP:
4727     DecodeMOVSHDUPMask(VT, Mask);
4728     IsUnary = true;
4729     break;
4730   case X86ISD::MOVDDUP:
4731     DecodeMOVDDUPMask(VT, Mask);
4732     IsUnary = true;
4733     break;
4734   case X86ISD::MOVLHPD:
4735   case X86ISD::MOVLPD:
4736   case X86ISD::MOVLPS:
4737     // Not yet implemented
4738     return false;
4739   case X86ISD::VPERMV: {
4740     IsUnary = true;
4741     SDValue MaskNode = N->getOperand(0);
4742     while (MaskNode->getOpcode() == ISD::BITCAST)
4743       MaskNode = MaskNode->getOperand(0);
4744
4745     unsigned MaskLoBits = Log2_64(VT.getVectorNumElements());
4746     SmallVector<uint64_t, 32> RawMask;
4747     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4748       // If we have a build-vector, then things are easy.
4749       assert(MaskNode.getSimpleValueType().isInteger() &&
4750              MaskNode.getSimpleValueType().getVectorNumElements() ==
4751              VT.getVectorNumElements());
4752
4753       for (unsigned i = 0; i < MaskNode->getNumOperands(); ++i) {
4754         SDValue Op = MaskNode->getOperand(i);
4755         if (Op->getOpcode() == ISD::UNDEF)
4756           RawMask.push_back((uint64_t)SM_SentinelUndef);
4757         else if (isa<ConstantSDNode>(Op)) {
4758           APInt MaskElement = cast<ConstantSDNode>(Op)->getAPIntValue();
4759           RawMask.push_back(MaskElement.getLoBits(MaskLoBits).getZExtValue());
4760         } else
4761           return false;
4762       }
4763       DecodeVPERMVMask(RawMask, Mask);
4764       break;
4765     }
4766     if (MaskNode->getOpcode() == X86ISD::VBROADCAST) {
4767       unsigned NumEltsInMask = MaskNode->getNumOperands();
4768       MaskNode = MaskNode->getOperand(0);
4769       auto *CN = dyn_cast<ConstantSDNode>(MaskNode);
4770       if (CN) {
4771         APInt MaskEltValue = CN->getAPIntValue();
4772         for (unsigned i = 0; i < NumEltsInMask; ++i)
4773           RawMask.push_back(MaskEltValue.getLoBits(MaskLoBits).getZExtValue());
4774         DecodeVPERMVMask(RawMask, Mask);
4775         break;
4776       }
4777       // It may be a scalar load
4778     }
4779
4780     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4781     if (!MaskLoad)
4782       return false;
4783
4784     SDValue Ptr = MaskLoad->getBasePtr();
4785     if (Ptr->getOpcode() == X86ISD::Wrapper ||
4786         Ptr->getOpcode() == X86ISD::WrapperRIP)
4787       Ptr = Ptr->getOperand(0);
4788
4789     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4790     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4791       return false;
4792
4793     auto *C = dyn_cast<Constant>(MaskCP->getConstVal());
4794     if (C) {
4795       DecodeVPERMVMask(C, VT, Mask);
4796       if (Mask.empty())
4797         return false;
4798       break;
4799     }
4800     return false;
4801   }
4802   case X86ISD::VPERMV3: {
4803     IsUnary = false;
4804     SDValue MaskNode = N->getOperand(1);
4805     while (MaskNode->getOpcode() == ISD::BITCAST)
4806       MaskNode = MaskNode->getOperand(1);
4807
4808     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4809       // If we have a build-vector, then things are easy.
4810       assert(MaskNode.getSimpleValueType().isInteger() &&
4811              MaskNode.getSimpleValueType().getVectorNumElements() ==
4812              VT.getVectorNumElements());
4813
4814       SmallVector<uint64_t, 32> RawMask;
4815       unsigned MaskLoBits = Log2_64(VT.getVectorNumElements()*2);
4816
4817       for (unsigned i = 0; i < MaskNode->getNumOperands(); ++i) {
4818         SDValue Op = MaskNode->getOperand(i);
4819         if (Op->getOpcode() == ISD::UNDEF)
4820           RawMask.push_back((uint64_t)SM_SentinelUndef);
4821         else {
4822           auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4823           if (!CN)
4824             return false;
4825           APInt MaskElement = CN->getAPIntValue();
4826           RawMask.push_back(MaskElement.getLoBits(MaskLoBits).getZExtValue());
4827         }
4828       }
4829       DecodeVPERMV3Mask(RawMask, Mask);
4830       break;
4831     }
4832
4833     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4834     if (!MaskLoad)
4835       return false;
4836
4837     SDValue Ptr = MaskLoad->getBasePtr();
4838     if (Ptr->getOpcode() == X86ISD::Wrapper ||
4839         Ptr->getOpcode() == X86ISD::WrapperRIP)
4840       Ptr = Ptr->getOperand(0);
4841
4842     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4843     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4844       return false;
4845
4846     auto *C = dyn_cast<Constant>(MaskCP->getConstVal());
4847     if (C) {
4848       DecodeVPERMV3Mask(C, VT, Mask);
4849       if (Mask.empty())
4850         return false;
4851       break;
4852     }
4853     return false;
4854   }
4855   default: llvm_unreachable("unknown target shuffle node");
4856   }
4857
4858   // If we have a fake unary shuffle, the shuffle mask is spread across two
4859   // inputs that are actually the same node. Re-map the mask to always point
4860   // into the first input.
4861   if (IsFakeUnary)
4862     for (int &M : Mask)
4863       if (M >= (int)Mask.size())
4864         M -= Mask.size();
4865
4866   return true;
4867 }
4868
4869 /// Returns the scalar element that will make up the ith
4870 /// element of the result of the vector shuffle.
4871 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4872                                    unsigned Depth) {
4873   if (Depth == 6)
4874     return SDValue();  // Limit search depth.
4875
4876   SDValue V = SDValue(N, 0);
4877   EVT VT = V.getValueType();
4878   unsigned Opcode = V.getOpcode();
4879
4880   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4881   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4882     int Elt = SV->getMaskElt(Index);
4883
4884     if (Elt < 0)
4885       return DAG.getUNDEF(VT.getVectorElementType());
4886
4887     unsigned NumElems = VT.getVectorNumElements();
4888     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4889                                          : SV->getOperand(1);
4890     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4891   }
4892
4893   // Recurse into target specific vector shuffles to find scalars.
4894   if (isTargetShuffle(Opcode)) {
4895     MVT ShufVT = V.getSimpleValueType();
4896     unsigned NumElems = ShufVT.getVectorNumElements();
4897     SmallVector<int, 16> ShuffleMask;
4898     bool IsUnary;
4899
4900     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4901       return SDValue();
4902
4903     int Elt = ShuffleMask[Index];
4904     if (Elt < 0)
4905       return DAG.getUNDEF(ShufVT.getVectorElementType());
4906
4907     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4908                                          : N->getOperand(1);
4909     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4910                                Depth+1);
4911   }
4912
4913   // Actual nodes that may contain scalar elements
4914   if (Opcode == ISD::BITCAST) {
4915     V = V.getOperand(0);
4916     EVT SrcVT = V.getValueType();
4917     unsigned NumElems = VT.getVectorNumElements();
4918
4919     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4920       return SDValue();
4921   }
4922
4923   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4924     return (Index == 0) ? V.getOperand(0)
4925                         : DAG.getUNDEF(VT.getVectorElementType());
4926
4927   if (V.getOpcode() == ISD::BUILD_VECTOR)
4928     return V.getOperand(Index);
4929
4930   return SDValue();
4931 }
4932
4933 /// Custom lower build_vector of v16i8.
4934 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4935                                        unsigned NumNonZero, unsigned NumZero,
4936                                        SelectionDAG &DAG,
4937                                        const X86Subtarget* Subtarget,
4938                                        const TargetLowering &TLI) {
4939   if (NumNonZero > 8)
4940     return SDValue();
4941
4942   SDLoc dl(Op);
4943   SDValue V;
4944   bool First = true;
4945
4946   // SSE4.1 - use PINSRB to insert each byte directly.
4947   if (Subtarget->hasSSE41()) {
4948     for (unsigned i = 0; i < 16; ++i) {
4949       bool isNonZero = (NonZeros & (1 << i)) != 0;
4950       if (isNonZero) {
4951         if (First) {
4952           if (NumZero)
4953             V = getZeroVector(MVT::v16i8, Subtarget, DAG, dl);
4954           else
4955             V = DAG.getUNDEF(MVT::v16i8);
4956           First = false;
4957         }
4958         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4959                         MVT::v16i8, V, Op.getOperand(i),
4960                         DAG.getIntPtrConstant(i, dl));
4961       }
4962     }
4963
4964     return V;
4965   }
4966
4967   // Pre-SSE4.1 - merge byte pairs and insert with PINSRW.
4968   for (unsigned i = 0; i < 16; ++i) {
4969     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4970     if (ThisIsNonZero && First) {
4971       if (NumZero)
4972         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4973       else
4974         V = DAG.getUNDEF(MVT::v8i16);
4975       First = false;
4976     }
4977
4978     if ((i & 1) != 0) {
4979       SDValue ThisElt, LastElt;
4980       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4981       if (LastIsNonZero) {
4982         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4983                               MVT::i16, Op.getOperand(i-1));
4984       }
4985       if (ThisIsNonZero) {
4986         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4987         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4988                               ThisElt, DAG.getConstant(8, dl, MVT::i8));
4989         if (LastIsNonZero)
4990           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4991       } else
4992         ThisElt = LastElt;
4993
4994       if (ThisElt.getNode())
4995         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4996                         DAG.getIntPtrConstant(i/2, dl));
4997     }
4998   }
4999
5000   return DAG.getBitcast(MVT::v16i8, V);
5001 }
5002
5003 /// Custom lower build_vector of v8i16.
5004 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5005                                      unsigned NumNonZero, unsigned NumZero,
5006                                      SelectionDAG &DAG,
5007                                      const X86Subtarget* Subtarget,
5008                                      const TargetLowering &TLI) {
5009   if (NumNonZero > 4)
5010     return SDValue();
5011
5012   SDLoc dl(Op);
5013   SDValue V;
5014   bool First = true;
5015   for (unsigned i = 0; i < 8; ++i) {
5016     bool isNonZero = (NonZeros & (1 << i)) != 0;
5017     if (isNonZero) {
5018       if (First) {
5019         if (NumZero)
5020           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5021         else
5022           V = DAG.getUNDEF(MVT::v8i16);
5023         First = false;
5024       }
5025       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5026                       MVT::v8i16, V, Op.getOperand(i),
5027                       DAG.getIntPtrConstant(i, dl));
5028     }
5029   }
5030
5031   return V;
5032 }
5033
5034 /// Custom lower build_vector of v4i32 or v4f32.
5035 static SDValue LowerBuildVectorv4x32(SDValue Op, SelectionDAG &DAG,
5036                                      const X86Subtarget *Subtarget,
5037                                      const TargetLowering &TLI) {
5038   // Find all zeroable elements.
5039   std::bitset<4> Zeroable;
5040   for (int i=0; i < 4; ++i) {
5041     SDValue Elt = Op->getOperand(i);
5042     Zeroable[i] = (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt));
5043   }
5044   assert(Zeroable.size() - Zeroable.count() > 1 &&
5045          "We expect at least two non-zero elements!");
5046
5047   // We only know how to deal with build_vector nodes where elements are either
5048   // zeroable or extract_vector_elt with constant index.
5049   SDValue FirstNonZero;
5050   unsigned FirstNonZeroIdx;
5051   for (unsigned i=0; i < 4; ++i) {
5052     if (Zeroable[i])
5053       continue;
5054     SDValue Elt = Op->getOperand(i);
5055     if (Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5056         !isa<ConstantSDNode>(Elt.getOperand(1)))
5057       return SDValue();
5058     // Make sure that this node is extracting from a 128-bit vector.
5059     MVT VT = Elt.getOperand(0).getSimpleValueType();
5060     if (!VT.is128BitVector())
5061       return SDValue();
5062     if (!FirstNonZero.getNode()) {
5063       FirstNonZero = Elt;
5064       FirstNonZeroIdx = i;
5065     }
5066   }
5067
5068   assert(FirstNonZero.getNode() && "Unexpected build vector of all zeros!");
5069   SDValue V1 = FirstNonZero.getOperand(0);
5070   MVT VT = V1.getSimpleValueType();
5071
5072   // See if this build_vector can be lowered as a blend with zero.
5073   SDValue Elt;
5074   unsigned EltMaskIdx, EltIdx;
5075   int Mask[4];
5076   for (EltIdx = 0; EltIdx < 4; ++EltIdx) {
5077     if (Zeroable[EltIdx]) {
5078       // The zero vector will be on the right hand side.
5079       Mask[EltIdx] = EltIdx+4;
5080       continue;
5081     }
5082
5083     Elt = Op->getOperand(EltIdx);
5084     // By construction, Elt is a EXTRACT_VECTOR_ELT with constant index.
5085     EltMaskIdx = cast<ConstantSDNode>(Elt.getOperand(1))->getZExtValue();
5086     if (Elt.getOperand(0) != V1 || EltMaskIdx != EltIdx)
5087       break;
5088     Mask[EltIdx] = EltIdx;
5089   }
5090
5091   if (EltIdx == 4) {
5092     // Let the shuffle legalizer deal with blend operations.
5093     SDValue VZero = getZeroVector(VT, Subtarget, DAG, SDLoc(Op));
5094     if (V1.getSimpleValueType() != VT)
5095       V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), VT, V1);
5096     return DAG.getVectorShuffle(VT, SDLoc(V1), V1, VZero, &Mask[0]);
5097   }
5098
5099   // See if we can lower this build_vector to a INSERTPS.
5100   if (!Subtarget->hasSSE41())
5101     return SDValue();
5102
5103   SDValue V2 = Elt.getOperand(0);
5104   if (Elt == FirstNonZero && EltIdx == FirstNonZeroIdx)
5105     V1 = SDValue();
5106
5107   bool CanFold = true;
5108   for (unsigned i = EltIdx + 1; i < 4 && CanFold; ++i) {
5109     if (Zeroable[i])
5110       continue;
5111
5112     SDValue Current = Op->getOperand(i);
5113     SDValue SrcVector = Current->getOperand(0);
5114     if (!V1.getNode())
5115       V1 = SrcVector;
5116     CanFold = SrcVector == V1 &&
5117       cast<ConstantSDNode>(Current.getOperand(1))->getZExtValue() == i;
5118   }
5119
5120   if (!CanFold)
5121     return SDValue();
5122
5123   assert(V1.getNode() && "Expected at least two non-zero elements!");
5124   if (V1.getSimpleValueType() != MVT::v4f32)
5125     V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), MVT::v4f32, V1);
5126   if (V2.getSimpleValueType() != MVT::v4f32)
5127     V2 = DAG.getNode(ISD::BITCAST, SDLoc(V2), MVT::v4f32, V2);
5128
5129   // Ok, we can emit an INSERTPS instruction.
5130   unsigned ZMask = Zeroable.to_ulong();
5131
5132   unsigned InsertPSMask = EltMaskIdx << 6 | EltIdx << 4 | ZMask;
5133   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
5134   SDLoc DL(Op);
5135   SDValue Result = DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
5136                                DAG.getIntPtrConstant(InsertPSMask, DL));
5137   return DAG.getBitcast(VT, Result);
5138 }
5139
5140 /// Return a vector logical shift node.
5141 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5142                          unsigned NumBits, SelectionDAG &DAG,
5143                          const TargetLowering &TLI, SDLoc dl) {
5144   assert(VT.is128BitVector() && "Unknown type for VShift");
5145   MVT ShVT = MVT::v2i64;
5146   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5147   SrcOp = DAG.getBitcast(ShVT, SrcOp);
5148   MVT ScalarShiftTy = TLI.getScalarShiftAmountTy(DAG.getDataLayout(), VT);
5149   assert(NumBits % 8 == 0 && "Only support byte sized shifts");
5150   SDValue ShiftVal = DAG.getConstant(NumBits/8, dl, ScalarShiftTy);
5151   return DAG.getBitcast(VT, DAG.getNode(Opc, dl, ShVT, SrcOp, ShiftVal));
5152 }
5153
5154 static SDValue
5155 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5156
5157   // Check if the scalar load can be widened into a vector load. And if
5158   // the address is "base + cst" see if the cst can be "absorbed" into
5159   // the shuffle mask.
5160   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5161     SDValue Ptr = LD->getBasePtr();
5162     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5163       return SDValue();
5164     EVT PVT = LD->getValueType(0);
5165     if (PVT != MVT::i32 && PVT != MVT::f32)
5166       return SDValue();
5167
5168     int FI = -1;
5169     int64_t Offset = 0;
5170     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5171       FI = FINode->getIndex();
5172       Offset = 0;
5173     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5174                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5175       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5176       Offset = Ptr.getConstantOperandVal(1);
5177       Ptr = Ptr.getOperand(0);
5178     } else {
5179       return SDValue();
5180     }
5181
5182     // FIXME: 256-bit vector instructions don't require a strict alignment,
5183     // improve this code to support it better.
5184     unsigned RequiredAlign = VT.getSizeInBits()/8;
5185     SDValue Chain = LD->getChain();
5186     // Make sure the stack object alignment is at least 16 or 32.
5187     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5188     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5189       if (MFI->isFixedObjectIndex(FI)) {
5190         // Can't change the alignment. FIXME: It's possible to compute
5191         // the exact stack offset and reference FI + adjust offset instead.
5192         // If someone *really* cares about this. That's the way to implement it.
5193         return SDValue();
5194       } else {
5195         MFI->setObjectAlignment(FI, RequiredAlign);
5196       }
5197     }
5198
5199     // (Offset % 16 or 32) must be multiple of 4. Then address is then
5200     // Ptr + (Offset & ~15).
5201     if (Offset < 0)
5202       return SDValue();
5203     if ((Offset % RequiredAlign) & 3)
5204       return SDValue();
5205     int64_t StartOffset = Offset & ~int64_t(RequiredAlign - 1);
5206     if (StartOffset) {
5207       SDLoc DL(Ptr);
5208       Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5209                         DAG.getConstant(StartOffset, DL, Ptr.getValueType()));
5210     }
5211
5212     int EltNo = (Offset - StartOffset) >> 2;
5213     unsigned NumElems = VT.getVectorNumElements();
5214
5215     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5216     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5217                              LD->getPointerInfo().getWithOffset(StartOffset),
5218                              false, false, false, 0);
5219
5220     SmallVector<int, 8> Mask(NumElems, EltNo);
5221
5222     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5223   }
5224
5225   return SDValue();
5226 }
5227
5228 /// Given the initializing elements 'Elts' of a vector of type 'VT', see if the
5229 /// elements can be replaced by a single large load which has the same value as
5230 /// a build_vector or insert_subvector whose loaded operands are 'Elts'.
5231 ///
5232 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5233 ///
5234 /// FIXME: we'd also like to handle the case where the last elements are zero
5235 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5236 /// There's even a handy isZeroNode for that purpose.
5237 static SDValue EltsFromConsecutiveLoads(EVT VT, ArrayRef<SDValue> Elts,
5238                                         SDLoc &DL, SelectionDAG &DAG,
5239                                         bool isAfterLegalize) {
5240   unsigned NumElems = Elts.size();
5241
5242   LoadSDNode *LDBase = nullptr;
5243   unsigned LastLoadedElt = -1U;
5244
5245   // For each element in the initializer, see if we've found a load or an undef.
5246   // If we don't find an initial load element, or later load elements are
5247   // non-consecutive, bail out.
5248   for (unsigned i = 0; i < NumElems; ++i) {
5249     SDValue Elt = Elts[i];
5250     // Look through a bitcast.
5251     if (Elt.getNode() && Elt.getOpcode() == ISD::BITCAST)
5252       Elt = Elt.getOperand(0);
5253     if (!Elt.getNode() ||
5254         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5255       return SDValue();
5256     if (!LDBase) {
5257       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5258         return SDValue();
5259       LDBase = cast<LoadSDNode>(Elt.getNode());
5260       LastLoadedElt = i;
5261       continue;
5262     }
5263     if (Elt.getOpcode() == ISD::UNDEF)
5264       continue;
5265
5266     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5267     EVT LdVT = Elt.getValueType();
5268     // Each loaded element must be the correct fractional portion of the
5269     // requested vector load.
5270     if (LdVT.getSizeInBits() != VT.getSizeInBits() / NumElems)
5271       return SDValue();
5272     if (!DAG.isConsecutiveLoad(LD, LDBase, LdVT.getSizeInBits() / 8, i))
5273       return SDValue();
5274     LastLoadedElt = i;
5275   }
5276
5277   // If we have found an entire vector of loads and undefs, then return a large
5278   // load of the entire vector width starting at the base pointer.  If we found
5279   // consecutive loads for the low half, generate a vzext_load node.
5280   if (LastLoadedElt == NumElems - 1) {
5281     assert(LDBase && "Did not find base load for merging consecutive loads");
5282     EVT EltVT = LDBase->getValueType(0);
5283     // Ensure that the input vector size for the merged loads matches the
5284     // cumulative size of the input elements.
5285     if (VT.getSizeInBits() != EltVT.getSizeInBits() * NumElems)
5286       return SDValue();
5287
5288     if (isAfterLegalize &&
5289         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5290       return SDValue();
5291
5292     SDValue NewLd = SDValue();
5293
5294     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5295                         LDBase->getPointerInfo(), LDBase->isVolatile(),
5296                         LDBase->isNonTemporal(), LDBase->isInvariant(),
5297                         LDBase->getAlignment());
5298
5299     if (LDBase->hasAnyUseOfValue(1)) {
5300       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5301                                      SDValue(LDBase, 1),
5302                                      SDValue(NewLd.getNode(), 1));
5303       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5304       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5305                              SDValue(NewLd.getNode(), 1));
5306     }
5307
5308     return NewLd;
5309   }
5310
5311   //TODO: The code below fires only for for loading the low v2i32 / v2f32
5312   //of a v4i32 / v4f32. It's probably worth generalizing.
5313   EVT EltVT = VT.getVectorElementType();
5314   if (NumElems == 4 && LastLoadedElt == 1 && (EltVT.getSizeInBits() == 32) &&
5315       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5316     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5317     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5318     SDValue ResNode =
5319         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5320                                 LDBase->getPointerInfo(),
5321                                 LDBase->getAlignment(),
5322                                 false/*isVolatile*/, true/*ReadMem*/,
5323                                 false/*WriteMem*/);
5324
5325     // Make sure the newly-created LOAD is in the same position as LDBase in
5326     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5327     // update uses of LDBase's output chain to use the TokenFactor.
5328     if (LDBase->hasAnyUseOfValue(1)) {
5329       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5330                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5331       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5332       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5333                              SDValue(ResNode.getNode(), 1));
5334     }
5335
5336     return DAG.getBitcast(VT, ResNode);
5337   }
5338   return SDValue();
5339 }
5340
5341 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5342 /// to generate a splat value for the following cases:
5343 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5344 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5345 /// a scalar load, or a constant.
5346 /// The VBROADCAST node is returned when a pattern is found,
5347 /// or SDValue() otherwise.
5348 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5349                                     SelectionDAG &DAG) {
5350   // VBROADCAST requires AVX.
5351   // TODO: Splats could be generated for non-AVX CPUs using SSE
5352   // instructions, but there's less potential gain for only 128-bit vectors.
5353   if (!Subtarget->hasAVX())
5354     return SDValue();
5355
5356   MVT VT = Op.getSimpleValueType();
5357   SDLoc dl(Op);
5358
5359   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5360          "Unsupported vector type for broadcast.");
5361
5362   SDValue Ld;
5363   bool ConstSplatVal;
5364
5365   switch (Op.getOpcode()) {
5366     default:
5367       // Unknown pattern found.
5368       return SDValue();
5369
5370     case ISD::BUILD_VECTOR: {
5371       auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
5372       BitVector UndefElements;
5373       SDValue Splat = BVOp->getSplatValue(&UndefElements);
5374
5375       // We need a splat of a single value to use broadcast, and it doesn't
5376       // make any sense if the value is only in one element of the vector.
5377       if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
5378         return SDValue();
5379
5380       Ld = Splat;
5381       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5382                        Ld.getOpcode() == ISD::ConstantFP);
5383
5384       // Make sure that all of the users of a non-constant load are from the
5385       // BUILD_VECTOR node.
5386       if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
5387         return SDValue();
5388       break;
5389     }
5390
5391     case ISD::VECTOR_SHUFFLE: {
5392       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5393
5394       // Shuffles must have a splat mask where the first element is
5395       // broadcasted.
5396       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5397         return SDValue();
5398
5399       SDValue Sc = Op.getOperand(0);
5400       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5401           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5402
5403         if (!Subtarget->hasInt256())
5404           return SDValue();
5405
5406         // Use the register form of the broadcast instruction available on AVX2.
5407         if (VT.getSizeInBits() >= 256)
5408           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5409         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5410       }
5411
5412       Ld = Sc.getOperand(0);
5413       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5414                        Ld.getOpcode() == ISD::ConstantFP);
5415
5416       // The scalar_to_vector node and the suspected
5417       // load node must have exactly one user.
5418       // Constants may have multiple users.
5419
5420       // AVX-512 has register version of the broadcast
5421       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5422         Ld.getValueType().getSizeInBits() >= 32;
5423       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5424           !hasRegVer))
5425         return SDValue();
5426       break;
5427     }
5428   }
5429
5430   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5431   bool IsGE256 = (VT.getSizeInBits() >= 256);
5432
5433   // When optimizing for size, generate up to 5 extra bytes for a broadcast
5434   // instruction to save 8 or more bytes of constant pool data.
5435   // TODO: If multiple splats are generated to load the same constant,
5436   // it may be detrimental to overall size. There needs to be a way to detect
5437   // that condition to know if this is truly a size win.
5438   bool OptForSize = DAG.getMachineFunction().getFunction()->optForSize();
5439
5440   // Handle broadcasting a single constant scalar from the constant pool
5441   // into a vector.
5442   // On Sandybridge (no AVX2), it is still better to load a constant vector
5443   // from the constant pool and not to broadcast it from a scalar.
5444   // But override that restriction when optimizing for size.
5445   // TODO: Check if splatting is recommended for other AVX-capable CPUs.
5446   if (ConstSplatVal && (Subtarget->hasAVX2() || OptForSize)) {
5447     EVT CVT = Ld.getValueType();
5448     assert(!CVT.isVector() && "Must not broadcast a vector type");
5449
5450     // Splat f32, i32, v4f64, v4i64 in all cases with AVX2.
5451     // For size optimization, also splat v2f64 and v2i64, and for size opt
5452     // with AVX2, also splat i8 and i16.
5453     // With pattern matching, the VBROADCAST node may become a VMOVDDUP.
5454     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5455         (OptForSize && (ScalarSize == 64 || Subtarget->hasAVX2()))) {
5456       const Constant *C = nullptr;
5457       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5458         C = CI->getConstantIntValue();
5459       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5460         C = CF->getConstantFPValue();
5461
5462       assert(C && "Invalid constant type");
5463
5464       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5465       SDValue CP =
5466           DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
5467       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5468       Ld = DAG.getLoad(
5469           CVT, dl, DAG.getEntryNode(), CP,
5470           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
5471           false, false, Alignment);
5472
5473       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5474     }
5475   }
5476
5477   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5478
5479   // Handle AVX2 in-register broadcasts.
5480   if (!IsLoad && Subtarget->hasInt256() &&
5481       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5482     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5483
5484   // The scalar source must be a normal load.
5485   if (!IsLoad)
5486     return SDValue();
5487
5488   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5489       (Subtarget->hasVLX() && ScalarSize == 64))
5490     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5491
5492   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5493   // double since there is no vbroadcastsd xmm
5494   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5495     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5496       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5497   }
5498
5499   // Unsupported broadcast.
5500   return SDValue();
5501 }
5502
5503 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5504 /// underlying vector and index.
5505 ///
5506 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5507 /// index.
5508 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5509                                          SDValue ExtIdx) {
5510   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5511   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5512     return Idx;
5513
5514   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5515   // lowered this:
5516   //   (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5517   // to:
5518   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
5519   //                           (extract_subvector (v8f32 %vreg0), Constant<4>),
5520   //                           undef)
5521   //                       Constant<0>)
5522   // In this case the vector is the extract_subvector expression and the index
5523   // is 2, as specified by the shuffle.
5524   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5525   SDValue ShuffleVec = SVOp->getOperand(0);
5526   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5527   assert(ShuffleVecVT.getVectorElementType() ==
5528          ExtractedFromVec.getSimpleValueType().getVectorElementType());
5529
5530   int ShuffleIdx = SVOp->getMaskElt(Idx);
5531   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5532     ExtractedFromVec = ShuffleVec;
5533     return ShuffleIdx;
5534   }
5535   return Idx;
5536 }
5537
5538 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5539   MVT VT = Op.getSimpleValueType();
5540
5541   // Skip if insert_vec_elt is not supported.
5542   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5543   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5544     return SDValue();
5545
5546   SDLoc DL(Op);
5547   unsigned NumElems = Op.getNumOperands();
5548
5549   SDValue VecIn1;
5550   SDValue VecIn2;
5551   SmallVector<unsigned, 4> InsertIndices;
5552   SmallVector<int, 8> Mask(NumElems, -1);
5553
5554   for (unsigned i = 0; i != NumElems; ++i) {
5555     unsigned Opc = Op.getOperand(i).getOpcode();
5556
5557     if (Opc == ISD::UNDEF)
5558       continue;
5559
5560     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5561       // Quit if more than 1 elements need inserting.
5562       if (InsertIndices.size() > 1)
5563         return SDValue();
5564
5565       InsertIndices.push_back(i);
5566       continue;
5567     }
5568
5569     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5570     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5571     // Quit if non-constant index.
5572     if (!isa<ConstantSDNode>(ExtIdx))
5573       return SDValue();
5574     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5575
5576     // Quit if extracted from vector of different type.
5577     if (ExtractedFromVec.getValueType() != VT)
5578       return SDValue();
5579
5580     if (!VecIn1.getNode())
5581       VecIn1 = ExtractedFromVec;
5582     else if (VecIn1 != ExtractedFromVec) {
5583       if (!VecIn2.getNode())
5584         VecIn2 = ExtractedFromVec;
5585       else if (VecIn2 != ExtractedFromVec)
5586         // Quit if more than 2 vectors to shuffle
5587         return SDValue();
5588     }
5589
5590     if (ExtractedFromVec == VecIn1)
5591       Mask[i] = Idx;
5592     else if (ExtractedFromVec == VecIn2)
5593       Mask[i] = Idx + NumElems;
5594   }
5595
5596   if (!VecIn1.getNode())
5597     return SDValue();
5598
5599   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5600   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5601   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5602     unsigned Idx = InsertIndices[i];
5603     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5604                      DAG.getIntPtrConstant(Idx, DL));
5605   }
5606
5607   return NV;
5608 }
5609
5610 static SDValue ConvertI1VectorToInteger(SDValue Op, SelectionDAG &DAG) {
5611   assert(ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
5612          Op.getScalarValueSizeInBits() == 1 &&
5613          "Can not convert non-constant vector");
5614   uint64_t Immediate = 0;
5615   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5616     SDValue In = Op.getOperand(idx);
5617     if (In.getOpcode() != ISD::UNDEF)
5618       Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5619   }
5620   SDLoc dl(Op);
5621   MVT VT =
5622    MVT::getIntegerVT(std::max((int)Op.getValueType().getSizeInBits(), 8));
5623   return DAG.getConstant(Immediate, dl, VT);
5624 }
5625 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5626 SDValue
5627 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5628
5629   MVT VT = Op.getSimpleValueType();
5630   assert((VT.getVectorElementType() == MVT::i1) &&
5631          "Unexpected type in LowerBUILD_VECTORvXi1!");
5632
5633   SDLoc dl(Op);
5634   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5635     SDValue Cst = DAG.getTargetConstant(0, dl, MVT::i1);
5636     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5637     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5638   }
5639
5640   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5641     SDValue Cst = DAG.getTargetConstant(1, dl, MVT::i1);
5642     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5643     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5644   }
5645
5646   if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
5647     SDValue Imm = ConvertI1VectorToInteger(Op, DAG);
5648     if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5649       return DAG.getBitcast(VT, Imm);
5650     SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5651     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5652                         DAG.getIntPtrConstant(0, dl));
5653   }
5654
5655   // Vector has one or more non-const elements
5656   uint64_t Immediate = 0;
5657   SmallVector<unsigned, 16> NonConstIdx;
5658   bool IsSplat = true;
5659   bool HasConstElts = false;
5660   int SplatIdx = -1;
5661   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5662     SDValue In = Op.getOperand(idx);
5663     if (In.getOpcode() == ISD::UNDEF)
5664       continue;
5665     if (!isa<ConstantSDNode>(In))
5666       NonConstIdx.push_back(idx);
5667     else {
5668       Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5669       HasConstElts = true;
5670     }
5671     if (SplatIdx == -1)
5672       SplatIdx = idx;
5673     else if (In != Op.getOperand(SplatIdx))
5674       IsSplat = false;
5675   }
5676
5677   // for splat use " (select i1 splat_elt, all-ones, all-zeroes)"
5678   if (IsSplat)
5679     return DAG.getNode(ISD::SELECT, dl, VT, Op.getOperand(SplatIdx),
5680                        DAG.getConstant(1, dl, VT),
5681                        DAG.getConstant(0, dl, VT));
5682
5683   // insert elements one by one
5684   SDValue DstVec;
5685   SDValue Imm;
5686   if (Immediate) {
5687     MVT ImmVT = MVT::getIntegerVT(std::max((int)VT.getSizeInBits(), 8));
5688     Imm = DAG.getConstant(Immediate, dl, ImmVT);
5689   }
5690   else if (HasConstElts)
5691     Imm = DAG.getConstant(0, dl, VT);
5692   else
5693     Imm = DAG.getUNDEF(VT);
5694   if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5695     DstVec = DAG.getBitcast(VT, Imm);
5696   else {
5697     SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5698     DstVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5699                          DAG.getIntPtrConstant(0, dl));
5700   }
5701
5702   for (unsigned i = 0; i < NonConstIdx.size(); ++i) {
5703     unsigned InsertIdx = NonConstIdx[i];
5704     DstVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5705                          Op.getOperand(InsertIdx),
5706                          DAG.getIntPtrConstant(InsertIdx, dl));
5707   }
5708   return DstVec;
5709 }
5710
5711 /// \brief Return true if \p N implements a horizontal binop and return the
5712 /// operands for the horizontal binop into V0 and V1.
5713 ///
5714 /// This is a helper function of LowerToHorizontalOp().
5715 /// This function checks that the build_vector \p N in input implements a
5716 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
5717 /// operation to match.
5718 /// For example, if \p Opcode is equal to ISD::ADD, then this function
5719 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
5720 /// is equal to ISD::SUB, then this function checks if this is a horizontal
5721 /// arithmetic sub.
5722 ///
5723 /// This function only analyzes elements of \p N whose indices are
5724 /// in range [BaseIdx, LastIdx).
5725 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
5726                               SelectionDAG &DAG,
5727                               unsigned BaseIdx, unsigned LastIdx,
5728                               SDValue &V0, SDValue &V1) {
5729   EVT VT = N->getValueType(0);
5730
5731   assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
5732   assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
5733          "Invalid Vector in input!");
5734
5735   bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
5736   bool CanFold = true;
5737   unsigned ExpectedVExtractIdx = BaseIdx;
5738   unsigned NumElts = LastIdx - BaseIdx;
5739   V0 = DAG.getUNDEF(VT);
5740   V1 = DAG.getUNDEF(VT);
5741
5742   // Check if N implements a horizontal binop.
5743   for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
5744     SDValue Op = N->getOperand(i + BaseIdx);
5745
5746     // Skip UNDEFs.
5747     if (Op->getOpcode() == ISD::UNDEF) {
5748       // Update the expected vector extract index.
5749       if (i * 2 == NumElts)
5750         ExpectedVExtractIdx = BaseIdx;
5751       ExpectedVExtractIdx += 2;
5752       continue;
5753     }
5754
5755     CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
5756
5757     if (!CanFold)
5758       break;
5759
5760     SDValue Op0 = Op.getOperand(0);
5761     SDValue Op1 = Op.getOperand(1);
5762
5763     // Try to match the following pattern:
5764     // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
5765     CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5766         Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5767         Op0.getOperand(0) == Op1.getOperand(0) &&
5768         isa<ConstantSDNode>(Op0.getOperand(1)) &&
5769         isa<ConstantSDNode>(Op1.getOperand(1)));
5770     if (!CanFold)
5771       break;
5772
5773     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5774     unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
5775
5776     if (i * 2 < NumElts) {
5777       if (V0.getOpcode() == ISD::UNDEF) {
5778         V0 = Op0.getOperand(0);
5779         if (V0.getValueType() != VT)
5780           return false;
5781       }
5782     } else {
5783       if (V1.getOpcode() == ISD::UNDEF) {
5784         V1 = Op0.getOperand(0);
5785         if (V1.getValueType() != VT)
5786           return false;
5787       }
5788       if (i * 2 == NumElts)
5789         ExpectedVExtractIdx = BaseIdx;
5790     }
5791
5792     SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
5793     if (I0 == ExpectedVExtractIdx)
5794       CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
5795     else if (IsCommutable && I1 == ExpectedVExtractIdx) {
5796       // Try to match the following dag sequence:
5797       // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
5798       CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
5799     } else
5800       CanFold = false;
5801
5802     ExpectedVExtractIdx += 2;
5803   }
5804
5805   return CanFold;
5806 }
5807
5808 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
5809 /// a concat_vector.
5810 ///
5811 /// This is a helper function of LowerToHorizontalOp().
5812 /// This function expects two 256-bit vectors called V0 and V1.
5813 /// At first, each vector is split into two separate 128-bit vectors.
5814 /// Then, the resulting 128-bit vectors are used to implement two
5815 /// horizontal binary operations.
5816 ///
5817 /// The kind of horizontal binary operation is defined by \p X86Opcode.
5818 ///
5819 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
5820 /// the two new horizontal binop.
5821 /// When Mode is set, the first horizontal binop dag node would take as input
5822 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
5823 /// horizontal binop dag node would take as input the lower 128-bit of V1
5824 /// and the upper 128-bit of V1.
5825 ///   Example:
5826 ///     HADD V0_LO, V0_HI
5827 ///     HADD V1_LO, V1_HI
5828 ///
5829 /// Otherwise, the first horizontal binop dag node takes as input the lower
5830 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
5831 /// dag node takes the upper 128-bit of V0 and the upper 128-bit of V1.
5832 ///   Example:
5833 ///     HADD V0_LO, V1_LO
5834 ///     HADD V0_HI, V1_HI
5835 ///
5836 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
5837 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
5838 /// the upper 128-bits of the result.
5839 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
5840                                      SDLoc DL, SelectionDAG &DAG,
5841                                      unsigned X86Opcode, bool Mode,
5842                                      bool isUndefLO, bool isUndefHI) {
5843   EVT VT = V0.getValueType();
5844   assert(VT.is256BitVector() && VT == V1.getValueType() &&
5845          "Invalid nodes in input!");
5846
5847   unsigned NumElts = VT.getVectorNumElements();
5848   SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
5849   SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
5850   SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
5851   SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
5852   EVT NewVT = V0_LO.getValueType();
5853
5854   SDValue LO = DAG.getUNDEF(NewVT);
5855   SDValue HI = DAG.getUNDEF(NewVT);
5856
5857   if (Mode) {
5858     // Don't emit a horizontal binop if the result is expected to be UNDEF.
5859     if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
5860       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
5861     if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
5862       HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
5863   } else {
5864     // Don't emit a horizontal binop if the result is expected to be UNDEF.
5865     if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
5866                        V1_LO->getOpcode() != ISD::UNDEF))
5867       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
5868
5869     if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
5870                        V1_HI->getOpcode() != ISD::UNDEF))
5871       HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
5872   }
5873
5874   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
5875 }
5876
5877 /// Try to fold a build_vector that performs an 'addsub' to an X86ISD::ADDSUB
5878 /// node.
5879 static SDValue LowerToAddSub(const BuildVectorSDNode *BV,
5880                              const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5881   MVT VT = BV->getSimpleValueType(0);
5882   if ((!Subtarget->hasSSE3() || (VT != MVT::v4f32 && VT != MVT::v2f64)) &&
5883       (!Subtarget->hasAVX() || (VT != MVT::v8f32 && VT != MVT::v4f64)))
5884     return SDValue();
5885
5886   SDLoc DL(BV);
5887   unsigned NumElts = VT.getVectorNumElements();
5888   SDValue InVec0 = DAG.getUNDEF(VT);
5889   SDValue InVec1 = DAG.getUNDEF(VT);
5890
5891   assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
5892           VT == MVT::v2f64) && "build_vector with an invalid type found!");
5893
5894   // Odd-numbered elements in the input build vector are obtained from
5895   // adding two integer/float elements.
5896   // Even-numbered elements in the input build vector are obtained from
5897   // subtracting two integer/float elements.
5898   unsigned ExpectedOpcode = ISD::FSUB;
5899   unsigned NextExpectedOpcode = ISD::FADD;
5900   bool AddFound = false;
5901   bool SubFound = false;
5902
5903   for (unsigned i = 0, e = NumElts; i != e; ++i) {
5904     SDValue Op = BV->getOperand(i);
5905
5906     // Skip 'undef' values.
5907     unsigned Opcode = Op.getOpcode();
5908     if (Opcode == ISD::UNDEF) {
5909       std::swap(ExpectedOpcode, NextExpectedOpcode);
5910       continue;
5911     }
5912
5913     // Early exit if we found an unexpected opcode.
5914     if (Opcode != ExpectedOpcode)
5915       return SDValue();
5916
5917     SDValue Op0 = Op.getOperand(0);
5918     SDValue Op1 = Op.getOperand(1);
5919
5920     // Try to match the following pattern:
5921     // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
5922     // Early exit if we cannot match that sequence.
5923     if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5924         Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5925         !isa<ConstantSDNode>(Op0.getOperand(1)) ||
5926         !isa<ConstantSDNode>(Op1.getOperand(1)) ||
5927         Op0.getOperand(1) != Op1.getOperand(1))
5928       return SDValue();
5929
5930     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5931     if (I0 != i)
5932       return SDValue();
5933
5934     // We found a valid add/sub node. Update the information accordingly.
5935     if (i & 1)
5936       AddFound = true;
5937     else
5938       SubFound = true;
5939
5940     // Update InVec0 and InVec1.
5941     if (InVec0.getOpcode() == ISD::UNDEF) {
5942       InVec0 = Op0.getOperand(0);
5943       if (InVec0.getSimpleValueType() != VT)
5944         return SDValue();
5945     }
5946     if (InVec1.getOpcode() == ISD::UNDEF) {
5947       InVec1 = Op1.getOperand(0);
5948       if (InVec1.getSimpleValueType() != VT)
5949         return SDValue();
5950     }
5951
5952     // Make sure that operands in input to each add/sub node always
5953     // come from a same pair of vectors.
5954     if (InVec0 != Op0.getOperand(0)) {
5955       if (ExpectedOpcode == ISD::FSUB)
5956         return SDValue();
5957
5958       // FADD is commutable. Try to commute the operands
5959       // and then test again.
5960       std::swap(Op0, Op1);
5961       if (InVec0 != Op0.getOperand(0))
5962         return SDValue();
5963     }
5964
5965     if (InVec1 != Op1.getOperand(0))
5966       return SDValue();
5967
5968     // Update the pair of expected opcodes.
5969     std::swap(ExpectedOpcode, NextExpectedOpcode);
5970   }
5971
5972   // Don't try to fold this build_vector into an ADDSUB if the inputs are undef.
5973   if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
5974       InVec1.getOpcode() != ISD::UNDEF)
5975     return DAG.getNode(X86ISD::ADDSUB, DL, VT, InVec0, InVec1);
5976
5977   return SDValue();
5978 }
5979
5980 /// Lower BUILD_VECTOR to a horizontal add/sub operation if possible.
5981 static SDValue LowerToHorizontalOp(const BuildVectorSDNode *BV,
5982                                    const X86Subtarget *Subtarget,
5983                                    SelectionDAG &DAG) {
5984   MVT VT = BV->getSimpleValueType(0);
5985   unsigned NumElts = VT.getVectorNumElements();
5986   unsigned NumUndefsLO = 0;
5987   unsigned NumUndefsHI = 0;
5988   unsigned Half = NumElts/2;
5989
5990   // Count the number of UNDEF operands in the build_vector in input.
5991   for (unsigned i = 0, e = Half; i != e; ++i)
5992     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5993       NumUndefsLO++;
5994
5995   for (unsigned i = Half, e = NumElts; i != e; ++i)
5996     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5997       NumUndefsHI++;
5998
5999   // Early exit if this is either a build_vector of all UNDEFs or all the
6000   // operands but one are UNDEF.
6001   if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
6002     return SDValue();
6003
6004   SDLoc DL(BV);
6005   SDValue InVec0, InVec1;
6006   if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
6007     // Try to match an SSE3 float HADD/HSUB.
6008     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6009       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6010
6011     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6012       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6013   } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
6014     // Try to match an SSSE3 integer HADD/HSUB.
6015     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6016       return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
6017
6018     if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6019       return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
6020   }
6021
6022   if (!Subtarget->hasAVX())
6023     return SDValue();
6024
6025   if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
6026     // Try to match an AVX horizontal add/sub of packed single/double
6027     // precision floating point values from 256-bit vectors.
6028     SDValue InVec2, InVec3;
6029     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
6030         isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
6031         ((InVec0.getOpcode() == ISD::UNDEF ||
6032           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6033         ((InVec1.getOpcode() == ISD::UNDEF ||
6034           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6035       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6036
6037     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
6038         isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
6039         ((InVec0.getOpcode() == ISD::UNDEF ||
6040           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6041         ((InVec1.getOpcode() == ISD::UNDEF ||
6042           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6043       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6044   } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
6045     // Try to match an AVX2 horizontal add/sub of signed integers.
6046     SDValue InVec2, InVec3;
6047     unsigned X86Opcode;
6048     bool CanFold = true;
6049
6050     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
6051         isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
6052         ((InVec0.getOpcode() == ISD::UNDEF ||
6053           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6054         ((InVec1.getOpcode() == ISD::UNDEF ||
6055           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6056       X86Opcode = X86ISD::HADD;
6057     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
6058         isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
6059         ((InVec0.getOpcode() == ISD::UNDEF ||
6060           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6061         ((InVec1.getOpcode() == ISD::UNDEF ||
6062           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6063       X86Opcode = X86ISD::HSUB;
6064     else
6065       CanFold = false;
6066
6067     if (CanFold) {
6068       // Fold this build_vector into a single horizontal add/sub.
6069       // Do this only if the target has AVX2.
6070       if (Subtarget->hasAVX2())
6071         return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
6072
6073       // Do not try to expand this build_vector into a pair of horizontal
6074       // add/sub if we can emit a pair of scalar add/sub.
6075       if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6076         return SDValue();
6077
6078       // Convert this build_vector into a pair of horizontal binop followed by
6079       // a concat vector.
6080       bool isUndefLO = NumUndefsLO == Half;
6081       bool isUndefHI = NumUndefsHI == Half;
6082       return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
6083                                    isUndefLO, isUndefHI);
6084     }
6085   }
6086
6087   if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
6088        VT == MVT::v16i16) && Subtarget->hasAVX()) {
6089     unsigned X86Opcode;
6090     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6091       X86Opcode = X86ISD::HADD;
6092     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6093       X86Opcode = X86ISD::HSUB;
6094     else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6095       X86Opcode = X86ISD::FHADD;
6096     else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6097       X86Opcode = X86ISD::FHSUB;
6098     else
6099       return SDValue();
6100
6101     // Don't try to expand this build_vector into a pair of horizontal add/sub
6102     // if we can simply emit a pair of scalar add/sub.
6103     if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6104       return SDValue();
6105
6106     // Convert this build_vector into two horizontal add/sub followed by
6107     // a concat vector.
6108     bool isUndefLO = NumUndefsLO == Half;
6109     bool isUndefHI = NumUndefsHI == Half;
6110     return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
6111                                  isUndefLO, isUndefHI);
6112   }
6113
6114   return SDValue();
6115 }
6116
6117 SDValue
6118 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6119   SDLoc dl(Op);
6120
6121   MVT VT = Op.getSimpleValueType();
6122   MVT ExtVT = VT.getVectorElementType();
6123   unsigned NumElems = Op.getNumOperands();
6124
6125   // Generate vectors for predicate vectors.
6126   if (VT.getVectorElementType() == MVT::i1 && Subtarget->hasAVX512())
6127     return LowerBUILD_VECTORvXi1(Op, DAG);
6128
6129   // Vectors containing all zeros can be matched by pxor and xorps later
6130   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6131     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
6132     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
6133     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
6134       return Op;
6135
6136     return getZeroVector(VT, Subtarget, DAG, dl);
6137   }
6138
6139   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
6140   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
6141   // vpcmpeqd on 256-bit vectors.
6142   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
6143     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
6144       return Op;
6145
6146     if (!VT.is512BitVector())
6147       return getOnesVector(VT, Subtarget, DAG, dl);
6148   }
6149
6150   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(Op.getNode());
6151   if (SDValue AddSub = LowerToAddSub(BV, Subtarget, DAG))
6152     return AddSub;
6153   if (SDValue HorizontalOp = LowerToHorizontalOp(BV, Subtarget, DAG))
6154     return HorizontalOp;
6155   if (SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG))
6156     return Broadcast;
6157
6158   unsigned EVTBits = ExtVT.getSizeInBits();
6159
6160   unsigned NumZero  = 0;
6161   unsigned NumNonZero = 0;
6162   unsigned NonZeros = 0;
6163   bool IsAllConstants = true;
6164   SmallSet<SDValue, 8> Values;
6165   for (unsigned i = 0; i < NumElems; ++i) {
6166     SDValue Elt = Op.getOperand(i);
6167     if (Elt.getOpcode() == ISD::UNDEF)
6168       continue;
6169     Values.insert(Elt);
6170     if (Elt.getOpcode() != ISD::Constant &&
6171         Elt.getOpcode() != ISD::ConstantFP)
6172       IsAllConstants = false;
6173     if (X86::isZeroNode(Elt))
6174       NumZero++;
6175     else {
6176       NonZeros |= (1 << i);
6177       NumNonZero++;
6178     }
6179   }
6180
6181   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
6182   if (NumNonZero == 0)
6183     return DAG.getUNDEF(VT);
6184
6185   // Special case for single non-zero, non-undef, element.
6186   if (NumNonZero == 1) {
6187     unsigned Idx = countTrailingZeros(NonZeros);
6188     SDValue Item = Op.getOperand(Idx);
6189
6190     // If this is an insertion of an i64 value on x86-32, and if the top bits of
6191     // the value are obviously zero, truncate the value to i32 and do the
6192     // insertion that way.  Only do this if the value is non-constant or if the
6193     // value is a constant being inserted into element 0.  It is cheaper to do
6194     // a constant pool load than it is to do a movd + shuffle.
6195     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
6196         (!IsAllConstants || Idx == 0)) {
6197       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
6198         // Handle SSE only.
6199         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
6200         MVT VecVT = MVT::v4i32;
6201
6202         // Truncate the value (which may itself be a constant) to i32, and
6203         // convert it to a vector with movd (S2V+shuffle to zero extend).
6204         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6205         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6206         return DAG.getBitcast(VT, getShuffleVectorZeroOrUndef(
6207                                       Item, Idx * 2, true, Subtarget, DAG));
6208       }
6209     }
6210
6211     // If we have a constant or non-constant insertion into the low element of
6212     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6213     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
6214     // depending on what the source datatype is.
6215     if (Idx == 0) {
6216       if (NumZero == 0)
6217         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6218
6219       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6220           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6221         if (VT.is512BitVector()) {
6222           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6223           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6224                              Item, DAG.getIntPtrConstant(0, dl));
6225         }
6226         assert((VT.is128BitVector() || VT.is256BitVector()) &&
6227                "Expected an SSE value type!");
6228         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6229         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6230         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6231       }
6232
6233       // We can't directly insert an i8 or i16 into a vector, so zero extend
6234       // it to i32 first.
6235       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6236         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6237         if (VT.is256BitVector()) {
6238           if (Subtarget->hasAVX()) {
6239             Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v8i32, Item);
6240             Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6241           } else {
6242             // Without AVX, we need to extend to a 128-bit vector and then
6243             // insert into the 256-bit vector.
6244             Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6245             SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6246             Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6247           }
6248         } else {
6249           assert(VT.is128BitVector() && "Expected an SSE value type!");
6250           Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6251           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6252         }
6253         return DAG.getBitcast(VT, Item);
6254       }
6255     }
6256
6257     // Is it a vector logical left shift?
6258     if (NumElems == 2 && Idx == 1 &&
6259         X86::isZeroNode(Op.getOperand(0)) &&
6260         !X86::isZeroNode(Op.getOperand(1))) {
6261       unsigned NumBits = VT.getSizeInBits();
6262       return getVShift(true, VT,
6263                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6264                                    VT, Op.getOperand(1)),
6265                        NumBits/2, DAG, *this, dl);
6266     }
6267
6268     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6269       return SDValue();
6270
6271     // Otherwise, if this is a vector with i32 or f32 elements, and the element
6272     // is a non-constant being inserted into an element other than the low one,
6273     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
6274     // movd/movss) to move this into the low element, then shuffle it into
6275     // place.
6276     if (EVTBits == 32) {
6277       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6278       return getShuffleVectorZeroOrUndef(Item, Idx, NumZero > 0, Subtarget, DAG);
6279     }
6280   }
6281
6282   // Splat is obviously ok. Let legalizer expand it to a shuffle.
6283   if (Values.size() == 1) {
6284     if (EVTBits == 32) {
6285       // Instead of a shuffle like this:
6286       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6287       // Check if it's possible to issue this instead.
6288       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6289       unsigned Idx = countTrailingZeros(NonZeros);
6290       SDValue Item = Op.getOperand(Idx);
6291       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6292         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6293     }
6294     return SDValue();
6295   }
6296
6297   // A vector full of immediates; various special cases are already
6298   // handled, so this is best done with a single constant-pool load.
6299   if (IsAllConstants)
6300     return SDValue();
6301
6302   // For AVX-length vectors, see if we can use a vector load to get all of the
6303   // elements, otherwise build the individual 128-bit pieces and use
6304   // shuffles to put them in place.
6305   if (VT.is256BitVector() || VT.is512BitVector()) {
6306     SmallVector<SDValue, 64> V(Op->op_begin(), Op->op_begin() + NumElems);
6307
6308     // Check for a build vector of consecutive loads.
6309     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6310       return LD;
6311
6312     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6313
6314     // Build both the lower and upper subvector.
6315     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6316                                 makeArrayRef(&V[0], NumElems/2));
6317     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6318                                 makeArrayRef(&V[NumElems / 2], NumElems/2));
6319
6320     // Recreate the wider vector with the lower and upper part.
6321     if (VT.is256BitVector())
6322       return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6323     return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6324   }
6325
6326   // Let legalizer expand 2-wide build_vectors.
6327   if (EVTBits == 64) {
6328     if (NumNonZero == 1) {
6329       // One half is zero or undef.
6330       unsigned Idx = countTrailingZeros(NonZeros);
6331       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6332                                  Op.getOperand(Idx));
6333       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6334     }
6335     return SDValue();
6336   }
6337
6338   // If element VT is < 32 bits, convert it to inserts into a zero vector.
6339   if (EVTBits == 8 && NumElems == 16)
6340     if (SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6341                                         Subtarget, *this))
6342       return V;
6343
6344   if (EVTBits == 16 && NumElems == 8)
6345     if (SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6346                                       Subtarget, *this))
6347       return V;
6348
6349   // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6350   if (EVTBits == 32 && NumElems == 4)
6351     if (SDValue V = LowerBuildVectorv4x32(Op, DAG, Subtarget, *this))
6352       return V;
6353
6354   // If element VT is == 32 bits, turn it into a number of shuffles.
6355   SmallVector<SDValue, 8> V(NumElems);
6356   if (NumElems == 4 && NumZero > 0) {
6357     for (unsigned i = 0; i < 4; ++i) {
6358       bool isZero = !(NonZeros & (1 << i));
6359       if (isZero)
6360         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6361       else
6362         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6363     }
6364
6365     for (unsigned i = 0; i < 2; ++i) {
6366       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6367         default: break;
6368         case 0:
6369           V[i] = V[i*2];  // Must be a zero vector.
6370           break;
6371         case 1:
6372           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6373           break;
6374         case 2:
6375           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6376           break;
6377         case 3:
6378           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6379           break;
6380       }
6381     }
6382
6383     bool Reverse1 = (NonZeros & 0x3) == 2;
6384     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6385     int MaskVec[] = {
6386       Reverse1 ? 1 : 0,
6387       Reverse1 ? 0 : 1,
6388       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6389       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
6390     };
6391     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6392   }
6393
6394   if (Values.size() > 1 && VT.is128BitVector()) {
6395     // Check for a build vector of consecutive loads.
6396     for (unsigned i = 0; i < NumElems; ++i)
6397       V[i] = Op.getOperand(i);
6398
6399     // Check for elements which are consecutive loads.
6400     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6401       return LD;
6402
6403     // Check for a build vector from mostly shuffle plus few inserting.
6404     if (SDValue Sh = buildFromShuffleMostly(Op, DAG))
6405       return Sh;
6406
6407     // For SSE 4.1, use insertps to put the high elements into the low element.
6408     if (Subtarget->hasSSE41()) {
6409       SDValue Result;
6410       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6411         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6412       else
6413         Result = DAG.getUNDEF(VT);
6414
6415       for (unsigned i = 1; i < NumElems; ++i) {
6416         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6417         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6418                              Op.getOperand(i), DAG.getIntPtrConstant(i, dl));
6419       }
6420       return Result;
6421     }
6422
6423     // Otherwise, expand into a number of unpckl*, start by extending each of
6424     // our (non-undef) elements to the full vector width with the element in the
6425     // bottom slot of the vector (which generates no code for SSE).
6426     for (unsigned i = 0; i < NumElems; ++i) {
6427       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6428         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6429       else
6430         V[i] = DAG.getUNDEF(VT);
6431     }
6432
6433     // Next, we iteratively mix elements, e.g. for v4f32:
6434     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6435     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6436     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
6437     unsigned EltStride = NumElems >> 1;
6438     while (EltStride != 0) {
6439       for (unsigned i = 0; i < EltStride; ++i) {
6440         // If V[i+EltStride] is undef and this is the first round of mixing,
6441         // then it is safe to just drop this shuffle: V[i] is already in the
6442         // right place, the one element (since it's the first round) being
6443         // inserted as undef can be dropped.  This isn't safe for successive
6444         // rounds because they will permute elements within both vectors.
6445         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6446             EltStride == NumElems/2)
6447           continue;
6448
6449         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6450       }
6451       EltStride >>= 1;
6452     }
6453     return V[0];
6454   }
6455   return SDValue();
6456 }
6457
6458 // 256-bit AVX can use the vinsertf128 instruction
6459 // to create 256-bit vectors from two other 128-bit ones.
6460 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6461   SDLoc dl(Op);
6462   MVT ResVT = Op.getSimpleValueType();
6463
6464   assert((ResVT.is256BitVector() ||
6465           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6466
6467   SDValue V1 = Op.getOperand(0);
6468   SDValue V2 = Op.getOperand(1);
6469   unsigned NumElems = ResVT.getVectorNumElements();
6470   if (ResVT.is256BitVector())
6471     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6472
6473   if (Op.getNumOperands() == 4) {
6474     MVT HalfVT = MVT::getVectorVT(ResVT.getVectorElementType(),
6475                                   ResVT.getVectorNumElements()/2);
6476     SDValue V3 = Op.getOperand(2);
6477     SDValue V4 = Op.getOperand(3);
6478     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6479       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6480   }
6481   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6482 }
6483
6484 static SDValue LowerCONCAT_VECTORSvXi1(SDValue Op,
6485                                        const X86Subtarget *Subtarget,
6486                                        SelectionDAG & DAG) {
6487   SDLoc dl(Op);
6488   MVT ResVT = Op.getSimpleValueType();
6489   unsigned NumOfOperands = Op.getNumOperands();
6490
6491   assert(isPowerOf2_32(NumOfOperands) &&
6492          "Unexpected number of operands in CONCAT_VECTORS");
6493
6494   if (NumOfOperands > 2) {
6495     MVT HalfVT = MVT::getVectorVT(ResVT.getVectorElementType(),
6496                                   ResVT.getVectorNumElements()/2);
6497     SmallVector<SDValue, 2> Ops;
6498     for (unsigned i = 0; i < NumOfOperands/2; i++)
6499       Ops.push_back(Op.getOperand(i));
6500     SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6501     Ops.clear();
6502     for (unsigned i = NumOfOperands/2; i < NumOfOperands; i++)
6503       Ops.push_back(Op.getOperand(i));
6504     SDValue Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6505     return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Lo, Hi);
6506   }
6507
6508   SDValue V1 = Op.getOperand(0);
6509   SDValue V2 = Op.getOperand(1);
6510   bool IsZeroV1 = ISD::isBuildVectorAllZeros(V1.getNode());
6511   bool IsZeroV2 = ISD::isBuildVectorAllZeros(V2.getNode());
6512
6513   if (IsZeroV1 && IsZeroV2)
6514     return getZeroVector(ResVT, Subtarget, DAG, dl);
6515
6516   SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
6517   SDValue Undef = DAG.getUNDEF(ResVT);
6518   unsigned NumElems = ResVT.getVectorNumElements();
6519   SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
6520
6521   V2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V2, ZeroIdx);
6522   V2 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V2, ShiftBits);
6523   if (IsZeroV1)
6524     return V2;
6525
6526   V1 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V1, ZeroIdx);
6527   // Zero the upper bits of V1
6528   V1 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V1, ShiftBits);
6529   V1 = DAG.getNode(X86ISD::VSRLI, dl, ResVT, V1, ShiftBits);
6530   if (IsZeroV2)
6531     return V1;
6532   return DAG.getNode(ISD::OR, dl, ResVT, V1, V2);
6533 }
6534
6535 static SDValue LowerCONCAT_VECTORS(SDValue Op,
6536                                    const X86Subtarget *Subtarget,
6537                                    SelectionDAG &DAG) {
6538   MVT VT = Op.getSimpleValueType();
6539   if (VT.getVectorElementType() == MVT::i1)
6540     return LowerCONCAT_VECTORSvXi1(Op, Subtarget, DAG);
6541
6542   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6543          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6544           Op.getNumOperands() == 4)));
6545
6546   // AVX can use the vinsertf128 instruction to create 256-bit vectors
6547   // from two other 128-bit ones.
6548
6549   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6550   return LowerAVXCONCAT_VECTORS(Op, DAG);
6551 }
6552
6553 //===----------------------------------------------------------------------===//
6554 // Vector shuffle lowering
6555 //
6556 // This is an experimental code path for lowering vector shuffles on x86. It is
6557 // designed to handle arbitrary vector shuffles and blends, gracefully
6558 // degrading performance as necessary. It works hard to recognize idiomatic
6559 // shuffles and lower them to optimal instruction patterns without leaving
6560 // a framework that allows reasonably efficient handling of all vector shuffle
6561 // patterns.
6562 //===----------------------------------------------------------------------===//
6563
6564 /// \brief Tiny helper function to identify a no-op mask.
6565 ///
6566 /// This is a somewhat boring predicate function. It checks whether the mask
6567 /// array input, which is assumed to be a single-input shuffle mask of the kind
6568 /// used by the X86 shuffle instructions (not a fully general
6569 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
6570 /// in-place shuffle are 'no-op's.
6571 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
6572   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6573     if (Mask[i] != -1 && Mask[i] != i)
6574       return false;
6575   return true;
6576 }
6577
6578 /// \brief Helper function to classify a mask as a single-input mask.
6579 ///
6580 /// This isn't a generic single-input test because in the vector shuffle
6581 /// lowering we canonicalize single inputs to be the first input operand. This
6582 /// means we can more quickly test for a single input by only checking whether
6583 /// an input from the second operand exists. We also assume that the size of
6584 /// mask corresponds to the size of the input vectors which isn't true in the
6585 /// fully general case.
6586 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
6587   for (int M : Mask)
6588     if (M >= (int)Mask.size())
6589       return false;
6590   return true;
6591 }
6592
6593 /// \brief Test whether there are elements crossing 128-bit lanes in this
6594 /// shuffle mask.
6595 ///
6596 /// X86 divides up its shuffles into in-lane and cross-lane shuffle operations
6597 /// and we routinely test for these.
6598 static bool is128BitLaneCrossingShuffleMask(MVT VT, ArrayRef<int> Mask) {
6599   int LaneSize = 128 / VT.getScalarSizeInBits();
6600   int Size = Mask.size();
6601   for (int i = 0; i < Size; ++i)
6602     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
6603       return true;
6604   return false;
6605 }
6606
6607 /// \brief Test whether a shuffle mask is equivalent within each 128-bit lane.
6608 ///
6609 /// This checks a shuffle mask to see if it is performing the same
6610 /// 128-bit lane-relative shuffle in each 128-bit lane. This trivially implies
6611 /// that it is also not lane-crossing. It may however involve a blend from the
6612 /// same lane of a second vector.
6613 ///
6614 /// The specific repeated shuffle mask is populated in \p RepeatedMask, as it is
6615 /// non-trivial to compute in the face of undef lanes. The representation is
6616 /// *not* suitable for use with existing 128-bit shuffles as it will contain
6617 /// entries from both V1 and V2 inputs to the wider mask.
6618 static bool
6619 is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
6620                                 SmallVectorImpl<int> &RepeatedMask) {
6621   int LaneSize = 128 / VT.getScalarSizeInBits();
6622   RepeatedMask.resize(LaneSize, -1);
6623   int Size = Mask.size();
6624   for (int i = 0; i < Size; ++i) {
6625     if (Mask[i] < 0)
6626       continue;
6627     if ((Mask[i] % Size) / LaneSize != i / LaneSize)
6628       // This entry crosses lanes, so there is no way to model this shuffle.
6629       return false;
6630
6631     // Ok, handle the in-lane shuffles by detecting if and when they repeat.
6632     if (RepeatedMask[i % LaneSize] == -1)
6633       // This is the first non-undef entry in this slot of a 128-bit lane.
6634       RepeatedMask[i % LaneSize] =
6635           Mask[i] < Size ? Mask[i] % LaneSize : Mask[i] % LaneSize + Size;
6636     else if (RepeatedMask[i % LaneSize] + (i / LaneSize) * LaneSize != Mask[i])
6637       // Found a mismatch with the repeated mask.
6638       return false;
6639   }
6640   return true;
6641 }
6642
6643 /// \brief Checks whether a shuffle mask is equivalent to an explicit list of
6644 /// arguments.
6645 ///
6646 /// This is a fast way to test a shuffle mask against a fixed pattern:
6647 ///
6648 ///   if (isShuffleEquivalent(Mask, 3, 2, {1, 0})) { ... }
6649 ///
6650 /// It returns true if the mask is exactly as wide as the argument list, and
6651 /// each element of the mask is either -1 (signifying undef) or the value given
6652 /// in the argument.
6653 static bool isShuffleEquivalent(SDValue V1, SDValue V2, ArrayRef<int> Mask,
6654                                 ArrayRef<int> ExpectedMask) {
6655   if (Mask.size() != ExpectedMask.size())
6656     return false;
6657
6658   int Size = Mask.size();
6659
6660   // If the values are build vectors, we can look through them to find
6661   // equivalent inputs that make the shuffles equivalent.
6662   auto *BV1 = dyn_cast<BuildVectorSDNode>(V1);
6663   auto *BV2 = dyn_cast<BuildVectorSDNode>(V2);
6664
6665   for (int i = 0; i < Size; ++i)
6666     if (Mask[i] != -1 && Mask[i] != ExpectedMask[i]) {
6667       auto *MaskBV = Mask[i] < Size ? BV1 : BV2;
6668       auto *ExpectedBV = ExpectedMask[i] < Size ? BV1 : BV2;
6669       if (!MaskBV || !ExpectedBV ||
6670           MaskBV->getOperand(Mask[i] % Size) !=
6671               ExpectedBV->getOperand(ExpectedMask[i] % Size))
6672         return false;
6673     }
6674
6675   return true;
6676 }
6677
6678 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
6679 ///
6680 /// This helper function produces an 8-bit shuffle immediate corresponding to
6681 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
6682 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
6683 /// example.
6684 ///
6685 /// NB: We rely heavily on "undef" masks preserving the input lane.
6686 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask, SDLoc DL,
6687                                           SelectionDAG &DAG) {
6688   assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
6689   assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
6690   assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
6691   assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
6692   assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
6693
6694   unsigned Imm = 0;
6695   Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
6696   Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
6697   Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
6698   Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
6699   return DAG.getConstant(Imm, DL, MVT::i8);
6700 }
6701
6702 /// \brief Compute whether each element of a shuffle is zeroable.
6703 ///
6704 /// A "zeroable" vector shuffle element is one which can be lowered to zero.
6705 /// Either it is an undef element in the shuffle mask, the element of the input
6706 /// referenced is undef, or the element of the input referenced is known to be
6707 /// zero. Many x86 shuffles can zero lanes cheaply and we often want to handle
6708 /// as many lanes with this technique as possible to simplify the remaining
6709 /// shuffle.
6710 static SmallBitVector computeZeroableShuffleElements(ArrayRef<int> Mask,
6711                                                      SDValue V1, SDValue V2) {
6712   SmallBitVector Zeroable(Mask.size(), false);
6713
6714   while (V1.getOpcode() == ISD::BITCAST)
6715     V1 = V1->getOperand(0);
6716   while (V2.getOpcode() == ISD::BITCAST)
6717     V2 = V2->getOperand(0);
6718
6719   bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
6720   bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
6721
6722   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6723     int M = Mask[i];
6724     // Handle the easy cases.
6725     if (M < 0 || (M >= 0 && M < Size && V1IsZero) || (M >= Size && V2IsZero)) {
6726       Zeroable[i] = true;
6727       continue;
6728     }
6729
6730     // If this is an index into a build_vector node (which has the same number
6731     // of elements), dig out the input value and use it.
6732     SDValue V = M < Size ? V1 : V2;
6733     if (V.getOpcode() != ISD::BUILD_VECTOR || Size != (int)V.getNumOperands())
6734       continue;
6735
6736     SDValue Input = V.getOperand(M % Size);
6737     // The UNDEF opcode check really should be dead code here, but not quite
6738     // worth asserting on (it isn't invalid, just unexpected).
6739     if (Input.getOpcode() == ISD::UNDEF || X86::isZeroNode(Input))
6740       Zeroable[i] = true;
6741   }
6742
6743   return Zeroable;
6744 }
6745
6746 // X86 has dedicated unpack instructions that can handle specific blend
6747 // operations: UNPCKH and UNPCKL.
6748 static SDValue lowerVectorShuffleWithUNPCK(SDLoc DL, MVT VT, ArrayRef<int> Mask,
6749                                            SDValue V1, SDValue V2,
6750                                            SelectionDAG &DAG) {
6751   int NumElts = VT.getVectorNumElements();
6752   int NumEltsInLane = 128 / VT.getScalarSizeInBits();
6753   SmallVector<int, 8> Unpckl;
6754   SmallVector<int, 8> Unpckh;
6755
6756   for (int i = 0; i < NumElts; ++i) {
6757     unsigned LaneStart = (i / NumEltsInLane) * NumEltsInLane;
6758     int LoPos = (i % NumEltsInLane) / 2 + LaneStart + NumElts * (i % 2);
6759     int HiPos = LoPos + NumEltsInLane / 2;
6760     Unpckl.push_back(LoPos);
6761     Unpckh.push_back(HiPos);
6762   }
6763
6764   if (isShuffleEquivalent(V1, V2, Mask, Unpckl))
6765     return DAG.getNode(X86ISD::UNPCKL, DL, VT, V1, V2);
6766   if (isShuffleEquivalent(V1, V2, Mask, Unpckh))
6767     return DAG.getNode(X86ISD::UNPCKH, DL, VT, V1, V2);
6768
6769   // Commute and try again.
6770   ShuffleVectorSDNode::commuteMask(Unpckl);
6771   if (isShuffleEquivalent(V1, V2, Mask, Unpckl))
6772     return DAG.getNode(X86ISD::UNPCKL, DL, VT, V2, V1);
6773
6774   ShuffleVectorSDNode::commuteMask(Unpckh);
6775   if (isShuffleEquivalent(V1, V2, Mask, Unpckh))
6776     return DAG.getNode(X86ISD::UNPCKH, DL, VT, V2, V1);
6777
6778   return SDValue();
6779 }
6780
6781 /// \brief Try to emit a bitmask instruction for a shuffle.
6782 ///
6783 /// This handles cases where we can model a blend exactly as a bitmask due to
6784 /// one of the inputs being zeroable.
6785 static SDValue lowerVectorShuffleAsBitMask(SDLoc DL, MVT VT, SDValue V1,
6786                                            SDValue V2, ArrayRef<int> Mask,
6787                                            SelectionDAG &DAG) {
6788   MVT EltVT = VT.getVectorElementType();
6789   int NumEltBits = EltVT.getSizeInBits();
6790   MVT IntEltVT = MVT::getIntegerVT(NumEltBits);
6791   SDValue Zero = DAG.getConstant(0, DL, IntEltVT);
6792   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6793                                     IntEltVT);
6794   if (EltVT.isFloatingPoint()) {
6795     Zero = DAG.getBitcast(EltVT, Zero);
6796     AllOnes = DAG.getBitcast(EltVT, AllOnes);
6797   }
6798   SmallVector<SDValue, 16> VMaskOps(Mask.size(), Zero);
6799   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6800   SDValue V;
6801   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6802     if (Zeroable[i])
6803       continue;
6804     if (Mask[i] % Size != i)
6805       return SDValue(); // Not a blend.
6806     if (!V)
6807       V = Mask[i] < Size ? V1 : V2;
6808     else if (V != (Mask[i] < Size ? V1 : V2))
6809       return SDValue(); // Can only let one input through the mask.
6810
6811     VMaskOps[i] = AllOnes;
6812   }
6813   if (!V)
6814     return SDValue(); // No non-zeroable elements!
6815
6816   SDValue VMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, VMaskOps);
6817   V = DAG.getNode(VT.isFloatingPoint()
6818                   ? (unsigned) X86ISD::FAND : (unsigned) ISD::AND,
6819                   DL, VT, V, VMask);
6820   return V;
6821 }
6822
6823 /// \brief Try to emit a blend instruction for a shuffle using bit math.
6824 ///
6825 /// This is used as a fallback approach when first class blend instructions are
6826 /// unavailable. Currently it is only suitable for integer vectors, but could
6827 /// be generalized for floating point vectors if desirable.
6828 static SDValue lowerVectorShuffleAsBitBlend(SDLoc DL, MVT VT, SDValue V1,
6829                                             SDValue V2, ArrayRef<int> Mask,
6830                                             SelectionDAG &DAG) {
6831   assert(VT.isInteger() && "Only supports integer vector types!");
6832   MVT EltVT = VT.getVectorElementType();
6833   int NumEltBits = EltVT.getSizeInBits();
6834   SDValue Zero = DAG.getConstant(0, DL, EltVT);
6835   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6836                                     EltVT);
6837   SmallVector<SDValue, 16> MaskOps;
6838   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6839     if (Mask[i] != -1 && Mask[i] != i && Mask[i] != i + Size)
6840       return SDValue(); // Shuffled input!
6841     MaskOps.push_back(Mask[i] < Size ? AllOnes : Zero);
6842   }
6843
6844   SDValue V1Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, MaskOps);
6845   V1 = DAG.getNode(ISD::AND, DL, VT, V1, V1Mask);
6846   // We have to cast V2 around.
6847   MVT MaskVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
6848   V2 = DAG.getBitcast(VT, DAG.getNode(X86ISD::ANDNP, DL, MaskVT,
6849                                       DAG.getBitcast(MaskVT, V1Mask),
6850                                       DAG.getBitcast(MaskVT, V2)));
6851   return DAG.getNode(ISD::OR, DL, VT, V1, V2);
6852 }
6853
6854 /// \brief Try to emit a blend instruction for a shuffle.
6855 ///
6856 /// This doesn't do any checks for the availability of instructions for blending
6857 /// these values. It relies on the availability of the X86ISD::BLENDI pattern to
6858 /// be matched in the backend with the type given. What it does check for is
6859 /// that the shuffle mask is a blend, or convertible into a blend with zero.
6860 static SDValue lowerVectorShuffleAsBlend(SDLoc DL, MVT VT, SDValue V1,
6861                                          SDValue V2, ArrayRef<int> Original,
6862                                          const X86Subtarget *Subtarget,
6863                                          SelectionDAG &DAG) {
6864   bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
6865   bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
6866   SmallVector<int, 8> Mask(Original.begin(), Original.end());
6867   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6868   bool ForceV1Zero = false, ForceV2Zero = false;
6869
6870   // Attempt to generate the binary blend mask. If an input is zero then
6871   // we can use any lane.
6872   // TODO: generalize the zero matching to any scalar like isShuffleEquivalent.
6873   unsigned BlendMask = 0;
6874   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6875     int M = Mask[i];
6876     if (M < 0)
6877       continue;
6878     if (M == i)
6879       continue;
6880     if (M == i + Size) {
6881       BlendMask |= 1u << i;
6882       continue;
6883     }
6884     if (Zeroable[i]) {
6885       if (V1IsZero) {
6886         ForceV1Zero = true;
6887         Mask[i] = i;
6888         continue;
6889       }
6890       if (V2IsZero) {
6891         ForceV2Zero = true;
6892         BlendMask |= 1u << i;
6893         Mask[i] = i + Size;
6894         continue;
6895       }
6896     }
6897     return SDValue(); // Shuffled input!
6898   }
6899
6900   // Create a REAL zero vector - ISD::isBuildVectorAllZeros allows UNDEFs.
6901   if (ForceV1Zero)
6902     V1 = getZeroVector(VT, Subtarget, DAG, DL);
6903   if (ForceV2Zero)
6904     V2 = getZeroVector(VT, Subtarget, DAG, DL);
6905
6906   auto ScaleBlendMask = [](unsigned BlendMask, int Size, int Scale) {
6907     unsigned ScaledMask = 0;
6908     for (int i = 0; i != Size; ++i)
6909       if (BlendMask & (1u << i))
6910         for (int j = 0; j != Scale; ++j)
6911           ScaledMask |= 1u << (i * Scale + j);
6912     return ScaledMask;
6913   };
6914
6915   switch (VT.SimpleTy) {
6916   case MVT::v2f64:
6917   case MVT::v4f32:
6918   case MVT::v4f64:
6919   case MVT::v8f32:
6920     return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V2,
6921                        DAG.getConstant(BlendMask, DL, MVT::i8));
6922
6923   case MVT::v4i64:
6924   case MVT::v8i32:
6925     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6926     // FALLTHROUGH
6927   case MVT::v2i64:
6928   case MVT::v4i32:
6929     // If we have AVX2 it is faster to use VPBLENDD when the shuffle fits into
6930     // that instruction.
6931     if (Subtarget->hasAVX2()) {
6932       // Scale the blend by the number of 32-bit dwords per element.
6933       int Scale =  VT.getScalarSizeInBits() / 32;
6934       BlendMask = ScaleBlendMask(BlendMask, Mask.size(), Scale);
6935       MVT BlendVT = VT.getSizeInBits() > 128 ? MVT::v8i32 : MVT::v4i32;
6936       V1 = DAG.getBitcast(BlendVT, V1);
6937       V2 = DAG.getBitcast(BlendVT, V2);
6938       return DAG.getBitcast(
6939           VT, DAG.getNode(X86ISD::BLENDI, DL, BlendVT, V1, V2,
6940                           DAG.getConstant(BlendMask, DL, MVT::i8)));
6941     }
6942     // FALLTHROUGH
6943   case MVT::v8i16: {
6944     // For integer shuffles we need to expand the mask and cast the inputs to
6945     // v8i16s prior to blending.
6946     int Scale = 8 / VT.getVectorNumElements();
6947     BlendMask = ScaleBlendMask(BlendMask, Mask.size(), Scale);
6948     V1 = DAG.getBitcast(MVT::v8i16, V1);
6949     V2 = DAG.getBitcast(MVT::v8i16, V2);
6950     return DAG.getBitcast(VT,
6951                           DAG.getNode(X86ISD::BLENDI, DL, MVT::v8i16, V1, V2,
6952                                       DAG.getConstant(BlendMask, DL, MVT::i8)));
6953   }
6954
6955   case MVT::v16i16: {
6956     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6957     SmallVector<int, 8> RepeatedMask;
6958     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
6959       // We can lower these with PBLENDW which is mirrored across 128-bit lanes.
6960       assert(RepeatedMask.size() == 8 && "Repeated mask size doesn't match!");
6961       BlendMask = 0;
6962       for (int i = 0; i < 8; ++i)
6963         if (RepeatedMask[i] >= 16)
6964           BlendMask |= 1u << i;
6965       return DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
6966                          DAG.getConstant(BlendMask, DL, MVT::i8));
6967     }
6968   }
6969     // FALLTHROUGH
6970   case MVT::v16i8:
6971   case MVT::v32i8: {
6972     assert((VT.is128BitVector() || Subtarget->hasAVX2()) &&
6973            "256-bit byte-blends require AVX2 support!");
6974
6975     // Attempt to lower to a bitmask if we can. VPAND is faster than VPBLENDVB.
6976     if (SDValue Masked = lowerVectorShuffleAsBitMask(DL, VT, V1, V2, Mask, DAG))
6977       return Masked;
6978
6979     // Scale the blend by the number of bytes per element.
6980     int Scale = VT.getScalarSizeInBits() / 8;
6981
6982     // This form of blend is always done on bytes. Compute the byte vector
6983     // type.
6984     MVT BlendVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
6985
6986     // Compute the VSELECT mask. Note that VSELECT is really confusing in the
6987     // mix of LLVM's code generator and the x86 backend. We tell the code
6988     // generator that boolean values in the elements of an x86 vector register
6989     // are -1 for true and 0 for false. We then use the LLVM semantics of 'true'
6990     // mapping a select to operand #1, and 'false' mapping to operand #2. The
6991     // reality in x86 is that vector masks (pre-AVX-512) use only the high bit
6992     // of the element (the remaining are ignored) and 0 in that high bit would
6993     // mean operand #1 while 1 in the high bit would mean operand #2. So while
6994     // the LLVM model for boolean values in vector elements gets the relevant
6995     // bit set, it is set backwards and over constrained relative to x86's
6996     // actual model.
6997     SmallVector<SDValue, 32> VSELECTMask;
6998     for (int i = 0, Size = Mask.size(); i < Size; ++i)
6999       for (int j = 0; j < Scale; ++j)
7000         VSELECTMask.push_back(
7001             Mask[i] < 0 ? DAG.getUNDEF(MVT::i8)
7002                         : DAG.getConstant(Mask[i] < Size ? -1 : 0, DL,
7003                                           MVT::i8));
7004
7005     V1 = DAG.getBitcast(BlendVT, V1);
7006     V2 = DAG.getBitcast(BlendVT, V2);
7007     return DAG.getBitcast(VT, DAG.getNode(ISD::VSELECT, DL, BlendVT,
7008                                           DAG.getNode(ISD::BUILD_VECTOR, DL,
7009                                                       BlendVT, VSELECTMask),
7010                                           V1, V2));
7011   }
7012
7013   default:
7014     llvm_unreachable("Not a supported integer vector type!");
7015   }
7016 }
7017
7018 /// \brief Try to lower as a blend of elements from two inputs followed by
7019 /// a single-input permutation.
7020 ///
7021 /// This matches the pattern where we can blend elements from two inputs and
7022 /// then reduce the shuffle to a single-input permutation.
7023 static SDValue lowerVectorShuffleAsBlendAndPermute(SDLoc DL, MVT VT, SDValue V1,
7024                                                    SDValue V2,
7025                                                    ArrayRef<int> Mask,
7026                                                    SelectionDAG &DAG) {
7027   // We build up the blend mask while checking whether a blend is a viable way
7028   // to reduce the shuffle.
7029   SmallVector<int, 32> BlendMask(Mask.size(), -1);
7030   SmallVector<int, 32> PermuteMask(Mask.size(), -1);
7031
7032   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7033     if (Mask[i] < 0)
7034       continue;
7035
7036     assert(Mask[i] < Size * 2 && "Shuffle input is out of bounds.");
7037
7038     if (BlendMask[Mask[i] % Size] == -1)
7039       BlendMask[Mask[i] % Size] = Mask[i];
7040     else if (BlendMask[Mask[i] % Size] != Mask[i])
7041       return SDValue(); // Can't blend in the needed input!
7042
7043     PermuteMask[i] = Mask[i] % Size;
7044   }
7045
7046   SDValue V = DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
7047   return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), PermuteMask);
7048 }
7049
7050 /// \brief Generic routine to decompose a shuffle and blend into indepndent
7051 /// blends and permutes.
7052 ///
7053 /// This matches the extremely common pattern for handling combined
7054 /// shuffle+blend operations on newer X86 ISAs where we have very fast blend
7055 /// operations. It will try to pick the best arrangement of shuffles and
7056 /// blends.
7057 static SDValue lowerVectorShuffleAsDecomposedShuffleBlend(SDLoc DL, MVT VT,
7058                                                           SDValue V1,
7059                                                           SDValue V2,
7060                                                           ArrayRef<int> Mask,
7061                                                           SelectionDAG &DAG) {
7062   // Shuffle the input elements into the desired positions in V1 and V2 and
7063   // blend them together.
7064   SmallVector<int, 32> V1Mask(Mask.size(), -1);
7065   SmallVector<int, 32> V2Mask(Mask.size(), -1);
7066   SmallVector<int, 32> BlendMask(Mask.size(), -1);
7067   for (int i = 0, Size = Mask.size(); i < Size; ++i)
7068     if (Mask[i] >= 0 && Mask[i] < Size) {
7069       V1Mask[i] = Mask[i];
7070       BlendMask[i] = i;
7071     } else if (Mask[i] >= Size) {
7072       V2Mask[i] = Mask[i] - Size;
7073       BlendMask[i] = i + Size;
7074     }
7075
7076   // Try to lower with the simpler initial blend strategy unless one of the
7077   // input shuffles would be a no-op. We prefer to shuffle inputs as the
7078   // shuffle may be able to fold with a load or other benefit. However, when
7079   // we'll have to do 2x as many shuffles in order to achieve this, blending
7080   // first is a better strategy.
7081   if (!isNoopShuffleMask(V1Mask) && !isNoopShuffleMask(V2Mask))
7082     if (SDValue BlendPerm =
7083             lowerVectorShuffleAsBlendAndPermute(DL, VT, V1, V2, Mask, DAG))
7084       return BlendPerm;
7085
7086   V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
7087   V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
7088   return DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
7089 }
7090
7091 /// \brief Try to lower a vector shuffle as a byte rotation.
7092 ///
7093 /// SSSE3 has a generic PALIGNR instruction in x86 that will do an arbitrary
7094 /// byte-rotation of the concatenation of two vectors; pre-SSSE3 can use
7095 /// a PSRLDQ/PSLLDQ/POR pattern to get a similar effect. This routine will
7096 /// try to generically lower a vector shuffle through such an pattern. It
7097 /// does not check for the profitability of lowering either as PALIGNR or
7098 /// PSRLDQ/PSLLDQ/POR, only whether the mask is valid to lower in that form.
7099 /// This matches shuffle vectors that look like:
7100 ///
7101 ///   v8i16 [11, 12, 13, 14, 15, 0, 1, 2]
7102 ///
7103 /// Essentially it concatenates V1 and V2, shifts right by some number of
7104 /// elements, and takes the low elements as the result. Note that while this is
7105 /// specified as a *right shift* because x86 is little-endian, it is a *left
7106 /// rotate* of the vector lanes.
7107 static SDValue lowerVectorShuffleAsByteRotate(SDLoc DL, MVT VT, SDValue V1,
7108                                               SDValue V2,
7109                                               ArrayRef<int> Mask,
7110                                               const X86Subtarget *Subtarget,
7111                                               SelectionDAG &DAG) {
7112   assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
7113
7114   int NumElts = Mask.size();
7115   int NumLanes = VT.getSizeInBits() / 128;
7116   int NumLaneElts = NumElts / NumLanes;
7117
7118   // We need to detect various ways of spelling a rotation:
7119   //   [11, 12, 13, 14, 15,  0,  1,  2]
7120   //   [-1, 12, 13, 14, -1, -1,  1, -1]
7121   //   [-1, -1, -1, -1, -1, -1,  1,  2]
7122   //   [ 3,  4,  5,  6,  7,  8,  9, 10]
7123   //   [-1,  4,  5,  6, -1, -1,  9, -1]
7124   //   [-1,  4,  5,  6, -1, -1, -1, -1]
7125   int Rotation = 0;
7126   SDValue Lo, Hi;
7127   for (int l = 0; l < NumElts; l += NumLaneElts) {
7128     for (int i = 0; i < NumLaneElts; ++i) {
7129       if (Mask[l + i] == -1)
7130         continue;
7131       assert(Mask[l + i] >= 0 && "Only -1 is a valid negative mask element!");
7132
7133       // Get the mod-Size index and lane correct it.
7134       int LaneIdx = (Mask[l + i] % NumElts) - l;
7135       // Make sure it was in this lane.
7136       if (LaneIdx < 0 || LaneIdx >= NumLaneElts)
7137         return SDValue();
7138
7139       // Determine where a rotated vector would have started.
7140       int StartIdx = i - LaneIdx;
7141       if (StartIdx == 0)
7142         // The identity rotation isn't interesting, stop.
7143         return SDValue();
7144
7145       // If we found the tail of a vector the rotation must be the missing
7146       // front. If we found the head of a vector, it must be how much of the
7147       // head.
7148       int CandidateRotation = StartIdx < 0 ? -StartIdx : NumLaneElts - StartIdx;
7149
7150       if (Rotation == 0)
7151         Rotation = CandidateRotation;
7152       else if (Rotation != CandidateRotation)
7153         // The rotations don't match, so we can't match this mask.
7154         return SDValue();
7155
7156       // Compute which value this mask is pointing at.
7157       SDValue MaskV = Mask[l + i] < NumElts ? V1 : V2;
7158
7159       // Compute which of the two target values this index should be assigned
7160       // to. This reflects whether the high elements are remaining or the low
7161       // elements are remaining.
7162       SDValue &TargetV = StartIdx < 0 ? Hi : Lo;
7163
7164       // Either set up this value if we've not encountered it before, or check
7165       // that it remains consistent.
7166       if (!TargetV)
7167         TargetV = MaskV;
7168       else if (TargetV != MaskV)
7169         // This may be a rotation, but it pulls from the inputs in some
7170         // unsupported interleaving.
7171         return SDValue();
7172     }
7173   }
7174
7175   // Check that we successfully analyzed the mask, and normalize the results.
7176   assert(Rotation != 0 && "Failed to locate a viable rotation!");
7177   assert((Lo || Hi) && "Failed to find a rotated input vector!");
7178   if (!Lo)
7179     Lo = Hi;
7180   else if (!Hi)
7181     Hi = Lo;
7182
7183   // The actual rotate instruction rotates bytes, so we need to scale the
7184   // rotation based on how many bytes are in the vector lane.
7185   int Scale = 16 / NumLaneElts;
7186
7187   // SSSE3 targets can use the palignr instruction.
7188   if (Subtarget->hasSSSE3()) {
7189     // Cast the inputs to i8 vector of correct length to match PALIGNR.
7190     MVT AlignVT = MVT::getVectorVT(MVT::i8, 16 * NumLanes);
7191     Lo = DAG.getBitcast(AlignVT, Lo);
7192     Hi = DAG.getBitcast(AlignVT, Hi);
7193
7194     return DAG.getBitcast(
7195         VT, DAG.getNode(X86ISD::PALIGNR, DL, AlignVT, Lo, Hi,
7196                         DAG.getConstant(Rotation * Scale, DL, MVT::i8)));
7197   }
7198
7199   assert(VT.is128BitVector() &&
7200          "Rotate-based lowering only supports 128-bit lowering!");
7201   assert(Mask.size() <= 16 &&
7202          "Can shuffle at most 16 bytes in a 128-bit vector!");
7203
7204   // Default SSE2 implementation
7205   int LoByteShift = 16 - Rotation * Scale;
7206   int HiByteShift = Rotation * Scale;
7207
7208   // Cast the inputs to v2i64 to match PSLLDQ/PSRLDQ.
7209   Lo = DAG.getBitcast(MVT::v2i64, Lo);
7210   Hi = DAG.getBitcast(MVT::v2i64, Hi);
7211
7212   SDValue LoShift = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v2i64, Lo,
7213                                 DAG.getConstant(LoByteShift, DL, MVT::i8));
7214   SDValue HiShift = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v2i64, Hi,
7215                                 DAG.getConstant(HiByteShift, DL, MVT::i8));
7216   return DAG.getBitcast(VT,
7217                         DAG.getNode(ISD::OR, DL, MVT::v2i64, LoShift, HiShift));
7218 }
7219
7220 /// \brief Try to lower a vector shuffle as a bit shift (shifts in zeros).
7221 ///
7222 /// Attempts to match a shuffle mask against the PSLL(W/D/Q/DQ) and
7223 /// PSRL(W/D/Q/DQ) SSE2 and AVX2 logical bit-shift instructions. The function
7224 /// matches elements from one of the input vectors shuffled to the left or
7225 /// right with zeroable elements 'shifted in'. It handles both the strictly
7226 /// bit-wise element shifts and the byte shift across an entire 128-bit double
7227 /// quad word lane.
7228 ///
7229 /// PSHL : (little-endian) left bit shift.
7230 /// [ zz, 0, zz,  2 ]
7231 /// [ -1, 4, zz, -1 ]
7232 /// PSRL : (little-endian) right bit shift.
7233 /// [  1, zz,  3, zz]
7234 /// [ -1, -1,  7, zz]
7235 /// PSLLDQ : (little-endian) left byte shift
7236 /// [ zz,  0,  1,  2,  3,  4,  5,  6]
7237 /// [ zz, zz, -1, -1,  2,  3,  4, -1]
7238 /// [ zz, zz, zz, zz, zz, zz, -1,  1]
7239 /// PSRLDQ : (little-endian) right byte shift
7240 /// [  5, 6,  7, zz, zz, zz, zz, zz]
7241 /// [ -1, 5,  6,  7, zz, zz, zz, zz]
7242 /// [  1, 2, -1, -1, -1, -1, zz, zz]
7243 static SDValue lowerVectorShuffleAsShift(SDLoc DL, MVT VT, SDValue V1,
7244                                          SDValue V2, ArrayRef<int> Mask,
7245                                          SelectionDAG &DAG) {
7246   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7247
7248   int Size = Mask.size();
7249   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
7250
7251   auto CheckZeros = [&](int Shift, int Scale, bool Left) {
7252     for (int i = 0; i < Size; i += Scale)
7253       for (int j = 0; j < Shift; ++j)
7254         if (!Zeroable[i + j + (Left ? 0 : (Scale - Shift))])
7255           return false;
7256
7257     return true;
7258   };
7259
7260   auto MatchShift = [&](int Shift, int Scale, bool Left, SDValue V) {
7261     for (int i = 0; i != Size; i += Scale) {
7262       unsigned Pos = Left ? i + Shift : i;
7263       unsigned Low = Left ? i : i + Shift;
7264       unsigned Len = Scale - Shift;
7265       if (!isSequentialOrUndefInRange(Mask, Pos, Len,
7266                                       Low + (V == V1 ? 0 : Size)))
7267         return SDValue();
7268     }
7269
7270     int ShiftEltBits = VT.getScalarSizeInBits() * Scale;
7271     bool ByteShift = ShiftEltBits > 64;
7272     unsigned OpCode = Left ? (ByteShift ? X86ISD::VSHLDQ : X86ISD::VSHLI)
7273                            : (ByteShift ? X86ISD::VSRLDQ : X86ISD::VSRLI);
7274     int ShiftAmt = Shift * VT.getScalarSizeInBits() / (ByteShift ? 8 : 1);
7275
7276     // Normalize the scale for byte shifts to still produce an i64 element
7277     // type.
7278     Scale = ByteShift ? Scale / 2 : Scale;
7279
7280     // We need to round trip through the appropriate type for the shift.
7281     MVT ShiftSVT = MVT::getIntegerVT(VT.getScalarSizeInBits() * Scale);
7282     MVT ShiftVT = MVT::getVectorVT(ShiftSVT, Size / Scale);
7283     assert(DAG.getTargetLoweringInfo().isTypeLegal(ShiftVT) &&
7284            "Illegal integer vector type");
7285     V = DAG.getBitcast(ShiftVT, V);
7286
7287     V = DAG.getNode(OpCode, DL, ShiftVT, V,
7288                     DAG.getConstant(ShiftAmt, DL, MVT::i8));
7289     return DAG.getBitcast(VT, V);
7290   };
7291
7292   // SSE/AVX supports logical shifts up to 64-bit integers - so we can just
7293   // keep doubling the size of the integer elements up to that. We can
7294   // then shift the elements of the integer vector by whole multiples of
7295   // their width within the elements of the larger integer vector. Test each
7296   // multiple to see if we can find a match with the moved element indices
7297   // and that the shifted in elements are all zeroable.
7298   for (int Scale = 2; Scale * VT.getScalarSizeInBits() <= 128; Scale *= 2)
7299     for (int Shift = 1; Shift != Scale; ++Shift)
7300       for (bool Left : {true, false})
7301         if (CheckZeros(Shift, Scale, Left))
7302           for (SDValue V : {V1, V2})
7303             if (SDValue Match = MatchShift(Shift, Scale, Left, V))
7304               return Match;
7305
7306   // no match
7307   return SDValue();
7308 }
7309
7310 /// \brief Try to lower a vector shuffle using SSE4a EXTRQ/INSERTQ.
7311 static SDValue lowerVectorShuffleWithSSE4A(SDLoc DL, MVT VT, SDValue V1,
7312                                            SDValue V2, ArrayRef<int> Mask,
7313                                            SelectionDAG &DAG) {
7314   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7315   assert(!Zeroable.all() && "Fully zeroable shuffle mask");
7316
7317   int Size = Mask.size();
7318   int HalfSize = Size / 2;
7319   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
7320
7321   // Upper half must be undefined.
7322   if (!isUndefInRange(Mask, HalfSize, HalfSize))
7323     return SDValue();
7324
7325   // EXTRQ: Extract Len elements from lower half of source, starting at Idx.
7326   // Remainder of lower half result is zero and upper half is all undef.
7327   auto LowerAsEXTRQ = [&]() {
7328     // Determine the extraction length from the part of the
7329     // lower half that isn't zeroable.
7330     int Len = HalfSize;
7331     for (; Len > 0; --Len)
7332       if (!Zeroable[Len - 1])
7333         break;
7334     assert(Len > 0 && "Zeroable shuffle mask");
7335
7336     // Attempt to match first Len sequential elements from the lower half.
7337     SDValue Src;
7338     int Idx = -1;
7339     for (int i = 0; i != Len; ++i) {
7340       int M = Mask[i];
7341       if (M < 0)
7342         continue;
7343       SDValue &V = (M < Size ? V1 : V2);
7344       M = M % Size;
7345
7346       // All mask elements must be in the lower half.
7347       if (M >= HalfSize)
7348         return SDValue();
7349
7350       if (Idx < 0 || (Src == V && Idx == (M - i))) {
7351         Src = V;
7352         Idx = M - i;
7353         continue;
7354       }
7355       return SDValue();
7356     }
7357
7358     if (Idx < 0)
7359       return SDValue();
7360
7361     assert((Idx + Len) <= HalfSize && "Illegal extraction mask");
7362     int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
7363     int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
7364     return DAG.getNode(X86ISD::EXTRQI, DL, VT, Src,
7365                        DAG.getConstant(BitLen, DL, MVT::i8),
7366                        DAG.getConstant(BitIdx, DL, MVT::i8));
7367   };
7368
7369   if (SDValue ExtrQ = LowerAsEXTRQ())
7370     return ExtrQ;
7371
7372   // INSERTQ: Extract lowest Len elements from lower half of second source and
7373   // insert over first source, starting at Idx.
7374   // { A[0], .., A[Idx-1], B[0], .., B[Len-1], A[Idx+Len], .., UNDEF, ... }
7375   auto LowerAsInsertQ = [&]() {
7376     for (int Idx = 0; Idx != HalfSize; ++Idx) {
7377       SDValue Base;
7378
7379       // Attempt to match first source from mask before insertion point.
7380       if (isUndefInRange(Mask, 0, Idx)) {
7381         /* EMPTY */
7382       } else if (isSequentialOrUndefInRange(Mask, 0, Idx, 0)) {
7383         Base = V1;
7384       } else if (isSequentialOrUndefInRange(Mask, 0, Idx, Size)) {
7385         Base = V2;
7386       } else {
7387         continue;
7388       }
7389
7390       // Extend the extraction length looking to match both the insertion of
7391       // the second source and the remaining elements of the first.
7392       for (int Hi = Idx + 1; Hi <= HalfSize; ++Hi) {
7393         SDValue Insert;
7394         int Len = Hi - Idx;
7395
7396         // Match insertion.
7397         if (isSequentialOrUndefInRange(Mask, Idx, Len, 0)) {
7398           Insert = V1;
7399         } else if (isSequentialOrUndefInRange(Mask, Idx, Len, Size)) {
7400           Insert = V2;
7401         } else {
7402           continue;
7403         }
7404
7405         // Match the remaining elements of the lower half.
7406         if (isUndefInRange(Mask, Hi, HalfSize - Hi)) {
7407           /* EMPTY */
7408         } else if ((!Base || (Base == V1)) &&
7409                    isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi, Hi)) {
7410           Base = V1;
7411         } else if ((!Base || (Base == V2)) &&
7412                    isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi,
7413                                               Size + Hi)) {
7414           Base = V2;
7415         } else {
7416           continue;
7417         }
7418
7419         // We may not have a base (first source) - this can safely be undefined.
7420         if (!Base)
7421           Base = DAG.getUNDEF(VT);
7422
7423         int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
7424         int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
7425         return DAG.getNode(X86ISD::INSERTQI, DL, VT, Base, Insert,
7426                            DAG.getConstant(BitLen, DL, MVT::i8),
7427                            DAG.getConstant(BitIdx, DL, MVT::i8));
7428       }
7429     }
7430
7431     return SDValue();
7432   };
7433
7434   if (SDValue InsertQ = LowerAsInsertQ())
7435     return InsertQ;
7436
7437   return SDValue();
7438 }
7439
7440 /// \brief Lower a vector shuffle as a zero or any extension.
7441 ///
7442 /// Given a specific number of elements, element bit width, and extension
7443 /// stride, produce either a zero or any extension based on the available
7444 /// features of the subtarget. The extended elements are consecutive and
7445 /// begin and can start from an offseted element index in the input; to
7446 /// avoid excess shuffling the offset must either being in the bottom lane
7447 /// or at the start of a higher lane. All extended elements must be from
7448 /// the same lane.
7449 static SDValue lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7450     SDLoc DL, MVT VT, int Scale, int Offset, bool AnyExt, SDValue InputV,
7451     ArrayRef<int> Mask, const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7452   assert(Scale > 1 && "Need a scale to extend.");
7453   int EltBits = VT.getScalarSizeInBits();
7454   int NumElements = VT.getVectorNumElements();
7455   int NumEltsPerLane = 128 / EltBits;
7456   int OffsetLane = Offset / NumEltsPerLane;
7457   assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
7458          "Only 8, 16, and 32 bit elements can be extended.");
7459   assert(Scale * EltBits <= 64 && "Cannot zero extend past 64 bits.");
7460   assert(0 <= Offset && "Extension offset must be positive.");
7461   assert((Offset < NumEltsPerLane || Offset % NumEltsPerLane == 0) &&
7462          "Extension offset must be in the first lane or start an upper lane.");
7463
7464   // Check that an index is in same lane as the base offset.
7465   auto SafeOffset = [&](int Idx) {
7466     return OffsetLane == (Idx / NumEltsPerLane);
7467   };
7468
7469   // Shift along an input so that the offset base moves to the first element.
7470   auto ShuffleOffset = [&](SDValue V) {
7471     if (!Offset)
7472       return V;
7473
7474     SmallVector<int, 8> ShMask((unsigned)NumElements, -1);
7475     for (int i = 0; i * Scale < NumElements; ++i) {
7476       int SrcIdx = i + Offset;
7477       ShMask[i] = SafeOffset(SrcIdx) ? SrcIdx : -1;
7478     }
7479     return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), ShMask);
7480   };
7481
7482   // Found a valid zext mask! Try various lowering strategies based on the
7483   // input type and available ISA extensions.
7484   if (Subtarget->hasSSE41()) {
7485     // Not worth offseting 128-bit vectors if scale == 2, a pattern using
7486     // PUNPCK will catch this in a later shuffle match.
7487     if (Offset && Scale == 2 && VT.is128BitVector())
7488       return SDValue();
7489     MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits * Scale),
7490                                  NumElements / Scale);
7491     InputV = DAG.getNode(X86ISD::VZEXT, DL, ExtVT, ShuffleOffset(InputV));
7492     return DAG.getBitcast(VT, InputV);
7493   }
7494
7495   assert(VT.is128BitVector() && "Only 128-bit vectors can be extended.");
7496
7497   // For any extends we can cheat for larger element sizes and use shuffle
7498   // instructions that can fold with a load and/or copy.
7499   if (AnyExt && EltBits == 32) {
7500     int PSHUFDMask[4] = {Offset, -1, SafeOffset(Offset + 1) ? Offset + 1 : -1,
7501                          -1};
7502     return DAG.getBitcast(
7503         VT, DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7504                         DAG.getBitcast(MVT::v4i32, InputV),
7505                         getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
7506   }
7507   if (AnyExt && EltBits == 16 && Scale > 2) {
7508     int PSHUFDMask[4] = {Offset / 2, -1,
7509                          SafeOffset(Offset + 1) ? (Offset + 1) / 2 : -1, -1};
7510     InputV = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7511                          DAG.getBitcast(MVT::v4i32, InputV),
7512                          getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG));
7513     int PSHUFWMask[4] = {1, -1, -1, -1};
7514     unsigned OddEvenOp = (Offset & 1 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW);
7515     return DAG.getBitcast(
7516         VT, DAG.getNode(OddEvenOp, DL, MVT::v8i16,
7517                         DAG.getBitcast(MVT::v8i16, InputV),
7518                         getV4X86ShuffleImm8ForMask(PSHUFWMask, DL, DAG)));
7519   }
7520
7521   // The SSE4A EXTRQ instruction can efficiently extend the first 2 lanes
7522   // to 64-bits.
7523   if ((Scale * EltBits) == 64 && EltBits < 32 && Subtarget->hasSSE4A()) {
7524     assert(NumElements == (int)Mask.size() && "Unexpected shuffle mask size!");
7525     assert(VT.is128BitVector() && "Unexpected vector width!");
7526
7527     int LoIdx = Offset * EltBits;
7528     SDValue Lo = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7529                              DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7530                                          DAG.getConstant(EltBits, DL, MVT::i8),
7531                                          DAG.getConstant(LoIdx, DL, MVT::i8)));
7532
7533     if (isUndefInRange(Mask, NumElements / 2, NumElements / 2) ||
7534         !SafeOffset(Offset + 1))
7535       return DAG.getNode(ISD::BITCAST, DL, VT, Lo);
7536
7537     int HiIdx = (Offset + 1) * EltBits;
7538     SDValue Hi = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7539                              DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7540                                          DAG.getConstant(EltBits, DL, MVT::i8),
7541                                          DAG.getConstant(HiIdx, DL, MVT::i8)));
7542     return DAG.getNode(ISD::BITCAST, DL, VT,
7543                        DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, Lo, Hi));
7544   }
7545
7546   // If this would require more than 2 unpack instructions to expand, use
7547   // pshufb when available. We can only use more than 2 unpack instructions
7548   // when zero extending i8 elements which also makes it easier to use pshufb.
7549   if (Scale > 4 && EltBits == 8 && Subtarget->hasSSSE3()) {
7550     assert(NumElements == 16 && "Unexpected byte vector width!");
7551     SDValue PSHUFBMask[16];
7552     for (int i = 0; i < 16; ++i) {
7553       int Idx = Offset + (i / Scale);
7554       PSHUFBMask[i] = DAG.getConstant(
7555           (i % Scale == 0 && SafeOffset(Idx)) ? Idx : 0x80, DL, MVT::i8);
7556     }
7557     InputV = DAG.getBitcast(MVT::v16i8, InputV);
7558     return DAG.getBitcast(VT,
7559                           DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, InputV,
7560                                       DAG.getNode(ISD::BUILD_VECTOR, DL,
7561                                                   MVT::v16i8, PSHUFBMask)));
7562   }
7563
7564   // If we are extending from an offset, ensure we start on a boundary that
7565   // we can unpack from.
7566   int AlignToUnpack = Offset % (NumElements / Scale);
7567   if (AlignToUnpack) {
7568     SmallVector<int, 8> ShMask((unsigned)NumElements, -1);
7569     for (int i = AlignToUnpack; i < NumElements; ++i)
7570       ShMask[i - AlignToUnpack] = i;
7571     InputV = DAG.getVectorShuffle(VT, DL, InputV, DAG.getUNDEF(VT), ShMask);
7572     Offset -= AlignToUnpack;
7573   }
7574
7575   // Otherwise emit a sequence of unpacks.
7576   do {
7577     unsigned UnpackLoHi = X86ISD::UNPCKL;
7578     if (Offset >= (NumElements / 2)) {
7579       UnpackLoHi = X86ISD::UNPCKH;
7580       Offset -= (NumElements / 2);
7581     }
7582
7583     MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
7584     SDValue Ext = AnyExt ? DAG.getUNDEF(InputVT)
7585                          : getZeroVector(InputVT, Subtarget, DAG, DL);
7586     InputV = DAG.getBitcast(InputVT, InputV);
7587     InputV = DAG.getNode(UnpackLoHi, DL, InputVT, InputV, Ext);
7588     Scale /= 2;
7589     EltBits *= 2;
7590     NumElements /= 2;
7591   } while (Scale > 1);
7592   return DAG.getBitcast(VT, InputV);
7593 }
7594
7595 /// \brief Try to lower a vector shuffle as a zero extension on any microarch.
7596 ///
7597 /// This routine will try to do everything in its power to cleverly lower
7598 /// a shuffle which happens to match the pattern of a zero extend. It doesn't
7599 /// check for the profitability of this lowering,  it tries to aggressively
7600 /// match this pattern. It will use all of the micro-architectural details it
7601 /// can to emit an efficient lowering. It handles both blends with all-zero
7602 /// inputs to explicitly zero-extend and undef-lanes (sometimes undef due to
7603 /// masking out later).
7604 ///
7605 /// The reason we have dedicated lowering for zext-style shuffles is that they
7606 /// are both incredibly common and often quite performance sensitive.
7607 static SDValue lowerVectorShuffleAsZeroOrAnyExtend(
7608     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7609     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7610   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7611
7612   int Bits = VT.getSizeInBits();
7613   int NumLanes = Bits / 128;
7614   int NumElements = VT.getVectorNumElements();
7615   int NumEltsPerLane = NumElements / NumLanes;
7616   assert(VT.getScalarSizeInBits() <= 32 &&
7617          "Exceeds 32-bit integer zero extension limit");
7618   assert((int)Mask.size() == NumElements && "Unexpected shuffle mask size");
7619
7620   // Define a helper function to check a particular ext-scale and lower to it if
7621   // valid.
7622   auto Lower = [&](int Scale) -> SDValue {
7623     SDValue InputV;
7624     bool AnyExt = true;
7625     int Offset = 0;
7626     int Matches = 0;
7627     for (int i = 0; i < NumElements; ++i) {
7628       int M = Mask[i];
7629       if (M == -1)
7630         continue; // Valid anywhere but doesn't tell us anything.
7631       if (i % Scale != 0) {
7632         // Each of the extended elements need to be zeroable.
7633         if (!Zeroable[i])
7634           return SDValue();
7635
7636         // We no longer are in the anyext case.
7637         AnyExt = false;
7638         continue;
7639       }
7640
7641       // Each of the base elements needs to be consecutive indices into the
7642       // same input vector.
7643       SDValue V = M < NumElements ? V1 : V2;
7644       M = M % NumElements;
7645       if (!InputV) {
7646         InputV = V;
7647         Offset = M - (i / Scale);
7648       } else if (InputV != V)
7649         return SDValue(); // Flip-flopping inputs.
7650
7651       // Offset must start in the lowest 128-bit lane or at the start of an
7652       // upper lane.
7653       // FIXME: Is it ever worth allowing a negative base offset?
7654       if (!((0 <= Offset && Offset < NumEltsPerLane) ||
7655             (Offset % NumEltsPerLane) == 0))
7656         return SDValue();
7657
7658       // If we are offsetting, all referenced entries must come from the same
7659       // lane.
7660       if (Offset && (Offset / NumEltsPerLane) != (M / NumEltsPerLane))
7661         return SDValue();
7662
7663       if ((M % NumElements) != (Offset + (i / Scale)))
7664         return SDValue(); // Non-consecutive strided elements.
7665       Matches++;
7666     }
7667
7668     // If we fail to find an input, we have a zero-shuffle which should always
7669     // have already been handled.
7670     // FIXME: Maybe handle this here in case during blending we end up with one?
7671     if (!InputV)
7672       return SDValue();
7673
7674     // If we are offsetting, don't extend if we only match a single input, we
7675     // can always do better by using a basic PSHUF or PUNPCK.
7676     if (Offset != 0 && Matches < 2)
7677       return SDValue();
7678
7679     return lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7680         DL, VT, Scale, Offset, AnyExt, InputV, Mask, Subtarget, DAG);
7681   };
7682
7683   // The widest scale possible for extending is to a 64-bit integer.
7684   assert(Bits % 64 == 0 &&
7685          "The number of bits in a vector must be divisible by 64 on x86!");
7686   int NumExtElements = Bits / 64;
7687
7688   // Each iteration, try extending the elements half as much, but into twice as
7689   // many elements.
7690   for (; NumExtElements < NumElements; NumExtElements *= 2) {
7691     assert(NumElements % NumExtElements == 0 &&
7692            "The input vector size must be divisible by the extended size.");
7693     if (SDValue V = Lower(NumElements / NumExtElements))
7694       return V;
7695   }
7696
7697   // General extends failed, but 128-bit vectors may be able to use MOVQ.
7698   if (Bits != 128)
7699     return SDValue();
7700
7701   // Returns one of the source operands if the shuffle can be reduced to a
7702   // MOVQ, copying the lower 64-bits and zero-extending to the upper 64-bits.
7703   auto CanZExtLowHalf = [&]() {
7704     for (int i = NumElements / 2; i != NumElements; ++i)
7705       if (!Zeroable[i])
7706         return SDValue();
7707     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, 0))
7708       return V1;
7709     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, NumElements))
7710       return V2;
7711     return SDValue();
7712   };
7713
7714   if (SDValue V = CanZExtLowHalf()) {
7715     V = DAG.getBitcast(MVT::v2i64, V);
7716     V = DAG.getNode(X86ISD::VZEXT_MOVL, DL, MVT::v2i64, V);
7717     return DAG.getBitcast(VT, V);
7718   }
7719
7720   // No viable ext lowering found.
7721   return SDValue();
7722 }
7723
7724 /// \brief Try to get a scalar value for a specific element of a vector.
7725 ///
7726 /// Looks through BUILD_VECTOR and SCALAR_TO_VECTOR nodes to find a scalar.
7727 static SDValue getScalarValueForVectorElement(SDValue V, int Idx,
7728                                               SelectionDAG &DAG) {
7729   MVT VT = V.getSimpleValueType();
7730   MVT EltVT = VT.getVectorElementType();
7731   while (V.getOpcode() == ISD::BITCAST)
7732     V = V.getOperand(0);
7733   // If the bitcasts shift the element size, we can't extract an equivalent
7734   // element from it.
7735   MVT NewVT = V.getSimpleValueType();
7736   if (!NewVT.isVector() || NewVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
7737     return SDValue();
7738
7739   if (V.getOpcode() == ISD::BUILD_VECTOR ||
7740       (Idx == 0 && V.getOpcode() == ISD::SCALAR_TO_VECTOR)) {
7741     // Ensure the scalar operand is the same size as the destination.
7742     // FIXME: Add support for scalar truncation where possible.
7743     SDValue S = V.getOperand(Idx);
7744     if (EltVT.getSizeInBits() == S.getSimpleValueType().getSizeInBits())
7745       return DAG.getNode(ISD::BITCAST, SDLoc(V), EltVT, S);
7746   }
7747
7748   return SDValue();
7749 }
7750
7751 /// \brief Helper to test for a load that can be folded with x86 shuffles.
7752 ///
7753 /// This is particularly important because the set of instructions varies
7754 /// significantly based on whether the operand is a load or not.
7755 static bool isShuffleFoldableLoad(SDValue V) {
7756   while (V.getOpcode() == ISD::BITCAST)
7757     V = V.getOperand(0);
7758
7759   return ISD::isNON_EXTLoad(V.getNode());
7760 }
7761
7762 /// \brief Try to lower insertion of a single element into a zero vector.
7763 ///
7764 /// This is a common pattern that we have especially efficient patterns to lower
7765 /// across all subtarget feature sets.
7766 static SDValue lowerVectorShuffleAsElementInsertion(
7767     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7768     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7769   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7770   MVT ExtVT = VT;
7771   MVT EltVT = VT.getVectorElementType();
7772
7773   int V2Index = std::find_if(Mask.begin(), Mask.end(),
7774                              [&Mask](int M) { return M >= (int)Mask.size(); }) -
7775                 Mask.begin();
7776   bool IsV1Zeroable = true;
7777   for (int i = 0, Size = Mask.size(); i < Size; ++i)
7778     if (i != V2Index && !Zeroable[i]) {
7779       IsV1Zeroable = false;
7780       break;
7781     }
7782
7783   // Check for a single input from a SCALAR_TO_VECTOR node.
7784   // FIXME: All of this should be canonicalized into INSERT_VECTOR_ELT and
7785   // all the smarts here sunk into that routine. However, the current
7786   // lowering of BUILD_VECTOR makes that nearly impossible until the old
7787   // vector shuffle lowering is dead.
7788   SDValue V2S = getScalarValueForVectorElement(V2, Mask[V2Index] - Mask.size(),
7789                                                DAG);
7790   if (V2S && DAG.getTargetLoweringInfo().isTypeLegal(V2S.getValueType())) {
7791     // We need to zext the scalar if it is smaller than an i32.
7792     V2S = DAG.getBitcast(EltVT, V2S);
7793     if (EltVT == MVT::i8 || EltVT == MVT::i16) {
7794       // Using zext to expand a narrow element won't work for non-zero
7795       // insertions.
7796       if (!IsV1Zeroable)
7797         return SDValue();
7798
7799       // Zero-extend directly to i32.
7800       ExtVT = MVT::v4i32;
7801       V2S = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, V2S);
7802     }
7803     V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
7804   } else if (Mask[V2Index] != (int)Mask.size() || EltVT == MVT::i8 ||
7805              EltVT == MVT::i16) {
7806     // Either not inserting from the low element of the input or the input
7807     // element size is too small to use VZEXT_MOVL to clear the high bits.
7808     return SDValue();
7809   }
7810
7811   if (!IsV1Zeroable) {
7812     // If V1 can't be treated as a zero vector we have fewer options to lower
7813     // this. We can't support integer vectors or non-zero targets cheaply, and
7814     // the V1 elements can't be permuted in any way.
7815     assert(VT == ExtVT && "Cannot change extended type when non-zeroable!");
7816     if (!VT.isFloatingPoint() || V2Index != 0)
7817       return SDValue();
7818     SmallVector<int, 8> V1Mask(Mask.begin(), Mask.end());
7819     V1Mask[V2Index] = -1;
7820     if (!isNoopShuffleMask(V1Mask))
7821       return SDValue();
7822     // This is essentially a special case blend operation, but if we have
7823     // general purpose blend operations, they are always faster. Bail and let
7824     // the rest of the lowering handle these as blends.
7825     if (Subtarget->hasSSE41())
7826       return SDValue();
7827
7828     // Otherwise, use MOVSD or MOVSS.
7829     assert((EltVT == MVT::f32 || EltVT == MVT::f64) &&
7830            "Only two types of floating point element types to handle!");
7831     return DAG.getNode(EltVT == MVT::f32 ? X86ISD::MOVSS : X86ISD::MOVSD, DL,
7832                        ExtVT, V1, V2);
7833   }
7834
7835   // This lowering only works for the low element with floating point vectors.
7836   if (VT.isFloatingPoint() && V2Index != 0)
7837     return SDValue();
7838
7839   V2 = DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2);
7840   if (ExtVT != VT)
7841     V2 = DAG.getBitcast(VT, V2);
7842
7843   if (V2Index != 0) {
7844     // If we have 4 or fewer lanes we can cheaply shuffle the element into
7845     // the desired position. Otherwise it is more efficient to do a vector
7846     // shift left. We know that we can do a vector shift left because all
7847     // the inputs are zero.
7848     if (VT.isFloatingPoint() || VT.getVectorNumElements() <= 4) {
7849       SmallVector<int, 4> V2Shuffle(Mask.size(), 1);
7850       V2Shuffle[V2Index] = 0;
7851       V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Shuffle);
7852     } else {
7853       V2 = DAG.getBitcast(MVT::v2i64, V2);
7854       V2 = DAG.getNode(
7855           X86ISD::VSHLDQ, DL, MVT::v2i64, V2,
7856           DAG.getConstant(V2Index * EltVT.getSizeInBits() / 8, DL,
7857                           DAG.getTargetLoweringInfo().getScalarShiftAmountTy(
7858                               DAG.getDataLayout(), VT)));
7859       V2 = DAG.getBitcast(VT, V2);
7860     }
7861   }
7862   return V2;
7863 }
7864
7865 /// \brief Try to lower broadcast of a single - truncated - integer element,
7866 /// coming from a scalar_to_vector/build_vector node \p V0 with larger elements.
7867 ///
7868 /// This assumes we have AVX2.
7869 static SDValue lowerVectorShuffleAsTruncBroadcast(SDLoc DL, MVT VT, SDValue V0,
7870                                                   int BroadcastIdx,
7871                                                   const X86Subtarget *Subtarget,
7872                                                   SelectionDAG &DAG) {
7873   assert(Subtarget->hasAVX2() &&
7874          "We can only lower integer broadcasts with AVX2!");
7875
7876   EVT EltVT = VT.getVectorElementType();
7877   EVT V0VT = V0.getValueType();
7878
7879   assert(VT.isInteger() && "Unexpected non-integer trunc broadcast!");
7880   assert(V0VT.isVector() && "Unexpected non-vector vector-sized value!");
7881
7882   EVT V0EltVT = V0VT.getVectorElementType();
7883   if (!V0EltVT.isInteger())
7884     return SDValue();
7885
7886   const unsigned EltSize = EltVT.getSizeInBits();
7887   const unsigned V0EltSize = V0EltVT.getSizeInBits();
7888
7889   // This is only a truncation if the original element type is larger.
7890   if (V0EltSize <= EltSize)
7891     return SDValue();
7892
7893   assert(((V0EltSize % EltSize) == 0) &&
7894          "Scalar type sizes must all be powers of 2 on x86!");
7895
7896   const unsigned V0Opc = V0.getOpcode();
7897   const unsigned Scale = V0EltSize / EltSize;
7898   const unsigned V0BroadcastIdx = BroadcastIdx / Scale;
7899
7900   if ((V0Opc != ISD::SCALAR_TO_VECTOR || V0BroadcastIdx != 0) &&
7901       V0Opc != ISD::BUILD_VECTOR)
7902     return SDValue();
7903
7904   SDValue Scalar = V0.getOperand(V0BroadcastIdx);
7905
7906   // If we're extracting non-least-significant bits, shift so we can truncate.
7907   // Hopefully, we can fold away the trunc/srl/load into the broadcast.
7908   // Even if we can't (and !isShuffleFoldableLoad(Scalar)), prefer
7909   // vpbroadcast+vmovd+shr to vpshufb(m)+vmovd.
7910   if (const int OffsetIdx = BroadcastIdx % Scale)
7911     Scalar = DAG.getNode(ISD::SRL, DL, Scalar.getValueType(), Scalar,
7912             DAG.getConstant(OffsetIdx * EltSize, DL, Scalar.getValueType()));
7913
7914   return DAG.getNode(X86ISD::VBROADCAST, DL, VT,
7915                      DAG.getNode(ISD::TRUNCATE, DL, EltVT, Scalar));
7916 }
7917
7918 /// \brief Try to lower broadcast of a single element.
7919 ///
7920 /// For convenience, this code also bundles all of the subtarget feature set
7921 /// filtering. While a little annoying to re-dispatch on type here, there isn't
7922 /// a convenient way to factor it out.
7923 static SDValue lowerVectorShuffleAsBroadcast(SDLoc DL, MVT VT, SDValue V,
7924                                              ArrayRef<int> Mask,
7925                                              const X86Subtarget *Subtarget,
7926                                              SelectionDAG &DAG) {
7927   if (!Subtarget->hasAVX())
7928     return SDValue();
7929   if (VT.isInteger() && !Subtarget->hasAVX2())
7930     return SDValue();
7931
7932   // Check that the mask is a broadcast.
7933   int BroadcastIdx = -1;
7934   for (int M : Mask)
7935     if (M >= 0 && BroadcastIdx == -1)
7936       BroadcastIdx = M;
7937     else if (M >= 0 && M != BroadcastIdx)
7938       return SDValue();
7939
7940   assert(BroadcastIdx < (int)Mask.size() && "We only expect to be called with "
7941                                             "a sorted mask where the broadcast "
7942                                             "comes from V1.");
7943
7944   // Go up the chain of (vector) values to find a scalar load that we can
7945   // combine with the broadcast.
7946   for (;;) {
7947     switch (V.getOpcode()) {
7948     case ISD::CONCAT_VECTORS: {
7949       int OperandSize = Mask.size() / V.getNumOperands();
7950       V = V.getOperand(BroadcastIdx / OperandSize);
7951       BroadcastIdx %= OperandSize;
7952       continue;
7953     }
7954
7955     case ISD::INSERT_SUBVECTOR: {
7956       SDValue VOuter = V.getOperand(0), VInner = V.getOperand(1);
7957       auto ConstantIdx = dyn_cast<ConstantSDNode>(V.getOperand(2));
7958       if (!ConstantIdx)
7959         break;
7960
7961       int BeginIdx = (int)ConstantIdx->getZExtValue();
7962       int EndIdx =
7963           BeginIdx + (int)VInner.getSimpleValueType().getVectorNumElements();
7964       if (BroadcastIdx >= BeginIdx && BroadcastIdx < EndIdx) {
7965         BroadcastIdx -= BeginIdx;
7966         V = VInner;
7967       } else {
7968         V = VOuter;
7969       }
7970       continue;
7971     }
7972     }
7973     break;
7974   }
7975
7976   // Check if this is a broadcast of a scalar. We special case lowering
7977   // for scalars so that we can more effectively fold with loads.
7978   // First, look through bitcast: if the original value has a larger element
7979   // type than the shuffle, the broadcast element is in essence truncated.
7980   // Make that explicit to ease folding.
7981   if (V.getOpcode() == ISD::BITCAST && VT.isInteger())
7982     if (SDValue TruncBroadcast = lowerVectorShuffleAsTruncBroadcast(
7983             DL, VT, V.getOperand(0), BroadcastIdx, Subtarget, DAG))
7984       return TruncBroadcast;
7985
7986   // Also check the simpler case, where we can directly reuse the scalar.
7987   if (V.getOpcode() == ISD::BUILD_VECTOR ||
7988       (V.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)) {
7989     V = V.getOperand(BroadcastIdx);
7990
7991     // If the scalar isn't a load, we can't broadcast from it in AVX1.
7992     // Only AVX2 has register broadcasts.
7993     if (!Subtarget->hasAVX2() && !isShuffleFoldableLoad(V))
7994       return SDValue();
7995   } else if (BroadcastIdx != 0 || !Subtarget->hasAVX2()) {
7996     // We can't broadcast from a vector register without AVX2, and we can only
7997     // broadcast from the zero-element of a vector register.
7998     return SDValue();
7999   }
8000
8001   return DAG.getNode(X86ISD::VBROADCAST, DL, VT, V);
8002 }
8003
8004 // Check for whether we can use INSERTPS to perform the shuffle. We only use
8005 // INSERTPS when the V1 elements are already in the correct locations
8006 // because otherwise we can just always use two SHUFPS instructions which
8007 // are much smaller to encode than a SHUFPS and an INSERTPS. We can also
8008 // perform INSERTPS if a single V1 element is out of place and all V2
8009 // elements are zeroable.
8010 static SDValue lowerVectorShuffleAsInsertPS(SDValue Op, SDValue V1, SDValue V2,
8011                                             ArrayRef<int> Mask,
8012                                             SelectionDAG &DAG) {
8013   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
8014   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8015   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8016   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8017
8018   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
8019
8020   unsigned ZMask = 0;
8021   int V1DstIndex = -1;
8022   int V2DstIndex = -1;
8023   bool V1UsedInPlace = false;
8024
8025   for (int i = 0; i < 4; ++i) {
8026     // Synthesize a zero mask from the zeroable elements (includes undefs).
8027     if (Zeroable[i]) {
8028       ZMask |= 1 << i;
8029       continue;
8030     }
8031
8032     // Flag if we use any V1 inputs in place.
8033     if (i == Mask[i]) {
8034       V1UsedInPlace = true;
8035       continue;
8036     }
8037
8038     // We can only insert a single non-zeroable element.
8039     if (V1DstIndex != -1 || V2DstIndex != -1)
8040       return SDValue();
8041
8042     if (Mask[i] < 4) {
8043       // V1 input out of place for insertion.
8044       V1DstIndex = i;
8045     } else {
8046       // V2 input for insertion.
8047       V2DstIndex = i;
8048     }
8049   }
8050
8051   // Don't bother if we have no (non-zeroable) element for insertion.
8052   if (V1DstIndex == -1 && V2DstIndex == -1)
8053     return SDValue();
8054
8055   // Determine element insertion src/dst indices. The src index is from the
8056   // start of the inserted vector, not the start of the concatenated vector.
8057   unsigned V2SrcIndex = 0;
8058   if (V1DstIndex != -1) {
8059     // If we have a V1 input out of place, we use V1 as the V2 element insertion
8060     // and don't use the original V2 at all.
8061     V2SrcIndex = Mask[V1DstIndex];
8062     V2DstIndex = V1DstIndex;
8063     V2 = V1;
8064   } else {
8065     V2SrcIndex = Mask[V2DstIndex] - 4;
8066   }
8067
8068   // If no V1 inputs are used in place, then the result is created only from
8069   // the zero mask and the V2 insertion - so remove V1 dependency.
8070   if (!V1UsedInPlace)
8071     V1 = DAG.getUNDEF(MVT::v4f32);
8072
8073   unsigned InsertPSMask = V2SrcIndex << 6 | V2DstIndex << 4 | ZMask;
8074   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
8075
8076   // Insert the V2 element into the desired position.
8077   SDLoc DL(Op);
8078   return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
8079                      DAG.getConstant(InsertPSMask, DL, MVT::i8));
8080 }
8081
8082 /// \brief Try to lower a shuffle as a permute of the inputs followed by an
8083 /// UNPCK instruction.
8084 ///
8085 /// This specifically targets cases where we end up with alternating between
8086 /// the two inputs, and so can permute them into something that feeds a single
8087 /// UNPCK instruction. Note that this routine only targets integer vectors
8088 /// because for floating point vectors we have a generalized SHUFPS lowering
8089 /// strategy that handles everything that doesn't *exactly* match an unpack,
8090 /// making this clever lowering unnecessary.
8091 static SDValue lowerVectorShuffleAsPermuteAndUnpack(SDLoc DL, MVT VT,
8092                                                     SDValue V1, SDValue V2,
8093                                                     ArrayRef<int> Mask,
8094                                                     SelectionDAG &DAG) {
8095   assert(!VT.isFloatingPoint() &&
8096          "This routine only supports integer vectors.");
8097   assert(!isSingleInputShuffleMask(Mask) &&
8098          "This routine should only be used when blending two inputs.");
8099   assert(Mask.size() >= 2 && "Single element masks are invalid.");
8100
8101   int Size = Mask.size();
8102
8103   int NumLoInputs = std::count_if(Mask.begin(), Mask.end(), [Size](int M) {
8104     return M >= 0 && M % Size < Size / 2;
8105   });
8106   int NumHiInputs = std::count_if(
8107       Mask.begin(), Mask.end(), [Size](int M) { return M % Size >= Size / 2; });
8108
8109   bool UnpackLo = NumLoInputs >= NumHiInputs;
8110
8111   auto TryUnpack = [&](MVT UnpackVT, int Scale) {
8112     SmallVector<int, 32> V1Mask(Mask.size(), -1);
8113     SmallVector<int, 32> V2Mask(Mask.size(), -1);
8114
8115     for (int i = 0; i < Size; ++i) {
8116       if (Mask[i] < 0)
8117         continue;
8118
8119       // Each element of the unpack contains Scale elements from this mask.
8120       int UnpackIdx = i / Scale;
8121
8122       // We only handle the case where V1 feeds the first slots of the unpack.
8123       // We rely on canonicalization to ensure this is the case.
8124       if ((UnpackIdx % 2 == 0) != (Mask[i] < Size))
8125         return SDValue();
8126
8127       // Setup the mask for this input. The indexing is tricky as we have to
8128       // handle the unpack stride.
8129       SmallVectorImpl<int> &VMask = (UnpackIdx % 2 == 0) ? V1Mask : V2Mask;
8130       VMask[(UnpackIdx / 2) * Scale + i % Scale + (UnpackLo ? 0 : Size / 2)] =
8131           Mask[i] % Size;
8132     }
8133
8134     // If we will have to shuffle both inputs to use the unpack, check whether
8135     // we can just unpack first and shuffle the result. If so, skip this unpack.
8136     if ((NumLoInputs == 0 || NumHiInputs == 0) && !isNoopShuffleMask(V1Mask) &&
8137         !isNoopShuffleMask(V2Mask))
8138       return SDValue();
8139
8140     // Shuffle the inputs into place.
8141     V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
8142     V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
8143
8144     // Cast the inputs to the type we will use to unpack them.
8145     V1 = DAG.getBitcast(UnpackVT, V1);
8146     V2 = DAG.getBitcast(UnpackVT, V2);
8147
8148     // Unpack the inputs and cast the result back to the desired type.
8149     return DAG.getBitcast(
8150         VT, DAG.getNode(UnpackLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
8151                         UnpackVT, V1, V2));
8152   };
8153
8154   // We try each unpack from the largest to the smallest to try and find one
8155   // that fits this mask.
8156   int OrigNumElements = VT.getVectorNumElements();
8157   int OrigScalarSize = VT.getScalarSizeInBits();
8158   for (int ScalarSize = 64; ScalarSize >= OrigScalarSize; ScalarSize /= 2) {
8159     int Scale = ScalarSize / OrigScalarSize;
8160     int NumElements = OrigNumElements / Scale;
8161     MVT UnpackVT = MVT::getVectorVT(MVT::getIntegerVT(ScalarSize), NumElements);
8162     if (SDValue Unpack = TryUnpack(UnpackVT, Scale))
8163       return Unpack;
8164   }
8165
8166   // If none of the unpack-rooted lowerings worked (or were profitable) try an
8167   // initial unpack.
8168   if (NumLoInputs == 0 || NumHiInputs == 0) {
8169     assert((NumLoInputs > 0 || NumHiInputs > 0) &&
8170            "We have to have *some* inputs!");
8171     int HalfOffset = NumLoInputs == 0 ? Size / 2 : 0;
8172
8173     // FIXME: We could consider the total complexity of the permute of each
8174     // possible unpacking. Or at the least we should consider how many
8175     // half-crossings are created.
8176     // FIXME: We could consider commuting the unpacks.
8177
8178     SmallVector<int, 32> PermMask;
8179     PermMask.assign(Size, -1);
8180     for (int i = 0; i < Size; ++i) {
8181       if (Mask[i] < 0)
8182         continue;
8183
8184       assert(Mask[i] % Size >= HalfOffset && "Found input from wrong half!");
8185
8186       PermMask[i] =
8187           2 * ((Mask[i] % Size) - HalfOffset) + (Mask[i] < Size ? 0 : 1);
8188     }
8189     return DAG.getVectorShuffle(
8190         VT, DL, DAG.getNode(NumLoInputs == 0 ? X86ISD::UNPCKH : X86ISD::UNPCKL,
8191                             DL, VT, V1, V2),
8192         DAG.getUNDEF(VT), PermMask);
8193   }
8194
8195   return SDValue();
8196 }
8197
8198 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
8199 ///
8200 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
8201 /// support for floating point shuffles but not integer shuffles. These
8202 /// instructions will incur a domain crossing penalty on some chips though so
8203 /// it is better to avoid lowering through this for integer vectors where
8204 /// possible.
8205 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8206                                        const X86Subtarget *Subtarget,
8207                                        SelectionDAG &DAG) {
8208   SDLoc DL(Op);
8209   assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
8210   assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
8211   assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
8212   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8213   ArrayRef<int> Mask = SVOp->getMask();
8214   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
8215
8216   if (isSingleInputShuffleMask(Mask)) {
8217     // Use low duplicate instructions for masks that match their pattern.
8218     if (Subtarget->hasSSE3())
8219       if (isShuffleEquivalent(V1, V2, Mask, {0, 0}))
8220         return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v2f64, V1);
8221
8222     // Straight shuffle of a single input vector. Simulate this by using the
8223     // single input as both of the "inputs" to this instruction..
8224     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
8225
8226     if (Subtarget->hasAVX()) {
8227       // If we have AVX, we can use VPERMILPS which will allow folding a load
8228       // into the shuffle.
8229       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v2f64, V1,
8230                          DAG.getConstant(SHUFPDMask, DL, MVT::i8));
8231     }
8232
8233     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V1,
8234                        DAG.getConstant(SHUFPDMask, DL, MVT::i8));
8235   }
8236   assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
8237   assert(Mask[1] >= 2 && "Non-canonicalized blend!");
8238
8239   // If we have a single input, insert that into V1 if we can do so cheaply.
8240   if ((Mask[0] >= 2) + (Mask[1] >= 2) == 1) {
8241     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8242             DL, MVT::v2f64, V1, V2, Mask, Subtarget, DAG))
8243       return Insertion;
8244     // Try inverting the insertion since for v2 masks it is easy to do and we
8245     // can't reliably sort the mask one way or the other.
8246     int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
8247                           Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
8248     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8249             DL, MVT::v2f64, V2, V1, InverseMask, Subtarget, DAG))
8250       return Insertion;
8251   }
8252
8253   // Try to use one of the special instruction patterns to handle two common
8254   // blend patterns if a zero-blend above didn't work.
8255   if (isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
8256       isShuffleEquivalent(V1, V2, Mask, {1, 3}))
8257     if (SDValue V1S = getScalarValueForVectorElement(V1, Mask[0], DAG))
8258       // We can either use a special instruction to load over the low double or
8259       // to move just the low double.
8260       return DAG.getNode(
8261           isShuffleFoldableLoad(V1S) ? X86ISD::MOVLPD : X86ISD::MOVSD,
8262           DL, MVT::v2f64, V2,
8263           DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V1S));
8264
8265   if (Subtarget->hasSSE41())
8266     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2f64, V1, V2, Mask,
8267                                                   Subtarget, DAG))
8268       return Blend;
8269
8270   // Use dedicated unpack instructions for masks that match their pattern.
8271   if (SDValue V =
8272           lowerVectorShuffleWithUNPCK(DL, MVT::v2f64, Mask, V1, V2, DAG))
8273     return V;
8274
8275   unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
8276   return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V2,
8277                      DAG.getConstant(SHUFPDMask, DL, MVT::i8));
8278 }
8279
8280 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
8281 ///
8282 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
8283 /// the integer unit to minimize domain crossing penalties. However, for blends
8284 /// it falls back to the floating point shuffle operation with appropriate bit
8285 /// casting.
8286 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8287                                        const X86Subtarget *Subtarget,
8288                                        SelectionDAG &DAG) {
8289   SDLoc DL(Op);
8290   assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
8291   assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
8292   assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
8293   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8294   ArrayRef<int> Mask = SVOp->getMask();
8295   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
8296
8297   if (isSingleInputShuffleMask(Mask)) {
8298     // Check for being able to broadcast a single element.
8299     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v2i64, V1,
8300                                                           Mask, Subtarget, DAG))
8301       return Broadcast;
8302
8303     // Straight shuffle of a single input vector. For everything from SSE2
8304     // onward this has a single fast instruction with no scary immediates.
8305     // We have to map the mask as it is actually a v4i32 shuffle instruction.
8306     V1 = DAG.getBitcast(MVT::v4i32, V1);
8307     int WidenedMask[4] = {
8308         std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
8309         std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
8310     return DAG.getBitcast(
8311         MVT::v2i64,
8312         DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
8313                     getV4X86ShuffleImm8ForMask(WidenedMask, DL, DAG)));
8314   }
8315   assert(Mask[0] != -1 && "No undef lanes in multi-input v2 shuffles!");
8316   assert(Mask[1] != -1 && "No undef lanes in multi-input v2 shuffles!");
8317   assert(Mask[0] < 2 && "We sort V1 to be the first input.");
8318   assert(Mask[1] >= 2 && "We sort V2 to be the second input.");
8319
8320   // If we have a blend of two PACKUS operations an the blend aligns with the
8321   // low and half halves, we can just merge the PACKUS operations. This is
8322   // particularly important as it lets us merge shuffles that this routine itself
8323   // creates.
8324   auto GetPackNode = [](SDValue V) {
8325     while (V.getOpcode() == ISD::BITCAST)
8326       V = V.getOperand(0);
8327
8328     return V.getOpcode() == X86ISD::PACKUS ? V : SDValue();
8329   };
8330   if (SDValue V1Pack = GetPackNode(V1))
8331     if (SDValue V2Pack = GetPackNode(V2))
8332       return DAG.getBitcast(MVT::v2i64,
8333                             DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8,
8334                                         Mask[0] == 0 ? V1Pack.getOperand(0)
8335                                                      : V1Pack.getOperand(1),
8336                                         Mask[1] == 2 ? V2Pack.getOperand(0)
8337                                                      : V2Pack.getOperand(1)));
8338
8339   // Try to use shift instructions.
8340   if (SDValue Shift =
8341           lowerVectorShuffleAsShift(DL, MVT::v2i64, V1, V2, Mask, DAG))
8342     return Shift;
8343
8344   // When loading a scalar and then shuffling it into a vector we can often do
8345   // the insertion cheaply.
8346   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8347           DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
8348     return Insertion;
8349   // Try inverting the insertion since for v2 masks it is easy to do and we
8350   // can't reliably sort the mask one way or the other.
8351   int InverseMask[2] = {Mask[0] ^ 2, Mask[1] ^ 2};
8352   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8353           DL, MVT::v2i64, V2, V1, InverseMask, Subtarget, DAG))
8354     return Insertion;
8355
8356   // We have different paths for blend lowering, but they all must use the
8357   // *exact* same predicate.
8358   bool IsBlendSupported = Subtarget->hasSSE41();
8359   if (IsBlendSupported)
8360     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2i64, V1, V2, Mask,
8361                                                   Subtarget, DAG))
8362       return Blend;
8363
8364   // Use dedicated unpack instructions for masks that match their pattern.
8365   if (SDValue V =
8366           lowerVectorShuffleWithUNPCK(DL, MVT::v2i64, Mask, V1, V2, DAG))
8367     return V;
8368
8369   // Try to use byte rotation instructions.
8370   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
8371   if (Subtarget->hasSSSE3())
8372     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8373             DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
8374       return Rotate;
8375
8376   // If we have direct support for blends, we should lower by decomposing into
8377   // a permute. That will be faster than the domain cross.
8378   if (IsBlendSupported)
8379     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v2i64, V1, V2,
8380                                                       Mask, DAG);
8381
8382   // We implement this with SHUFPD which is pretty lame because it will likely
8383   // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
8384   // However, all the alternatives are still more cycles and newer chips don't
8385   // have this problem. It would be really nice if x86 had better shuffles here.
8386   V1 = DAG.getBitcast(MVT::v2f64, V1);
8387   V2 = DAG.getBitcast(MVT::v2f64, V2);
8388   return DAG.getBitcast(MVT::v2i64,
8389                         DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
8390 }
8391
8392 /// \brief Test whether this can be lowered with a single SHUFPS instruction.
8393 ///
8394 /// This is used to disable more specialized lowerings when the shufps lowering
8395 /// will happen to be efficient.
8396 static bool isSingleSHUFPSMask(ArrayRef<int> Mask) {
8397   // This routine only handles 128-bit shufps.
8398   assert(Mask.size() == 4 && "Unsupported mask size!");
8399
8400   // To lower with a single SHUFPS we need to have the low half and high half
8401   // each requiring a single input.
8402   if (Mask[0] != -1 && Mask[1] != -1 && (Mask[0] < 4) != (Mask[1] < 4))
8403     return false;
8404   if (Mask[2] != -1 && Mask[3] != -1 && (Mask[2] < 4) != (Mask[3] < 4))
8405     return false;
8406
8407   return true;
8408 }
8409
8410 /// \brief Lower a vector shuffle using the SHUFPS instruction.
8411 ///
8412 /// This is a helper routine dedicated to lowering vector shuffles using SHUFPS.
8413 /// It makes no assumptions about whether this is the *best* lowering, it simply
8414 /// uses it.
8415 static SDValue lowerVectorShuffleWithSHUFPS(SDLoc DL, MVT VT,
8416                                             ArrayRef<int> Mask, SDValue V1,
8417                                             SDValue V2, SelectionDAG &DAG) {
8418   SDValue LowV = V1, HighV = V2;
8419   int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
8420
8421   int NumV2Elements =
8422       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8423
8424   if (NumV2Elements == 1) {
8425     int V2Index =
8426         std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
8427         Mask.begin();
8428
8429     // Compute the index adjacent to V2Index and in the same half by toggling
8430     // the low bit.
8431     int V2AdjIndex = V2Index ^ 1;
8432
8433     if (Mask[V2AdjIndex] == -1) {
8434       // Handles all the cases where we have a single V2 element and an undef.
8435       // This will only ever happen in the high lanes because we commute the
8436       // vector otherwise.
8437       if (V2Index < 2)
8438         std::swap(LowV, HighV);
8439       NewMask[V2Index] -= 4;
8440     } else {
8441       // Handle the case where the V2 element ends up adjacent to a V1 element.
8442       // To make this work, blend them together as the first step.
8443       int V1Index = V2AdjIndex;
8444       int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
8445       V2 = DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
8446                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
8447
8448       // Now proceed to reconstruct the final blend as we have the necessary
8449       // high or low half formed.
8450       if (V2Index < 2) {
8451         LowV = V2;
8452         HighV = V1;
8453       } else {
8454         HighV = V2;
8455       }
8456       NewMask[V1Index] = 2; // We put the V1 element in V2[2].
8457       NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
8458     }
8459   } else if (NumV2Elements == 2) {
8460     if (Mask[0] < 4 && Mask[1] < 4) {
8461       // Handle the easy case where we have V1 in the low lanes and V2 in the
8462       // high lanes.
8463       NewMask[2] -= 4;
8464       NewMask[3] -= 4;
8465     } else if (Mask[2] < 4 && Mask[3] < 4) {
8466       // We also handle the reversed case because this utility may get called
8467       // when we detect a SHUFPS pattern but can't easily commute the shuffle to
8468       // arrange things in the right direction.
8469       NewMask[0] -= 4;
8470       NewMask[1] -= 4;
8471       HighV = V1;
8472       LowV = V2;
8473     } else {
8474       // We have a mixture of V1 and V2 in both low and high lanes. Rather than
8475       // trying to place elements directly, just blend them and set up the final
8476       // shuffle to place them.
8477
8478       // The first two blend mask elements are for V1, the second two are for
8479       // V2.
8480       int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
8481                           Mask[2] < 4 ? Mask[2] : Mask[3],
8482                           (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
8483                           (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
8484       V1 = DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
8485                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
8486
8487       // Now we do a normal shuffle of V1 by giving V1 as both operands to
8488       // a blend.
8489       LowV = HighV = V1;
8490       NewMask[0] = Mask[0] < 4 ? 0 : 2;
8491       NewMask[1] = Mask[0] < 4 ? 2 : 0;
8492       NewMask[2] = Mask[2] < 4 ? 1 : 3;
8493       NewMask[3] = Mask[2] < 4 ? 3 : 1;
8494     }
8495   }
8496   return DAG.getNode(X86ISD::SHUFP, DL, VT, LowV, HighV,
8497                      getV4X86ShuffleImm8ForMask(NewMask, DL, DAG));
8498 }
8499
8500 /// \brief Lower 4-lane 32-bit floating point shuffles.
8501 ///
8502 /// Uses instructions exclusively from the floating point unit to minimize
8503 /// domain crossing penalties, as these are sufficient to implement all v4f32
8504 /// shuffles.
8505 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8506                                        const X86Subtarget *Subtarget,
8507                                        SelectionDAG &DAG) {
8508   SDLoc DL(Op);
8509   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
8510   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8511   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8512   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8513   ArrayRef<int> Mask = SVOp->getMask();
8514   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8515
8516   int NumV2Elements =
8517       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8518
8519   if (NumV2Elements == 0) {
8520     // Check for being able to broadcast a single element.
8521     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f32, V1,
8522                                                           Mask, Subtarget, DAG))
8523       return Broadcast;
8524
8525     // Use even/odd duplicate instructions for masks that match their pattern.
8526     if (Subtarget->hasSSE3()) {
8527       if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
8528         return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v4f32, V1);
8529       if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3}))
8530         return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v4f32, V1);
8531     }
8532
8533     if (Subtarget->hasAVX()) {
8534       // If we have AVX, we can use VPERMILPS which will allow folding a load
8535       // into the shuffle.
8536       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f32, V1,
8537                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8538     }
8539
8540     // Otherwise, use a straight shuffle of a single input vector. We pass the
8541     // input vector to both operands to simulate this with a SHUFPS.
8542     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
8543                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8544   }
8545
8546   // There are special ways we can lower some single-element blends. However, we
8547   // have custom ways we can lower more complex single-element blends below that
8548   // we defer to if both this and BLENDPS fail to match, so restrict this to
8549   // when the V2 input is targeting element 0 of the mask -- that is the fast
8550   // case here.
8551   if (NumV2Elements == 1 && Mask[0] >= 4)
8552     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4f32, V1, V2,
8553                                                          Mask, Subtarget, DAG))
8554       return V;
8555
8556   if (Subtarget->hasSSE41()) {
8557     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f32, V1, V2, Mask,
8558                                                   Subtarget, DAG))
8559       return Blend;
8560
8561     // Use INSERTPS if we can complete the shuffle efficiently.
8562     if (SDValue V = lowerVectorShuffleAsInsertPS(Op, V1, V2, Mask, DAG))
8563       return V;
8564
8565     if (!isSingleSHUFPSMask(Mask))
8566       if (SDValue BlendPerm = lowerVectorShuffleAsBlendAndPermute(
8567               DL, MVT::v4f32, V1, V2, Mask, DAG))
8568         return BlendPerm;
8569   }
8570
8571   // Use dedicated unpack instructions for masks that match their pattern.
8572   if (SDValue V =
8573           lowerVectorShuffleWithUNPCK(DL, MVT::v4f32, Mask, V1, V2, DAG))
8574     return V;
8575
8576   // Otherwise fall back to a SHUFPS lowering strategy.
8577   return lowerVectorShuffleWithSHUFPS(DL, MVT::v4f32, Mask, V1, V2, DAG);
8578 }
8579
8580 /// \brief Lower 4-lane i32 vector shuffles.
8581 ///
8582 /// We try to handle these with integer-domain shuffles where we can, but for
8583 /// blends we use the floating point domain blend instructions.
8584 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8585                                        const X86Subtarget *Subtarget,
8586                                        SelectionDAG &DAG) {
8587   SDLoc DL(Op);
8588   assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
8589   assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8590   assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8591   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8592   ArrayRef<int> Mask = SVOp->getMask();
8593   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8594
8595   // Whenever we can lower this as a zext, that instruction is strictly faster
8596   // than any alternative. It also allows us to fold memory operands into the
8597   // shuffle in many cases.
8598   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v4i32, V1, V2,
8599                                                          Mask, Subtarget, DAG))
8600     return ZExt;
8601
8602   int NumV2Elements =
8603       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8604
8605   if (NumV2Elements == 0) {
8606     // Check for being able to broadcast a single element.
8607     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i32, V1,
8608                                                           Mask, Subtarget, DAG))
8609       return Broadcast;
8610
8611     // Straight shuffle of a single input vector. For everything from SSE2
8612     // onward this has a single fast instruction with no scary immediates.
8613     // We coerce the shuffle pattern to be compatible with UNPCK instructions
8614     // but we aren't actually going to use the UNPCK instruction because doing
8615     // so prevents folding a load into this instruction or making a copy.
8616     const int UnpackLoMask[] = {0, 0, 1, 1};
8617     const int UnpackHiMask[] = {2, 2, 3, 3};
8618     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 1, 1}))
8619       Mask = UnpackLoMask;
8620     else if (isShuffleEquivalent(V1, V2, Mask, {2, 2, 3, 3}))
8621       Mask = UnpackHiMask;
8622
8623     return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
8624                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8625   }
8626
8627   // Try to use shift instructions.
8628   if (SDValue Shift =
8629           lowerVectorShuffleAsShift(DL, MVT::v4i32, V1, V2, Mask, DAG))
8630     return Shift;
8631
8632   // There are special ways we can lower some single-element blends.
8633   if (NumV2Elements == 1)
8634     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4i32, V1, V2,
8635                                                          Mask, Subtarget, DAG))
8636       return V;
8637
8638   // We have different paths for blend lowering, but they all must use the
8639   // *exact* same predicate.
8640   bool IsBlendSupported = Subtarget->hasSSE41();
8641   if (IsBlendSupported)
8642     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i32, V1, V2, Mask,
8643                                                   Subtarget, DAG))
8644       return Blend;
8645
8646   if (SDValue Masked =
8647           lowerVectorShuffleAsBitMask(DL, MVT::v4i32, V1, V2, Mask, DAG))
8648     return Masked;
8649
8650   // Use dedicated unpack instructions for masks that match their pattern.
8651   if (SDValue V =
8652           lowerVectorShuffleWithUNPCK(DL, MVT::v4i32, Mask, V1, V2, DAG))
8653     return V;
8654
8655   // Try to use byte rotation instructions.
8656   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
8657   if (Subtarget->hasSSSE3())
8658     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8659             DL, MVT::v4i32, V1, V2, Mask, Subtarget, DAG))
8660       return Rotate;
8661
8662   // If we have direct support for blends, we should lower by decomposing into
8663   // a permute. That will be faster than the domain cross.
8664   if (IsBlendSupported)
8665     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i32, V1, V2,
8666                                                       Mask, DAG);
8667
8668   // Try to lower by permuting the inputs into an unpack instruction.
8669   if (SDValue Unpack = lowerVectorShuffleAsPermuteAndUnpack(DL, MVT::v4i32, V1,
8670                                                             V2, Mask, DAG))
8671     return Unpack;
8672
8673   // We implement this with SHUFPS because it can blend from two vectors.
8674   // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
8675   // up the inputs, bypassing domain shift penalties that we would encur if we
8676   // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
8677   // relevant.
8678   return DAG.getBitcast(
8679       MVT::v4i32,
8680       DAG.getVectorShuffle(MVT::v4f32, DL, DAG.getBitcast(MVT::v4f32, V1),
8681                            DAG.getBitcast(MVT::v4f32, V2), Mask));
8682 }
8683
8684 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
8685 /// shuffle lowering, and the most complex part.
8686 ///
8687 /// The lowering strategy is to try to form pairs of input lanes which are
8688 /// targeted at the same half of the final vector, and then use a dword shuffle
8689 /// to place them onto the right half, and finally unpack the paired lanes into
8690 /// their final position.
8691 ///
8692 /// The exact breakdown of how to form these dword pairs and align them on the
8693 /// correct sides is really tricky. See the comments within the function for
8694 /// more of the details.
8695 ///
8696 /// This code also handles repeated 128-bit lanes of v8i16 shuffles, but each
8697 /// lane must shuffle the *exact* same way. In fact, you must pass a v8 Mask to
8698 /// this routine for it to work correctly. To shuffle a 256-bit or 512-bit i16
8699 /// vector, form the analogous 128-bit 8-element Mask.
8700 static SDValue lowerV8I16GeneralSingleInputVectorShuffle(
8701     SDLoc DL, MVT VT, SDValue V, MutableArrayRef<int> Mask,
8702     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
8703   assert(VT.getVectorElementType() == MVT::i16 && "Bad input type!");
8704   MVT PSHUFDVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
8705
8706   assert(Mask.size() == 8 && "Shuffle mask length doen't match!");
8707   MutableArrayRef<int> LoMask = Mask.slice(0, 4);
8708   MutableArrayRef<int> HiMask = Mask.slice(4, 4);
8709
8710   SmallVector<int, 4> LoInputs;
8711   std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
8712                [](int M) { return M >= 0; });
8713   std::sort(LoInputs.begin(), LoInputs.end());
8714   LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
8715   SmallVector<int, 4> HiInputs;
8716   std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
8717                [](int M) { return M >= 0; });
8718   std::sort(HiInputs.begin(), HiInputs.end());
8719   HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
8720   int NumLToL =
8721       std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
8722   int NumHToL = LoInputs.size() - NumLToL;
8723   int NumLToH =
8724       std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
8725   int NumHToH = HiInputs.size() - NumLToH;
8726   MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
8727   MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
8728   MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
8729   MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
8730
8731   // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
8732   // such inputs we can swap two of the dwords across the half mark and end up
8733   // with <=2 inputs to each half in each half. Once there, we can fall through
8734   // to the generic code below. For example:
8735   //
8736   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8737   // Mask:  [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
8738   //
8739   // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
8740   // and an existing 2-into-2 on the other half. In this case we may have to
8741   // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
8742   // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
8743   // Fortunately, we don't have to handle anything but a 2-into-2 pattern
8744   // because any other situation (including a 3-into-1 or 1-into-3 in the other
8745   // half than the one we target for fixing) will be fixed when we re-enter this
8746   // path. We will also combine away any sequence of PSHUFD instructions that
8747   // result into a single instruction. Here is an example of the tricky case:
8748   //
8749   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8750   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
8751   //
8752   // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
8753   //
8754   // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
8755   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
8756   //
8757   // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
8758   // Mask:  [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
8759   //
8760   // The result is fine to be handled by the generic logic.
8761   auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
8762                           ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
8763                           int AOffset, int BOffset) {
8764     assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
8765            "Must call this with A having 3 or 1 inputs from the A half.");
8766     assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
8767            "Must call this with B having 1 or 3 inputs from the B half.");
8768     assert(AToAInputs.size() + BToAInputs.size() == 4 &&
8769            "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
8770
8771     bool ThreeAInputs = AToAInputs.size() == 3;
8772
8773     // Compute the index of dword with only one word among the three inputs in
8774     // a half by taking the sum of the half with three inputs and subtracting
8775     // the sum of the actual three inputs. The difference is the remaining
8776     // slot.
8777     int ADWord, BDWord;
8778     int &TripleDWord = ThreeAInputs ? ADWord : BDWord;
8779     int &OneInputDWord = ThreeAInputs ? BDWord : ADWord;
8780     int TripleInputOffset = ThreeAInputs ? AOffset : BOffset;
8781     ArrayRef<int> TripleInputs = ThreeAInputs ? AToAInputs : BToAInputs;
8782     int OneInput = ThreeAInputs ? BToAInputs[0] : AToAInputs[0];
8783     int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
8784     int TripleNonInputIdx =
8785         TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
8786     TripleDWord = TripleNonInputIdx / 2;
8787
8788     // We use xor with one to compute the adjacent DWord to whichever one the
8789     // OneInput is in.
8790     OneInputDWord = (OneInput / 2) ^ 1;
8791
8792     // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
8793     // and BToA inputs. If there is also such a problem with the BToB and AToB
8794     // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
8795     // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
8796     // is essential that we don't *create* a 3<-1 as then we might oscillate.
8797     if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
8798       // Compute how many inputs will be flipped by swapping these DWords. We
8799       // need
8800       // to balance this to ensure we don't form a 3-1 shuffle in the other
8801       // half.
8802       int NumFlippedAToBInputs =
8803           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
8804           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
8805       int NumFlippedBToBInputs =
8806           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
8807           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
8808       if ((NumFlippedAToBInputs == 1 &&
8809            (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
8810           (NumFlippedBToBInputs == 1 &&
8811            (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
8812         // We choose whether to fix the A half or B half based on whether that
8813         // half has zero flipped inputs. At zero, we may not be able to fix it
8814         // with that half. We also bias towards fixing the B half because that
8815         // will more commonly be the high half, and we have to bias one way.
8816         auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
8817                                                        ArrayRef<int> Inputs) {
8818           int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
8819           bool IsFixIdxInput = std::find(Inputs.begin(), Inputs.end(),
8820                                          PinnedIdx ^ 1) != Inputs.end();
8821           // Determine whether the free index is in the flipped dword or the
8822           // unflipped dword based on where the pinned index is. We use this bit
8823           // in an xor to conditionally select the adjacent dword.
8824           int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
8825           bool IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8826                                              FixFreeIdx) != Inputs.end();
8827           if (IsFixIdxInput == IsFixFreeIdxInput)
8828             FixFreeIdx += 1;
8829           IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8830                                         FixFreeIdx) != Inputs.end();
8831           assert(IsFixIdxInput != IsFixFreeIdxInput &&
8832                  "We need to be changing the number of flipped inputs!");
8833           int PSHUFHalfMask[] = {0, 1, 2, 3};
8834           std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
8835           V = DAG.getNode(FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
8836                           MVT::v8i16, V,
8837                           getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DL, DAG));
8838
8839           for (int &M : Mask)
8840             if (M != -1 && M == FixIdx)
8841               M = FixFreeIdx;
8842             else if (M != -1 && M == FixFreeIdx)
8843               M = FixIdx;
8844         };
8845         if (NumFlippedBToBInputs != 0) {
8846           int BPinnedIdx =
8847               BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8848           FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
8849         } else {
8850           assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
8851           int APinnedIdx = ThreeAInputs ? TripleNonInputIdx : OneInput;
8852           FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
8853         }
8854       }
8855     }
8856
8857     int PSHUFDMask[] = {0, 1, 2, 3};
8858     PSHUFDMask[ADWord] = BDWord;
8859     PSHUFDMask[BDWord] = ADWord;
8860     V = DAG.getBitcast(
8861         VT,
8862         DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
8863                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
8864
8865     // Adjust the mask to match the new locations of A and B.
8866     for (int &M : Mask)
8867       if (M != -1 && M/2 == ADWord)
8868         M = 2 * BDWord + M % 2;
8869       else if (M != -1 && M/2 == BDWord)
8870         M = 2 * ADWord + M % 2;
8871
8872     // Recurse back into this routine to re-compute state now that this isn't
8873     // a 3 and 1 problem.
8874     return lowerV8I16GeneralSingleInputVectorShuffle(DL, VT, V, Mask, Subtarget,
8875                                                      DAG);
8876   };
8877   if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
8878     return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
8879   else if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
8880     return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
8881
8882   // At this point there are at most two inputs to the low and high halves from
8883   // each half. That means the inputs can always be grouped into dwords and
8884   // those dwords can then be moved to the correct half with a dword shuffle.
8885   // We use at most one low and one high word shuffle to collect these paired
8886   // inputs into dwords, and finally a dword shuffle to place them.
8887   int PSHUFLMask[4] = {-1, -1, -1, -1};
8888   int PSHUFHMask[4] = {-1, -1, -1, -1};
8889   int PSHUFDMask[4] = {-1, -1, -1, -1};
8890
8891   // First fix the masks for all the inputs that are staying in their
8892   // original halves. This will then dictate the targets of the cross-half
8893   // shuffles.
8894   auto fixInPlaceInputs =
8895       [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
8896                     MutableArrayRef<int> SourceHalfMask,
8897                     MutableArrayRef<int> HalfMask, int HalfOffset) {
8898     if (InPlaceInputs.empty())
8899       return;
8900     if (InPlaceInputs.size() == 1) {
8901       SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8902           InPlaceInputs[0] - HalfOffset;
8903       PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
8904       return;
8905     }
8906     if (IncomingInputs.empty()) {
8907       // Just fix all of the in place inputs.
8908       for (int Input : InPlaceInputs) {
8909         SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
8910         PSHUFDMask[Input / 2] = Input / 2;
8911       }
8912       return;
8913     }
8914
8915     assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
8916     SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8917         InPlaceInputs[0] - HalfOffset;
8918     // Put the second input next to the first so that they are packed into
8919     // a dword. We find the adjacent index by toggling the low bit.
8920     int AdjIndex = InPlaceInputs[0] ^ 1;
8921     SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
8922     std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
8923     PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
8924   };
8925   fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
8926   fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
8927
8928   // Now gather the cross-half inputs and place them into a free dword of
8929   // their target half.
8930   // FIXME: This operation could almost certainly be simplified dramatically to
8931   // look more like the 3-1 fixing operation.
8932   auto moveInputsToRightHalf = [&PSHUFDMask](
8933       MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
8934       MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
8935       MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
8936       int DestOffset) {
8937     auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
8938       return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
8939     };
8940     auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
8941                                                int Word) {
8942       int LowWord = Word & ~1;
8943       int HighWord = Word | 1;
8944       return isWordClobbered(SourceHalfMask, LowWord) ||
8945              isWordClobbered(SourceHalfMask, HighWord);
8946     };
8947
8948     if (IncomingInputs.empty())
8949       return;
8950
8951     if (ExistingInputs.empty()) {
8952       // Map any dwords with inputs from them into the right half.
8953       for (int Input : IncomingInputs) {
8954         // If the source half mask maps over the inputs, turn those into
8955         // swaps and use the swapped lane.
8956         if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
8957           if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
8958             SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
8959                 Input - SourceOffset;
8960             // We have to swap the uses in our half mask in one sweep.
8961             for (int &M : HalfMask)
8962               if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
8963                 M = Input;
8964               else if (M == Input)
8965                 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8966           } else {
8967             assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
8968                        Input - SourceOffset &&
8969                    "Previous placement doesn't match!");
8970           }
8971           // Note that this correctly re-maps both when we do a swap and when
8972           // we observe the other side of the swap above. We rely on that to
8973           // avoid swapping the members of the input list directly.
8974           Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8975         }
8976
8977         // Map the input's dword into the correct half.
8978         if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
8979           PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
8980         else
8981           assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
8982                      Input / 2 &&
8983                  "Previous placement doesn't match!");
8984       }
8985
8986       // And just directly shift any other-half mask elements to be same-half
8987       // as we will have mirrored the dword containing the element into the
8988       // same position within that half.
8989       for (int &M : HalfMask)
8990         if (M >= SourceOffset && M < SourceOffset + 4) {
8991           M = M - SourceOffset + DestOffset;
8992           assert(M >= 0 && "This should never wrap below zero!");
8993         }
8994       return;
8995     }
8996
8997     // Ensure we have the input in a viable dword of its current half. This
8998     // is particularly tricky because the original position may be clobbered
8999     // by inputs being moved and *staying* in that half.
9000     if (IncomingInputs.size() == 1) {
9001       if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
9002         int InputFixed = std::find(std::begin(SourceHalfMask),
9003                                    std::end(SourceHalfMask), -1) -
9004                          std::begin(SourceHalfMask) + SourceOffset;
9005         SourceHalfMask[InputFixed - SourceOffset] =
9006             IncomingInputs[0] - SourceOffset;
9007         std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
9008                      InputFixed);
9009         IncomingInputs[0] = InputFixed;
9010       }
9011     } else if (IncomingInputs.size() == 2) {
9012       if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
9013           isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
9014         // We have two non-adjacent or clobbered inputs we need to extract from
9015         // the source half. To do this, we need to map them into some adjacent
9016         // dword slot in the source mask.
9017         int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
9018                               IncomingInputs[1] - SourceOffset};
9019
9020         // If there is a free slot in the source half mask adjacent to one of
9021         // the inputs, place the other input in it. We use (Index XOR 1) to
9022         // compute an adjacent index.
9023         if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
9024             SourceHalfMask[InputsFixed[0] ^ 1] == -1) {
9025           SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
9026           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
9027           InputsFixed[1] = InputsFixed[0] ^ 1;
9028         } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
9029                    SourceHalfMask[InputsFixed[1] ^ 1] == -1) {
9030           SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
9031           SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
9032           InputsFixed[0] = InputsFixed[1] ^ 1;
9033         } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] == -1 &&
9034                    SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] == -1) {
9035           // The two inputs are in the same DWord but it is clobbered and the
9036           // adjacent DWord isn't used at all. Move both inputs to the free
9037           // slot.
9038           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
9039           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
9040           InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
9041           InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
9042         } else {
9043           // The only way we hit this point is if there is no clobbering
9044           // (because there are no off-half inputs to this half) and there is no
9045           // free slot adjacent to one of the inputs. In this case, we have to
9046           // swap an input with a non-input.
9047           for (int i = 0; i < 4; ++i)
9048             assert((SourceHalfMask[i] == -1 || SourceHalfMask[i] == i) &&
9049                    "We can't handle any clobbers here!");
9050           assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
9051                  "Cannot have adjacent inputs here!");
9052
9053           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
9054           SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
9055
9056           // We also have to update the final source mask in this case because
9057           // it may need to undo the above swap.
9058           for (int &M : FinalSourceHalfMask)
9059             if (M == (InputsFixed[0] ^ 1) + SourceOffset)
9060               M = InputsFixed[1] + SourceOffset;
9061             else if (M == InputsFixed[1] + SourceOffset)
9062               M = (InputsFixed[0] ^ 1) + SourceOffset;
9063
9064           InputsFixed[1] = InputsFixed[0] ^ 1;
9065         }
9066
9067         // Point everything at the fixed inputs.
9068         for (int &M : HalfMask)
9069           if (M == IncomingInputs[0])
9070             M = InputsFixed[0] + SourceOffset;
9071           else if (M == IncomingInputs[1])
9072             M = InputsFixed[1] + SourceOffset;
9073
9074         IncomingInputs[0] = InputsFixed[0] + SourceOffset;
9075         IncomingInputs[1] = InputsFixed[1] + SourceOffset;
9076       }
9077     } else {
9078       llvm_unreachable("Unhandled input size!");
9079     }
9080
9081     // Now hoist the DWord down to the right half.
9082     int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
9083     assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
9084     PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
9085     for (int &M : HalfMask)
9086       for (int Input : IncomingInputs)
9087         if (M == Input)
9088           M = FreeDWord * 2 + Input % 2;
9089   };
9090   moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
9091                         /*SourceOffset*/ 4, /*DestOffset*/ 0);
9092   moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
9093                         /*SourceOffset*/ 0, /*DestOffset*/ 4);
9094
9095   // Now enact all the shuffles we've computed to move the inputs into their
9096   // target half.
9097   if (!isNoopShuffleMask(PSHUFLMask))
9098     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
9099                     getV4X86ShuffleImm8ForMask(PSHUFLMask, DL, DAG));
9100   if (!isNoopShuffleMask(PSHUFHMask))
9101     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
9102                     getV4X86ShuffleImm8ForMask(PSHUFHMask, DL, DAG));
9103   if (!isNoopShuffleMask(PSHUFDMask))
9104     V = DAG.getBitcast(
9105         VT,
9106         DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
9107                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
9108
9109   // At this point, each half should contain all its inputs, and we can then
9110   // just shuffle them into their final position.
9111   assert(std::count_if(LoMask.begin(), LoMask.end(),
9112                        [](int M) { return M >= 4; }) == 0 &&
9113          "Failed to lift all the high half inputs to the low mask!");
9114   assert(std::count_if(HiMask.begin(), HiMask.end(),
9115                        [](int M) { return M >= 0 && M < 4; }) == 0 &&
9116          "Failed to lift all the low half inputs to the high mask!");
9117
9118   // Do a half shuffle for the low mask.
9119   if (!isNoopShuffleMask(LoMask))
9120     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
9121                     getV4X86ShuffleImm8ForMask(LoMask, DL, DAG));
9122
9123   // Do a half shuffle with the high mask after shifting its values down.
9124   for (int &M : HiMask)
9125     if (M >= 0)
9126       M -= 4;
9127   if (!isNoopShuffleMask(HiMask))
9128     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
9129                     getV4X86ShuffleImm8ForMask(HiMask, DL, DAG));
9130
9131   return V;
9132 }
9133
9134 /// \brief Helper to form a PSHUFB-based shuffle+blend.
9135 static SDValue lowerVectorShuffleAsPSHUFB(SDLoc DL, MVT VT, SDValue V1,
9136                                           SDValue V2, ArrayRef<int> Mask,
9137                                           SelectionDAG &DAG, bool &V1InUse,
9138                                           bool &V2InUse) {
9139   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
9140   SDValue V1Mask[16];
9141   SDValue V2Mask[16];
9142   V1InUse = false;
9143   V2InUse = false;
9144
9145   int Size = Mask.size();
9146   int Scale = 16 / Size;
9147   for (int i = 0; i < 16; ++i) {
9148     if (Mask[i / Scale] == -1) {
9149       V1Mask[i] = V2Mask[i] = DAG.getUNDEF(MVT::i8);
9150     } else {
9151       const int ZeroMask = 0x80;
9152       int V1Idx = Mask[i / Scale] < Size ? Mask[i / Scale] * Scale + i % Scale
9153                                           : ZeroMask;
9154       int V2Idx = Mask[i / Scale] < Size
9155                       ? ZeroMask
9156                       : (Mask[i / Scale] - Size) * Scale + i % Scale;
9157       if (Zeroable[i / Scale])
9158         V1Idx = V2Idx = ZeroMask;
9159       V1Mask[i] = DAG.getConstant(V1Idx, DL, MVT::i8);
9160       V2Mask[i] = DAG.getConstant(V2Idx, DL, MVT::i8);
9161       V1InUse |= (ZeroMask != V1Idx);
9162       V2InUse |= (ZeroMask != V2Idx);
9163     }
9164   }
9165
9166   if (V1InUse)
9167     V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
9168                      DAG.getBitcast(MVT::v16i8, V1),
9169                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
9170   if (V2InUse)
9171     V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
9172                      DAG.getBitcast(MVT::v16i8, V2),
9173                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
9174
9175   // If we need shuffled inputs from both, blend the two.
9176   SDValue V;
9177   if (V1InUse && V2InUse)
9178     V = DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
9179   else
9180     V = V1InUse ? V1 : V2;
9181
9182   // Cast the result back to the correct type.
9183   return DAG.getBitcast(VT, V);
9184 }
9185
9186 /// \brief Generic lowering of 8-lane i16 shuffles.
9187 ///
9188 /// This handles both single-input shuffles and combined shuffle/blends with
9189 /// two inputs. The single input shuffles are immediately delegated to
9190 /// a dedicated lowering routine.
9191 ///
9192 /// The blends are lowered in one of three fundamental ways. If there are few
9193 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
9194 /// of the input is significantly cheaper when lowered as an interleaving of
9195 /// the two inputs, try to interleave them. Otherwise, blend the low and high
9196 /// halves of the inputs separately (making them have relatively few inputs)
9197 /// and then concatenate them.
9198 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9199                                        const X86Subtarget *Subtarget,
9200                                        SelectionDAG &DAG) {
9201   SDLoc DL(Op);
9202   assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
9203   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
9204   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
9205   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9206   ArrayRef<int> OrigMask = SVOp->getMask();
9207   int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
9208                         OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
9209   MutableArrayRef<int> Mask(MaskStorage);
9210
9211   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9212
9213   // Whenever we can lower this as a zext, that instruction is strictly faster
9214   // than any alternative.
9215   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
9216           DL, MVT::v8i16, V1, V2, OrigMask, Subtarget, DAG))
9217     return ZExt;
9218
9219   auto isV1 = [](int M) { return M >= 0 && M < 8; };
9220   (void)isV1;
9221   auto isV2 = [](int M) { return M >= 8; };
9222
9223   int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
9224
9225   if (NumV2Inputs == 0) {
9226     // Check for being able to broadcast a single element.
9227     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i16, V1,
9228                                                           Mask, Subtarget, DAG))
9229       return Broadcast;
9230
9231     // Try to use shift instructions.
9232     if (SDValue Shift =
9233             lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V1, Mask, DAG))
9234       return Shift;
9235
9236     // Use dedicated unpack instructions for masks that match their pattern.
9237     if (SDValue V =
9238             lowerVectorShuffleWithUNPCK(DL, MVT::v8i16, Mask, V1, V2, DAG))
9239       return V;
9240
9241     // Try to use byte rotation instructions.
9242     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(DL, MVT::v8i16, V1, V1,
9243                                                         Mask, Subtarget, DAG))
9244       return Rotate;
9245
9246     return lowerV8I16GeneralSingleInputVectorShuffle(DL, MVT::v8i16, V1, Mask,
9247                                                      Subtarget, DAG);
9248   }
9249
9250   assert(std::any_of(Mask.begin(), Mask.end(), isV1) &&
9251          "All single-input shuffles should be canonicalized to be V1-input "
9252          "shuffles.");
9253
9254   // Try to use shift instructions.
9255   if (SDValue Shift =
9256           lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V2, Mask, DAG))
9257     return Shift;
9258
9259   // See if we can use SSE4A Extraction / Insertion.
9260   if (Subtarget->hasSSE4A())
9261     if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v8i16, V1, V2, Mask, DAG))
9262       return V;
9263
9264   // There are special ways we can lower some single-element blends.
9265   if (NumV2Inputs == 1)
9266     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v8i16, V1, V2,
9267                                                          Mask, Subtarget, DAG))
9268       return V;
9269
9270   // We have different paths for blend lowering, but they all must use the
9271   // *exact* same predicate.
9272   bool IsBlendSupported = Subtarget->hasSSE41();
9273   if (IsBlendSupported)
9274     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i16, V1, V2, Mask,
9275                                                   Subtarget, DAG))
9276       return Blend;
9277
9278   if (SDValue Masked =
9279           lowerVectorShuffleAsBitMask(DL, MVT::v8i16, V1, V2, Mask, DAG))
9280     return Masked;
9281
9282   // Use dedicated unpack instructions for masks that match their pattern.
9283   if (SDValue V =
9284           lowerVectorShuffleWithUNPCK(DL, MVT::v8i16, Mask, V1, V2, DAG))
9285     return V;
9286
9287   // Try to use byte rotation instructions.
9288   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9289           DL, MVT::v8i16, V1, V2, Mask, Subtarget, DAG))
9290     return Rotate;
9291
9292   if (SDValue BitBlend =
9293           lowerVectorShuffleAsBitBlend(DL, MVT::v8i16, V1, V2, Mask, DAG))
9294     return BitBlend;
9295
9296   if (SDValue Unpack = lowerVectorShuffleAsPermuteAndUnpack(DL, MVT::v8i16, V1,
9297                                                             V2, Mask, DAG))
9298     return Unpack;
9299
9300   // If we can't directly blend but can use PSHUFB, that will be better as it
9301   // can both shuffle and set up the inefficient blend.
9302   if (!IsBlendSupported && Subtarget->hasSSSE3()) {
9303     bool V1InUse, V2InUse;
9304     return lowerVectorShuffleAsPSHUFB(DL, MVT::v8i16, V1, V2, Mask, DAG,
9305                                       V1InUse, V2InUse);
9306   }
9307
9308   // We can always bit-blend if we have to so the fallback strategy is to
9309   // decompose into single-input permutes and blends.
9310   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i16, V1, V2,
9311                                                       Mask, DAG);
9312 }
9313
9314 /// \brief Check whether a compaction lowering can be done by dropping even
9315 /// elements and compute how many times even elements must be dropped.
9316 ///
9317 /// This handles shuffles which take every Nth element where N is a power of
9318 /// two. Example shuffle masks:
9319 ///
9320 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14,  0,  2,  4,  6,  8, 10, 12, 14
9321 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
9322 ///  N = 2:  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12
9323 ///  N = 2:  0,  4,  8, 12, 16, 20, 24, 28,  0,  4,  8, 12, 16, 20, 24, 28
9324 ///  N = 3:  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8
9325 ///  N = 3:  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24
9326 ///
9327 /// Any of these lanes can of course be undef.
9328 ///
9329 /// This routine only supports N <= 3.
9330 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
9331 /// for larger N.
9332 ///
9333 /// \returns N above, or the number of times even elements must be dropped if
9334 /// there is such a number. Otherwise returns zero.
9335 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
9336   // Figure out whether we're looping over two inputs or just one.
9337   bool IsSingleInput = isSingleInputShuffleMask(Mask);
9338
9339   // The modulus for the shuffle vector entries is based on whether this is
9340   // a single input or not.
9341   int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
9342   assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
9343          "We should only be called with masks with a power-of-2 size!");
9344
9345   uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
9346
9347   // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
9348   // and 2^3 simultaneously. This is because we may have ambiguity with
9349   // partially undef inputs.
9350   bool ViableForN[3] = {true, true, true};
9351
9352   for (int i = 0, e = Mask.size(); i < e; ++i) {
9353     // Ignore undef lanes, we'll optimistically collapse them to the pattern we
9354     // want.
9355     if (Mask[i] == -1)
9356       continue;
9357
9358     bool IsAnyViable = false;
9359     for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
9360       if (ViableForN[j]) {
9361         uint64_t N = j + 1;
9362
9363         // The shuffle mask must be equal to (i * 2^N) % M.
9364         if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
9365           IsAnyViable = true;
9366         else
9367           ViableForN[j] = false;
9368       }
9369     // Early exit if we exhaust the possible powers of two.
9370     if (!IsAnyViable)
9371       break;
9372   }
9373
9374   for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
9375     if (ViableForN[j])
9376       return j + 1;
9377
9378   // Return 0 as there is no viable power of two.
9379   return 0;
9380 }
9381
9382 /// \brief Generic lowering of v16i8 shuffles.
9383 ///
9384 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
9385 /// detect any complexity reducing interleaving. If that doesn't help, it uses
9386 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
9387 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
9388 /// back together.
9389 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9390                                        const X86Subtarget *Subtarget,
9391                                        SelectionDAG &DAG) {
9392   SDLoc DL(Op);
9393   assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
9394   assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
9395   assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
9396   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9397   ArrayRef<int> Mask = SVOp->getMask();
9398   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
9399
9400   // Try to use shift instructions.
9401   if (SDValue Shift =
9402           lowerVectorShuffleAsShift(DL, MVT::v16i8, V1, V2, Mask, DAG))
9403     return Shift;
9404
9405   // Try to use byte rotation instructions.
9406   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9407           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
9408     return Rotate;
9409
9410   // Try to use a zext lowering.
9411   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
9412           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
9413     return ZExt;
9414
9415   // See if we can use SSE4A Extraction / Insertion.
9416   if (Subtarget->hasSSE4A())
9417     if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v16i8, V1, V2, Mask, DAG))
9418       return V;
9419
9420   int NumV2Elements =
9421       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 16; });
9422
9423   // For single-input shuffles, there are some nicer lowering tricks we can use.
9424   if (NumV2Elements == 0) {
9425     // Check for being able to broadcast a single element.
9426     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i8, V1,
9427                                                           Mask, Subtarget, DAG))
9428       return Broadcast;
9429
9430     // Check whether we can widen this to an i16 shuffle by duplicating bytes.
9431     // Notably, this handles splat and partial-splat shuffles more efficiently.
9432     // However, it only makes sense if the pre-duplication shuffle simplifies
9433     // things significantly. Currently, this means we need to be able to
9434     // express the pre-duplication shuffle as an i16 shuffle.
9435     //
9436     // FIXME: We should check for other patterns which can be widened into an
9437     // i16 shuffle as well.
9438     auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
9439       for (int i = 0; i < 16; i += 2)
9440         if (Mask[i] != -1 && Mask[i + 1] != -1 && Mask[i] != Mask[i + 1])
9441           return false;
9442
9443       return true;
9444     };
9445     auto tryToWidenViaDuplication = [&]() -> SDValue {
9446       if (!canWidenViaDuplication(Mask))
9447         return SDValue();
9448       SmallVector<int, 4> LoInputs;
9449       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
9450                    [](int M) { return M >= 0 && M < 8; });
9451       std::sort(LoInputs.begin(), LoInputs.end());
9452       LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
9453                      LoInputs.end());
9454       SmallVector<int, 4> HiInputs;
9455       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
9456                    [](int M) { return M >= 8; });
9457       std::sort(HiInputs.begin(), HiInputs.end());
9458       HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
9459                      HiInputs.end());
9460
9461       bool TargetLo = LoInputs.size() >= HiInputs.size();
9462       ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
9463       ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
9464
9465       int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
9466       SmallDenseMap<int, int, 8> LaneMap;
9467       for (int I : InPlaceInputs) {
9468         PreDupI16Shuffle[I/2] = I/2;
9469         LaneMap[I] = I;
9470       }
9471       int j = TargetLo ? 0 : 4, je = j + 4;
9472       for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
9473         // Check if j is already a shuffle of this input. This happens when
9474         // there are two adjacent bytes after we move the low one.
9475         if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
9476           // If we haven't yet mapped the input, search for a slot into which
9477           // we can map it.
9478           while (j < je && PreDupI16Shuffle[j] != -1)
9479             ++j;
9480
9481           if (j == je)
9482             // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
9483             return SDValue();
9484
9485           // Map this input with the i16 shuffle.
9486           PreDupI16Shuffle[j] = MovingInputs[i] / 2;
9487         }
9488
9489         // Update the lane map based on the mapping we ended up with.
9490         LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
9491       }
9492       V1 = DAG.getBitcast(
9493           MVT::v16i8,
9494           DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
9495                                DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
9496
9497       // Unpack the bytes to form the i16s that will be shuffled into place.
9498       V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
9499                        MVT::v16i8, V1, V1);
9500
9501       int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9502       for (int i = 0; i < 16; ++i)
9503         if (Mask[i] != -1) {
9504           int MappedMask = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
9505           assert(MappedMask < 8 && "Invalid v8 shuffle mask!");
9506           if (PostDupI16Shuffle[i / 2] == -1)
9507             PostDupI16Shuffle[i / 2] = MappedMask;
9508           else
9509             assert(PostDupI16Shuffle[i / 2] == MappedMask &&
9510                    "Conflicting entrties in the original shuffle!");
9511         }
9512       return DAG.getBitcast(
9513           MVT::v16i8,
9514           DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
9515                                DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
9516     };
9517     if (SDValue V = tryToWidenViaDuplication())
9518       return V;
9519   }
9520
9521   if (SDValue Masked =
9522           lowerVectorShuffleAsBitMask(DL, MVT::v16i8, V1, V2, Mask, DAG))
9523     return Masked;
9524
9525   // Use dedicated unpack instructions for masks that match their pattern.
9526   if (SDValue V =
9527           lowerVectorShuffleWithUNPCK(DL, MVT::v16i8, Mask, V1, V2, DAG))
9528     return V;
9529
9530   // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
9531   // with PSHUFB. It is important to do this before we attempt to generate any
9532   // blends but after all of the single-input lowerings. If the single input
9533   // lowerings can find an instruction sequence that is faster than a PSHUFB, we
9534   // want to preserve that and we can DAG combine any longer sequences into
9535   // a PSHUFB in the end. But once we start blending from multiple inputs,
9536   // the complexity of DAG combining bad patterns back into PSHUFB is too high,
9537   // and there are *very* few patterns that would actually be faster than the
9538   // PSHUFB approach because of its ability to zero lanes.
9539   //
9540   // FIXME: The only exceptions to the above are blends which are exact
9541   // interleavings with direct instructions supporting them. We currently don't
9542   // handle those well here.
9543   if (Subtarget->hasSSSE3()) {
9544     bool V1InUse = false;
9545     bool V2InUse = false;
9546
9547     SDValue PSHUFB = lowerVectorShuffleAsPSHUFB(DL, MVT::v16i8, V1, V2, Mask,
9548                                                 DAG, V1InUse, V2InUse);
9549
9550     // If both V1 and V2 are in use and we can use a direct blend or an unpack,
9551     // do so. This avoids using them to handle blends-with-zero which is
9552     // important as a single pshufb is significantly faster for that.
9553     if (V1InUse && V2InUse) {
9554       if (Subtarget->hasSSE41())
9555         if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i8, V1, V2,
9556                                                       Mask, Subtarget, DAG))
9557           return Blend;
9558
9559       // We can use an unpack to do the blending rather than an or in some
9560       // cases. Even though the or may be (very minorly) more efficient, we
9561       // preference this lowering because there are common cases where part of
9562       // the complexity of the shuffles goes away when we do the final blend as
9563       // an unpack.
9564       // FIXME: It might be worth trying to detect if the unpack-feeding
9565       // shuffles will both be pshufb, in which case we shouldn't bother with
9566       // this.
9567       if (SDValue Unpack = lowerVectorShuffleAsPermuteAndUnpack(
9568               DL, MVT::v16i8, V1, V2, Mask, DAG))
9569         return Unpack;
9570     }
9571
9572     return PSHUFB;
9573   }
9574
9575   // There are special ways we can lower some single-element blends.
9576   if (NumV2Elements == 1)
9577     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v16i8, V1, V2,
9578                                                          Mask, Subtarget, DAG))
9579       return V;
9580
9581   if (SDValue BitBlend =
9582           lowerVectorShuffleAsBitBlend(DL, MVT::v16i8, V1, V2, Mask, DAG))
9583     return BitBlend;
9584
9585   // Check whether a compaction lowering can be done. This handles shuffles
9586   // which take every Nth element for some even N. See the helper function for
9587   // details.
9588   //
9589   // We special case these as they can be particularly efficiently handled with
9590   // the PACKUSB instruction on x86 and they show up in common patterns of
9591   // rearranging bytes to truncate wide elements.
9592   if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
9593     // NumEvenDrops is the power of two stride of the elements. Another way of
9594     // thinking about it is that we need to drop the even elements this many
9595     // times to get the original input.
9596     bool IsSingleInput = isSingleInputShuffleMask(Mask);
9597
9598     // First we need to zero all the dropped bytes.
9599     assert(NumEvenDrops <= 3 &&
9600            "No support for dropping even elements more than 3 times.");
9601     // We use the mask type to pick which bytes are preserved based on how many
9602     // elements are dropped.
9603     MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
9604     SDValue ByteClearMask = DAG.getBitcast(
9605         MVT::v16i8, DAG.getConstant(0xFF, DL, MaskVTs[NumEvenDrops - 1]));
9606     V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
9607     if (!IsSingleInput)
9608       V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
9609
9610     // Now pack things back together.
9611     V1 = DAG.getBitcast(MVT::v8i16, V1);
9612     V2 = IsSingleInput ? V1 : DAG.getBitcast(MVT::v8i16, V2);
9613     SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
9614     for (int i = 1; i < NumEvenDrops; ++i) {
9615       Result = DAG.getBitcast(MVT::v8i16, Result);
9616       Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
9617     }
9618
9619     return Result;
9620   }
9621
9622   // Handle multi-input cases by blending single-input shuffles.
9623   if (NumV2Elements > 0)
9624     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v16i8, V1, V2,
9625                                                       Mask, DAG);
9626
9627   // The fallback path for single-input shuffles widens this into two v8i16
9628   // vectors with unpacks, shuffles those, and then pulls them back together
9629   // with a pack.
9630   SDValue V = V1;
9631
9632   int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9633   int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9634   for (int i = 0; i < 16; ++i)
9635     if (Mask[i] >= 0)
9636       (i < 8 ? LoBlendMask[i] : HiBlendMask[i % 8]) = Mask[i];
9637
9638   SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
9639
9640   SDValue VLoHalf, VHiHalf;
9641   // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
9642   // them out and avoid using UNPCK{L,H} to extract the elements of V as
9643   // i16s.
9644   if (std::none_of(std::begin(LoBlendMask), std::end(LoBlendMask),
9645                    [](int M) { return M >= 0 && M % 2 == 1; }) &&
9646       std::none_of(std::begin(HiBlendMask), std::end(HiBlendMask),
9647                    [](int M) { return M >= 0 && M % 2 == 1; })) {
9648     // Use a mask to drop the high bytes.
9649     VLoHalf = DAG.getBitcast(MVT::v8i16, V);
9650     VLoHalf = DAG.getNode(ISD::AND, DL, MVT::v8i16, VLoHalf,
9651                      DAG.getConstant(0x00FF, DL, MVT::v8i16));
9652
9653     // This will be a single vector shuffle instead of a blend so nuke VHiHalf.
9654     VHiHalf = DAG.getUNDEF(MVT::v8i16);
9655
9656     // Squash the masks to point directly into VLoHalf.
9657     for (int &M : LoBlendMask)
9658       if (M >= 0)
9659         M /= 2;
9660     for (int &M : HiBlendMask)
9661       if (M >= 0)
9662         M /= 2;
9663   } else {
9664     // Otherwise just unpack the low half of V into VLoHalf and the high half into
9665     // VHiHalf so that we can blend them as i16s.
9666     VLoHalf = DAG.getBitcast(
9667         MVT::v8i16, DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
9668     VHiHalf = DAG.getBitcast(
9669         MVT::v8i16, DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
9670   }
9671
9672   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, LoBlendMask);
9673   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, HiBlendMask);
9674
9675   return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
9676 }
9677
9678 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
9679 ///
9680 /// This routine breaks down the specific type of 128-bit shuffle and
9681 /// dispatches to the lowering routines accordingly.
9682 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9683                                         MVT VT, const X86Subtarget *Subtarget,
9684                                         SelectionDAG &DAG) {
9685   switch (VT.SimpleTy) {
9686   case MVT::v2i64:
9687     return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9688   case MVT::v2f64:
9689     return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9690   case MVT::v4i32:
9691     return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9692   case MVT::v4f32:
9693     return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9694   case MVT::v8i16:
9695     return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
9696   case MVT::v16i8:
9697     return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
9698
9699   default:
9700     llvm_unreachable("Unimplemented!");
9701   }
9702 }
9703
9704 /// \brief Helper function to test whether a shuffle mask could be
9705 /// simplified by widening the elements being shuffled.
9706 ///
9707 /// Appends the mask for wider elements in WidenedMask if valid. Otherwise
9708 /// leaves it in an unspecified state.
9709 ///
9710 /// NOTE: This must handle normal vector shuffle masks and *target* vector
9711 /// shuffle masks. The latter have the special property of a '-2' representing
9712 /// a zero-ed lane of a vector.
9713 static bool canWidenShuffleElements(ArrayRef<int> Mask,
9714                                     SmallVectorImpl<int> &WidenedMask) {
9715   for (int i = 0, Size = Mask.size(); i < Size; i += 2) {
9716     // If both elements are undef, its trivial.
9717     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] == SM_SentinelUndef) {
9718       WidenedMask.push_back(SM_SentinelUndef);
9719       continue;
9720     }
9721
9722     // Check for an undef mask and a mask value properly aligned to fit with
9723     // a pair of values. If we find such a case, use the non-undef mask's value.
9724     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] >= 0 && Mask[i + 1] % 2 == 1) {
9725       WidenedMask.push_back(Mask[i + 1] / 2);
9726       continue;
9727     }
9728     if (Mask[i + 1] == SM_SentinelUndef && Mask[i] >= 0 && Mask[i] % 2 == 0) {
9729       WidenedMask.push_back(Mask[i] / 2);
9730       continue;
9731     }
9732
9733     // When zeroing, we need to spread the zeroing across both lanes to widen.
9734     if (Mask[i] == SM_SentinelZero || Mask[i + 1] == SM_SentinelZero) {
9735       if ((Mask[i] == SM_SentinelZero || Mask[i] == SM_SentinelUndef) &&
9736           (Mask[i + 1] == SM_SentinelZero || Mask[i + 1] == SM_SentinelUndef)) {
9737         WidenedMask.push_back(SM_SentinelZero);
9738         continue;
9739       }
9740       return false;
9741     }
9742
9743     // Finally check if the two mask values are adjacent and aligned with
9744     // a pair.
9745     if (Mask[i] != SM_SentinelUndef && Mask[i] % 2 == 0 && Mask[i] + 1 == Mask[i + 1]) {
9746       WidenedMask.push_back(Mask[i] / 2);
9747       continue;
9748     }
9749
9750     // Otherwise we can't safely widen the elements used in this shuffle.
9751     return false;
9752   }
9753   assert(WidenedMask.size() == Mask.size() / 2 &&
9754          "Incorrect size of mask after widening the elements!");
9755
9756   return true;
9757 }
9758
9759 /// \brief Generic routine to split vector shuffle into half-sized shuffles.
9760 ///
9761 /// This routine just extracts two subvectors, shuffles them independently, and
9762 /// then concatenates them back together. This should work effectively with all
9763 /// AVX vector shuffle types.
9764 static SDValue splitAndLowerVectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9765                                           SDValue V2, ArrayRef<int> Mask,
9766                                           SelectionDAG &DAG) {
9767   assert(VT.getSizeInBits() >= 256 &&
9768          "Only for 256-bit or wider vector shuffles!");
9769   assert(V1.getSimpleValueType() == VT && "Bad operand type!");
9770   assert(V2.getSimpleValueType() == VT && "Bad operand type!");
9771
9772   ArrayRef<int> LoMask = Mask.slice(0, Mask.size() / 2);
9773   ArrayRef<int> HiMask = Mask.slice(Mask.size() / 2);
9774
9775   int NumElements = VT.getVectorNumElements();
9776   int SplitNumElements = NumElements / 2;
9777   MVT ScalarVT = VT.getVectorElementType();
9778   MVT SplitVT = MVT::getVectorVT(ScalarVT, NumElements / 2);
9779
9780   // Rather than splitting build-vectors, just build two narrower build
9781   // vectors. This helps shuffling with splats and zeros.
9782   auto SplitVector = [&](SDValue V) {
9783     while (V.getOpcode() == ISD::BITCAST)
9784       V = V->getOperand(0);
9785
9786     MVT OrigVT = V.getSimpleValueType();
9787     int OrigNumElements = OrigVT.getVectorNumElements();
9788     int OrigSplitNumElements = OrigNumElements / 2;
9789     MVT OrigScalarVT = OrigVT.getVectorElementType();
9790     MVT OrigSplitVT = MVT::getVectorVT(OrigScalarVT, OrigNumElements / 2);
9791
9792     SDValue LoV, HiV;
9793
9794     auto *BV = dyn_cast<BuildVectorSDNode>(V);
9795     if (!BV) {
9796       LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9797                         DAG.getIntPtrConstant(0, DL));
9798       HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9799                         DAG.getIntPtrConstant(OrigSplitNumElements, DL));
9800     } else {
9801
9802       SmallVector<SDValue, 16> LoOps, HiOps;
9803       for (int i = 0; i < OrigSplitNumElements; ++i) {
9804         LoOps.push_back(BV->getOperand(i));
9805         HiOps.push_back(BV->getOperand(i + OrigSplitNumElements));
9806       }
9807       LoV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, LoOps);
9808       HiV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, HiOps);
9809     }
9810     return std::make_pair(DAG.getBitcast(SplitVT, LoV),
9811                           DAG.getBitcast(SplitVT, HiV));
9812   };
9813
9814   SDValue LoV1, HiV1, LoV2, HiV2;
9815   std::tie(LoV1, HiV1) = SplitVector(V1);
9816   std::tie(LoV2, HiV2) = SplitVector(V2);
9817
9818   // Now create two 4-way blends of these half-width vectors.
9819   auto HalfBlend = [&](ArrayRef<int> HalfMask) {
9820     bool UseLoV1 = false, UseHiV1 = false, UseLoV2 = false, UseHiV2 = false;
9821     SmallVector<int, 32> V1BlendMask, V2BlendMask, BlendMask;
9822     for (int i = 0; i < SplitNumElements; ++i) {
9823       int M = HalfMask[i];
9824       if (M >= NumElements) {
9825         if (M >= NumElements + SplitNumElements)
9826           UseHiV2 = true;
9827         else
9828           UseLoV2 = true;
9829         V2BlendMask.push_back(M - NumElements);
9830         V1BlendMask.push_back(-1);
9831         BlendMask.push_back(SplitNumElements + i);
9832       } else if (M >= 0) {
9833         if (M >= SplitNumElements)
9834           UseHiV1 = true;
9835         else
9836           UseLoV1 = true;
9837         V2BlendMask.push_back(-1);
9838         V1BlendMask.push_back(M);
9839         BlendMask.push_back(i);
9840       } else {
9841         V2BlendMask.push_back(-1);
9842         V1BlendMask.push_back(-1);
9843         BlendMask.push_back(-1);
9844       }
9845     }
9846
9847     // Because the lowering happens after all combining takes place, we need to
9848     // manually combine these blend masks as much as possible so that we create
9849     // a minimal number of high-level vector shuffle nodes.
9850
9851     // First try just blending the halves of V1 or V2.
9852     if (!UseLoV1 && !UseHiV1 && !UseLoV2 && !UseHiV2)
9853       return DAG.getUNDEF(SplitVT);
9854     if (!UseLoV2 && !UseHiV2)
9855       return DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9856     if (!UseLoV1 && !UseHiV1)
9857       return DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9858
9859     SDValue V1Blend, V2Blend;
9860     if (UseLoV1 && UseHiV1) {
9861       V1Blend =
9862         DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9863     } else {
9864       // We only use half of V1 so map the usage down into the final blend mask.
9865       V1Blend = UseLoV1 ? LoV1 : HiV1;
9866       for (int i = 0; i < SplitNumElements; ++i)
9867         if (BlendMask[i] >= 0 && BlendMask[i] < SplitNumElements)
9868           BlendMask[i] = V1BlendMask[i] - (UseLoV1 ? 0 : SplitNumElements);
9869     }
9870     if (UseLoV2 && UseHiV2) {
9871       V2Blend =
9872         DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9873     } else {
9874       // We only use half of V2 so map the usage down into the final blend mask.
9875       V2Blend = UseLoV2 ? LoV2 : HiV2;
9876       for (int i = 0; i < SplitNumElements; ++i)
9877         if (BlendMask[i] >= SplitNumElements)
9878           BlendMask[i] = V2BlendMask[i] + (UseLoV2 ? SplitNumElements : 0);
9879     }
9880     return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
9881   };
9882   SDValue Lo = HalfBlend(LoMask);
9883   SDValue Hi = HalfBlend(HiMask);
9884   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
9885 }
9886
9887 /// \brief Either split a vector in halves or decompose the shuffles and the
9888 /// blend.
9889 ///
9890 /// This is provided as a good fallback for many lowerings of non-single-input
9891 /// shuffles with more than one 128-bit lane. In those cases, we want to select
9892 /// between splitting the shuffle into 128-bit components and stitching those
9893 /// back together vs. extracting the single-input shuffles and blending those
9894 /// results.
9895 static SDValue lowerVectorShuffleAsSplitOrBlend(SDLoc DL, MVT VT, SDValue V1,
9896                                                 SDValue V2, ArrayRef<int> Mask,
9897                                                 SelectionDAG &DAG) {
9898   assert(!isSingleInputShuffleMask(Mask) && "This routine must not be used to "
9899                                             "lower single-input shuffles as it "
9900                                             "could then recurse on itself.");
9901   int Size = Mask.size();
9902
9903   // If this can be modeled as a broadcast of two elements followed by a blend,
9904   // prefer that lowering. This is especially important because broadcasts can
9905   // often fold with memory operands.
9906   auto DoBothBroadcast = [&] {
9907     int V1BroadcastIdx = -1, V2BroadcastIdx = -1;
9908     for (int M : Mask)
9909       if (M >= Size) {
9910         if (V2BroadcastIdx == -1)
9911           V2BroadcastIdx = M - Size;
9912         else if (M - Size != V2BroadcastIdx)
9913           return false;
9914       } else if (M >= 0) {
9915         if (V1BroadcastIdx == -1)
9916           V1BroadcastIdx = M;
9917         else if (M != V1BroadcastIdx)
9918           return false;
9919       }
9920     return true;
9921   };
9922   if (DoBothBroadcast())
9923     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask,
9924                                                       DAG);
9925
9926   // If the inputs all stem from a single 128-bit lane of each input, then we
9927   // split them rather than blending because the split will decompose to
9928   // unusually few instructions.
9929   int LaneCount = VT.getSizeInBits() / 128;
9930   int LaneSize = Size / LaneCount;
9931   SmallBitVector LaneInputs[2];
9932   LaneInputs[0].resize(LaneCount, false);
9933   LaneInputs[1].resize(LaneCount, false);
9934   for (int i = 0; i < Size; ++i)
9935     if (Mask[i] >= 0)
9936       LaneInputs[Mask[i] / Size][(Mask[i] % Size) / LaneSize] = true;
9937   if (LaneInputs[0].count() <= 1 && LaneInputs[1].count() <= 1)
9938     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9939
9940   // Otherwise, just fall back to decomposed shuffles and a blend. This requires
9941   // that the decomposed single-input shuffles don't end up here.
9942   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9943 }
9944
9945 /// \brief Lower a vector shuffle crossing multiple 128-bit lanes as
9946 /// a permutation and blend of those lanes.
9947 ///
9948 /// This essentially blends the out-of-lane inputs to each lane into the lane
9949 /// from a permuted copy of the vector. This lowering strategy results in four
9950 /// instructions in the worst case for a single-input cross lane shuffle which
9951 /// is lower than any other fully general cross-lane shuffle strategy I'm aware
9952 /// of. Special cases for each particular shuffle pattern should be handled
9953 /// prior to trying this lowering.
9954 static SDValue lowerVectorShuffleAsLanePermuteAndBlend(SDLoc DL, MVT VT,
9955                                                        SDValue V1, SDValue V2,
9956                                                        ArrayRef<int> Mask,
9957                                                        SelectionDAG &DAG) {
9958   // FIXME: This should probably be generalized for 512-bit vectors as well.
9959   assert(VT.is256BitVector() && "Only for 256-bit vector shuffles!");
9960   int LaneSize = Mask.size() / 2;
9961
9962   // If there are only inputs from one 128-bit lane, splitting will in fact be
9963   // less expensive. The flags track whether the given lane contains an element
9964   // that crosses to another lane.
9965   bool LaneCrossing[2] = {false, false};
9966   for (int i = 0, Size = Mask.size(); i < Size; ++i)
9967     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
9968       LaneCrossing[(Mask[i] % Size) / LaneSize] = true;
9969   if (!LaneCrossing[0] || !LaneCrossing[1])
9970     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9971
9972   if (isSingleInputShuffleMask(Mask)) {
9973     SmallVector<int, 32> FlippedBlendMask;
9974     for (int i = 0, Size = Mask.size(); i < Size; ++i)
9975       FlippedBlendMask.push_back(
9976           Mask[i] < 0 ? -1 : (((Mask[i] % Size) / LaneSize == i / LaneSize)
9977                                   ? Mask[i]
9978                                   : Mask[i] % LaneSize +
9979                                         (i / LaneSize) * LaneSize + Size));
9980
9981     // Flip the vector, and blend the results which should now be in-lane. The
9982     // VPERM2X128 mask uses the low 2 bits for the low source and bits 4 and
9983     // 5 for the high source. The value 3 selects the high half of source 2 and
9984     // the value 2 selects the low half of source 2. We only use source 2 to
9985     // allow folding it into a memory operand.
9986     unsigned PERMMask = 3 | 2 << 4;
9987     SDValue Flipped = DAG.getNode(X86ISD::VPERM2X128, DL, VT, DAG.getUNDEF(VT),
9988                                   V1, DAG.getConstant(PERMMask, DL, MVT::i8));
9989     return DAG.getVectorShuffle(VT, DL, V1, Flipped, FlippedBlendMask);
9990   }
9991
9992   // This now reduces to two single-input shuffles of V1 and V2 which at worst
9993   // will be handled by the above logic and a blend of the results, much like
9994   // other patterns in AVX.
9995   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9996 }
9997
9998 /// \brief Handle lowering 2-lane 128-bit shuffles.
9999 static SDValue lowerV2X128VectorShuffle(SDLoc DL, MVT VT, SDValue V1,
10000                                         SDValue V2, ArrayRef<int> Mask,
10001                                         const X86Subtarget *Subtarget,
10002                                         SelectionDAG &DAG) {
10003   // TODO: If minimizing size and one of the inputs is a zero vector and the
10004   // the zero vector has only one use, we could use a VPERM2X128 to save the
10005   // instruction bytes needed to explicitly generate the zero vector.
10006
10007   // Blends are faster and handle all the non-lane-crossing cases.
10008   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, VT, V1, V2, Mask,
10009                                                 Subtarget, DAG))
10010     return Blend;
10011
10012   bool IsV1Zero = ISD::isBuildVectorAllZeros(V1.getNode());
10013   bool IsV2Zero = ISD::isBuildVectorAllZeros(V2.getNode());
10014
10015   // If either input operand is a zero vector, use VPERM2X128 because its mask
10016   // allows us to replace the zero input with an implicit zero.
10017   if (!IsV1Zero && !IsV2Zero) {
10018     // Check for patterns which can be matched with a single insert of a 128-bit
10019     // subvector.
10020     bool OnlyUsesV1 = isShuffleEquivalent(V1, V2, Mask, {0, 1, 0, 1});
10021     if (OnlyUsesV1 || isShuffleEquivalent(V1, V2, Mask, {0, 1, 4, 5})) {
10022       MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(),
10023                                    VT.getVectorNumElements() / 2);
10024       SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
10025                                 DAG.getIntPtrConstant(0, DL));
10026       SDValue HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT,
10027                                 OnlyUsesV1 ? V1 : V2,
10028                                 DAG.getIntPtrConstant(0, DL));
10029       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoV, HiV);
10030     }
10031   }
10032
10033   // Otherwise form a 128-bit permutation. After accounting for undefs,
10034   // convert the 64-bit shuffle mask selection values into 128-bit
10035   // selection bits by dividing the indexes by 2 and shifting into positions
10036   // defined by a vperm2*128 instruction's immediate control byte.
10037
10038   // The immediate permute control byte looks like this:
10039   //    [1:0] - select 128 bits from sources for low half of destination
10040   //    [2]   - ignore
10041   //    [3]   - zero low half of destination
10042   //    [5:4] - select 128 bits from sources for high half of destination
10043   //    [6]   - ignore
10044   //    [7]   - zero high half of destination
10045
10046   int MaskLO = Mask[0];
10047   if (MaskLO == SM_SentinelUndef)
10048     MaskLO = Mask[1] == SM_SentinelUndef ? 0 : Mask[1];
10049
10050   int MaskHI = Mask[2];
10051   if (MaskHI == SM_SentinelUndef)
10052     MaskHI = Mask[3] == SM_SentinelUndef ? 0 : Mask[3];
10053
10054   unsigned PermMask = MaskLO / 2 | (MaskHI / 2) << 4;
10055
10056   // If either input is a zero vector, replace it with an undef input.
10057   // Shuffle mask values <  4 are selecting elements of V1.
10058   // Shuffle mask values >= 4 are selecting elements of V2.
10059   // Adjust each half of the permute mask by clearing the half that was
10060   // selecting the zero vector and setting the zero mask bit.
10061   if (IsV1Zero) {
10062     V1 = DAG.getUNDEF(VT);
10063     if (MaskLO < 4)
10064       PermMask = (PermMask & 0xf0) | 0x08;
10065     if (MaskHI < 4)
10066       PermMask = (PermMask & 0x0f) | 0x80;
10067   }
10068   if (IsV2Zero) {
10069     V2 = DAG.getUNDEF(VT);
10070     if (MaskLO >= 4)
10071       PermMask = (PermMask & 0xf0) | 0x08;
10072     if (MaskHI >= 4)
10073       PermMask = (PermMask & 0x0f) | 0x80;
10074   }
10075
10076   return DAG.getNode(X86ISD::VPERM2X128, DL, VT, V1, V2,
10077                      DAG.getConstant(PermMask, DL, MVT::i8));
10078 }
10079
10080 /// \brief Lower a vector shuffle by first fixing the 128-bit lanes and then
10081 /// shuffling each lane.
10082 ///
10083 /// This will only succeed when the result of fixing the 128-bit lanes results
10084 /// in a single-input non-lane-crossing shuffle with a repeating shuffle mask in
10085 /// each 128-bit lanes. This handles many cases where we can quickly blend away
10086 /// the lane crosses early and then use simpler shuffles within each lane.
10087 ///
10088 /// FIXME: It might be worthwhile at some point to support this without
10089 /// requiring the 128-bit lane-relative shuffles to be repeating, but currently
10090 /// in x86 only floating point has interesting non-repeating shuffles, and even
10091 /// those are still *marginally* more expensive.
10092 static SDValue lowerVectorShuffleByMerging128BitLanes(
10093     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
10094     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
10095   assert(!isSingleInputShuffleMask(Mask) &&
10096          "This is only useful with multiple inputs.");
10097
10098   int Size = Mask.size();
10099   int LaneSize = 128 / VT.getScalarSizeInBits();
10100   int NumLanes = Size / LaneSize;
10101   assert(NumLanes > 1 && "Only handles 256-bit and wider shuffles.");
10102
10103   // See if we can build a hypothetical 128-bit lane-fixing shuffle mask. Also
10104   // check whether the in-128-bit lane shuffles share a repeating pattern.
10105   SmallVector<int, 4> Lanes;
10106   Lanes.resize(NumLanes, -1);
10107   SmallVector<int, 4> InLaneMask;
10108   InLaneMask.resize(LaneSize, -1);
10109   for (int i = 0; i < Size; ++i) {
10110     if (Mask[i] < 0)
10111       continue;
10112
10113     int j = i / LaneSize;
10114
10115     if (Lanes[j] < 0) {
10116       // First entry we've seen for this lane.
10117       Lanes[j] = Mask[i] / LaneSize;
10118     } else if (Lanes[j] != Mask[i] / LaneSize) {
10119       // This doesn't match the lane selected previously!
10120       return SDValue();
10121     }
10122
10123     // Check that within each lane we have a consistent shuffle mask.
10124     int k = i % LaneSize;
10125     if (InLaneMask[k] < 0) {
10126       InLaneMask[k] = Mask[i] % LaneSize;
10127     } else if (InLaneMask[k] != Mask[i] % LaneSize) {
10128       // This doesn't fit a repeating in-lane mask.
10129       return SDValue();
10130     }
10131   }
10132
10133   // First shuffle the lanes into place.
10134   MVT LaneVT = MVT::getVectorVT(VT.isFloatingPoint() ? MVT::f64 : MVT::i64,
10135                                 VT.getSizeInBits() / 64);
10136   SmallVector<int, 8> LaneMask;
10137   LaneMask.resize(NumLanes * 2, -1);
10138   for (int i = 0; i < NumLanes; ++i)
10139     if (Lanes[i] >= 0) {
10140       LaneMask[2 * i + 0] = 2*Lanes[i] + 0;
10141       LaneMask[2 * i + 1] = 2*Lanes[i] + 1;
10142     }
10143
10144   V1 = DAG.getBitcast(LaneVT, V1);
10145   V2 = DAG.getBitcast(LaneVT, V2);
10146   SDValue LaneShuffle = DAG.getVectorShuffle(LaneVT, DL, V1, V2, LaneMask);
10147
10148   // Cast it back to the type we actually want.
10149   LaneShuffle = DAG.getBitcast(VT, LaneShuffle);
10150
10151   // Now do a simple shuffle that isn't lane crossing.
10152   SmallVector<int, 8> NewMask;
10153   NewMask.resize(Size, -1);
10154   for (int i = 0; i < Size; ++i)
10155     if (Mask[i] >= 0)
10156       NewMask[i] = (i / LaneSize) * LaneSize + Mask[i] % LaneSize;
10157   assert(!is128BitLaneCrossingShuffleMask(VT, NewMask) &&
10158          "Must not introduce lane crosses at this point!");
10159
10160   return DAG.getVectorShuffle(VT, DL, LaneShuffle, DAG.getUNDEF(VT), NewMask);
10161 }
10162
10163 /// \brief Test whether the specified input (0 or 1) is in-place blended by the
10164 /// given mask.
10165 ///
10166 /// This returns true if the elements from a particular input are already in the
10167 /// slot required by the given mask and require no permutation.
10168 static bool isShuffleMaskInputInPlace(int Input, ArrayRef<int> Mask) {
10169   assert((Input == 0 || Input == 1) && "Only two inputs to shuffles.");
10170   int Size = Mask.size();
10171   for (int i = 0; i < Size; ++i)
10172     if (Mask[i] >= 0 && Mask[i] / Size == Input && Mask[i] % Size != i)
10173       return false;
10174
10175   return true;
10176 }
10177
10178 static SDValue lowerVectorShuffleWithSHUFPD(SDLoc DL, MVT VT,
10179                                             ArrayRef<int> Mask, SDValue V1,
10180                                             SDValue V2, SelectionDAG &DAG) {
10181
10182   // Mask for V8F64: 0/1,  8/9,  2/3,  10/11, 4/5, ..
10183   // Mask for V4F64; 0/1,  4/5,  2/3,  6/7..
10184   assert(VT.getScalarSizeInBits() == 64 && "Unexpected data type for VSHUFPD");
10185   int NumElts = VT.getVectorNumElements();
10186   bool ShufpdMask = true;
10187   bool CommutableMask = true;
10188   unsigned Immediate = 0;
10189   for (int i = 0; i < NumElts; ++i) {
10190     if (Mask[i] < 0)
10191       continue;
10192     int Val = (i & 6) + NumElts * (i & 1);
10193     int CommutVal = (i & 0xe) + NumElts * ((i & 1)^1);
10194     if (Mask[i] < Val ||  Mask[i] > Val + 1)
10195       ShufpdMask = false;
10196     if (Mask[i] < CommutVal ||  Mask[i] > CommutVal + 1)
10197       CommutableMask = false;
10198     Immediate |= (Mask[i] % 2) << i;
10199   }
10200   if (ShufpdMask)
10201     return DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
10202                        DAG.getConstant(Immediate, DL, MVT::i8));
10203   if (CommutableMask)
10204     return DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
10205                        DAG.getConstant(Immediate, DL, MVT::i8));
10206   return SDValue();
10207 }
10208
10209 /// \brief Handle lowering of 4-lane 64-bit floating point shuffles.
10210 ///
10211 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
10212 /// isn't available.
10213 static SDValue lowerV4F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10214                                        const X86Subtarget *Subtarget,
10215                                        SelectionDAG &DAG) {
10216   SDLoc DL(Op);
10217   assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
10218   assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
10219   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10220   ArrayRef<int> Mask = SVOp->getMask();
10221   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
10222
10223   SmallVector<int, 4> WidenedMask;
10224   if (canWidenShuffleElements(Mask, WidenedMask))
10225     return lowerV2X128VectorShuffle(DL, MVT::v4f64, V1, V2, Mask, Subtarget,
10226                                     DAG);
10227
10228   if (isSingleInputShuffleMask(Mask)) {
10229     // Check for being able to broadcast a single element.
10230     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f64, V1,
10231                                                           Mask, Subtarget, DAG))
10232       return Broadcast;
10233
10234     // Use low duplicate instructions for masks that match their pattern.
10235     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
10236       return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v4f64, V1);
10237
10238     if (!is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask)) {
10239       // Non-half-crossing single input shuffles can be lowerid with an
10240       // interleaved permutation.
10241       unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
10242                               ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
10243       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f64, V1,
10244                          DAG.getConstant(VPERMILPMask, DL, MVT::i8));
10245     }
10246
10247     // With AVX2 we have direct support for this permutation.
10248     if (Subtarget->hasAVX2())
10249       return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4f64, V1,
10250                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
10251
10252     // Otherwise, fall back.
10253     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v4f64, V1, V2, Mask,
10254                                                    DAG);
10255   }
10256
10257   // Use dedicated unpack instructions for masks that match their pattern.
10258   if (SDValue V =
10259           lowerVectorShuffleWithUNPCK(DL, MVT::v4f64, Mask, V1, V2, DAG))
10260     return V;
10261
10262   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f64, V1, V2, Mask,
10263                                                 Subtarget, DAG))
10264     return Blend;
10265
10266   // Check if the blend happens to exactly fit that of SHUFPD.
10267   if (SDValue Op =
10268       lowerVectorShuffleWithSHUFPD(DL, MVT::v4f64, Mask, V1, V2, DAG))
10269     return Op;
10270
10271   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10272   // shuffle. However, if we have AVX2 and either inputs are already in place,
10273   // we will be able to shuffle even across lanes the other input in a single
10274   // instruction so skip this pattern.
10275   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
10276                                  isShuffleMaskInputInPlace(1, Mask))))
10277     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10278             DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
10279       return Result;
10280
10281   // If we have AVX2 then we always want to lower with a blend because an v4 we
10282   // can fully permute the elements.
10283   if (Subtarget->hasAVX2())
10284     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4f64, V1, V2,
10285                                                       Mask, DAG);
10286
10287   // Otherwise fall back on generic lowering.
10288   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v4f64, V1, V2, Mask, DAG);
10289 }
10290
10291 /// \brief Handle lowering of 4-lane 64-bit integer shuffles.
10292 ///
10293 /// This routine is only called when we have AVX2 and thus a reasonable
10294 /// instruction set for v4i64 shuffling..
10295 static SDValue lowerV4I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10296                                        const X86Subtarget *Subtarget,
10297                                        SelectionDAG &DAG) {
10298   SDLoc DL(Op);
10299   assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
10300   assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
10301   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10302   ArrayRef<int> Mask = SVOp->getMask();
10303   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
10304   assert(Subtarget->hasAVX2() && "We can only lower v4i64 with AVX2!");
10305
10306   SmallVector<int, 4> WidenedMask;
10307   if (canWidenShuffleElements(Mask, WidenedMask))
10308     return lowerV2X128VectorShuffle(DL, MVT::v4i64, V1, V2, Mask, Subtarget,
10309                                     DAG);
10310
10311   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i64, V1, V2, Mask,
10312                                                 Subtarget, DAG))
10313     return Blend;
10314
10315   // Check for being able to broadcast a single element.
10316   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i64, V1,
10317                                                         Mask, Subtarget, DAG))
10318     return Broadcast;
10319
10320   // When the shuffle is mirrored between the 128-bit lanes of the unit, we can
10321   // use lower latency instructions that will operate on both 128-bit lanes.
10322   SmallVector<int, 2> RepeatedMask;
10323   if (is128BitLaneRepeatedShuffleMask(MVT::v4i64, Mask, RepeatedMask)) {
10324     if (isSingleInputShuffleMask(Mask)) {
10325       int PSHUFDMask[] = {-1, -1, -1, -1};
10326       for (int i = 0; i < 2; ++i)
10327         if (RepeatedMask[i] >= 0) {
10328           PSHUFDMask[2 * i] = 2 * RepeatedMask[i];
10329           PSHUFDMask[2 * i + 1] = 2 * RepeatedMask[i] + 1;
10330         }
10331       return DAG.getBitcast(
10332           MVT::v4i64,
10333           DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32,
10334                       DAG.getBitcast(MVT::v8i32, V1),
10335                       getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
10336     }
10337   }
10338
10339   // AVX2 provides a direct instruction for permuting a single input across
10340   // lanes.
10341   if (isSingleInputShuffleMask(Mask))
10342     return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4i64, V1,
10343                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
10344
10345   // Try to use shift instructions.
10346   if (SDValue Shift =
10347           lowerVectorShuffleAsShift(DL, MVT::v4i64, V1, V2, Mask, DAG))
10348     return Shift;
10349
10350   // Use dedicated unpack instructions for masks that match their pattern.
10351   if (SDValue V =
10352           lowerVectorShuffleWithUNPCK(DL, MVT::v4i64, Mask, V1, V2, DAG))
10353     return V;
10354
10355   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10356   // shuffle. However, if we have AVX2 and either inputs are already in place,
10357   // we will be able to shuffle even across lanes the other input in a single
10358   // instruction so skip this pattern.
10359   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
10360                                  isShuffleMaskInputInPlace(1, Mask))))
10361     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10362             DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
10363       return Result;
10364
10365   // Otherwise fall back on generic blend lowering.
10366   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i64, V1, V2,
10367                                                     Mask, DAG);
10368 }
10369
10370 /// \brief Handle lowering of 8-lane 32-bit floating point shuffles.
10371 ///
10372 /// Also ends up handling lowering of 8-lane 32-bit integer shuffles when AVX2
10373 /// isn't available.
10374 static SDValue lowerV8F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10375                                        const X86Subtarget *Subtarget,
10376                                        SelectionDAG &DAG) {
10377   SDLoc DL(Op);
10378   assert(V1.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
10379   assert(V2.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
10380   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10381   ArrayRef<int> Mask = SVOp->getMask();
10382   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10383
10384   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8f32, V1, V2, Mask,
10385                                                 Subtarget, DAG))
10386     return Blend;
10387
10388   // Check for being able to broadcast a single element.
10389   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8f32, V1,
10390                                                         Mask, Subtarget, DAG))
10391     return Broadcast;
10392
10393   // If the shuffle mask is repeated in each 128-bit lane, we have many more
10394   // options to efficiently lower the shuffle.
10395   SmallVector<int, 4> RepeatedMask;
10396   if (is128BitLaneRepeatedShuffleMask(MVT::v8f32, Mask, RepeatedMask)) {
10397     assert(RepeatedMask.size() == 4 &&
10398            "Repeated masks must be half the mask width!");
10399
10400     // Use even/odd duplicate instructions for masks that match their pattern.
10401     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2, 4, 4, 6, 6}))
10402       return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v8f32, V1);
10403     if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3, 5, 5, 7, 7}))
10404       return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v8f32, V1);
10405
10406     if (isSingleInputShuffleMask(Mask))
10407       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, V1,
10408                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
10409
10410     // Use dedicated unpack instructions for masks that match their pattern.
10411     if (SDValue V =
10412             lowerVectorShuffleWithUNPCK(DL, MVT::v8f32, Mask, V1, V2, DAG))
10413       return V;
10414
10415     // Otherwise, fall back to a SHUFPS sequence. Here it is important that we
10416     // have already handled any direct blends. We also need to squash the
10417     // repeated mask into a simulated v4f32 mask.
10418     for (int i = 0; i < 4; ++i)
10419       if (RepeatedMask[i] >= 8)
10420         RepeatedMask[i] -= 4;
10421     return lowerVectorShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask, V1, V2, DAG);
10422   }
10423
10424   // If we have a single input shuffle with different shuffle patterns in the
10425   // two 128-bit lanes use the variable mask to VPERMILPS.
10426   if (isSingleInputShuffleMask(Mask)) {
10427     SDValue VPermMask[8];
10428     for (int i = 0; i < 8; ++i)
10429       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10430                                  : DAG.getConstant(Mask[i], DL, MVT::i32);
10431     if (!is128BitLaneCrossingShuffleMask(MVT::v8f32, Mask))
10432       return DAG.getNode(
10433           X86ISD::VPERMILPV, DL, MVT::v8f32, V1,
10434           DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask));
10435
10436     if (Subtarget->hasAVX2())
10437       return DAG.getNode(
10438           X86ISD::VPERMV, DL, MVT::v8f32,
10439           DAG.getBitcast(MVT::v8f32, DAG.getNode(ISD::BUILD_VECTOR, DL,
10440                                                  MVT::v8i32, VPermMask)),
10441           V1);
10442
10443     // Otherwise, fall back.
10444     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v8f32, V1, V2, Mask,
10445                                                    DAG);
10446   }
10447
10448   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10449   // shuffle.
10450   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10451           DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
10452     return Result;
10453
10454   // If we have AVX2 then we always want to lower with a blend because at v8 we
10455   // can fully permute the elements.
10456   if (Subtarget->hasAVX2())
10457     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8f32, V1, V2,
10458                                                       Mask, DAG);
10459
10460   // Otherwise fall back on generic lowering.
10461   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask, DAG);
10462 }
10463
10464 /// \brief Handle lowering of 8-lane 32-bit integer shuffles.
10465 ///
10466 /// This routine is only called when we have AVX2 and thus a reasonable
10467 /// instruction set for v8i32 shuffling..
10468 static SDValue lowerV8I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10469                                        const X86Subtarget *Subtarget,
10470                                        SelectionDAG &DAG) {
10471   SDLoc DL(Op);
10472   assert(V1.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10473   assert(V2.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10474   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10475   ArrayRef<int> Mask = SVOp->getMask();
10476   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10477   assert(Subtarget->hasAVX2() && "We can only lower v8i32 with AVX2!");
10478
10479   // Whenever we can lower this as a zext, that instruction is strictly faster
10480   // than any alternative. It also allows us to fold memory operands into the
10481   // shuffle in many cases.
10482   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v8i32, V1, V2,
10483                                                          Mask, Subtarget, DAG))
10484     return ZExt;
10485
10486   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i32, V1, V2, Mask,
10487                                                 Subtarget, DAG))
10488     return Blend;
10489
10490   // Check for being able to broadcast a single element.
10491   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i32, V1,
10492                                                         Mask, Subtarget, DAG))
10493     return Broadcast;
10494
10495   // If the shuffle mask is repeated in each 128-bit lane we can use more
10496   // efficient instructions that mirror the shuffles across the two 128-bit
10497   // lanes.
10498   SmallVector<int, 4> RepeatedMask;
10499   if (is128BitLaneRepeatedShuffleMask(MVT::v8i32, Mask, RepeatedMask)) {
10500     assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
10501     if (isSingleInputShuffleMask(Mask))
10502       return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32, V1,
10503                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
10504
10505     // Use dedicated unpack instructions for masks that match their pattern.
10506     if (SDValue V =
10507             lowerVectorShuffleWithUNPCK(DL, MVT::v8i32, Mask, V1, V2, DAG))
10508       return V;
10509   }
10510
10511   // Try to use shift instructions.
10512   if (SDValue Shift =
10513           lowerVectorShuffleAsShift(DL, MVT::v8i32, V1, V2, Mask, DAG))
10514     return Shift;
10515
10516   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10517           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10518     return Rotate;
10519
10520   // If the shuffle patterns aren't repeated but it is a single input, directly
10521   // generate a cross-lane VPERMD instruction.
10522   if (isSingleInputShuffleMask(Mask)) {
10523     SDValue VPermMask[8];
10524     for (int i = 0; i < 8; ++i)
10525       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10526                                  : DAG.getConstant(Mask[i], DL, MVT::i32);
10527     return DAG.getNode(
10528         X86ISD::VPERMV, DL, MVT::v8i32,
10529         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask), V1);
10530   }
10531
10532   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10533   // shuffle.
10534   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10535           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10536     return Result;
10537
10538   // Otherwise fall back on generic blend lowering.
10539   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i32, V1, V2,
10540                                                     Mask, DAG);
10541 }
10542
10543 /// \brief Handle lowering of 16-lane 16-bit integer shuffles.
10544 ///
10545 /// This routine is only called when we have AVX2 and thus a reasonable
10546 /// instruction set for v16i16 shuffling..
10547 static SDValue lowerV16I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10548                                         const X86Subtarget *Subtarget,
10549                                         SelectionDAG &DAG) {
10550   SDLoc DL(Op);
10551   assert(V1.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10552   assert(V2.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10553   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10554   ArrayRef<int> Mask = SVOp->getMask();
10555   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10556   assert(Subtarget->hasAVX2() && "We can only lower v16i16 with AVX2!");
10557
10558   // Whenever we can lower this as a zext, that instruction is strictly faster
10559   // than any alternative. It also allows us to fold memory operands into the
10560   // shuffle in many cases.
10561   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v16i16, V1, V2,
10562                                                          Mask, Subtarget, DAG))
10563     return ZExt;
10564
10565   // Check for being able to broadcast a single element.
10566   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i16, V1,
10567                                                         Mask, Subtarget, DAG))
10568     return Broadcast;
10569
10570   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i16, V1, V2, Mask,
10571                                                 Subtarget, DAG))
10572     return Blend;
10573
10574   // Use dedicated unpack instructions for masks that match their pattern.
10575   if (SDValue V =
10576           lowerVectorShuffleWithUNPCK(DL, MVT::v16i16, Mask, V1, V2, DAG))
10577     return V;
10578
10579   // Try to use shift instructions.
10580   if (SDValue Shift =
10581           lowerVectorShuffleAsShift(DL, MVT::v16i16, V1, V2, Mask, DAG))
10582     return Shift;
10583
10584   // Try to use byte rotation instructions.
10585   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10586           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10587     return Rotate;
10588
10589   if (isSingleInputShuffleMask(Mask)) {
10590     // There are no generalized cross-lane shuffle operations available on i16
10591     // element types.
10592     if (is128BitLaneCrossingShuffleMask(MVT::v16i16, Mask))
10593       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v16i16, V1, V2,
10594                                                      Mask, DAG);
10595
10596     SmallVector<int, 8> RepeatedMask;
10597     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
10598       // As this is a single-input shuffle, the repeated mask should be
10599       // a strictly valid v8i16 mask that we can pass through to the v8i16
10600       // lowering to handle even the v16 case.
10601       return lowerV8I16GeneralSingleInputVectorShuffle(
10602           DL, MVT::v16i16, V1, RepeatedMask, Subtarget, DAG);
10603     }
10604
10605     SDValue PSHUFBMask[32];
10606     for (int i = 0; i < 16; ++i) {
10607       if (Mask[i] == -1) {
10608         PSHUFBMask[2 * i] = PSHUFBMask[2 * i + 1] = DAG.getUNDEF(MVT::i8);
10609         continue;
10610       }
10611
10612       int M = i < 8 ? Mask[i] : Mask[i] - 8;
10613       assert(M >= 0 && M < 8 && "Invalid single-input mask!");
10614       PSHUFBMask[2 * i] = DAG.getConstant(2 * M, DL, MVT::i8);
10615       PSHUFBMask[2 * i + 1] = DAG.getConstant(2 * M + 1, DL, MVT::i8);
10616     }
10617     return DAG.getBitcast(MVT::v16i16,
10618                           DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8,
10619                                       DAG.getBitcast(MVT::v32i8, V1),
10620                                       DAG.getNode(ISD::BUILD_VECTOR, DL,
10621                                                   MVT::v32i8, PSHUFBMask)));
10622   }
10623
10624   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10625   // shuffle.
10626   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10627           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10628     return Result;
10629
10630   // Otherwise fall back on generic lowering.
10631   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v16i16, V1, V2, Mask, DAG);
10632 }
10633
10634 /// \brief Handle lowering of 32-lane 8-bit integer shuffles.
10635 ///
10636 /// This routine is only called when we have AVX2 and thus a reasonable
10637 /// instruction set for v32i8 shuffling..
10638 static SDValue lowerV32I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10639                                        const X86Subtarget *Subtarget,
10640                                        SelectionDAG &DAG) {
10641   SDLoc DL(Op);
10642   assert(V1.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10643   assert(V2.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10644   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10645   ArrayRef<int> Mask = SVOp->getMask();
10646   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10647   assert(Subtarget->hasAVX2() && "We can only lower v32i8 with AVX2!");
10648
10649   // Whenever we can lower this as a zext, that instruction is strictly faster
10650   // than any alternative. It also allows us to fold memory operands into the
10651   // shuffle in many cases.
10652   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v32i8, V1, V2,
10653                                                          Mask, Subtarget, DAG))
10654     return ZExt;
10655
10656   // Check for being able to broadcast a single element.
10657   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v32i8, V1,
10658                                                         Mask, Subtarget, DAG))
10659     return Broadcast;
10660
10661   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v32i8, V1, V2, Mask,
10662                                                 Subtarget, DAG))
10663     return Blend;
10664
10665   // Use dedicated unpack instructions for masks that match their pattern.
10666   if (SDValue V =
10667           lowerVectorShuffleWithUNPCK(DL, MVT::v32i8, Mask, V1, V2, DAG))
10668     return V;
10669
10670   // Try to use shift instructions.
10671   if (SDValue Shift =
10672           lowerVectorShuffleAsShift(DL, MVT::v32i8, V1, V2, Mask, DAG))
10673     return Shift;
10674
10675   // Try to use byte rotation instructions.
10676   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10677           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
10678     return Rotate;
10679
10680   if (isSingleInputShuffleMask(Mask)) {
10681     // There are no generalized cross-lane shuffle operations available on i8
10682     // element types.
10683     if (is128BitLaneCrossingShuffleMask(MVT::v32i8, Mask))
10684       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v32i8, V1, V2,
10685                                                      Mask, DAG);
10686
10687     SDValue PSHUFBMask[32];
10688     for (int i = 0; i < 32; ++i)
10689       PSHUFBMask[i] =
10690           Mask[i] < 0
10691               ? DAG.getUNDEF(MVT::i8)
10692               : DAG.getConstant(Mask[i] < 16 ? Mask[i] : Mask[i] - 16, DL,
10693                                 MVT::i8);
10694
10695     return DAG.getNode(
10696         X86ISD::PSHUFB, DL, MVT::v32i8, V1,
10697         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask));
10698   }
10699
10700   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10701   // shuffle.
10702   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10703           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
10704     return Result;
10705
10706   // Otherwise fall back on generic lowering.
10707   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v32i8, V1, V2, Mask, DAG);
10708 }
10709
10710 /// \brief High-level routine to lower various 256-bit x86 vector shuffles.
10711 ///
10712 /// This routine either breaks down the specific type of a 256-bit x86 vector
10713 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
10714 /// together based on the available instructions.
10715 static SDValue lower256BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10716                                         MVT VT, const X86Subtarget *Subtarget,
10717                                         SelectionDAG &DAG) {
10718   SDLoc DL(Op);
10719   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10720   ArrayRef<int> Mask = SVOp->getMask();
10721
10722   // If we have a single input to the zero element, insert that into V1 if we
10723   // can do so cheaply.
10724   int NumElts = VT.getVectorNumElements();
10725   int NumV2Elements = std::count_if(Mask.begin(), Mask.end(), [NumElts](int M) {
10726     return M >= NumElts;
10727   });
10728
10729   if (NumV2Elements == 1 && Mask[0] >= NumElts)
10730     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
10731                               DL, VT, V1, V2, Mask, Subtarget, DAG))
10732       return Insertion;
10733
10734   // There is a really nice hard cut-over between AVX1 and AVX2 that means we
10735   // can check for those subtargets here and avoid much of the subtarget
10736   // querying in the per-vector-type lowering routines. With AVX1 we have
10737   // essentially *zero* ability to manipulate a 256-bit vector with integer
10738   // types. Since we'll use floating point types there eventually, just
10739   // immediately cast everything to a float and operate entirely in that domain.
10740   if (VT.isInteger() && !Subtarget->hasAVX2()) {
10741     int ElementBits = VT.getScalarSizeInBits();
10742     if (ElementBits < 32)
10743       // No floating point type available, decompose into 128-bit vectors.
10744       return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10745
10746     MVT FpVT = MVT::getVectorVT(MVT::getFloatingPointVT(ElementBits),
10747                                 VT.getVectorNumElements());
10748     V1 = DAG.getBitcast(FpVT, V1);
10749     V2 = DAG.getBitcast(FpVT, V2);
10750     return DAG.getBitcast(VT, DAG.getVectorShuffle(FpVT, DL, V1, V2, Mask));
10751   }
10752
10753   switch (VT.SimpleTy) {
10754   case MVT::v4f64:
10755     return lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10756   case MVT::v4i64:
10757     return lowerV4I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10758   case MVT::v8f32:
10759     return lowerV8F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10760   case MVT::v8i32:
10761     return lowerV8I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10762   case MVT::v16i16:
10763     return lowerV16I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10764   case MVT::v32i8:
10765     return lowerV32I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10766
10767   default:
10768     llvm_unreachable("Not a valid 256-bit x86 vector type!");
10769   }
10770 }
10771
10772 /// \brief Try to lower a vector shuffle as a 128-bit shuffles.
10773 static SDValue lowerV4X128VectorShuffle(SDLoc DL, MVT VT,
10774                                         ArrayRef<int> Mask,
10775                                         SDValue V1, SDValue V2,
10776                                         SelectionDAG &DAG) {
10777   assert(VT.getScalarSizeInBits() == 64 &&
10778          "Unexpected element type size for 128bit shuffle.");
10779
10780   // To handle 256 bit vector requires VLX and most probably
10781   // function lowerV2X128VectorShuffle() is better solution.
10782   assert(VT.is512BitVector() && "Unexpected vector size for 128bit shuffle.");
10783
10784   SmallVector<int, 4> WidenedMask;
10785   if (!canWidenShuffleElements(Mask, WidenedMask))
10786     return SDValue();
10787
10788   // Form a 128-bit permutation.
10789   // Convert the 64-bit shuffle mask selection values into 128-bit selection
10790   // bits defined by a vshuf64x2 instruction's immediate control byte.
10791   unsigned PermMask = 0, Imm = 0;
10792   unsigned ControlBitsNum = WidenedMask.size() / 2;
10793
10794   for (int i = 0, Size = WidenedMask.size(); i < Size; ++i) {
10795     if (WidenedMask[i] == SM_SentinelZero)
10796       return SDValue();
10797
10798     // Use first element in place of undef mask.
10799     Imm = (WidenedMask[i] == SM_SentinelUndef) ? 0 : WidenedMask[i];
10800     PermMask |= (Imm % WidenedMask.size()) << (i * ControlBitsNum);
10801   }
10802
10803   return DAG.getNode(X86ISD::SHUF128, DL, VT, V1, V2,
10804                      DAG.getConstant(PermMask, DL, MVT::i8));
10805 }
10806
10807 static SDValue lowerVectorShuffleWithPERMV(SDLoc DL, MVT VT,
10808                                            ArrayRef<int> Mask, SDValue V1,
10809                                            SDValue V2, SelectionDAG &DAG) {
10810
10811   assert(VT.getScalarSizeInBits() >= 16 && "Unexpected data type for PERMV");
10812
10813   MVT MaskEltVT = MVT::getIntegerVT(VT.getScalarSizeInBits());
10814   MVT MaskVecVT = MVT::getVectorVT(MaskEltVT, VT.getVectorNumElements());
10815
10816   SDValue MaskNode = getConstVector(Mask, MaskVecVT, DAG, DL, true);
10817   if (isSingleInputShuffleMask(Mask))
10818     return DAG.getNode(X86ISD::VPERMV, DL, VT, MaskNode, V1);
10819
10820   return DAG.getNode(X86ISD::VPERMV3, DL, VT, V1, MaskNode, V2);
10821 }
10822
10823 /// \brief Handle lowering of 8-lane 64-bit floating point shuffles.
10824 static SDValue lowerV8F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10825                                        const X86Subtarget *Subtarget,
10826                                        SelectionDAG &DAG) {
10827   SDLoc DL(Op);
10828   assert(V1.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10829   assert(V2.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10830   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10831   ArrayRef<int> Mask = SVOp->getMask();
10832   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10833
10834   if (SDValue Shuf128 =
10835           lowerV4X128VectorShuffle(DL, MVT::v8f64, Mask, V1, V2, DAG))
10836     return Shuf128;
10837
10838   if (SDValue Unpck =
10839           lowerVectorShuffleWithUNPCK(DL, MVT::v8f64, Mask, V1, V2, DAG))
10840     return Unpck;
10841
10842   return lowerVectorShuffleWithPERMV(DL, MVT::v8f64, Mask, V1, V2, DAG);
10843 }
10844
10845 /// \brief Handle lowering of 16-lane 32-bit floating point shuffles.
10846 static SDValue lowerV16F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10847                                         const X86Subtarget *Subtarget,
10848                                         SelectionDAG &DAG) {
10849   SDLoc DL(Op);
10850   assert(V1.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10851   assert(V2.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10852   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10853   ArrayRef<int> Mask = SVOp->getMask();
10854   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10855
10856   if (SDValue Unpck =
10857           lowerVectorShuffleWithUNPCK(DL, MVT::v16f32, Mask, V1, V2, DAG))
10858     return Unpck;
10859
10860   return lowerVectorShuffleWithPERMV(DL, MVT::v16f32, Mask, V1, V2, DAG);
10861 }
10862
10863 /// \brief Handle lowering of 8-lane 64-bit integer shuffles.
10864 static SDValue lowerV8I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10865                                        const X86Subtarget *Subtarget,
10866                                        SelectionDAG &DAG) {
10867   SDLoc DL(Op);
10868   assert(V1.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10869   assert(V2.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10870   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10871   ArrayRef<int> Mask = SVOp->getMask();
10872   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10873
10874   if (SDValue Shuf128 =
10875           lowerV4X128VectorShuffle(DL, MVT::v8i64, Mask, V1, V2, DAG))
10876     return Shuf128;
10877
10878   if (SDValue Unpck =
10879           lowerVectorShuffleWithUNPCK(DL, MVT::v8i64, Mask, V1, V2, DAG))
10880     return Unpck;
10881
10882   return lowerVectorShuffleWithPERMV(DL, MVT::v8i64, Mask, V1, V2, DAG);
10883 }
10884
10885 /// \brief Handle lowering of 16-lane 32-bit integer shuffles.
10886 static SDValue lowerV16I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10887                                         const X86Subtarget *Subtarget,
10888                                         SelectionDAG &DAG) {
10889   SDLoc DL(Op);
10890   assert(V1.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10891   assert(V2.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10892   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10893   ArrayRef<int> Mask = SVOp->getMask();
10894   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10895
10896   if (SDValue Unpck =
10897           lowerVectorShuffleWithUNPCK(DL, MVT::v16i32, Mask, V1, V2, DAG))
10898     return Unpck;
10899
10900   return lowerVectorShuffleWithPERMV(DL, MVT::v16i32, Mask, V1, V2, DAG);
10901 }
10902
10903 /// \brief Handle lowering of 32-lane 16-bit integer shuffles.
10904 static SDValue lowerV32I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10905                                         const X86Subtarget *Subtarget,
10906                                         SelectionDAG &DAG) {
10907   SDLoc DL(Op);
10908   assert(V1.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10909   assert(V2.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10910   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10911   ArrayRef<int> Mask = SVOp->getMask();
10912   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10913   assert(Subtarget->hasBWI() && "We can only lower v32i16 with AVX-512-BWI!");
10914
10915   return lowerVectorShuffleWithPERMV(DL, MVT::v32i16, Mask, V1, V2, DAG);
10916 }
10917
10918 /// \brief Handle lowering of 64-lane 8-bit integer shuffles.
10919 static SDValue lowerV64I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10920                                        const X86Subtarget *Subtarget,
10921                                        SelectionDAG &DAG) {
10922   SDLoc DL(Op);
10923   assert(V1.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10924   assert(V2.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10925   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10926   ArrayRef<int> Mask = SVOp->getMask();
10927   assert(Mask.size() == 64 && "Unexpected mask size for v64 shuffle!");
10928   assert(Subtarget->hasBWI() && "We can only lower v64i8 with AVX-512-BWI!");
10929
10930   // FIXME: Implement direct support for this type!
10931   return splitAndLowerVectorShuffle(DL, MVT::v64i8, V1, V2, Mask, DAG);
10932 }
10933
10934 /// \brief High-level routine to lower various 512-bit x86 vector shuffles.
10935 ///
10936 /// This routine either breaks down the specific type of a 512-bit x86 vector
10937 /// shuffle or splits it into two 256-bit shuffles and fuses the results back
10938 /// together based on the available instructions.
10939 static SDValue lower512BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10940                                         MVT VT, const X86Subtarget *Subtarget,
10941                                         SelectionDAG &DAG) {
10942   SDLoc DL(Op);
10943   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10944   ArrayRef<int> Mask = SVOp->getMask();
10945   assert(Subtarget->hasAVX512() &&
10946          "Cannot lower 512-bit vectors w/ basic ISA!");
10947
10948   // Check for being able to broadcast a single element.
10949   if (SDValue Broadcast =
10950           lowerVectorShuffleAsBroadcast(DL, VT, V1, Mask, Subtarget, DAG))
10951     return Broadcast;
10952
10953   // Dispatch to each element type for lowering. If we don't have supprot for
10954   // specific element type shuffles at 512 bits, immediately split them and
10955   // lower them. Each lowering routine of a given type is allowed to assume that
10956   // the requisite ISA extensions for that element type are available.
10957   switch (VT.SimpleTy) {
10958   case MVT::v8f64:
10959     return lowerV8F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10960   case MVT::v16f32:
10961     return lowerV16F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10962   case MVT::v8i64:
10963     return lowerV8I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10964   case MVT::v16i32:
10965     return lowerV16I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10966   case MVT::v32i16:
10967     if (Subtarget->hasBWI())
10968       return lowerV32I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10969     break;
10970   case MVT::v64i8:
10971     if (Subtarget->hasBWI())
10972       return lowerV64I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10973     break;
10974
10975   default:
10976     llvm_unreachable("Not a valid 512-bit x86 vector type!");
10977   }
10978
10979   // Otherwise fall back on splitting.
10980   return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10981 }
10982
10983 // Lower vXi1 vector shuffles.
10984 // There is no a dedicated instruction on AVX-512 that shuffles the masks.
10985 // The only way to shuffle bits is to sign-extend the mask vector to SIMD
10986 // vector, shuffle and then truncate it back.
10987 static SDValue lower1BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10988                                       MVT VT, const X86Subtarget *Subtarget,
10989                                       SelectionDAG &DAG) {
10990   SDLoc DL(Op);
10991   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10992   ArrayRef<int> Mask = SVOp->getMask();
10993   assert(Subtarget->hasAVX512() &&
10994          "Cannot lower 512-bit vectors w/o basic ISA!");
10995   MVT ExtVT;
10996   switch (VT.SimpleTy) {
10997   default:
10998     llvm_unreachable("Expected a vector of i1 elements");
10999   case MVT::v2i1:
11000     ExtVT = MVT::v2i64;
11001     break;
11002   case MVT::v4i1:
11003     ExtVT = MVT::v4i32;
11004     break;
11005   case MVT::v8i1:
11006     ExtVT = MVT::v8i64; // Take 512-bit type, more shuffles on KNL
11007     break;
11008   case MVT::v16i1:
11009     ExtVT = MVT::v16i32;
11010     break;
11011   case MVT::v32i1:
11012     ExtVT = MVT::v32i16;
11013     break;
11014   case MVT::v64i1:
11015     ExtVT = MVT::v64i8;
11016     break;
11017   }
11018
11019   if (ISD::isBuildVectorAllZeros(V1.getNode()))
11020     V1 = getZeroVector(ExtVT, Subtarget, DAG, DL);
11021   else if (ISD::isBuildVectorAllOnes(V1.getNode()))
11022     V1 = getOnesVector(ExtVT, Subtarget, DAG, DL);
11023   else
11024     V1 = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, V1);
11025
11026   if (V2.isUndef())
11027     V2 = DAG.getUNDEF(ExtVT);
11028   else if (ISD::isBuildVectorAllZeros(V2.getNode()))
11029     V2 = getZeroVector(ExtVT, Subtarget, DAG, DL);
11030   else if (ISD::isBuildVectorAllOnes(V2.getNode()))
11031     V2 = getOnesVector(ExtVT, Subtarget, DAG, DL);
11032   else
11033     V2 = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, V2);
11034   return DAG.getNode(ISD::TRUNCATE, DL, VT,
11035                      DAG.getVectorShuffle(ExtVT, DL, V1, V2, Mask));
11036 }
11037 /// \brief Top-level lowering for x86 vector shuffles.
11038 ///
11039 /// This handles decomposition, canonicalization, and lowering of all x86
11040 /// vector shuffles. Most of the specific lowering strategies are encapsulated
11041 /// above in helper routines. The canonicalization attempts to widen shuffles
11042 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
11043 /// s.t. only one of the two inputs needs to be tested, etc.
11044 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
11045                                   SelectionDAG &DAG) {
11046   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11047   ArrayRef<int> Mask = SVOp->getMask();
11048   SDValue V1 = Op.getOperand(0);
11049   SDValue V2 = Op.getOperand(1);
11050   MVT VT = Op.getSimpleValueType();
11051   int NumElements = VT.getVectorNumElements();
11052   SDLoc dl(Op);
11053   bool Is1BitVector = (VT.getVectorElementType() == MVT::i1);
11054
11055   assert((VT.getSizeInBits() != 64 || Is1BitVector) &&
11056          "Can't lower MMX shuffles");
11057
11058   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
11059   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
11060   if (V1IsUndef && V2IsUndef)
11061     return DAG.getUNDEF(VT);
11062
11063   // When we create a shuffle node we put the UNDEF node to second operand,
11064   // but in some cases the first operand may be transformed to UNDEF.
11065   // In this case we should just commute the node.
11066   if (V1IsUndef)
11067     return DAG.getCommutedVectorShuffle(*SVOp);
11068
11069   // Check for non-undef masks pointing at an undef vector and make the masks
11070   // undef as well. This makes it easier to match the shuffle based solely on
11071   // the mask.
11072   if (V2IsUndef)
11073     for (int M : Mask)
11074       if (M >= NumElements) {
11075         SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
11076         for (int &M : NewMask)
11077           if (M >= NumElements)
11078             M = -1;
11079         return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
11080       }
11081
11082   // We actually see shuffles that are entirely re-arrangements of a set of
11083   // zero inputs. This mostly happens while decomposing complex shuffles into
11084   // simple ones. Directly lower these as a buildvector of zeros.
11085   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
11086   if (Zeroable.all())
11087     return getZeroVector(VT, Subtarget, DAG, dl);
11088
11089   // Try to collapse shuffles into using a vector type with fewer elements but
11090   // wider element types. We cap this to not form integers or floating point
11091   // elements wider than 64 bits, but it might be interesting to form i128
11092   // integers to handle flipping the low and high halves of AVX 256-bit vectors.
11093   SmallVector<int, 16> WidenedMask;
11094   if (VT.getScalarSizeInBits() < 64 && !Is1BitVector &&
11095       canWidenShuffleElements(Mask, WidenedMask)) {
11096     MVT NewEltVT = VT.isFloatingPoint()
11097                        ? MVT::getFloatingPointVT(VT.getScalarSizeInBits() * 2)
11098                        : MVT::getIntegerVT(VT.getScalarSizeInBits() * 2);
11099     MVT NewVT = MVT::getVectorVT(NewEltVT, VT.getVectorNumElements() / 2);
11100     // Make sure that the new vector type is legal. For example, v2f64 isn't
11101     // legal on SSE1.
11102     if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
11103       V1 = DAG.getBitcast(NewVT, V1);
11104       V2 = DAG.getBitcast(NewVT, V2);
11105       return DAG.getBitcast(
11106           VT, DAG.getVectorShuffle(NewVT, dl, V1, V2, WidenedMask));
11107     }
11108   }
11109
11110   int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
11111   for (int M : SVOp->getMask())
11112     if (M < 0)
11113       ++NumUndefElements;
11114     else if (M < NumElements)
11115       ++NumV1Elements;
11116     else
11117       ++NumV2Elements;
11118
11119   // Commute the shuffle as needed such that more elements come from V1 than
11120   // V2. This allows us to match the shuffle pattern strictly on how many
11121   // elements come from V1 without handling the symmetric cases.
11122   if (NumV2Elements > NumV1Elements)
11123     return DAG.getCommutedVectorShuffle(*SVOp);
11124
11125   // When the number of V1 and V2 elements are the same, try to minimize the
11126   // number of uses of V2 in the low half of the vector. When that is tied,
11127   // ensure that the sum of indices for V1 is equal to or lower than the sum
11128   // indices for V2. When those are equal, try to ensure that the number of odd
11129   // indices for V1 is lower than the number of odd indices for V2.
11130   if (NumV1Elements == NumV2Elements) {
11131     int LowV1Elements = 0, LowV2Elements = 0;
11132     for (int M : SVOp->getMask().slice(0, NumElements / 2))
11133       if (M >= NumElements)
11134         ++LowV2Elements;
11135       else if (M >= 0)
11136         ++LowV1Elements;
11137     if (LowV2Elements > LowV1Elements) {
11138       return DAG.getCommutedVectorShuffle(*SVOp);
11139     } else if (LowV2Elements == LowV1Elements) {
11140       int SumV1Indices = 0, SumV2Indices = 0;
11141       for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
11142         if (SVOp->getMask()[i] >= NumElements)
11143           SumV2Indices += i;
11144         else if (SVOp->getMask()[i] >= 0)
11145           SumV1Indices += i;
11146       if (SumV2Indices < SumV1Indices) {
11147         return DAG.getCommutedVectorShuffle(*SVOp);
11148       } else if (SumV2Indices == SumV1Indices) {
11149         int NumV1OddIndices = 0, NumV2OddIndices = 0;
11150         for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
11151           if (SVOp->getMask()[i] >= NumElements)
11152             NumV2OddIndices += i % 2;
11153           else if (SVOp->getMask()[i] >= 0)
11154             NumV1OddIndices += i % 2;
11155         if (NumV2OddIndices < NumV1OddIndices)
11156           return DAG.getCommutedVectorShuffle(*SVOp);
11157       }
11158     }
11159   }
11160
11161   // For each vector width, delegate to a specialized lowering routine.
11162   if (VT.is128BitVector())
11163     return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
11164
11165   if (VT.is256BitVector())
11166     return lower256BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
11167
11168   if (VT.is512BitVector())
11169     return lower512BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
11170
11171   if (Is1BitVector)
11172     return lower1BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
11173   llvm_unreachable("Unimplemented!");
11174 }
11175
11176 // This function assumes its argument is a BUILD_VECTOR of constants or
11177 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
11178 // true.
11179 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
11180                                     unsigned &MaskValue) {
11181   MaskValue = 0;
11182   unsigned NumElems = BuildVector->getNumOperands();
11183
11184   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
11185   // We don't handle the >2 lanes case right now.
11186   unsigned NumLanes = (NumElems - 1) / 8 + 1;
11187   if (NumLanes > 2)
11188     return false;
11189
11190   unsigned NumElemsInLane = NumElems / NumLanes;
11191
11192   // Blend for v16i16 should be symmetric for the both lanes.
11193   for (unsigned i = 0; i < NumElemsInLane; ++i) {
11194     SDValue EltCond = BuildVector->getOperand(i);
11195     SDValue SndLaneEltCond =
11196         (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
11197
11198     int Lane1Cond = -1, Lane2Cond = -1;
11199     if (isa<ConstantSDNode>(EltCond))
11200       Lane1Cond = !isZero(EltCond);
11201     if (isa<ConstantSDNode>(SndLaneEltCond))
11202       Lane2Cond = !isZero(SndLaneEltCond);
11203
11204     unsigned LaneMask = 0;
11205     if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
11206       // Lane1Cond != 0, means we want the first argument.
11207       // Lane1Cond == 0, means we want the second argument.
11208       // The encoding of this argument is 0 for the first argument, 1
11209       // for the second. Therefore, invert the condition.
11210       LaneMask = !Lane1Cond << i;
11211     else if (Lane1Cond < 0)
11212       LaneMask = !Lane2Cond << i;
11213     else
11214       return false;
11215
11216     MaskValue |= LaneMask;
11217     if (NumLanes == 2)
11218       MaskValue |= LaneMask << NumElemsInLane;
11219   }
11220   return true;
11221 }
11222
11223 /// \brief Try to lower a VSELECT instruction to a vector shuffle.
11224 static SDValue lowerVSELECTtoVectorShuffle(SDValue Op,
11225                                            const X86Subtarget *Subtarget,
11226                                            SelectionDAG &DAG) {
11227   SDValue Cond = Op.getOperand(0);
11228   SDValue LHS = Op.getOperand(1);
11229   SDValue RHS = Op.getOperand(2);
11230   SDLoc dl(Op);
11231   MVT VT = Op.getSimpleValueType();
11232
11233   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
11234     return SDValue();
11235   auto *CondBV = cast<BuildVectorSDNode>(Cond);
11236
11237   // Only non-legal VSELECTs reach this lowering, convert those into generic
11238   // shuffles and re-use the shuffle lowering path for blends.
11239   SmallVector<int, 32> Mask;
11240   for (int i = 0, Size = VT.getVectorNumElements(); i < Size; ++i) {
11241     SDValue CondElt = CondBV->getOperand(i);
11242     Mask.push_back(
11243         isa<ConstantSDNode>(CondElt) ? i + (isZero(CondElt) ? Size : 0) : -1);
11244   }
11245   return DAG.getVectorShuffle(VT, dl, LHS, RHS, Mask);
11246 }
11247
11248 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
11249   // A vselect where all conditions and data are constants can be optimized into
11250   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
11251   if (ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(0).getNode()) &&
11252       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(1).getNode()) &&
11253       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(2).getNode()))
11254     return SDValue();
11255
11256   // Try to lower this to a blend-style vector shuffle. This can handle all
11257   // constant condition cases.
11258   if (SDValue BlendOp = lowerVSELECTtoVectorShuffle(Op, Subtarget, DAG))
11259     return BlendOp;
11260
11261   // Variable blends are only legal from SSE4.1 onward.
11262   if (!Subtarget->hasSSE41())
11263     return SDValue();
11264
11265   // Only some types will be legal on some subtargets. If we can emit a legal
11266   // VSELECT-matching blend, return Op, and but if we need to expand, return
11267   // a null value.
11268   switch (Op.getSimpleValueType().SimpleTy) {
11269   default:
11270     // Most of the vector types have blends past SSE4.1.
11271     return Op;
11272
11273   case MVT::v32i8:
11274     // The byte blends for AVX vectors were introduced only in AVX2.
11275     if (Subtarget->hasAVX2())
11276       return Op;
11277
11278     return SDValue();
11279
11280   case MVT::v8i16:
11281   case MVT::v16i16:
11282     // AVX-512 BWI and VLX features support VSELECT with i16 elements.
11283     if (Subtarget->hasBWI() && Subtarget->hasVLX())
11284       return Op;
11285
11286     // FIXME: We should custom lower this by fixing the condition and using i8
11287     // blends.
11288     return SDValue();
11289   }
11290 }
11291
11292 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
11293   MVT VT = Op.getSimpleValueType();
11294   SDLoc dl(Op);
11295
11296   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
11297     return SDValue();
11298
11299   if (VT.getSizeInBits() == 8) {
11300     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
11301                                   Op.getOperand(0), Op.getOperand(1));
11302     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
11303                                   DAG.getValueType(VT));
11304     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
11305   }
11306
11307   if (VT.getSizeInBits() == 16) {
11308     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11309     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
11310     if (Idx == 0)
11311       return DAG.getNode(
11312           ISD::TRUNCATE, dl, MVT::i16,
11313           DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
11314                       DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
11315                       Op.getOperand(1)));
11316     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
11317                                   Op.getOperand(0), Op.getOperand(1));
11318     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
11319                                   DAG.getValueType(VT));
11320     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
11321   }
11322
11323   if (VT == MVT::f32) {
11324     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
11325     // the result back to FR32 register. It's only worth matching if the
11326     // result has a single use which is a store or a bitcast to i32.  And in
11327     // the case of a store, it's not worth it if the index is a constant 0,
11328     // because a MOVSSmr can be used instead, which is smaller and faster.
11329     if (!Op.hasOneUse())
11330       return SDValue();
11331     SDNode *User = *Op.getNode()->use_begin();
11332     if ((User->getOpcode() != ISD::STORE ||
11333          (isa<ConstantSDNode>(Op.getOperand(1)) &&
11334           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
11335         (User->getOpcode() != ISD::BITCAST ||
11336          User->getValueType(0) != MVT::i32))
11337       return SDValue();
11338     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
11339                                   DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
11340                                   Op.getOperand(1));
11341     return DAG.getBitcast(MVT::f32, Extract);
11342   }
11343
11344   if (VT == MVT::i32 || VT == MVT::i64) {
11345     // ExtractPS/pextrq works with constant index.
11346     if (isa<ConstantSDNode>(Op.getOperand(1)))
11347       return Op;
11348   }
11349   return SDValue();
11350 }
11351
11352 /// Extract one bit from mask vector, like v16i1 or v8i1.
11353 /// AVX-512 feature.
11354 SDValue
11355 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
11356   SDValue Vec = Op.getOperand(0);
11357   SDLoc dl(Vec);
11358   MVT VecVT = Vec.getSimpleValueType();
11359   SDValue Idx = Op.getOperand(1);
11360   MVT EltVT = Op.getSimpleValueType();
11361
11362   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
11363   assert((VecVT.getVectorNumElements() <= 16 || Subtarget->hasBWI()) &&
11364          "Unexpected vector type in ExtractBitFromMaskVector");
11365
11366   // variable index can't be handled in mask registers,
11367   // extend vector to VR512
11368   if (!isa<ConstantSDNode>(Idx)) {
11369     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
11370     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
11371     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
11372                               ExtVT.getVectorElementType(), Ext, Idx);
11373     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
11374   }
11375
11376   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11377   const TargetRegisterClass* rc = getRegClassFor(VecVT);
11378   if (!Subtarget->hasDQI() && (VecVT.getVectorNumElements() <= 8))
11379     rc = getRegClassFor(MVT::v16i1);
11380   unsigned MaxSift = rc->getSize()*8 - 1;
11381   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
11382                     DAG.getConstant(MaxSift - IdxVal, dl, MVT::i8));
11383   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
11384                     DAG.getConstant(MaxSift, dl, MVT::i8));
11385   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
11386                        DAG.getIntPtrConstant(0, dl));
11387 }
11388
11389 SDValue
11390 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
11391                                            SelectionDAG &DAG) const {
11392   SDLoc dl(Op);
11393   SDValue Vec = Op.getOperand(0);
11394   MVT VecVT = Vec.getSimpleValueType();
11395   SDValue Idx = Op.getOperand(1);
11396
11397   if (Op.getSimpleValueType() == MVT::i1)
11398     return ExtractBitFromMaskVector(Op, DAG);
11399
11400   if (!isa<ConstantSDNode>(Idx)) {
11401     if (VecVT.is512BitVector() ||
11402         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
11403          VecVT.getVectorElementType().getSizeInBits() == 32)) {
11404
11405       MVT MaskEltVT =
11406         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
11407       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
11408                                     MaskEltVT.getSizeInBits());
11409
11410       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
11411       auto PtrVT = getPointerTy(DAG.getDataLayout());
11412       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
11413                                  getZeroVector(MaskVT, Subtarget, DAG, dl), Idx,
11414                                  DAG.getConstant(0, dl, PtrVT));
11415       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
11416       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Perm,
11417                          DAG.getConstant(0, dl, PtrVT));
11418     }
11419     return SDValue();
11420   }
11421
11422   // If this is a 256-bit vector result, first extract the 128-bit vector and
11423   // then extract the element from the 128-bit vector.
11424   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
11425
11426     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11427     // Get the 128-bit vector.
11428     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
11429     MVT EltVT = VecVT.getVectorElementType();
11430
11431     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
11432     assert(isPowerOf2_32(ElemsPerChunk) && "Elements per chunk not power of 2");
11433
11434     // Find IdxVal modulo ElemsPerChunk. Since ElemsPerChunk is a power of 2
11435     // this can be done with a mask.
11436     IdxVal &= ElemsPerChunk - 1;
11437     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
11438                        DAG.getConstant(IdxVal, dl, MVT::i32));
11439   }
11440
11441   assert(VecVT.is128BitVector() && "Unexpected vector length");
11442
11443   if (Subtarget->hasSSE41())
11444     if (SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG))
11445       return Res;
11446
11447   MVT VT = Op.getSimpleValueType();
11448   // TODO: handle v16i8.
11449   if (VT.getSizeInBits() == 16) {
11450     SDValue Vec = Op.getOperand(0);
11451     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11452     if (Idx == 0)
11453       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
11454                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
11455                                      DAG.getBitcast(MVT::v4i32, Vec),
11456                                      Op.getOperand(1)));
11457     // Transform it so it match pextrw which produces a 32-bit result.
11458     MVT EltVT = MVT::i32;
11459     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
11460                                   Op.getOperand(0), Op.getOperand(1));
11461     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
11462                                   DAG.getValueType(VT));
11463     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
11464   }
11465
11466   if (VT.getSizeInBits() == 32) {
11467     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11468     if (Idx == 0)
11469       return Op;
11470
11471     // SHUFPS the element to the lowest double word, then movss.
11472     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
11473     MVT VVT = Op.getOperand(0).getSimpleValueType();
11474     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
11475                                        DAG.getUNDEF(VVT), Mask);
11476     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
11477                        DAG.getIntPtrConstant(0, dl));
11478   }
11479
11480   if (VT.getSizeInBits() == 64) {
11481     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
11482     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
11483     //        to match extract_elt for f64.
11484     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11485     if (Idx == 0)
11486       return Op;
11487
11488     // UNPCKHPD the element to the lowest double word, then movsd.
11489     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
11490     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
11491     int Mask[2] = { 1, -1 };
11492     MVT VVT = Op.getOperand(0).getSimpleValueType();
11493     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
11494                                        DAG.getUNDEF(VVT), Mask);
11495     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
11496                        DAG.getIntPtrConstant(0, dl));
11497   }
11498
11499   return SDValue();
11500 }
11501
11502 /// Insert one bit to mask vector, like v16i1 or v8i1.
11503 /// AVX-512 feature.
11504 SDValue
11505 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
11506   SDLoc dl(Op);
11507   SDValue Vec = Op.getOperand(0);
11508   SDValue Elt = Op.getOperand(1);
11509   SDValue Idx = Op.getOperand(2);
11510   MVT VecVT = Vec.getSimpleValueType();
11511
11512   if (!isa<ConstantSDNode>(Idx)) {
11513     // Non constant index. Extend source and destination,
11514     // insert element and then truncate the result.
11515     MVT ExtVecVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
11516     MVT ExtEltVT = (VecVT == MVT::v8i1 ?  MVT::i64 : MVT::i32);
11517     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
11518       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
11519       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
11520     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
11521   }
11522
11523   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11524   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
11525   if (IdxVal)
11526     EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
11527                            DAG.getConstant(IdxVal, dl, MVT::i8));
11528   if (Vec.getOpcode() == ISD::UNDEF)
11529     return EltInVec;
11530   return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
11531 }
11532
11533 SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
11534                                                   SelectionDAG &DAG) const {
11535   MVT VT = Op.getSimpleValueType();
11536   MVT EltVT = VT.getVectorElementType();
11537
11538   if (EltVT == MVT::i1)
11539     return InsertBitToMaskVector(Op, DAG);
11540
11541   SDLoc dl(Op);
11542   SDValue N0 = Op.getOperand(0);
11543   SDValue N1 = Op.getOperand(1);
11544   SDValue N2 = Op.getOperand(2);
11545   if (!isa<ConstantSDNode>(N2))
11546     return SDValue();
11547   auto *N2C = cast<ConstantSDNode>(N2);
11548   unsigned IdxVal = N2C->getZExtValue();
11549
11550   // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
11551   // into that, and then insert the subvector back into the result.
11552   if (VT.is256BitVector() || VT.is512BitVector()) {
11553     // With a 256-bit vector, we can insert into the zero element efficiently
11554     // using a blend if we have AVX or AVX2 and the right data type.
11555     if (VT.is256BitVector() && IdxVal == 0) {
11556       // TODO: It is worthwhile to cast integer to floating point and back
11557       // and incur a domain crossing penalty if that's what we'll end up
11558       // doing anyway after extracting to a 128-bit vector.
11559       if ((Subtarget->hasAVX() && (EltVT == MVT::f64 || EltVT == MVT::f32)) ||
11560           (Subtarget->hasAVX2() && EltVT == MVT::i32)) {
11561         SDValue N1Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, N1);
11562         N2 = DAG.getIntPtrConstant(1, dl);
11563         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1Vec, N2);
11564       }
11565     }
11566
11567     // Get the desired 128-bit vector chunk.
11568     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
11569
11570     // Insert the element into the desired chunk.
11571     unsigned NumEltsIn128 = 128 / EltVT.getSizeInBits();
11572     assert(isPowerOf2_32(NumEltsIn128));
11573     // Since NumEltsIn128 is a power of 2 we can use mask instead of modulo.
11574     unsigned IdxIn128 = IdxVal & (NumEltsIn128 - 1);
11575
11576     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
11577                     DAG.getConstant(IdxIn128, dl, MVT::i32));
11578
11579     // Insert the changed part back into the bigger vector
11580     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
11581   }
11582   assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
11583
11584   if (Subtarget->hasSSE41()) {
11585     if (EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) {
11586       unsigned Opc;
11587       if (VT == MVT::v8i16) {
11588         Opc = X86ISD::PINSRW;
11589       } else {
11590         assert(VT == MVT::v16i8);
11591         Opc = X86ISD::PINSRB;
11592       }
11593
11594       // Transform it so it match pinsr{b,w} which expects a GR32 as its second
11595       // argument.
11596       if (N1.getValueType() != MVT::i32)
11597         N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11598       if (N2.getValueType() != MVT::i32)
11599         N2 = DAG.getIntPtrConstant(IdxVal, dl);
11600       return DAG.getNode(Opc, dl, VT, N0, N1, N2);
11601     }
11602
11603     if (EltVT == MVT::f32) {
11604       // Bits [7:6] of the constant are the source select. This will always be
11605       //   zero here. The DAG Combiner may combine an extract_elt index into
11606       //   these bits. For example (insert (extract, 3), 2) could be matched by
11607       //   putting the '3' into bits [7:6] of X86ISD::INSERTPS.
11608       // Bits [5:4] of the constant are the destination select. This is the
11609       //   value of the incoming immediate.
11610       // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
11611       //   combine either bitwise AND or insert of float 0.0 to set these bits.
11612
11613       bool MinSize = DAG.getMachineFunction().getFunction()->optForMinSize();
11614       if (IdxVal == 0 && (!MinSize || !MayFoldLoad(N1))) {
11615         // If this is an insertion of 32-bits into the low 32-bits of
11616         // a vector, we prefer to generate a blend with immediate rather
11617         // than an insertps. Blends are simpler operations in hardware and so
11618         // will always have equal or better performance than insertps.
11619         // But if optimizing for size and there's a load folding opportunity,
11620         // generate insertps because blendps does not have a 32-bit memory
11621         // operand form.
11622         N2 = DAG.getIntPtrConstant(1, dl);
11623         N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11624         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1, N2);
11625       }
11626       N2 = DAG.getIntPtrConstant(IdxVal << 4, dl);
11627       // Create this as a scalar to vector..
11628       N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11629       return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
11630     }
11631
11632     if (EltVT == MVT::i32 || EltVT == MVT::i64) {
11633       // PINSR* works with constant index.
11634       return Op;
11635     }
11636   }
11637
11638   if (EltVT == MVT::i8)
11639     return SDValue();
11640
11641   if (EltVT.getSizeInBits() == 16) {
11642     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
11643     // as its second argument.
11644     if (N1.getValueType() != MVT::i32)
11645       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11646     if (N2.getValueType() != MVT::i32)
11647       N2 = DAG.getIntPtrConstant(IdxVal, dl);
11648     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
11649   }
11650   return SDValue();
11651 }
11652
11653 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
11654   SDLoc dl(Op);
11655   MVT OpVT = Op.getSimpleValueType();
11656
11657   // If this is a 256-bit vector result, first insert into a 128-bit
11658   // vector and then insert into the 256-bit vector.
11659   if (!OpVT.is128BitVector()) {
11660     // Insert into a 128-bit vector.
11661     unsigned SizeFactor = OpVT.getSizeInBits()/128;
11662     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
11663                                  OpVT.getVectorNumElements() / SizeFactor);
11664
11665     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
11666
11667     // Insert the 128-bit vector.
11668     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
11669   }
11670
11671   if (OpVT == MVT::v1i64 &&
11672       Op.getOperand(0).getValueType() == MVT::i64)
11673     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
11674
11675   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
11676   assert(OpVT.is128BitVector() && "Expected an SSE type!");
11677   return DAG.getBitcast(
11678       OpVT, DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, AnyExt));
11679 }
11680
11681 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
11682 // a simple subregister reference or explicit instructions to grab
11683 // upper bits of a vector.
11684 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
11685                                       SelectionDAG &DAG) {
11686   SDLoc dl(Op);
11687   SDValue In =  Op.getOperand(0);
11688   SDValue Idx = Op.getOperand(1);
11689   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11690   MVT ResVT   = Op.getSimpleValueType();
11691   MVT InVT    = In.getSimpleValueType();
11692
11693   if (Subtarget->hasFp256()) {
11694     if (ResVT.is128BitVector() &&
11695         (InVT.is256BitVector() || InVT.is512BitVector()) &&
11696         isa<ConstantSDNode>(Idx)) {
11697       return Extract128BitVector(In, IdxVal, DAG, dl);
11698     }
11699     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
11700         isa<ConstantSDNode>(Idx)) {
11701       return Extract256BitVector(In, IdxVal, DAG, dl);
11702     }
11703   }
11704   return SDValue();
11705 }
11706
11707 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
11708 // simple superregister reference or explicit instructions to insert
11709 // the upper bits of a vector.
11710 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
11711                                      SelectionDAG &DAG) {
11712   if (!Subtarget->hasAVX())
11713     return SDValue();
11714
11715   SDLoc dl(Op);
11716   SDValue Vec = Op.getOperand(0);
11717   SDValue SubVec = Op.getOperand(1);
11718   SDValue Idx = Op.getOperand(2);
11719
11720   if (!isa<ConstantSDNode>(Idx))
11721     return SDValue();
11722
11723   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11724   MVT OpVT = Op.getSimpleValueType();
11725   MVT SubVecVT = SubVec.getSimpleValueType();
11726
11727   // Fold two 16-byte subvector loads into one 32-byte load:
11728   // (insert_subvector (insert_subvector undef, (load addr), 0),
11729   //                   (load addr + 16), Elts/2)
11730   // --> load32 addr
11731   if ((IdxVal == OpVT.getVectorNumElements() / 2) &&
11732       Vec.getOpcode() == ISD::INSERT_SUBVECTOR &&
11733       OpVT.is256BitVector() && SubVecVT.is128BitVector()) {
11734     auto *Idx2 = dyn_cast<ConstantSDNode>(Vec.getOperand(2));
11735     if (Idx2 && Idx2->getZExtValue() == 0) {
11736       SDValue SubVec2 = Vec.getOperand(1);
11737       // If needed, look through a bitcast to get to the load.
11738       if (SubVec2.getNode() && SubVec2.getOpcode() == ISD::BITCAST)
11739         SubVec2 = SubVec2.getOperand(0);
11740
11741       if (auto *FirstLd = dyn_cast<LoadSDNode>(SubVec2)) {
11742         bool Fast;
11743         unsigned Alignment = FirstLd->getAlignment();
11744         unsigned AS = FirstLd->getAddressSpace();
11745         const X86TargetLowering *TLI = Subtarget->getTargetLowering();
11746         if (TLI->allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(),
11747                                     OpVT, AS, Alignment, &Fast) && Fast) {
11748           SDValue Ops[] = { SubVec2, SubVec };
11749           if (SDValue Ld = EltsFromConsecutiveLoads(OpVT, Ops, dl, DAG, false))
11750             return Ld;
11751         }
11752       }
11753     }
11754   }
11755
11756   if ((OpVT.is256BitVector() || OpVT.is512BitVector()) &&
11757       SubVecVT.is128BitVector())
11758     return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
11759
11760   if (OpVT.is512BitVector() && SubVecVT.is256BitVector())
11761     return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
11762
11763   if (OpVT.getVectorElementType() == MVT::i1) {
11764     if (IdxVal == 0  && Vec.getOpcode() == ISD::UNDEF) // the operation is legal
11765       return Op;
11766     SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
11767     SDValue Undef = DAG.getUNDEF(OpVT);
11768     unsigned NumElems = OpVT.getVectorNumElements();
11769     SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
11770
11771     if (IdxVal == OpVT.getVectorNumElements() / 2) {
11772       // Zero upper bits of the Vec
11773       Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
11774       Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
11775
11776       SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
11777                                  SubVec, ZeroIdx);
11778       Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
11779       return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
11780     }
11781     if (IdxVal == 0) {
11782       SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
11783                                  SubVec, ZeroIdx);
11784       // Zero upper bits of the Vec2
11785       Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
11786       Vec2 = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec2, ShiftBits);
11787       // Zero lower bits of the Vec
11788       Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
11789       Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
11790       // Merge them together
11791       return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
11792     }
11793   }
11794   return SDValue();
11795 }
11796
11797 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
11798 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
11799 // one of the above mentioned nodes. It has to be wrapped because otherwise
11800 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
11801 // be used to form addressing mode. These wrapped nodes will be selected
11802 // into MOV32ri.
11803 SDValue
11804 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
11805   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
11806
11807   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11808   // global base reg.
11809   unsigned char OpFlag = 0;
11810   unsigned WrapperKind = X86ISD::Wrapper;
11811   CodeModel::Model M = DAG.getTarget().getCodeModel();
11812
11813   if (Subtarget->isPICStyleRIPRel() &&
11814       (M == CodeModel::Small || M == CodeModel::Kernel))
11815     WrapperKind = X86ISD::WrapperRIP;
11816   else if (Subtarget->isPICStyleGOT())
11817     OpFlag = X86II::MO_GOTOFF;
11818   else if (Subtarget->isPICStyleStubPIC())
11819     OpFlag = X86II::MO_PIC_BASE_OFFSET;
11820
11821   auto PtrVT = getPointerTy(DAG.getDataLayout());
11822   SDValue Result = DAG.getTargetConstantPool(
11823       CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(), OpFlag);
11824   SDLoc DL(CP);
11825   Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11826   // With PIC, the address is actually $g + Offset.
11827   if (OpFlag) {
11828     Result =
11829         DAG.getNode(ISD::ADD, DL, PtrVT,
11830                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11831   }
11832
11833   return Result;
11834 }
11835
11836 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
11837   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
11838
11839   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11840   // global base reg.
11841   unsigned char OpFlag = 0;
11842   unsigned WrapperKind = X86ISD::Wrapper;
11843   CodeModel::Model M = DAG.getTarget().getCodeModel();
11844
11845   if (Subtarget->isPICStyleRIPRel() &&
11846       (M == CodeModel::Small || M == CodeModel::Kernel))
11847     WrapperKind = X86ISD::WrapperRIP;
11848   else if (Subtarget->isPICStyleGOT())
11849     OpFlag = X86II::MO_GOTOFF;
11850   else if (Subtarget->isPICStyleStubPIC())
11851     OpFlag = X86II::MO_PIC_BASE_OFFSET;
11852
11853   auto PtrVT = getPointerTy(DAG.getDataLayout());
11854   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, OpFlag);
11855   SDLoc DL(JT);
11856   Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11857
11858   // With PIC, the address is actually $g + Offset.
11859   if (OpFlag)
11860     Result =
11861         DAG.getNode(ISD::ADD, DL, PtrVT,
11862                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11863
11864   return Result;
11865 }
11866
11867 SDValue
11868 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
11869   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
11870
11871   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11872   // global base reg.
11873   unsigned char OpFlag = 0;
11874   unsigned WrapperKind = X86ISD::Wrapper;
11875   CodeModel::Model M = DAG.getTarget().getCodeModel();
11876
11877   if (Subtarget->isPICStyleRIPRel() &&
11878       (M == CodeModel::Small || M == CodeModel::Kernel)) {
11879     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
11880       OpFlag = X86II::MO_GOTPCREL;
11881     WrapperKind = X86ISD::WrapperRIP;
11882   } else if (Subtarget->isPICStyleGOT()) {
11883     OpFlag = X86II::MO_GOT;
11884   } else if (Subtarget->isPICStyleStubPIC()) {
11885     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
11886   } else if (Subtarget->isPICStyleStubNoDynamic()) {
11887     OpFlag = X86II::MO_DARWIN_NONLAZY;
11888   }
11889
11890   auto PtrVT = getPointerTy(DAG.getDataLayout());
11891   SDValue Result = DAG.getTargetExternalSymbol(Sym, PtrVT, OpFlag);
11892
11893   SDLoc DL(Op);
11894   Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11895
11896   // With PIC, the address is actually $g + Offset.
11897   if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
11898       !Subtarget->is64Bit()) {
11899     Result =
11900         DAG.getNode(ISD::ADD, DL, PtrVT,
11901                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11902   }
11903
11904   // For symbols that require a load from a stub to get the address, emit the
11905   // load.
11906   if (isGlobalStubReference(OpFlag))
11907     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
11908                          MachinePointerInfo::getGOT(DAG.getMachineFunction()),
11909                          false, false, false, 0);
11910
11911   return Result;
11912 }
11913
11914 SDValue
11915 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
11916   // Create the TargetBlockAddressAddress node.
11917   unsigned char OpFlags =
11918     Subtarget->ClassifyBlockAddressReference();
11919   CodeModel::Model M = DAG.getTarget().getCodeModel();
11920   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
11921   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
11922   SDLoc dl(Op);
11923   auto PtrVT = getPointerTy(DAG.getDataLayout());
11924   SDValue Result = DAG.getTargetBlockAddress(BA, PtrVT, Offset, OpFlags);
11925
11926   if (Subtarget->isPICStyleRIPRel() &&
11927       (M == CodeModel::Small || M == CodeModel::Kernel))
11928     Result = DAG.getNode(X86ISD::WrapperRIP, dl, PtrVT, Result);
11929   else
11930     Result = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, Result);
11931
11932   // With PIC, the address is actually $g + Offset.
11933   if (isGlobalRelativeToPICBase(OpFlags)) {
11934     Result = DAG.getNode(ISD::ADD, dl, PtrVT,
11935                          DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
11936   }
11937
11938   return Result;
11939 }
11940
11941 SDValue
11942 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
11943                                       int64_t Offset, SelectionDAG &DAG) const {
11944   // Create the TargetGlobalAddress node, folding in the constant
11945   // offset if it is legal.
11946   unsigned char OpFlags =
11947       Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
11948   CodeModel::Model M = DAG.getTarget().getCodeModel();
11949   auto PtrVT = getPointerTy(DAG.getDataLayout());
11950   SDValue Result;
11951   if (OpFlags == X86II::MO_NO_FLAG &&
11952       X86::isOffsetSuitableForCodeModel(Offset, M)) {
11953     // A direct static reference to a global.
11954     Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, Offset);
11955     Offset = 0;
11956   } else {
11957     Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, OpFlags);
11958   }
11959
11960   if (Subtarget->isPICStyleRIPRel() &&
11961       (M == CodeModel::Small || M == CodeModel::Kernel))
11962     Result = DAG.getNode(X86ISD::WrapperRIP, dl, PtrVT, Result);
11963   else
11964     Result = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, Result);
11965
11966   // With PIC, the address is actually $g + Offset.
11967   if (isGlobalRelativeToPICBase(OpFlags)) {
11968     Result = DAG.getNode(ISD::ADD, dl, PtrVT,
11969                          DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
11970   }
11971
11972   // For globals that require a load from a stub to get the address, emit the
11973   // load.
11974   if (isGlobalStubReference(OpFlags))
11975     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
11976                          MachinePointerInfo::getGOT(DAG.getMachineFunction()),
11977                          false, false, false, 0);
11978
11979   // If there was a non-zero offset that we didn't fold, create an explicit
11980   // addition for it.
11981   if (Offset != 0)
11982     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result,
11983                          DAG.getConstant(Offset, dl, PtrVT));
11984
11985   return Result;
11986 }
11987
11988 SDValue
11989 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
11990   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
11991   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
11992   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
11993 }
11994
11995 static SDValue
11996 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
11997            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
11998            unsigned char OperandFlags, bool LocalDynamic = false) {
11999   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12000   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
12001   SDLoc dl(GA);
12002   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
12003                                            GA->getValueType(0),
12004                                            GA->getOffset(),
12005                                            OperandFlags);
12006
12007   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
12008                                            : X86ISD::TLSADDR;
12009
12010   if (InFlag) {
12011     SDValue Ops[] = { Chain,  TGA, *InFlag };
12012     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
12013   } else {
12014     SDValue Ops[]  = { Chain, TGA };
12015     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
12016   }
12017
12018   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
12019   MFI->setAdjustsStack(true);
12020   MFI->setHasCalls(true);
12021
12022   SDValue Flag = Chain.getValue(1);
12023   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
12024 }
12025
12026 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
12027 static SDValue
12028 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
12029                                 const EVT PtrVT) {
12030   SDValue InFlag;
12031   SDLoc dl(GA);  // ? function entry point might be better
12032   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
12033                                    DAG.getNode(X86ISD::GlobalBaseReg,
12034                                                SDLoc(), PtrVT), InFlag);
12035   InFlag = Chain.getValue(1);
12036
12037   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
12038 }
12039
12040 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
12041 static SDValue
12042 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
12043                                 const EVT PtrVT) {
12044   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
12045                     X86::RAX, X86II::MO_TLSGD);
12046 }
12047
12048 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
12049                                            SelectionDAG &DAG,
12050                                            const EVT PtrVT,
12051                                            bool is64Bit) {
12052   SDLoc dl(GA);
12053
12054   // Get the start address of the TLS block for this module.
12055   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
12056       .getInfo<X86MachineFunctionInfo>();
12057   MFI->incNumLocalDynamicTLSAccesses();
12058
12059   SDValue Base;
12060   if (is64Bit) {
12061     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
12062                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
12063   } else {
12064     SDValue InFlag;
12065     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
12066         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
12067     InFlag = Chain.getValue(1);
12068     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
12069                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
12070   }
12071
12072   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
12073   // of Base.
12074
12075   // Build x@dtpoff.
12076   unsigned char OperandFlags = X86II::MO_DTPOFF;
12077   unsigned WrapperKind = X86ISD::Wrapper;
12078   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
12079                                            GA->getValueType(0),
12080                                            GA->getOffset(), OperandFlags);
12081   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
12082
12083   // Add x@dtpoff with the base.
12084   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
12085 }
12086
12087 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
12088 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
12089                                    const EVT PtrVT, TLSModel::Model model,
12090                                    bool is64Bit, bool isPIC) {
12091   SDLoc dl(GA);
12092
12093   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
12094   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
12095                                                          is64Bit ? 257 : 256));
12096
12097   SDValue ThreadPointer =
12098       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0, dl),
12099                   MachinePointerInfo(Ptr), false, false, false, 0);
12100
12101   unsigned char OperandFlags = 0;
12102   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
12103   // initialexec.
12104   unsigned WrapperKind = X86ISD::Wrapper;
12105   if (model == TLSModel::LocalExec) {
12106     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
12107   } else if (model == TLSModel::InitialExec) {
12108     if (is64Bit) {
12109       OperandFlags = X86II::MO_GOTTPOFF;
12110       WrapperKind = X86ISD::WrapperRIP;
12111     } else {
12112       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
12113     }
12114   } else {
12115     llvm_unreachable("Unexpected model");
12116   }
12117
12118   // emit "addl x@ntpoff,%eax" (local exec)
12119   // or "addl x@indntpoff,%eax" (initial exec)
12120   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
12121   SDValue TGA =
12122       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
12123                                  GA->getOffset(), OperandFlags);
12124   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
12125
12126   if (model == TLSModel::InitialExec) {
12127     if (isPIC && !is64Bit) {
12128       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
12129                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
12130                            Offset);
12131     }
12132
12133     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
12134                          MachinePointerInfo::getGOT(DAG.getMachineFunction()),
12135                          false, false, false, 0);
12136   }
12137
12138   // The address of the thread local variable is the add of the thread
12139   // pointer with the offset of the variable.
12140   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
12141 }
12142
12143 SDValue
12144 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
12145
12146   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
12147   const GlobalValue *GV = GA->getGlobal();
12148   auto PtrVT = getPointerTy(DAG.getDataLayout());
12149
12150   if (Subtarget->isTargetELF()) {
12151     if (DAG.getTarget().Options.EmulatedTLS)
12152       return LowerToTLSEmulatedModel(GA, DAG);
12153     TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
12154     switch (model) {
12155       case TLSModel::GeneralDynamic:
12156         if (Subtarget->is64Bit())
12157           return LowerToTLSGeneralDynamicModel64(GA, DAG, PtrVT);
12158         return LowerToTLSGeneralDynamicModel32(GA, DAG, PtrVT);
12159       case TLSModel::LocalDynamic:
12160         return LowerToTLSLocalDynamicModel(GA, DAG, PtrVT,
12161                                            Subtarget->is64Bit());
12162       case TLSModel::InitialExec:
12163       case TLSModel::LocalExec:
12164         return LowerToTLSExecModel(GA, DAG, PtrVT, model, Subtarget->is64Bit(),
12165                                    DAG.getTarget().getRelocationModel() ==
12166                                        Reloc::PIC_);
12167     }
12168     llvm_unreachable("Unknown TLS model.");
12169   }
12170
12171   if (Subtarget->isTargetDarwin()) {
12172     // Darwin only has one model of TLS.  Lower to that.
12173     unsigned char OpFlag = 0;
12174     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
12175                            X86ISD::WrapperRIP : X86ISD::Wrapper;
12176
12177     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
12178     // global base reg.
12179     bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
12180                  !Subtarget->is64Bit();
12181     if (PIC32)
12182       OpFlag = X86II::MO_TLVP_PIC_BASE;
12183     else
12184       OpFlag = X86II::MO_TLVP;
12185     SDLoc DL(Op);
12186     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
12187                                                 GA->getValueType(0),
12188                                                 GA->getOffset(), OpFlag);
12189     SDValue Offset = DAG.getNode(WrapperKind, DL, PtrVT, Result);
12190
12191     // With PIC32, the address is actually $g + Offset.
12192     if (PIC32)
12193       Offset = DAG.getNode(ISD::ADD, DL, PtrVT,
12194                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
12195                            Offset);
12196
12197     // Lowering the machine isd will make sure everything is in the right
12198     // location.
12199     SDValue Chain = DAG.getEntryNode();
12200     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
12201     SDValue Args[] = { Chain, Offset };
12202     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
12203
12204     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
12205     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12206     MFI->setAdjustsStack(true);
12207
12208     // And our return value (tls address) is in the standard call return value
12209     // location.
12210     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
12211     return DAG.getCopyFromReg(Chain, DL, Reg, PtrVT, Chain.getValue(1));
12212   }
12213
12214   if (Subtarget->isTargetKnownWindowsMSVC() ||
12215       Subtarget->isTargetWindowsGNU()) {
12216     // Just use the implicit TLS architecture
12217     // Need to generate someting similar to:
12218     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
12219     //                                  ; from TEB
12220     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
12221     //   mov     rcx, qword [rdx+rcx*8]
12222     //   mov     eax, .tls$:tlsvar
12223     //   [rax+rcx] contains the address
12224     // Windows 64bit: gs:0x58
12225     // Windows 32bit: fs:__tls_array
12226
12227     SDLoc dl(GA);
12228     SDValue Chain = DAG.getEntryNode();
12229
12230     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
12231     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
12232     // use its literal value of 0x2C.
12233     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
12234                                         ? Type::getInt8PtrTy(*DAG.getContext(),
12235                                                              256)
12236                                         : Type::getInt32PtrTy(*DAG.getContext(),
12237                                                               257));
12238
12239     SDValue TlsArray = Subtarget->is64Bit()
12240                            ? DAG.getIntPtrConstant(0x58, dl)
12241                            : (Subtarget->isTargetWindowsGNU()
12242                                   ? DAG.getIntPtrConstant(0x2C, dl)
12243                                   : DAG.getExternalSymbol("_tls_array", PtrVT));
12244
12245     SDValue ThreadPointer =
12246         DAG.getLoad(PtrVT, dl, Chain, TlsArray, MachinePointerInfo(Ptr), false,
12247                     false, false, 0);
12248
12249     SDValue res;
12250     if (GV->getThreadLocalMode() == GlobalVariable::LocalExecTLSModel) {
12251       res = ThreadPointer;
12252     } else {
12253       // Load the _tls_index variable
12254       SDValue IDX = DAG.getExternalSymbol("_tls_index", PtrVT);
12255       if (Subtarget->is64Bit())
12256         IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, PtrVT, Chain, IDX,
12257                              MachinePointerInfo(), MVT::i32, false, false,
12258                              false, 0);
12259       else
12260         IDX = DAG.getLoad(PtrVT, dl, Chain, IDX, MachinePointerInfo(), false,
12261                           false, false, 0);
12262
12263       auto &DL = DAG.getDataLayout();
12264       SDValue Scale =
12265           DAG.getConstant(Log2_64_Ceil(DL.getPointerSize()), dl, PtrVT);
12266       IDX = DAG.getNode(ISD::SHL, dl, PtrVT, IDX, Scale);
12267
12268       res = DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, IDX);
12269     }
12270
12271     res = DAG.getLoad(PtrVT, dl, Chain, res, MachinePointerInfo(), false, false,
12272                       false, 0);
12273
12274     // Get the offset of start of .tls section
12275     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
12276                                              GA->getValueType(0),
12277                                              GA->getOffset(), X86II::MO_SECREL);
12278     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, TGA);
12279
12280     // The address of the thread local variable is the add of the thread
12281     // pointer with the offset of the variable.
12282     return DAG.getNode(ISD::ADD, dl, PtrVT, res, Offset);
12283   }
12284
12285   llvm_unreachable("TLS not implemented for this target.");
12286 }
12287
12288 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
12289 /// and take a 2 x i32 value to shift plus a shift amount.
12290 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
12291   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
12292   MVT VT = Op.getSimpleValueType();
12293   unsigned VTBits = VT.getSizeInBits();
12294   SDLoc dl(Op);
12295   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
12296   SDValue ShOpLo = Op.getOperand(0);
12297   SDValue ShOpHi = Op.getOperand(1);
12298   SDValue ShAmt  = Op.getOperand(2);
12299   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
12300   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
12301   // during isel.
12302   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
12303                                   DAG.getConstant(VTBits - 1, dl, MVT::i8));
12304   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
12305                                      DAG.getConstant(VTBits - 1, dl, MVT::i8))
12306                        : DAG.getConstant(0, dl, VT);
12307
12308   SDValue Tmp2, Tmp3;
12309   if (Op.getOpcode() == ISD::SHL_PARTS) {
12310     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
12311     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
12312   } else {
12313     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
12314     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
12315   }
12316
12317   // If the shift amount is larger or equal than the width of a part we can't
12318   // rely on the results of shld/shrd. Insert a test and select the appropriate
12319   // values for large shift amounts.
12320   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
12321                                 DAG.getConstant(VTBits, dl, MVT::i8));
12322   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
12323                              AndNode, DAG.getConstant(0, dl, MVT::i8));
12324
12325   SDValue Hi, Lo;
12326   SDValue CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
12327   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
12328   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
12329
12330   if (Op.getOpcode() == ISD::SHL_PARTS) {
12331     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
12332     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
12333   } else {
12334     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
12335     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
12336   }
12337
12338   SDValue Ops[2] = { Lo, Hi };
12339   return DAG.getMergeValues(Ops, dl);
12340 }
12341
12342 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
12343                                            SelectionDAG &DAG) const {
12344   SDValue Src = Op.getOperand(0);
12345   MVT SrcVT = Src.getSimpleValueType();
12346   MVT VT = Op.getSimpleValueType();
12347   SDLoc dl(Op);
12348
12349   if (SrcVT.isVector()) {
12350     if (SrcVT == MVT::v2i32 && VT == MVT::v2f64) {
12351       return DAG.getNode(X86ISD::CVTDQ2PD, dl, VT,
12352                          DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i32, Src,
12353                          DAG.getUNDEF(SrcVT)));
12354     }
12355     if (SrcVT.getVectorElementType() == MVT::i1) {
12356       MVT IntegerVT = MVT::getVectorVT(MVT::i32, SrcVT.getVectorNumElements());
12357       return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
12358                          DAG.getNode(ISD::SIGN_EXTEND, dl, IntegerVT, Src));
12359     }
12360     return SDValue();
12361   }
12362
12363   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
12364          "Unknown SINT_TO_FP to lower!");
12365
12366   // These are really Legal; return the operand so the caller accepts it as
12367   // Legal.
12368   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
12369     return Op;
12370   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
12371       Subtarget->is64Bit()) {
12372     return Op;
12373   }
12374
12375   unsigned Size = SrcVT.getSizeInBits()/8;
12376   MachineFunction &MF = DAG.getMachineFunction();
12377   auto PtrVT = getPointerTy(MF.getDataLayout());
12378   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
12379   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12380   SDValue Chain = DAG.getStore(
12381       DAG.getEntryNode(), dl, Op.getOperand(0), StackSlot,
12382       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI), false,
12383       false, 0);
12384   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
12385 }
12386
12387 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
12388                                      SDValue StackSlot,
12389                                      SelectionDAG &DAG) const {
12390   // Build the FILD
12391   SDLoc DL(Op);
12392   SDVTList Tys;
12393   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
12394   if (useSSE)
12395     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
12396   else
12397     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
12398
12399   unsigned ByteSize = SrcVT.getSizeInBits()/8;
12400
12401   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
12402   MachineMemOperand *MMO;
12403   if (FI) {
12404     int SSFI = FI->getIndex();
12405     MMO = DAG.getMachineFunction().getMachineMemOperand(
12406         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12407         MachineMemOperand::MOLoad, ByteSize, ByteSize);
12408   } else {
12409     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
12410     StackSlot = StackSlot.getOperand(1);
12411   }
12412   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
12413   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
12414                                            X86ISD::FILD, DL,
12415                                            Tys, Ops, SrcVT, MMO);
12416
12417   if (useSSE) {
12418     Chain = Result.getValue(1);
12419     SDValue InFlag = Result.getValue(2);
12420
12421     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
12422     // shouldn't be necessary except that RFP cannot be live across
12423     // multiple blocks. When stackifier is fixed, they can be uncoupled.
12424     MachineFunction &MF = DAG.getMachineFunction();
12425     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
12426     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
12427     auto PtrVT = getPointerTy(MF.getDataLayout());
12428     SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12429     Tys = DAG.getVTList(MVT::Other);
12430     SDValue Ops[] = {
12431       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
12432     };
12433     MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
12434         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12435         MachineMemOperand::MOStore, SSFISize, SSFISize);
12436
12437     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
12438                                     Ops, Op.getValueType(), MMO);
12439     Result = DAG.getLoad(
12440         Op.getValueType(), DL, Chain, StackSlot,
12441         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12442         false, false, false, 0);
12443   }
12444
12445   return Result;
12446 }
12447
12448 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
12449 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
12450                                                SelectionDAG &DAG) const {
12451   // This algorithm is not obvious. Here it is what we're trying to output:
12452   /*
12453      movq       %rax,  %xmm0
12454      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
12455      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
12456      #ifdef __SSE3__
12457        haddpd   %xmm0, %xmm0
12458      #else
12459        pshufd   $0x4e, %xmm0, %xmm1
12460        addpd    %xmm1, %xmm0
12461      #endif
12462   */
12463
12464   SDLoc dl(Op);
12465   LLVMContext *Context = DAG.getContext();
12466
12467   // Build some magic constants.
12468   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
12469   Constant *C0 = ConstantDataVector::get(*Context, CV0);
12470   auto PtrVT = getPointerTy(DAG.getDataLayout());
12471   SDValue CPIdx0 = DAG.getConstantPool(C0, PtrVT, 16);
12472
12473   SmallVector<Constant*,2> CV1;
12474   CV1.push_back(
12475     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
12476                                       APInt(64, 0x4330000000000000ULL))));
12477   CV1.push_back(
12478     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
12479                                       APInt(64, 0x4530000000000000ULL))));
12480   Constant *C1 = ConstantVector::get(CV1);
12481   SDValue CPIdx1 = DAG.getConstantPool(C1, PtrVT, 16);
12482
12483   // Load the 64-bit value into an XMM register.
12484   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
12485                             Op.getOperand(0));
12486   SDValue CLod0 =
12487       DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
12488                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12489                   false, false, false, 16);
12490   SDValue Unpck1 =
12491       getUnpackl(DAG, dl, MVT::v4i32, DAG.getBitcast(MVT::v4i32, XR1), CLod0);
12492
12493   SDValue CLod1 =
12494       DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
12495                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12496                   false, false, false, 16);
12497   SDValue XR2F = DAG.getBitcast(MVT::v2f64, Unpck1);
12498   // TODO: Are there any fast-math-flags to propagate here?
12499   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
12500   SDValue Result;
12501
12502   if (Subtarget->hasSSE3()) {
12503     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
12504     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
12505   } else {
12506     SDValue S2F = DAG.getBitcast(MVT::v4i32, Sub);
12507     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
12508                                            S2F, 0x4E, DAG);
12509     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
12510                          DAG.getBitcast(MVT::v2f64, Shuffle), Sub);
12511   }
12512
12513   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
12514                      DAG.getIntPtrConstant(0, dl));
12515 }
12516
12517 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
12518 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
12519                                                SelectionDAG &DAG) const {
12520   SDLoc dl(Op);
12521   // FP constant to bias correct the final result.
12522   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
12523                                    MVT::f64);
12524
12525   // Load the 32-bit value into an XMM register.
12526   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
12527                              Op.getOperand(0));
12528
12529   // Zero out the upper parts of the register.
12530   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
12531
12532   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
12533                      DAG.getBitcast(MVT::v2f64, Load),
12534                      DAG.getIntPtrConstant(0, dl));
12535
12536   // Or the load with the bias.
12537   SDValue Or = DAG.getNode(
12538       ISD::OR, dl, MVT::v2i64,
12539       DAG.getBitcast(MVT::v2i64,
12540                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Load)),
12541       DAG.getBitcast(MVT::v2i64,
12542                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Bias)));
12543   Or =
12544       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
12545                   DAG.getBitcast(MVT::v2f64, Or), DAG.getIntPtrConstant(0, dl));
12546
12547   // Subtract the bias.
12548   // TODO: Are there any fast-math-flags to propagate here?
12549   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
12550
12551   // Handle final rounding.
12552   MVT DestVT = Op.getSimpleValueType();
12553
12554   if (DestVT.bitsLT(MVT::f64))
12555     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
12556                        DAG.getIntPtrConstant(0, dl));
12557   if (DestVT.bitsGT(MVT::f64))
12558     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
12559
12560   // Handle final rounding.
12561   return Sub;
12562 }
12563
12564 static SDValue lowerUINT_TO_FP_vXi32(SDValue Op, SelectionDAG &DAG,
12565                                      const X86Subtarget &Subtarget) {
12566   // The algorithm is the following:
12567   // #ifdef __SSE4_1__
12568   //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
12569   //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
12570   //                                 (uint4) 0x53000000, 0xaa);
12571   // #else
12572   //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
12573   //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
12574   // #endif
12575   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
12576   //     return (float4) lo + fhi;
12577
12578   // We shouldn't use it when unsafe-fp-math is enabled though: we might later
12579   // reassociate the two FADDs, and if we do that, the algorithm fails
12580   // spectacularly (PR24512).
12581   // FIXME: If we ever have some kind of Machine FMF, this should be marked
12582   // as non-fast and always be enabled. Why isn't SDAG FMF enough? Because
12583   // there's also the MachineCombiner reassociations happening on Machine IR.
12584   if (DAG.getTarget().Options.UnsafeFPMath)
12585     return SDValue();
12586
12587   SDLoc DL(Op);
12588   SDValue V = Op->getOperand(0);
12589   MVT VecIntVT = V.getSimpleValueType();
12590   bool Is128 = VecIntVT == MVT::v4i32;
12591   MVT VecFloatVT = Is128 ? MVT::v4f32 : MVT::v8f32;
12592   // If we convert to something else than the supported type, e.g., to v4f64,
12593   // abort early.
12594   if (VecFloatVT != Op->getSimpleValueType(0))
12595     return SDValue();
12596
12597   unsigned NumElts = VecIntVT.getVectorNumElements();
12598   assert((VecIntVT == MVT::v4i32 || VecIntVT == MVT::v8i32) &&
12599          "Unsupported custom type");
12600   assert(NumElts <= 8 && "The size of the constant array must be fixed");
12601
12602   // In the #idef/#else code, we have in common:
12603   // - The vector of constants:
12604   // -- 0x4b000000
12605   // -- 0x53000000
12606   // - A shift:
12607   // -- v >> 16
12608
12609   // Create the splat vector for 0x4b000000.
12610   SDValue CstLow = DAG.getConstant(0x4b000000, DL, MVT::i32);
12611   SDValue CstLowArray[] = {CstLow, CstLow, CstLow, CstLow,
12612                            CstLow, CstLow, CstLow, CstLow};
12613   SDValue VecCstLow = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12614                                   makeArrayRef(&CstLowArray[0], NumElts));
12615   // Create the splat vector for 0x53000000.
12616   SDValue CstHigh = DAG.getConstant(0x53000000, DL, MVT::i32);
12617   SDValue CstHighArray[] = {CstHigh, CstHigh, CstHigh, CstHigh,
12618                             CstHigh, CstHigh, CstHigh, CstHigh};
12619   SDValue VecCstHigh = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12620                                    makeArrayRef(&CstHighArray[0], NumElts));
12621
12622   // Create the right shift.
12623   SDValue CstShift = DAG.getConstant(16, DL, MVT::i32);
12624   SDValue CstShiftArray[] = {CstShift, CstShift, CstShift, CstShift,
12625                              CstShift, CstShift, CstShift, CstShift};
12626   SDValue VecCstShift = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12627                                     makeArrayRef(&CstShiftArray[0], NumElts));
12628   SDValue HighShift = DAG.getNode(ISD::SRL, DL, VecIntVT, V, VecCstShift);
12629
12630   SDValue Low, High;
12631   if (Subtarget.hasSSE41()) {
12632     MVT VecI16VT = Is128 ? MVT::v8i16 : MVT::v16i16;
12633     //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
12634     SDValue VecCstLowBitcast = DAG.getBitcast(VecI16VT, VecCstLow);
12635     SDValue VecBitcast = DAG.getBitcast(VecI16VT, V);
12636     // Low will be bitcasted right away, so do not bother bitcasting back to its
12637     // original type.
12638     Low = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecBitcast,
12639                       VecCstLowBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
12640     //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
12641     //                                 (uint4) 0x53000000, 0xaa);
12642     SDValue VecCstHighBitcast = DAG.getBitcast(VecI16VT, VecCstHigh);
12643     SDValue VecShiftBitcast = DAG.getBitcast(VecI16VT, HighShift);
12644     // High will be bitcasted right away, so do not bother bitcasting back to
12645     // its original type.
12646     High = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecShiftBitcast,
12647                        VecCstHighBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
12648   } else {
12649     SDValue CstMask = DAG.getConstant(0xffff, DL, MVT::i32);
12650     SDValue VecCstMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT, CstMask,
12651                                      CstMask, CstMask, CstMask);
12652     //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
12653     SDValue LowAnd = DAG.getNode(ISD::AND, DL, VecIntVT, V, VecCstMask);
12654     Low = DAG.getNode(ISD::OR, DL, VecIntVT, LowAnd, VecCstLow);
12655
12656     //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
12657     High = DAG.getNode(ISD::OR, DL, VecIntVT, HighShift, VecCstHigh);
12658   }
12659
12660   // Create the vector constant for -(0x1.0p39f + 0x1.0p23f).
12661   SDValue CstFAdd = DAG.getConstantFP(
12662       APFloat(APFloat::IEEEsingle, APInt(32, 0xD3000080)), DL, MVT::f32);
12663   SDValue CstFAddArray[] = {CstFAdd, CstFAdd, CstFAdd, CstFAdd,
12664                             CstFAdd, CstFAdd, CstFAdd, CstFAdd};
12665   SDValue VecCstFAdd = DAG.getNode(ISD::BUILD_VECTOR, DL, VecFloatVT,
12666                                    makeArrayRef(&CstFAddArray[0], NumElts));
12667
12668   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
12669   SDValue HighBitcast = DAG.getBitcast(VecFloatVT, High);
12670   // TODO: Are there any fast-math-flags to propagate here?
12671   SDValue FHigh =
12672       DAG.getNode(ISD::FADD, DL, VecFloatVT, HighBitcast, VecCstFAdd);
12673   //     return (float4) lo + fhi;
12674   SDValue LowBitcast = DAG.getBitcast(VecFloatVT, Low);
12675   return DAG.getNode(ISD::FADD, DL, VecFloatVT, LowBitcast, FHigh);
12676 }
12677
12678 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
12679                                                SelectionDAG &DAG) const {
12680   SDValue N0 = Op.getOperand(0);
12681   MVT SVT = N0.getSimpleValueType();
12682   SDLoc dl(Op);
12683
12684   switch (SVT.SimpleTy) {
12685   default:
12686     llvm_unreachable("Custom UINT_TO_FP is not supported!");
12687   case MVT::v4i8:
12688   case MVT::v4i16:
12689   case MVT::v8i8:
12690   case MVT::v8i16: {
12691     MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
12692     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
12693                        DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
12694   }
12695   case MVT::v4i32:
12696   case MVT::v8i32:
12697     return lowerUINT_TO_FP_vXi32(Op, DAG, *Subtarget);
12698   case MVT::v16i8:
12699   case MVT::v16i16:
12700     assert(Subtarget->hasAVX512());
12701     return DAG.getNode(ISD::UINT_TO_FP, dl, Op.getValueType(),
12702                        DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v16i32, N0));
12703   }
12704 }
12705
12706 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
12707                                            SelectionDAG &DAG) const {
12708   SDValue N0 = Op.getOperand(0);
12709   SDLoc dl(Op);
12710   auto PtrVT = getPointerTy(DAG.getDataLayout());
12711
12712   if (Op.getSimpleValueType().isVector())
12713     return lowerUINT_TO_FP_vec(Op, DAG);
12714
12715   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
12716   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
12717   // the optimization here.
12718   if (DAG.SignBitIsZero(N0))
12719     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
12720
12721   MVT SrcVT = N0.getSimpleValueType();
12722   MVT DstVT = Op.getSimpleValueType();
12723
12724   if (Subtarget->hasAVX512() && isScalarFPTypeInSSEReg(DstVT) &&
12725       (SrcVT == MVT::i32 || (SrcVT == MVT::i64 && Subtarget->is64Bit()))) {
12726     // Conversions from unsigned i32 to f32/f64 are legal,
12727     // using VCVTUSI2SS/SD.  Same for i64 in 64-bit mode.
12728     return Op;
12729   }
12730
12731   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
12732     return LowerUINT_TO_FP_i64(Op, DAG);
12733   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
12734     return LowerUINT_TO_FP_i32(Op, DAG);
12735   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
12736     return SDValue();
12737
12738   // Make a 64-bit buffer, and use it to build an FILD.
12739   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
12740   if (SrcVT == MVT::i32) {
12741     SDValue WordOff = DAG.getConstant(4, dl, PtrVT);
12742     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, WordOff);
12743     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
12744                                   StackSlot, MachinePointerInfo(),
12745                                   false, false, 0);
12746     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, dl, MVT::i32),
12747                                   OffsetSlot, MachinePointerInfo(),
12748                                   false, false, 0);
12749     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
12750     return Fild;
12751   }
12752
12753   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
12754   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
12755                                StackSlot, MachinePointerInfo(),
12756                                false, false, 0);
12757   // For i64 source, we need to add the appropriate power of 2 if the input
12758   // was negative.  This is the same as the optimization in
12759   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
12760   // we must be careful to do the computation in x87 extended precision, not
12761   // in SSE. (The generic code can't know it's OK to do this, or how to.)
12762   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
12763   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
12764       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12765       MachineMemOperand::MOLoad, 8, 8);
12766
12767   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
12768   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
12769   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
12770                                          MVT::i64, MMO);
12771
12772   APInt FF(32, 0x5F800000ULL);
12773
12774   // Check whether the sign bit is set.
12775   SDValue SignSet = DAG.getSetCC(
12776       dl, getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64),
12777       Op.getOperand(0), DAG.getConstant(0, dl, MVT::i64), ISD::SETLT);
12778
12779   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
12780   SDValue FudgePtr = DAG.getConstantPool(
12781       ConstantInt::get(*DAG.getContext(), FF.zext(64)), PtrVT);
12782
12783   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
12784   SDValue Zero = DAG.getIntPtrConstant(0, dl);
12785   SDValue Four = DAG.getIntPtrConstant(4, dl);
12786   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
12787                                Zero, Four);
12788   FudgePtr = DAG.getNode(ISD::ADD, dl, PtrVT, FudgePtr, Offset);
12789
12790   // Load the value out, extending it from f32 to f80.
12791   // FIXME: Avoid the extend by constructing the right constant pool?
12792   SDValue Fudge = DAG.getExtLoad(
12793       ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(), FudgePtr,
12794       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), MVT::f32,
12795       false, false, false, 4);
12796   // Extend everything to 80 bits to force it to be done on x87.
12797   // TODO: Are there any fast-math-flags to propagate here?
12798   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
12799   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add,
12800                      DAG.getIntPtrConstant(0, dl));
12801 }
12802
12803 // If the given FP_TO_SINT (IsSigned) or FP_TO_UINT (!IsSigned) operation
12804 // is legal, or has an fp128 or f16 source (which needs to be promoted to f32),
12805 // just return an <SDValue(), SDValue()> pair.
12806 // Otherwise it is assumed to be a conversion from one of f32, f64 or f80
12807 // to i16, i32 or i64, and we lower it to a legal sequence.
12808 // If lowered to the final integer result we return a <result, SDValue()> pair.
12809 // Otherwise we lower it to a sequence ending with a FIST, return a
12810 // <FIST, StackSlot> pair, and the caller is responsible for loading
12811 // the final integer result from StackSlot.
12812 std::pair<SDValue,SDValue>
12813 X86TargetLowering::FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
12814                                    bool IsSigned, bool IsReplace) const {
12815   SDLoc DL(Op);
12816
12817   EVT DstTy = Op.getValueType();
12818   EVT TheVT = Op.getOperand(0).getValueType();
12819   auto PtrVT = getPointerTy(DAG.getDataLayout());
12820
12821   if (TheVT != MVT::f32 && TheVT != MVT::f64 && TheVT != MVT::f80) {
12822     // f16 must be promoted before using the lowering in this routine.
12823     // fp128 does not use this lowering.
12824     return std::make_pair(SDValue(), SDValue());
12825   }
12826
12827   // If using FIST to compute an unsigned i64, we'll need some fixup
12828   // to handle values above the maximum signed i64.  A FIST is always
12829   // used for the 32-bit subtarget, but also for f80 on a 64-bit target.
12830   bool UnsignedFixup = !IsSigned &&
12831                        DstTy == MVT::i64 &&
12832                        (!Subtarget->is64Bit() ||
12833                         !isScalarFPTypeInSSEReg(TheVT));
12834
12835   if (!IsSigned && DstTy != MVT::i64 && !Subtarget->hasAVX512()) {
12836     // Replace the fp-to-uint32 operation with an fp-to-sint64 FIST.
12837     // The low 32 bits of the fist result will have the correct uint32 result.
12838     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
12839     DstTy = MVT::i64;
12840   }
12841
12842   assert(DstTy.getSimpleVT() <= MVT::i64 &&
12843          DstTy.getSimpleVT() >= MVT::i16 &&
12844          "Unknown FP_TO_INT to lower!");
12845
12846   // These are really Legal.
12847   if (DstTy == MVT::i32 &&
12848       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
12849     return std::make_pair(SDValue(), SDValue());
12850   if (Subtarget->is64Bit() &&
12851       DstTy == MVT::i64 &&
12852       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
12853     return std::make_pair(SDValue(), SDValue());
12854
12855   // We lower FP->int64 into FISTP64 followed by a load from a temporary
12856   // stack slot.
12857   MachineFunction &MF = DAG.getMachineFunction();
12858   unsigned MemSize = DstTy.getSizeInBits()/8;
12859   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
12860   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12861
12862   unsigned Opc;
12863   switch (DstTy.getSimpleVT().SimpleTy) {
12864   default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
12865   case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
12866   case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
12867   case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
12868   }
12869
12870   SDValue Chain = DAG.getEntryNode();
12871   SDValue Value = Op.getOperand(0);
12872   SDValue Adjust; // 0x0 or 0x80000000, for result sign bit adjustment.
12873
12874   if (UnsignedFixup) {
12875     //
12876     // Conversion to unsigned i64 is implemented with a select,
12877     // depending on whether the source value fits in the range
12878     // of a signed i64.  Let Thresh be the FP equivalent of
12879     // 0x8000000000000000ULL.
12880     //
12881     //  Adjust i32 = (Value < Thresh) ? 0 : 0x80000000;
12882     //  FistSrc    = (Value < Thresh) ? Value : (Value - Thresh);
12883     //  Fist-to-mem64 FistSrc
12884     //  Add 0 or 0x800...0ULL to the 64-bit result, which is equivalent
12885     //  to XOR'ing the high 32 bits with Adjust.
12886     //
12887     // Being a power of 2, Thresh is exactly representable in all FP formats.
12888     // For X87 we'd like to use the smallest FP type for this constant, but
12889     // for DAG type consistency we have to match the FP operand type.
12890
12891     APFloat Thresh(APFloat::IEEEsingle, APInt(32, 0x5f000000));
12892     LLVM_ATTRIBUTE_UNUSED APFloat::opStatus Status = APFloat::opOK;
12893     bool LosesInfo = false;
12894     if (TheVT == MVT::f64)
12895       // The rounding mode is irrelevant as the conversion should be exact.
12896       Status = Thresh.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
12897                               &LosesInfo);
12898     else if (TheVT == MVT::f80)
12899       Status = Thresh.convert(APFloat::x87DoubleExtended,
12900                               APFloat::rmNearestTiesToEven, &LosesInfo);
12901
12902     assert(Status == APFloat::opOK && !LosesInfo &&
12903            "FP conversion should have been exact");
12904
12905     SDValue ThreshVal = DAG.getConstantFP(Thresh, DL, TheVT);
12906
12907     SDValue Cmp = DAG.getSetCC(DL,
12908                                getSetCCResultType(DAG.getDataLayout(),
12909                                                   *DAG.getContext(), TheVT),
12910                                Value, ThreshVal, ISD::SETLT);
12911     Adjust = DAG.getSelect(DL, MVT::i32, Cmp,
12912                            DAG.getConstant(0, DL, MVT::i32),
12913                            DAG.getConstant(0x80000000, DL, MVT::i32));
12914     SDValue Sub = DAG.getNode(ISD::FSUB, DL, TheVT, Value, ThreshVal);
12915     Cmp = DAG.getSetCC(DL, getSetCCResultType(DAG.getDataLayout(),
12916                                               *DAG.getContext(), TheVT),
12917                        Value, ThreshVal, ISD::SETLT);
12918     Value = DAG.getSelect(DL, TheVT, Cmp, Value, Sub);
12919   }
12920
12921   // FIXME This causes a redundant load/store if the SSE-class value is already
12922   // in memory, such as if it is on the callstack.
12923   if (isScalarFPTypeInSSEReg(TheVT)) {
12924     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
12925     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
12926                          MachinePointerInfo::getFixedStack(MF, SSFI), false,
12927                          false, 0);
12928     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
12929     SDValue Ops[] = {
12930       Chain, StackSlot, DAG.getValueType(TheVT)
12931     };
12932
12933     MachineMemOperand *MMO =
12934         MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
12935                                 MachineMemOperand::MOLoad, MemSize, MemSize);
12936     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
12937     Chain = Value.getValue(1);
12938     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
12939     StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12940   }
12941
12942   MachineMemOperand *MMO =
12943       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
12944                               MachineMemOperand::MOStore, MemSize, MemSize);
12945
12946   if (UnsignedFixup) {
12947
12948     // Insert the FIST, load its result as two i32's,
12949     // and XOR the high i32 with Adjust.
12950
12951     SDValue FistOps[] = { Chain, Value, StackSlot };
12952     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
12953                                            FistOps, DstTy, MMO);
12954
12955     SDValue Low32 = DAG.getLoad(MVT::i32, DL, FIST, StackSlot,
12956                                 MachinePointerInfo(),
12957                                 false, false, false, 0);
12958     SDValue HighAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackSlot,
12959                                    DAG.getConstant(4, DL, PtrVT));
12960
12961     SDValue High32 = DAG.getLoad(MVT::i32, DL, FIST, HighAddr,
12962                                  MachinePointerInfo(),
12963                                  false, false, false, 0);
12964     High32 = DAG.getNode(ISD::XOR, DL, MVT::i32, High32, Adjust);
12965
12966     if (Subtarget->is64Bit()) {
12967       // Join High32 and Low32 into a 64-bit result.
12968       // (High32 << 32) | Low32
12969       Low32 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Low32);
12970       High32 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, High32);
12971       High32 = DAG.getNode(ISD::SHL, DL, MVT::i64, High32,
12972                            DAG.getConstant(32, DL, MVT::i8));
12973       SDValue Result = DAG.getNode(ISD::OR, DL, MVT::i64, High32, Low32);
12974       return std::make_pair(Result, SDValue());
12975     }
12976
12977     SDValue ResultOps[] = { Low32, High32 };
12978
12979     SDValue pair = IsReplace
12980       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, ResultOps)
12981       : DAG.getMergeValues(ResultOps, DL);
12982     return std::make_pair(pair, SDValue());
12983   } else {
12984     // Build the FP_TO_INT*_IN_MEM
12985     SDValue Ops[] = { Chain, Value, StackSlot };
12986     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
12987                                            Ops, DstTy, MMO);
12988     return std::make_pair(FIST, StackSlot);
12989   }
12990 }
12991
12992 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
12993                               const X86Subtarget *Subtarget) {
12994   MVT VT = Op->getSimpleValueType(0);
12995   SDValue In = Op->getOperand(0);
12996   MVT InVT = In.getSimpleValueType();
12997   SDLoc dl(Op);
12998
12999   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
13000     return DAG.getNode(ISD::ZERO_EXTEND, dl, VT, In);
13001
13002   // Optimize vectors in AVX mode:
13003   //
13004   //   v8i16 -> v8i32
13005   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
13006   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
13007   //   Concat upper and lower parts.
13008   //
13009   //   v4i32 -> v4i64
13010   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
13011   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
13012   //   Concat upper and lower parts.
13013   //
13014
13015   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
13016       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
13017       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
13018     return SDValue();
13019
13020   if (Subtarget->hasInt256())
13021     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
13022
13023   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
13024   SDValue Undef = DAG.getUNDEF(InVT);
13025   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
13026   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
13027   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
13028
13029   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
13030                              VT.getVectorNumElements()/2);
13031
13032   OpLo = DAG.getBitcast(HVT, OpLo);
13033   OpHi = DAG.getBitcast(HVT, OpHi);
13034
13035   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
13036 }
13037
13038 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
13039                   const X86Subtarget *Subtarget, SelectionDAG &DAG) {
13040   MVT VT = Op->getSimpleValueType(0);
13041   SDValue In = Op->getOperand(0);
13042   MVT InVT = In.getSimpleValueType();
13043   SDLoc DL(Op);
13044   unsigned int NumElts = VT.getVectorNumElements();
13045   if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
13046     return SDValue();
13047
13048   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
13049     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
13050
13051   assert(InVT.getVectorElementType() == MVT::i1);
13052   MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
13053   SDValue One =
13054    DAG.getConstant(APInt(ExtVT.getScalarSizeInBits(), 1), DL, ExtVT);
13055   SDValue Zero =
13056    DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), DL, ExtVT);
13057
13058   SDValue V = DAG.getNode(ISD::VSELECT, DL, ExtVT, In, One, Zero);
13059   if (VT.is512BitVector())
13060     return V;
13061   return DAG.getNode(X86ISD::VTRUNC, DL, VT, V);
13062 }
13063
13064 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
13065                                SelectionDAG &DAG) {
13066   if (Subtarget->hasFp256())
13067     if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
13068       return Res;
13069
13070   return SDValue();
13071 }
13072
13073 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
13074                                 SelectionDAG &DAG) {
13075   SDLoc DL(Op);
13076   MVT VT = Op.getSimpleValueType();
13077   SDValue In = Op.getOperand(0);
13078   MVT SVT = In.getSimpleValueType();
13079
13080   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
13081     return LowerZERO_EXTEND_AVX512(Op, Subtarget, DAG);
13082
13083   if (Subtarget->hasFp256())
13084     if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
13085       return Res;
13086
13087   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
13088          VT.getVectorNumElements() != SVT.getVectorNumElements());
13089   return SDValue();
13090 }
13091
13092 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
13093   SDLoc DL(Op);
13094   MVT VT = Op.getSimpleValueType();
13095   SDValue In = Op.getOperand(0);
13096   MVT InVT = In.getSimpleValueType();
13097
13098   if (VT == MVT::i1) {
13099     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
13100            "Invalid scalar TRUNCATE operation");
13101     if (InVT.getSizeInBits() >= 32)
13102       return SDValue();
13103     In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
13104     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
13105   }
13106   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
13107          "Invalid TRUNCATE operation");
13108
13109   // move vector to mask - truncate solution for SKX
13110   if (VT.getVectorElementType() == MVT::i1) {
13111     if (InVT.is512BitVector() && InVT.getScalarSizeInBits() <= 16 &&
13112         Subtarget->hasBWI())
13113       return Op; // legal, will go to VPMOVB2M, VPMOVW2M
13114     if ((InVT.is256BitVector() || InVT.is128BitVector())
13115         && InVT.getScalarSizeInBits() <= 16 &&
13116         Subtarget->hasBWI() && Subtarget->hasVLX())
13117       return Op; // legal, will go to VPMOVB2M, VPMOVW2M
13118     if (InVT.is512BitVector() && InVT.getScalarSizeInBits() >= 32 &&
13119         Subtarget->hasDQI())
13120       return Op; // legal, will go to VPMOVD2M, VPMOVQ2M
13121     if ((InVT.is256BitVector() || InVT.is128BitVector())
13122         && InVT.getScalarSizeInBits() >= 32 &&
13123         Subtarget->hasDQI() && Subtarget->hasVLX())
13124       return Op; // legal, will go to VPMOVB2M, VPMOVQ2M
13125   }
13126
13127   if (VT.getVectorElementType() == MVT::i1) {
13128     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
13129     unsigned NumElts = InVT.getVectorNumElements();
13130     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
13131     if (InVT.getSizeInBits() < 512) {
13132       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
13133       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
13134       InVT = ExtVT;
13135     }
13136
13137     SDValue OneV =
13138      DAG.getConstant(APInt::getSignBit(InVT.getScalarSizeInBits()), DL, InVT);
13139     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
13140     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
13141   }
13142
13143   // vpmovqb/w/d, vpmovdb/w, vpmovwb
13144   if (Subtarget->hasAVX512()) {
13145     // word to byte only under BWI
13146     if (InVT == MVT::v16i16 && !Subtarget->hasBWI()) // v16i16 -> v16i8
13147       return DAG.getNode(X86ISD::VTRUNC, DL, VT,
13148                          DAG.getNode(X86ISD::VSEXT, DL, MVT::v16i32, In));
13149     return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
13150   }
13151   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
13152     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
13153     if (Subtarget->hasInt256()) {
13154       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
13155       In = DAG.getBitcast(MVT::v8i32, In);
13156       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
13157                                 ShufMask);
13158       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
13159                          DAG.getIntPtrConstant(0, DL));
13160     }
13161
13162     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
13163                                DAG.getIntPtrConstant(0, DL));
13164     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
13165                                DAG.getIntPtrConstant(2, DL));
13166     OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
13167     OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
13168     static const int ShufMask[] = {0, 2, 4, 6};
13169     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
13170   }
13171
13172   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
13173     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
13174     if (Subtarget->hasInt256()) {
13175       In = DAG.getBitcast(MVT::v32i8, In);
13176
13177       SmallVector<SDValue,32> pshufbMask;
13178       for (unsigned i = 0; i < 2; ++i) {
13179         pshufbMask.push_back(DAG.getConstant(0x0, DL, MVT::i8));
13180         pshufbMask.push_back(DAG.getConstant(0x1, DL, MVT::i8));
13181         pshufbMask.push_back(DAG.getConstant(0x4, DL, MVT::i8));
13182         pshufbMask.push_back(DAG.getConstant(0x5, DL, MVT::i8));
13183         pshufbMask.push_back(DAG.getConstant(0x8, DL, MVT::i8));
13184         pshufbMask.push_back(DAG.getConstant(0x9, DL, MVT::i8));
13185         pshufbMask.push_back(DAG.getConstant(0xc, DL, MVT::i8));
13186         pshufbMask.push_back(DAG.getConstant(0xd, DL, MVT::i8));
13187         for (unsigned j = 0; j < 8; ++j)
13188           pshufbMask.push_back(DAG.getConstant(0x80, DL, MVT::i8));
13189       }
13190       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
13191       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
13192       In = DAG.getBitcast(MVT::v4i64, In);
13193
13194       static const int ShufMask[] = {0,  2,  -1,  -1};
13195       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
13196                                 &ShufMask[0]);
13197       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
13198                        DAG.getIntPtrConstant(0, DL));
13199       return DAG.getBitcast(VT, In);
13200     }
13201
13202     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
13203                                DAG.getIntPtrConstant(0, DL));
13204
13205     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
13206                                DAG.getIntPtrConstant(4, DL));
13207
13208     OpLo = DAG.getBitcast(MVT::v16i8, OpLo);
13209     OpHi = DAG.getBitcast(MVT::v16i8, OpHi);
13210
13211     // The PSHUFB mask:
13212     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
13213                                    -1, -1, -1, -1, -1, -1, -1, -1};
13214
13215     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
13216     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
13217     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
13218
13219     OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
13220     OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
13221
13222     // The MOVLHPS Mask:
13223     static const int ShufMask2[] = {0, 1, 4, 5};
13224     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
13225     return DAG.getBitcast(MVT::v8i16, res);
13226   }
13227
13228   // Handle truncation of V256 to V128 using shuffles.
13229   if (!VT.is128BitVector() || !InVT.is256BitVector())
13230     return SDValue();
13231
13232   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
13233
13234   unsigned NumElems = VT.getVectorNumElements();
13235   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
13236
13237   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
13238   // Prepare truncation shuffle mask
13239   for (unsigned i = 0; i != NumElems; ++i)
13240     MaskVec[i] = i * 2;
13241   SDValue V = DAG.getVectorShuffle(NVT, DL, DAG.getBitcast(NVT, In),
13242                                    DAG.getUNDEF(NVT), &MaskVec[0]);
13243   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
13244                      DAG.getIntPtrConstant(0, DL));
13245 }
13246
13247 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
13248                                            SelectionDAG &DAG) const {
13249   assert(!Op.getSimpleValueType().isVector());
13250
13251   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
13252     /*IsSigned=*/ true, /*IsReplace=*/ false);
13253   SDValue FIST = Vals.first, StackSlot = Vals.second;
13254   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
13255   if (!FIST.getNode())
13256     return Op;
13257
13258   if (StackSlot.getNode())
13259     // Load the result.
13260     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
13261                        FIST, StackSlot, MachinePointerInfo(),
13262                        false, false, false, 0);
13263
13264   // The node is the result.
13265   return FIST;
13266 }
13267
13268 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
13269                                            SelectionDAG &DAG) const {
13270   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
13271     /*IsSigned=*/ false, /*IsReplace=*/ false);
13272   SDValue FIST = Vals.first, StackSlot = Vals.second;
13273   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
13274   if (!FIST.getNode())
13275     return Op;
13276
13277   if (StackSlot.getNode())
13278     // Load the result.
13279     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
13280                        FIST, StackSlot, MachinePointerInfo(),
13281                        false, false, false, 0);
13282
13283   // The node is the result.
13284   return FIST;
13285 }
13286
13287 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
13288   SDLoc DL(Op);
13289   MVT VT = Op.getSimpleValueType();
13290   SDValue In = Op.getOperand(0);
13291   MVT SVT = In.getSimpleValueType();
13292
13293   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
13294
13295   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
13296                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
13297                                  In, DAG.getUNDEF(SVT)));
13298 }
13299
13300 /// The only differences between FABS and FNEG are the mask and the logic op.
13301 /// FNEG also has a folding opportunity for FNEG(FABS(x)).
13302 static SDValue LowerFABSorFNEG(SDValue Op, SelectionDAG &DAG) {
13303   assert((Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) &&
13304          "Wrong opcode for lowering FABS or FNEG.");
13305
13306   bool IsFABS = (Op.getOpcode() == ISD::FABS);
13307
13308   // If this is a FABS and it has an FNEG user, bail out to fold the combination
13309   // into an FNABS. We'll lower the FABS after that if it is still in use.
13310   if (IsFABS)
13311     for (SDNode *User : Op->uses())
13312       if (User->getOpcode() == ISD::FNEG)
13313         return Op;
13314
13315   SDLoc dl(Op);
13316   MVT VT = Op.getSimpleValueType();
13317
13318   // FIXME: Use function attribute "OptimizeForSize" and/or CodeGenOpt::Level to
13319   // decide if we should generate a 16-byte constant mask when we only need 4 or
13320   // 8 bytes for the scalar case.
13321
13322   MVT LogicVT;
13323   MVT EltVT;
13324   unsigned NumElts;
13325
13326   if (VT.isVector()) {
13327     LogicVT = VT;
13328     EltVT = VT.getVectorElementType();
13329     NumElts = VT.getVectorNumElements();
13330   } else {
13331     // There are no scalar bitwise logical SSE/AVX instructions, so we
13332     // generate a 16-byte vector constant and logic op even for the scalar case.
13333     // Using a 16-byte mask allows folding the load of the mask with
13334     // the logic op, so it can save (~4 bytes) on code size.
13335     LogicVT = (VT == MVT::f64) ? MVT::v2f64 : MVT::v4f32;
13336     EltVT = VT;
13337     NumElts = (VT == MVT::f64) ? 2 : 4;
13338   }
13339
13340   unsigned EltBits = EltVT.getSizeInBits();
13341   LLVMContext *Context = DAG.getContext();
13342   // For FABS, mask is 0x7f...; for FNEG, mask is 0x80...
13343   APInt MaskElt =
13344     IsFABS ? APInt::getSignedMaxValue(EltBits) : APInt::getSignBit(EltBits);
13345   Constant *C = ConstantInt::get(*Context, MaskElt);
13346   C = ConstantVector::getSplat(NumElts, C);
13347   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13348   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
13349   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
13350   SDValue Mask =
13351       DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
13352                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13353                   false, false, false, Alignment);
13354
13355   SDValue Op0 = Op.getOperand(0);
13356   bool IsFNABS = !IsFABS && (Op0.getOpcode() == ISD::FABS);
13357   unsigned LogicOp =
13358     IsFABS ? X86ISD::FAND : IsFNABS ? X86ISD::FOR : X86ISD::FXOR;
13359   SDValue Operand = IsFNABS ? Op0.getOperand(0) : Op0;
13360
13361   if (VT.isVector())
13362     return DAG.getNode(LogicOp, dl, LogicVT, Operand, Mask);
13363
13364   // For the scalar case extend to a 128-bit vector, perform the logic op,
13365   // and extract the scalar result back out.
13366   Operand = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Operand);
13367   SDValue LogicNode = DAG.getNode(LogicOp, dl, LogicVT, Operand, Mask);
13368   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, LogicNode,
13369                      DAG.getIntPtrConstant(0, dl));
13370 }
13371
13372 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
13373   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13374   LLVMContext *Context = DAG.getContext();
13375   SDValue Op0 = Op.getOperand(0);
13376   SDValue Op1 = Op.getOperand(1);
13377   SDLoc dl(Op);
13378   MVT VT = Op.getSimpleValueType();
13379   MVT SrcVT = Op1.getSimpleValueType();
13380
13381   // If second operand is smaller, extend it first.
13382   if (SrcVT.bitsLT(VT)) {
13383     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
13384     SrcVT = VT;
13385   }
13386   // And if it is bigger, shrink it first.
13387   if (SrcVT.bitsGT(VT)) {
13388     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1, dl));
13389     SrcVT = VT;
13390   }
13391
13392   // At this point the operands and the result should have the same
13393   // type, and that won't be f80 since that is not custom lowered.
13394
13395   const fltSemantics &Sem =
13396       VT == MVT::f64 ? APFloat::IEEEdouble : APFloat::IEEEsingle;
13397   const unsigned SizeInBits = VT.getSizeInBits();
13398
13399   SmallVector<Constant *, 4> CV(
13400       VT == MVT::f64 ? 2 : 4,
13401       ConstantFP::get(*Context, APFloat(Sem, APInt(SizeInBits, 0))));
13402
13403   // First, clear all bits but the sign bit from the second operand (sign).
13404   CV[0] = ConstantFP::get(*Context,
13405                           APFloat(Sem, APInt::getHighBitsSet(SizeInBits, 1)));
13406   Constant *C = ConstantVector::get(CV);
13407   auto PtrVT = TLI.getPointerTy(DAG.getDataLayout());
13408   SDValue CPIdx = DAG.getConstantPool(C, PtrVT, 16);
13409
13410   // Perform all logic operations as 16-byte vectors because there are no
13411   // scalar FP logic instructions in SSE. This allows load folding of the
13412   // constants into the logic instructions.
13413   MVT LogicVT = (VT == MVT::f64) ? MVT::v2f64 : MVT::v4f32;
13414   SDValue Mask1 =
13415       DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
13416                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13417                   false, false, false, 16);
13418   Op1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Op1);
13419   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, LogicVT, Op1, Mask1);
13420
13421   // Next, clear the sign bit from the first operand (magnitude).
13422   // If it's a constant, we can clear it here.
13423   if (ConstantFPSDNode *Op0CN = dyn_cast<ConstantFPSDNode>(Op0)) {
13424     APFloat APF = Op0CN->getValueAPF();
13425     // If the magnitude is a positive zero, the sign bit alone is enough.
13426     if (APF.isPosZero())
13427       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SrcVT, SignBit,
13428                          DAG.getIntPtrConstant(0, dl));
13429     APF.clearSign();
13430     CV[0] = ConstantFP::get(*Context, APF);
13431   } else {
13432     CV[0] = ConstantFP::get(
13433         *Context,
13434         APFloat(Sem, APInt::getLowBitsSet(SizeInBits, SizeInBits - 1)));
13435   }
13436   C = ConstantVector::get(CV);
13437   CPIdx = DAG.getConstantPool(C, PtrVT, 16);
13438   SDValue Val =
13439       DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
13440                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13441                   false, false, false, 16);
13442   // If the magnitude operand wasn't a constant, we need to AND out the sign.
13443   if (!isa<ConstantFPSDNode>(Op0)) {
13444     Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Op0);
13445     Val = DAG.getNode(X86ISD::FAND, dl, LogicVT, Op0, Val);
13446   }
13447   // OR the magnitude value with the sign bit.
13448   Val = DAG.getNode(X86ISD::FOR, dl, LogicVT, Val, SignBit);
13449   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SrcVT, Val,
13450                      DAG.getIntPtrConstant(0, dl));
13451 }
13452
13453 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
13454   SDValue N0 = Op.getOperand(0);
13455   SDLoc dl(Op);
13456   MVT VT = Op.getSimpleValueType();
13457
13458   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
13459   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
13460                                   DAG.getConstant(1, dl, VT));
13461   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, dl, VT));
13462 }
13463
13464 // Check whether an OR'd tree is PTEST-able.
13465 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
13466                                       SelectionDAG &DAG) {
13467   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
13468
13469   if (!Subtarget->hasSSE41())
13470     return SDValue();
13471
13472   if (!Op->hasOneUse())
13473     return SDValue();
13474
13475   SDNode *N = Op.getNode();
13476   SDLoc DL(N);
13477
13478   SmallVector<SDValue, 8> Opnds;
13479   DenseMap<SDValue, unsigned> VecInMap;
13480   SmallVector<SDValue, 8> VecIns;
13481   EVT VT = MVT::Other;
13482
13483   // Recognize a special case where a vector is casted into wide integer to
13484   // test all 0s.
13485   Opnds.push_back(N->getOperand(0));
13486   Opnds.push_back(N->getOperand(1));
13487
13488   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
13489     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
13490     // BFS traverse all OR'd operands.
13491     if (I->getOpcode() == ISD::OR) {
13492       Opnds.push_back(I->getOperand(0));
13493       Opnds.push_back(I->getOperand(1));
13494       // Re-evaluate the number of nodes to be traversed.
13495       e += 2; // 2 more nodes (LHS and RHS) are pushed.
13496       continue;
13497     }
13498
13499     // Quit if a non-EXTRACT_VECTOR_ELT
13500     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13501       return SDValue();
13502
13503     // Quit if without a constant index.
13504     SDValue Idx = I->getOperand(1);
13505     if (!isa<ConstantSDNode>(Idx))
13506       return SDValue();
13507
13508     SDValue ExtractedFromVec = I->getOperand(0);
13509     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
13510     if (M == VecInMap.end()) {
13511       VT = ExtractedFromVec.getValueType();
13512       // Quit if not 128/256-bit vector.
13513       if (!VT.is128BitVector() && !VT.is256BitVector())
13514         return SDValue();
13515       // Quit if not the same type.
13516       if (VecInMap.begin() != VecInMap.end() &&
13517           VT != VecInMap.begin()->first.getValueType())
13518         return SDValue();
13519       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
13520       VecIns.push_back(ExtractedFromVec);
13521     }
13522     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
13523   }
13524
13525   assert((VT.is128BitVector() || VT.is256BitVector()) &&
13526          "Not extracted from 128-/256-bit vector.");
13527
13528   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
13529
13530   for (DenseMap<SDValue, unsigned>::const_iterator
13531         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
13532     // Quit if not all elements are used.
13533     if (I->second != FullMask)
13534       return SDValue();
13535   }
13536
13537   MVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
13538
13539   // Cast all vectors into TestVT for PTEST.
13540   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
13541     VecIns[i] = DAG.getBitcast(TestVT, VecIns[i]);
13542
13543   // If more than one full vectors are evaluated, OR them first before PTEST.
13544   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
13545     // Each iteration will OR 2 nodes and append the result until there is only
13546     // 1 node left, i.e. the final OR'd value of all vectors.
13547     SDValue LHS = VecIns[Slot];
13548     SDValue RHS = VecIns[Slot + 1];
13549     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
13550   }
13551
13552   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
13553                      VecIns.back(), VecIns.back());
13554 }
13555
13556 /// \brief return true if \c Op has a use that doesn't just read flags.
13557 static bool hasNonFlagsUse(SDValue Op) {
13558   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
13559        ++UI) {
13560     SDNode *User = *UI;
13561     unsigned UOpNo = UI.getOperandNo();
13562     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
13563       // Look pass truncate.
13564       UOpNo = User->use_begin().getOperandNo();
13565       User = *User->use_begin();
13566     }
13567
13568     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
13569         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
13570       return true;
13571   }
13572   return false;
13573 }
13574
13575 /// Emit nodes that will be selected as "test Op0,Op0", or something
13576 /// equivalent.
13577 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
13578                                     SelectionDAG &DAG) const {
13579   if (Op.getValueType() == MVT::i1) {
13580     SDValue ExtOp = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i8, Op);
13581     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, ExtOp,
13582                        DAG.getConstant(0, dl, MVT::i8));
13583   }
13584   // CF and OF aren't always set the way we want. Determine which
13585   // of these we need.
13586   bool NeedCF = false;
13587   bool NeedOF = false;
13588   switch (X86CC) {
13589   default: break;
13590   case X86::COND_A: case X86::COND_AE:
13591   case X86::COND_B: case X86::COND_BE:
13592     NeedCF = true;
13593     break;
13594   case X86::COND_G: case X86::COND_GE:
13595   case X86::COND_L: case X86::COND_LE:
13596   case X86::COND_O: case X86::COND_NO: {
13597     // Check if we really need to set the
13598     // Overflow flag. If NoSignedWrap is present
13599     // that is not actually needed.
13600     switch (Op->getOpcode()) {
13601     case ISD::ADD:
13602     case ISD::SUB:
13603     case ISD::MUL:
13604     case ISD::SHL: {
13605       const auto *BinNode = cast<BinaryWithFlagsSDNode>(Op.getNode());
13606       if (BinNode->Flags.hasNoSignedWrap())
13607         break;
13608     }
13609     default:
13610       NeedOF = true;
13611       break;
13612     }
13613     break;
13614   }
13615   }
13616   // See if we can use the EFLAGS value from the operand instead of
13617   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
13618   // we prove that the arithmetic won't overflow, we can't use OF or CF.
13619   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
13620     // Emit a CMP with 0, which is the TEST pattern.
13621     //if (Op.getValueType() == MVT::i1)
13622     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
13623     //                     DAG.getConstant(0, MVT::i1));
13624     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
13625                        DAG.getConstant(0, dl, Op.getValueType()));
13626   }
13627   unsigned Opcode = 0;
13628   unsigned NumOperands = 0;
13629
13630   // Truncate operations may prevent the merge of the SETCC instruction
13631   // and the arithmetic instruction before it. Attempt to truncate the operands
13632   // of the arithmetic instruction and use a reduced bit-width instruction.
13633   bool NeedTruncation = false;
13634   SDValue ArithOp = Op;
13635   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
13636     SDValue Arith = Op->getOperand(0);
13637     // Both the trunc and the arithmetic op need to have one user each.
13638     if (Arith->hasOneUse())
13639       switch (Arith.getOpcode()) {
13640         default: break;
13641         case ISD::ADD:
13642         case ISD::SUB:
13643         case ISD::AND:
13644         case ISD::OR:
13645         case ISD::XOR: {
13646           NeedTruncation = true;
13647           ArithOp = Arith;
13648         }
13649       }
13650   }
13651
13652   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
13653   // which may be the result of a CAST.  We use the variable 'Op', which is the
13654   // non-casted variable when we check for possible users.
13655   switch (ArithOp.getOpcode()) {
13656   case ISD::ADD:
13657     // Due to an isel shortcoming, be conservative if this add is likely to be
13658     // selected as part of a load-modify-store instruction. When the root node
13659     // in a match is a store, isel doesn't know how to remap non-chain non-flag
13660     // uses of other nodes in the match, such as the ADD in this case. This
13661     // leads to the ADD being left around and reselected, with the result being
13662     // two adds in the output.  Alas, even if none our users are stores, that
13663     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
13664     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
13665     // climbing the DAG back to the root, and it doesn't seem to be worth the
13666     // effort.
13667     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
13668          UE = Op.getNode()->use_end(); UI != UE; ++UI)
13669       if (UI->getOpcode() != ISD::CopyToReg &&
13670           UI->getOpcode() != ISD::SETCC &&
13671           UI->getOpcode() != ISD::STORE)
13672         goto default_case;
13673
13674     if (ConstantSDNode *C =
13675         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
13676       // An add of one will be selected as an INC.
13677       if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
13678         Opcode = X86ISD::INC;
13679         NumOperands = 1;
13680         break;
13681       }
13682
13683       // An add of negative one (subtract of one) will be selected as a DEC.
13684       if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
13685         Opcode = X86ISD::DEC;
13686         NumOperands = 1;
13687         break;
13688       }
13689     }
13690
13691     // Otherwise use a regular EFLAGS-setting add.
13692     Opcode = X86ISD::ADD;
13693     NumOperands = 2;
13694     break;
13695   case ISD::SHL:
13696   case ISD::SRL:
13697     // If we have a constant logical shift that's only used in a comparison
13698     // against zero turn it into an equivalent AND. This allows turning it into
13699     // a TEST instruction later.
13700     if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
13701         isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
13702       EVT VT = Op.getValueType();
13703       unsigned BitWidth = VT.getSizeInBits();
13704       unsigned ShAmt = Op->getConstantOperandVal(1);
13705       if (ShAmt >= BitWidth) // Avoid undefined shifts.
13706         break;
13707       APInt Mask = ArithOp.getOpcode() == ISD::SRL
13708                        ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
13709                        : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
13710       if (!Mask.isSignedIntN(32)) // Avoid large immediates.
13711         break;
13712       SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
13713                                 DAG.getConstant(Mask, dl, VT));
13714       DAG.ReplaceAllUsesWith(Op, New);
13715       Op = New;
13716     }
13717     break;
13718
13719   case ISD::AND:
13720     // If the primary and result isn't used, don't bother using X86ISD::AND,
13721     // because a TEST instruction will be better.
13722     if (!hasNonFlagsUse(Op))
13723       break;
13724     // FALL THROUGH
13725   case ISD::SUB:
13726   case ISD::OR:
13727   case ISD::XOR:
13728     // Due to the ISEL shortcoming noted above, be conservative if this op is
13729     // likely to be selected as part of a load-modify-store instruction.
13730     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
13731            UE = Op.getNode()->use_end(); UI != UE; ++UI)
13732       if (UI->getOpcode() == ISD::STORE)
13733         goto default_case;
13734
13735     // Otherwise use a regular EFLAGS-setting instruction.
13736     switch (ArithOp.getOpcode()) {
13737     default: llvm_unreachable("unexpected operator!");
13738     case ISD::SUB: Opcode = X86ISD::SUB; break;
13739     case ISD::XOR: Opcode = X86ISD::XOR; break;
13740     case ISD::AND: Opcode = X86ISD::AND; break;
13741     case ISD::OR: {
13742       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
13743         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
13744         if (EFLAGS.getNode())
13745           return EFLAGS;
13746       }
13747       Opcode = X86ISD::OR;
13748       break;
13749     }
13750     }
13751
13752     NumOperands = 2;
13753     break;
13754   case X86ISD::ADD:
13755   case X86ISD::SUB:
13756   case X86ISD::INC:
13757   case X86ISD::DEC:
13758   case X86ISD::OR:
13759   case X86ISD::XOR:
13760   case X86ISD::AND:
13761     return SDValue(Op.getNode(), 1);
13762   default:
13763   default_case:
13764     break;
13765   }
13766
13767   // If we found that truncation is beneficial, perform the truncation and
13768   // update 'Op'.
13769   if (NeedTruncation) {
13770     EVT VT = Op.getValueType();
13771     SDValue WideVal = Op->getOperand(0);
13772     EVT WideVT = WideVal.getValueType();
13773     unsigned ConvertedOp = 0;
13774     // Use a target machine opcode to prevent further DAGCombine
13775     // optimizations that may separate the arithmetic operations
13776     // from the setcc node.
13777     switch (WideVal.getOpcode()) {
13778       default: break;
13779       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
13780       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
13781       case ISD::AND: ConvertedOp = X86ISD::AND; break;
13782       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
13783       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
13784     }
13785
13786     if (ConvertedOp) {
13787       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13788       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
13789         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
13790         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
13791         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
13792       }
13793     }
13794   }
13795
13796   if (Opcode == 0)
13797     // Emit a CMP with 0, which is the TEST pattern.
13798     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
13799                        DAG.getConstant(0, dl, Op.getValueType()));
13800
13801   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
13802   SmallVector<SDValue, 4> Ops(Op->op_begin(), Op->op_begin() + NumOperands);
13803
13804   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
13805   DAG.ReplaceAllUsesWith(Op, New);
13806   return SDValue(New.getNode(), 1);
13807 }
13808
13809 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
13810 /// equivalent.
13811 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
13812                                    SDLoc dl, SelectionDAG &DAG) const {
13813   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
13814     if (C->getAPIntValue() == 0)
13815       return EmitTest(Op0, X86CC, dl, DAG);
13816
13817      assert(Op0.getValueType() != MVT::i1 &&
13818             "Unexpected comparison operation for MVT::i1 operands");
13819   }
13820
13821   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
13822        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
13823     // Do the comparison at i32 if it's smaller, besides the Atom case.
13824     // This avoids subregister aliasing issues. Keep the smaller reference
13825     // if we're optimizing for size, however, as that'll allow better folding
13826     // of memory operations.
13827     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
13828         !DAG.getMachineFunction().getFunction()->optForMinSize() &&
13829         !Subtarget->isAtom()) {
13830       unsigned ExtendOp =
13831           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
13832       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
13833       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
13834     }
13835     // Use SUB instead of CMP to enable CSE between SUB and CMP.
13836     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
13837     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
13838                               Op0, Op1);
13839     return SDValue(Sub.getNode(), 1);
13840   }
13841   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
13842 }
13843
13844 /// Convert a comparison if required by the subtarget.
13845 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
13846                                                  SelectionDAG &DAG) const {
13847   // If the subtarget does not support the FUCOMI instruction, floating-point
13848   // comparisons have to be converted.
13849   if (Subtarget->hasCMov() ||
13850       Cmp.getOpcode() != X86ISD::CMP ||
13851       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
13852       !Cmp.getOperand(1).getValueType().isFloatingPoint())
13853     return Cmp;
13854
13855   // The instruction selector will select an FUCOM instruction instead of
13856   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
13857   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
13858   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
13859   SDLoc dl(Cmp);
13860   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
13861   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
13862   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
13863                             DAG.getConstant(8, dl, MVT::i8));
13864   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
13865   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
13866 }
13867
13868 /// The minimum architected relative accuracy is 2^-12. We need one
13869 /// Newton-Raphson step to have a good float result (24 bits of precision).
13870 SDValue X86TargetLowering::getRsqrtEstimate(SDValue Op,
13871                                             DAGCombinerInfo &DCI,
13872                                             unsigned &RefinementSteps,
13873                                             bool &UseOneConstNR) const {
13874   EVT VT = Op.getValueType();
13875   const char *RecipOp;
13876
13877   // SSE1 has rsqrtss and rsqrtps. AVX adds a 256-bit variant for rsqrtps.
13878   // TODO: Add support for AVX512 (v16f32).
13879   // It is likely not profitable to do this for f64 because a double-precision
13880   // rsqrt estimate with refinement on x86 prior to FMA requires at least 16
13881   // instructions: convert to single, rsqrtss, convert back to double, refine
13882   // (3 steps = at least 13 insts). If an 'rsqrtsd' variant was added to the ISA
13883   // along with FMA, this could be a throughput win.
13884   if (VT == MVT::f32 && Subtarget->hasSSE1())
13885     RecipOp = "sqrtf";
13886   else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
13887            (VT == MVT::v8f32 && Subtarget->hasAVX()))
13888     RecipOp = "vec-sqrtf";
13889   else
13890     return SDValue();
13891
13892   TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
13893   if (!Recips.isEnabled(RecipOp))
13894     return SDValue();
13895
13896   RefinementSteps = Recips.getRefinementSteps(RecipOp);
13897   UseOneConstNR = false;
13898   return DCI.DAG.getNode(X86ISD::FRSQRT, SDLoc(Op), VT, Op);
13899 }
13900
13901 /// The minimum architected relative accuracy is 2^-12. We need one
13902 /// Newton-Raphson step to have a good float result (24 bits of precision).
13903 SDValue X86TargetLowering::getRecipEstimate(SDValue Op,
13904                                             DAGCombinerInfo &DCI,
13905                                             unsigned &RefinementSteps) const {
13906   EVT VT = Op.getValueType();
13907   const char *RecipOp;
13908
13909   // SSE1 has rcpss and rcpps. AVX adds a 256-bit variant for rcpps.
13910   // TODO: Add support for AVX512 (v16f32).
13911   // It is likely not profitable to do this for f64 because a double-precision
13912   // reciprocal estimate with refinement on x86 prior to FMA requires
13913   // 15 instructions: convert to single, rcpss, convert back to double, refine
13914   // (3 steps = 12 insts). If an 'rcpsd' variant was added to the ISA
13915   // along with FMA, this could be a throughput win.
13916   if (VT == MVT::f32 && Subtarget->hasSSE1())
13917     RecipOp = "divf";
13918   else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
13919            (VT == MVT::v8f32 && Subtarget->hasAVX()))
13920     RecipOp = "vec-divf";
13921   else
13922     return SDValue();
13923
13924   TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
13925   if (!Recips.isEnabled(RecipOp))
13926     return SDValue();
13927
13928   RefinementSteps = Recips.getRefinementSteps(RecipOp);
13929   return DCI.DAG.getNode(X86ISD::FRCP, SDLoc(Op), VT, Op);
13930 }
13931
13932 /// If we have at least two divisions that use the same divisor, convert to
13933 /// multplication by a reciprocal. This may need to be adjusted for a given
13934 /// CPU if a division's cost is not at least twice the cost of a multiplication.
13935 /// This is because we still need one division to calculate the reciprocal and
13936 /// then we need two multiplies by that reciprocal as replacements for the
13937 /// original divisions.
13938 unsigned X86TargetLowering::combineRepeatedFPDivisors() const {
13939   return 2;
13940 }
13941
13942 static bool isAllOnes(SDValue V) {
13943   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
13944   return C && C->isAllOnesValue();
13945 }
13946
13947 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
13948 /// if it's possible.
13949 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
13950                                      SDLoc dl, SelectionDAG &DAG) const {
13951   SDValue Op0 = And.getOperand(0);
13952   SDValue Op1 = And.getOperand(1);
13953   if (Op0.getOpcode() == ISD::TRUNCATE)
13954     Op0 = Op0.getOperand(0);
13955   if (Op1.getOpcode() == ISD::TRUNCATE)
13956     Op1 = Op1.getOperand(0);
13957
13958   SDValue LHS, RHS;
13959   if (Op1.getOpcode() == ISD::SHL)
13960     std::swap(Op0, Op1);
13961   if (Op0.getOpcode() == ISD::SHL) {
13962     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
13963       if (And00C->getZExtValue() == 1) {
13964         // If we looked past a truncate, check that it's only truncating away
13965         // known zeros.
13966         unsigned BitWidth = Op0.getValueSizeInBits();
13967         unsigned AndBitWidth = And.getValueSizeInBits();
13968         if (BitWidth > AndBitWidth) {
13969           APInt Zeros, Ones;
13970           DAG.computeKnownBits(Op0, Zeros, Ones);
13971           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
13972             return SDValue();
13973         }
13974         LHS = Op1;
13975         RHS = Op0.getOperand(1);
13976       }
13977   } else if (Op1.getOpcode() == ISD::Constant) {
13978     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
13979     uint64_t AndRHSVal = AndRHS->getZExtValue();
13980     SDValue AndLHS = Op0;
13981
13982     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
13983       LHS = AndLHS.getOperand(0);
13984       RHS = AndLHS.getOperand(1);
13985     }
13986
13987     // Use BT if the immediate can't be encoded in a TEST instruction.
13988     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
13989       LHS = AndLHS;
13990       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), dl, LHS.getValueType());
13991     }
13992   }
13993
13994   if (LHS.getNode()) {
13995     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
13996     // instruction.  Since the shift amount is in-range-or-undefined, we know
13997     // that doing a bittest on the i32 value is ok.  We extend to i32 because
13998     // the encoding for the i16 version is larger than the i32 version.
13999     // Also promote i16 to i32 for performance / code size reason.
14000     if (LHS.getValueType() == MVT::i8 ||
14001         LHS.getValueType() == MVT::i16)
14002       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
14003
14004     // If the operand types disagree, extend the shift amount to match.  Since
14005     // BT ignores high bits (like shifts) we can use anyextend.
14006     if (LHS.getValueType() != RHS.getValueType())
14007       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
14008
14009     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
14010     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
14011     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14012                        DAG.getConstant(Cond, dl, MVT::i8), BT);
14013   }
14014
14015   return SDValue();
14016 }
14017
14018 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
14019 /// mask CMPs.
14020 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
14021                               SDValue &Op1) {
14022   unsigned SSECC;
14023   bool Swap = false;
14024
14025   // SSE Condition code mapping:
14026   //  0 - EQ
14027   //  1 - LT
14028   //  2 - LE
14029   //  3 - UNORD
14030   //  4 - NEQ
14031   //  5 - NLT
14032   //  6 - NLE
14033   //  7 - ORD
14034   switch (SetCCOpcode) {
14035   default: llvm_unreachable("Unexpected SETCC condition");
14036   case ISD::SETOEQ:
14037   case ISD::SETEQ:  SSECC = 0; break;
14038   case ISD::SETOGT:
14039   case ISD::SETGT:  Swap = true; // Fallthrough
14040   case ISD::SETLT:
14041   case ISD::SETOLT: SSECC = 1; break;
14042   case ISD::SETOGE:
14043   case ISD::SETGE:  Swap = true; // Fallthrough
14044   case ISD::SETLE:
14045   case ISD::SETOLE: SSECC = 2; break;
14046   case ISD::SETUO:  SSECC = 3; break;
14047   case ISD::SETUNE:
14048   case ISD::SETNE:  SSECC = 4; break;
14049   case ISD::SETULE: Swap = true; // Fallthrough
14050   case ISD::SETUGE: SSECC = 5; break;
14051   case ISD::SETULT: Swap = true; // Fallthrough
14052   case ISD::SETUGT: SSECC = 6; break;
14053   case ISD::SETO:   SSECC = 7; break;
14054   case ISD::SETUEQ:
14055   case ISD::SETONE: SSECC = 8; break;
14056   }
14057   if (Swap)
14058     std::swap(Op0, Op1);
14059
14060   return SSECC;
14061 }
14062
14063 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
14064 // ones, and then concatenate the result back.
14065 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
14066   MVT VT = Op.getSimpleValueType();
14067
14068   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
14069          "Unsupported value type for operation");
14070
14071   unsigned NumElems = VT.getVectorNumElements();
14072   SDLoc dl(Op);
14073   SDValue CC = Op.getOperand(2);
14074
14075   // Extract the LHS vectors
14076   SDValue LHS = Op.getOperand(0);
14077   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
14078   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
14079
14080   // Extract the RHS vectors
14081   SDValue RHS = Op.getOperand(1);
14082   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
14083   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
14084
14085   // Issue the operation on the smaller types and concatenate the result back
14086   MVT EltVT = VT.getVectorElementType();
14087   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
14088   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
14089                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
14090                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
14091 }
14092
14093 static SDValue LowerBoolVSETCC_AVX512(SDValue Op, SelectionDAG &DAG) {
14094   SDValue Op0 = Op.getOperand(0);
14095   SDValue Op1 = Op.getOperand(1);
14096   SDValue CC = Op.getOperand(2);
14097   MVT VT = Op.getSimpleValueType();
14098   SDLoc dl(Op);
14099
14100   assert(Op0.getSimpleValueType().getVectorElementType() == MVT::i1 &&
14101          "Unexpected type for boolean compare operation");
14102   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
14103   SDValue NotOp0 = DAG.getNode(ISD::XOR, dl, VT, Op0,
14104                                DAG.getConstant(-1, dl, VT));
14105   SDValue NotOp1 = DAG.getNode(ISD::XOR, dl, VT, Op1,
14106                                DAG.getConstant(-1, dl, VT));
14107   switch (SetCCOpcode) {
14108   default: llvm_unreachable("Unexpected SETCC condition");
14109   case ISD::SETEQ:
14110     // (x == y) -> ~(x ^ y)
14111     return DAG.getNode(ISD::XOR, dl, VT,
14112                        DAG.getNode(ISD::XOR, dl, VT, Op0, Op1),
14113                        DAG.getConstant(-1, dl, VT));
14114   case ISD::SETNE:
14115     // (x != y) -> (x ^ y)
14116     return DAG.getNode(ISD::XOR, dl, VT, Op0, Op1);
14117   case ISD::SETUGT:
14118   case ISD::SETGT:
14119     // (x > y) -> (x & ~y)
14120     return DAG.getNode(ISD::AND, dl, VT, Op0, NotOp1);
14121   case ISD::SETULT:
14122   case ISD::SETLT:
14123     // (x < y) -> (~x & y)
14124     return DAG.getNode(ISD::AND, dl, VT, NotOp0, Op1);
14125   case ISD::SETULE:
14126   case ISD::SETLE:
14127     // (x <= y) -> (~x | y)
14128     return DAG.getNode(ISD::OR, dl, VT, NotOp0, Op1);
14129   case ISD::SETUGE:
14130   case ISD::SETGE:
14131     // (x >=y) -> (x | ~y)
14132     return DAG.getNode(ISD::OR, dl, VT, Op0, NotOp1);
14133   }
14134 }
14135
14136 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
14137                                      const X86Subtarget *Subtarget) {
14138   SDValue Op0 = Op.getOperand(0);
14139   SDValue Op1 = Op.getOperand(1);
14140   SDValue CC = Op.getOperand(2);
14141   MVT VT = Op.getSimpleValueType();
14142   SDLoc dl(Op);
14143
14144   assert(Op0.getSimpleValueType().getVectorElementType().getSizeInBits() >= 8 &&
14145          Op.getSimpleValueType().getVectorElementType() == MVT::i1 &&
14146          "Cannot set masked compare for this operation");
14147
14148   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
14149   unsigned  Opc = 0;
14150   bool Unsigned = false;
14151   bool Swap = false;
14152   unsigned SSECC;
14153   switch (SetCCOpcode) {
14154   default: llvm_unreachable("Unexpected SETCC condition");
14155   case ISD::SETNE:  SSECC = 4; break;
14156   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
14157   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
14158   case ISD::SETLT:  Swap = true; //fall-through
14159   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
14160   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
14161   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
14162   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
14163   case ISD::SETULE: Unsigned = true; //fall-through
14164   case ISD::SETLE:  SSECC = 2; break;
14165   }
14166
14167   if (Swap)
14168     std::swap(Op0, Op1);
14169   if (Opc)
14170     return DAG.getNode(Opc, dl, VT, Op0, Op1);
14171   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
14172   return DAG.getNode(Opc, dl, VT, Op0, Op1,
14173                      DAG.getConstant(SSECC, dl, MVT::i8));
14174 }
14175
14176 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
14177 /// operand \p Op1.  If non-trivial (for example because it's not constant)
14178 /// return an empty value.
14179 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
14180 {
14181   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
14182   if (!BV)
14183     return SDValue();
14184
14185   MVT VT = Op1.getSimpleValueType();
14186   MVT EVT = VT.getVectorElementType();
14187   unsigned n = VT.getVectorNumElements();
14188   SmallVector<SDValue, 8> ULTOp1;
14189
14190   for (unsigned i = 0; i < n; ++i) {
14191     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
14192     if (!Elt || Elt->isOpaque() || Elt->getSimpleValueType(0) != EVT)
14193       return SDValue();
14194
14195     // Avoid underflow.
14196     APInt Val = Elt->getAPIntValue();
14197     if (Val == 0)
14198       return SDValue();
14199
14200     ULTOp1.push_back(DAG.getConstant(Val - 1, dl, EVT));
14201   }
14202
14203   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
14204 }
14205
14206 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
14207                            SelectionDAG &DAG) {
14208   SDValue Op0 = Op.getOperand(0);
14209   SDValue Op1 = Op.getOperand(1);
14210   SDValue CC = Op.getOperand(2);
14211   MVT VT = Op.getSimpleValueType();
14212   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
14213   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
14214   SDLoc dl(Op);
14215
14216   if (isFP) {
14217 #ifndef NDEBUG
14218     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
14219     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
14220 #endif
14221
14222     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
14223     unsigned Opc = X86ISD::CMPP;
14224     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
14225       assert(VT.getVectorNumElements() <= 16);
14226       Opc = X86ISD::CMPM;
14227     }
14228     // In the two special cases we can't handle, emit two comparisons.
14229     if (SSECC == 8) {
14230       unsigned CC0, CC1;
14231       unsigned CombineOpc;
14232       if (SetCCOpcode == ISD::SETUEQ) {
14233         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
14234       } else {
14235         assert(SetCCOpcode == ISD::SETONE);
14236         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
14237       }
14238
14239       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
14240                                  DAG.getConstant(CC0, dl, MVT::i8));
14241       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
14242                                  DAG.getConstant(CC1, dl, MVT::i8));
14243       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
14244     }
14245     // Handle all other FP comparisons here.
14246     return DAG.getNode(Opc, dl, VT, Op0, Op1,
14247                        DAG.getConstant(SSECC, dl, MVT::i8));
14248   }
14249
14250   MVT VTOp0 = Op0.getSimpleValueType();
14251   assert(VTOp0 == Op1.getSimpleValueType() &&
14252          "Expected operands with same type!");
14253   assert(VT.getVectorNumElements() == VTOp0.getVectorNumElements() &&
14254          "Invalid number of packed elements for source and destination!");
14255
14256   if (VT.is128BitVector() && VTOp0.is256BitVector()) {
14257     // On non-AVX512 targets, a vector of MVT::i1 is promoted by the type
14258     // legalizer to a wider vector type.  In the case of 'vsetcc' nodes, the
14259     // legalizer firstly checks if the first operand in input to the setcc has
14260     // a legal type. If so, then it promotes the return type to that same type.
14261     // Otherwise, the return type is promoted to the 'next legal type' which,
14262     // for a vector of MVT::i1 is always a 128-bit integer vector type.
14263     //
14264     // We reach this code only if the following two conditions are met:
14265     // 1. Both return type and operand type have been promoted to wider types
14266     //    by the type legalizer.
14267     // 2. The original operand type has been promoted to a 256-bit vector.
14268     //
14269     // Note that condition 2. only applies for AVX targets.
14270     SDValue NewOp = DAG.getSetCC(dl, VTOp0, Op0, Op1, SetCCOpcode);
14271     return DAG.getZExtOrTrunc(NewOp, dl, VT);
14272   }
14273
14274   // The non-AVX512 code below works under the assumption that source and
14275   // destination types are the same.
14276   assert((Subtarget->hasAVX512() || (VT == VTOp0)) &&
14277          "Value types for source and destination must be the same!");
14278
14279   // Break 256-bit integer vector compare into smaller ones.
14280   if (VT.is256BitVector() && !Subtarget->hasInt256())
14281     return Lower256IntVSETCC(Op, DAG);
14282
14283   MVT OpVT = Op1.getSimpleValueType();
14284   if (OpVT.getVectorElementType() == MVT::i1)
14285     return LowerBoolVSETCC_AVX512(Op, DAG);
14286
14287   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
14288   if (Subtarget->hasAVX512()) {
14289     if (Op1.getSimpleValueType().is512BitVector() ||
14290         (Subtarget->hasBWI() && Subtarget->hasVLX()) ||
14291         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
14292       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
14293
14294     // In AVX-512 architecture setcc returns mask with i1 elements,
14295     // But there is no compare instruction for i8 and i16 elements in KNL.
14296     // We are not talking about 512-bit operands in this case, these
14297     // types are illegal.
14298     if (MaskResult &&
14299         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
14300          OpVT.getVectorElementType().getSizeInBits() >= 8))
14301       return DAG.getNode(ISD::TRUNCATE, dl, VT,
14302                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
14303   }
14304
14305   // Lower using XOP integer comparisons.
14306   if ((VT == MVT::v16i8 || VT == MVT::v8i16 ||
14307        VT == MVT::v4i32 || VT == MVT::v2i64) && Subtarget->hasXOP()) {
14308     // Translate compare code to XOP PCOM compare mode.
14309     unsigned CmpMode = 0;
14310     switch (SetCCOpcode) {
14311     default: llvm_unreachable("Unexpected SETCC condition");
14312     case ISD::SETULT:
14313     case ISD::SETLT: CmpMode = 0x00; break;
14314     case ISD::SETULE:
14315     case ISD::SETLE: CmpMode = 0x01; break;
14316     case ISD::SETUGT:
14317     case ISD::SETGT: CmpMode = 0x02; break;
14318     case ISD::SETUGE:
14319     case ISD::SETGE: CmpMode = 0x03; break;
14320     case ISD::SETEQ: CmpMode = 0x04; break;
14321     case ISD::SETNE: CmpMode = 0x05; break;
14322     }
14323
14324     // Are we comparing unsigned or signed integers?
14325     unsigned Opc = ISD::isUnsignedIntSetCC(SetCCOpcode)
14326       ? X86ISD::VPCOMU : X86ISD::VPCOM;
14327
14328     return DAG.getNode(Opc, dl, VT, Op0, Op1,
14329                        DAG.getConstant(CmpMode, dl, MVT::i8));
14330   }
14331
14332   // We are handling one of the integer comparisons here.  Since SSE only has
14333   // GT and EQ comparisons for integer, swapping operands and multiple
14334   // operations may be required for some comparisons.
14335   unsigned Opc;
14336   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
14337   bool Subus = false;
14338
14339   switch (SetCCOpcode) {
14340   default: llvm_unreachable("Unexpected SETCC condition");
14341   case ISD::SETNE:  Invert = true;
14342   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
14343   case ISD::SETLT:  Swap = true;
14344   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
14345   case ISD::SETGE:  Swap = true;
14346   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
14347                     Invert = true; break;
14348   case ISD::SETULT: Swap = true;
14349   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
14350                     FlipSigns = true; break;
14351   case ISD::SETUGE: Swap = true;
14352   case ISD::SETULE: Opc = X86ISD::PCMPGT;
14353                     FlipSigns = true; Invert = true; break;
14354   }
14355
14356   // Special case: Use min/max operations for SETULE/SETUGE
14357   MVT VET = VT.getVectorElementType();
14358   bool hasMinMax =
14359        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
14360     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
14361
14362   if (hasMinMax) {
14363     switch (SetCCOpcode) {
14364     default: break;
14365     case ISD::SETULE: Opc = ISD::UMIN; MinMax = true; break;
14366     case ISD::SETUGE: Opc = ISD::UMAX; MinMax = true; break;
14367     }
14368
14369     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
14370   }
14371
14372   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
14373   if (!MinMax && hasSubus) {
14374     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
14375     // Op0 u<= Op1:
14376     //   t = psubus Op0, Op1
14377     //   pcmpeq t, <0..0>
14378     switch (SetCCOpcode) {
14379     default: break;
14380     case ISD::SETULT: {
14381       // If the comparison is against a constant we can turn this into a
14382       // setule.  With psubus, setule does not require a swap.  This is
14383       // beneficial because the constant in the register is no longer
14384       // destructed as the destination so it can be hoisted out of a loop.
14385       // Only do this pre-AVX since vpcmp* is no longer destructive.
14386       if (Subtarget->hasAVX())
14387         break;
14388       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
14389       if (ULEOp1.getNode()) {
14390         Op1 = ULEOp1;
14391         Subus = true; Invert = false; Swap = false;
14392       }
14393       break;
14394     }
14395     // Psubus is better than flip-sign because it requires no inversion.
14396     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
14397     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
14398     }
14399
14400     if (Subus) {
14401       Opc = X86ISD::SUBUS;
14402       FlipSigns = false;
14403     }
14404   }
14405
14406   if (Swap)
14407     std::swap(Op0, Op1);
14408
14409   // Check that the operation in question is available (most are plain SSE2,
14410   // but PCMPGTQ and PCMPEQQ have different requirements).
14411   if (VT == MVT::v2i64) {
14412     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
14413       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
14414
14415       // First cast everything to the right type.
14416       Op0 = DAG.getBitcast(MVT::v4i32, Op0);
14417       Op1 = DAG.getBitcast(MVT::v4i32, Op1);
14418
14419       // Since SSE has no unsigned integer comparisons, we need to flip the sign
14420       // bits of the inputs before performing those operations. The lower
14421       // compare is always unsigned.
14422       SDValue SB;
14423       if (FlipSigns) {
14424         SB = DAG.getConstant(0x80000000U, dl, MVT::v4i32);
14425       } else {
14426         SDValue Sign = DAG.getConstant(0x80000000U, dl, MVT::i32);
14427         SDValue Zero = DAG.getConstant(0x00000000U, dl, MVT::i32);
14428         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
14429                          Sign, Zero, Sign, Zero);
14430       }
14431       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
14432       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
14433
14434       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
14435       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
14436       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
14437
14438       // Create masks for only the low parts/high parts of the 64 bit integers.
14439       static const int MaskHi[] = { 1, 1, 3, 3 };
14440       static const int MaskLo[] = { 0, 0, 2, 2 };
14441       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
14442       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
14443       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
14444
14445       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
14446       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
14447
14448       if (Invert)
14449         Result = DAG.getNOT(dl, Result, MVT::v4i32);
14450
14451       return DAG.getBitcast(VT, Result);
14452     }
14453
14454     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
14455       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
14456       // pcmpeqd + pshufd + pand.
14457       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
14458
14459       // First cast everything to the right type.
14460       Op0 = DAG.getBitcast(MVT::v4i32, Op0);
14461       Op1 = DAG.getBitcast(MVT::v4i32, Op1);
14462
14463       // Do the compare.
14464       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
14465
14466       // Make sure the lower and upper halves are both all-ones.
14467       static const int Mask[] = { 1, 0, 3, 2 };
14468       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
14469       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
14470
14471       if (Invert)
14472         Result = DAG.getNOT(dl, Result, MVT::v4i32);
14473
14474       return DAG.getBitcast(VT, Result);
14475     }
14476   }
14477
14478   // Since SSE has no unsigned integer comparisons, we need to flip the sign
14479   // bits of the inputs before performing those operations.
14480   if (FlipSigns) {
14481     MVT EltVT = VT.getVectorElementType();
14482     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), dl,
14483                                  VT);
14484     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
14485     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
14486   }
14487
14488   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
14489
14490   // If the logical-not of the result is required, perform that now.
14491   if (Invert)
14492     Result = DAG.getNOT(dl, Result, VT);
14493
14494   if (MinMax)
14495     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
14496
14497   if (Subus)
14498     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
14499                          getZeroVector(VT, Subtarget, DAG, dl));
14500
14501   return Result;
14502 }
14503
14504 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
14505
14506   MVT VT = Op.getSimpleValueType();
14507
14508   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
14509
14510   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
14511          && "SetCC type must be 8-bit or 1-bit integer");
14512   SDValue Op0 = Op.getOperand(0);
14513   SDValue Op1 = Op.getOperand(1);
14514   SDLoc dl(Op);
14515   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
14516
14517   // Optimize to BT if possible.
14518   // Lower (X & (1 << N)) == 0 to BT(X, N).
14519   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
14520   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
14521   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
14522       Op1.getOpcode() == ISD::Constant &&
14523       cast<ConstantSDNode>(Op1)->isNullValue() &&
14524       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14525     if (SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG)) {
14526       if (VT == MVT::i1)
14527         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewSetCC);
14528       return NewSetCC;
14529     }
14530   }
14531
14532   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
14533   // these.
14534   if (Op1.getOpcode() == ISD::Constant &&
14535       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
14536        cast<ConstantSDNode>(Op1)->isNullValue()) &&
14537       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14538
14539     // If the input is a setcc, then reuse the input setcc or use a new one with
14540     // the inverted condition.
14541     if (Op0.getOpcode() == X86ISD::SETCC) {
14542       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
14543       bool Invert = (CC == ISD::SETNE) ^
14544         cast<ConstantSDNode>(Op1)->isNullValue();
14545       if (!Invert)
14546         return Op0;
14547
14548       CCode = X86::GetOppositeBranchCondition(CCode);
14549       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14550                                   DAG.getConstant(CCode, dl, MVT::i8),
14551                                   Op0.getOperand(1));
14552       if (VT == MVT::i1)
14553         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
14554       return SetCC;
14555     }
14556   }
14557   if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
14558       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
14559       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14560
14561     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
14562     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, dl, MVT::i1), NewCC);
14563   }
14564
14565   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
14566   unsigned X86CC = TranslateX86CC(CC, dl, isFP, Op0, Op1, DAG);
14567   if (X86CC == X86::COND_INVALID)
14568     return SDValue();
14569
14570   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
14571   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
14572   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14573                               DAG.getConstant(X86CC, dl, MVT::i8), EFLAGS);
14574   if (VT == MVT::i1)
14575     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
14576   return SetCC;
14577 }
14578
14579 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
14580 static bool isX86LogicalCmp(SDValue Op) {
14581   unsigned Opc = Op.getNode()->getOpcode();
14582   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
14583       Opc == X86ISD::SAHF)
14584     return true;
14585   if (Op.getResNo() == 1 &&
14586       (Opc == X86ISD::ADD ||
14587        Opc == X86ISD::SUB ||
14588        Opc == X86ISD::ADC ||
14589        Opc == X86ISD::SBB ||
14590        Opc == X86ISD::SMUL ||
14591        Opc == X86ISD::UMUL ||
14592        Opc == X86ISD::INC ||
14593        Opc == X86ISD::DEC ||
14594        Opc == X86ISD::OR ||
14595        Opc == X86ISD::XOR ||
14596        Opc == X86ISD::AND))
14597     return true;
14598
14599   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
14600     return true;
14601
14602   return false;
14603 }
14604
14605 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
14606   if (V.getOpcode() != ISD::TRUNCATE)
14607     return false;
14608
14609   SDValue VOp0 = V.getOperand(0);
14610   unsigned InBits = VOp0.getValueSizeInBits();
14611   unsigned Bits = V.getValueSizeInBits();
14612   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
14613 }
14614
14615 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
14616   bool addTest = true;
14617   SDValue Cond  = Op.getOperand(0);
14618   SDValue Op1 = Op.getOperand(1);
14619   SDValue Op2 = Op.getOperand(2);
14620   SDLoc DL(Op);
14621   MVT VT = Op1.getSimpleValueType();
14622   SDValue CC;
14623
14624   // Lower FP selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
14625   // are available or VBLENDV if AVX is available.
14626   // Otherwise FP cmovs get lowered into a less efficient branch sequence later.
14627   if (Cond.getOpcode() == ISD::SETCC &&
14628       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
14629        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
14630       VT == Cond.getOperand(0).getSimpleValueType() && Cond->hasOneUse()) {
14631     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
14632     int SSECC = translateX86FSETCC(
14633         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
14634
14635     if (SSECC != 8) {
14636       if (Subtarget->hasAVX512()) {
14637         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
14638                                   DAG.getConstant(SSECC, DL, MVT::i8));
14639         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
14640       }
14641
14642       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
14643                                 DAG.getConstant(SSECC, DL, MVT::i8));
14644
14645       // If we have AVX, we can use a variable vector select (VBLENDV) instead
14646       // of 3 logic instructions for size savings and potentially speed.
14647       // Unfortunately, there is no scalar form of VBLENDV.
14648
14649       // If either operand is a constant, don't try this. We can expect to
14650       // optimize away at least one of the logic instructions later in that
14651       // case, so that sequence would be faster than a variable blend.
14652
14653       // BLENDV was introduced with SSE 4.1, but the 2 register form implicitly
14654       // uses XMM0 as the selection register. That may need just as many
14655       // instructions as the AND/ANDN/OR sequence due to register moves, so
14656       // don't bother.
14657
14658       if (Subtarget->hasAVX() &&
14659           !isa<ConstantFPSDNode>(Op1) && !isa<ConstantFPSDNode>(Op2)) {
14660
14661         // Convert to vectors, do a VSELECT, and convert back to scalar.
14662         // All of the conversions should be optimized away.
14663
14664         MVT VecVT = VT == MVT::f32 ? MVT::v4f32 : MVT::v2f64;
14665         SDValue VOp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op1);
14666         SDValue VOp2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op2);
14667         SDValue VCmp = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Cmp);
14668
14669         MVT VCmpVT = VT == MVT::f32 ? MVT::v4i32 : MVT::v2i64;
14670         VCmp = DAG.getBitcast(VCmpVT, VCmp);
14671
14672         SDValue VSel = DAG.getNode(ISD::VSELECT, DL, VecVT, VCmp, VOp1, VOp2);
14673
14674         return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
14675                            VSel, DAG.getIntPtrConstant(0, DL));
14676       }
14677       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
14678       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
14679       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
14680     }
14681   }
14682
14683   if (VT.isVector() && VT.getVectorElementType() == MVT::i1) {
14684     SDValue Op1Scalar;
14685     if (ISD::isBuildVectorOfConstantSDNodes(Op1.getNode()))
14686       Op1Scalar = ConvertI1VectorToInteger(Op1, DAG);
14687     else if (Op1.getOpcode() == ISD::BITCAST && Op1.getOperand(0))
14688       Op1Scalar = Op1.getOperand(0);
14689     SDValue Op2Scalar;
14690     if (ISD::isBuildVectorOfConstantSDNodes(Op2.getNode()))
14691       Op2Scalar = ConvertI1VectorToInteger(Op2, DAG);
14692     else if (Op2.getOpcode() == ISD::BITCAST && Op2.getOperand(0))
14693       Op2Scalar = Op2.getOperand(0);
14694     if (Op1Scalar.getNode() && Op2Scalar.getNode()) {
14695       SDValue newSelect = DAG.getNode(ISD::SELECT, DL,
14696                                       Op1Scalar.getValueType(),
14697                                       Cond, Op1Scalar, Op2Scalar);
14698       if (newSelect.getValueSizeInBits() == VT.getSizeInBits())
14699         return DAG.getBitcast(VT, newSelect);
14700       SDValue ExtVec = DAG.getBitcast(MVT::v8i1, newSelect);
14701       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, ExtVec,
14702                          DAG.getIntPtrConstant(0, DL));
14703     }
14704   }
14705
14706   if (VT == MVT::v4i1 || VT == MVT::v2i1) {
14707     SDValue zeroConst = DAG.getIntPtrConstant(0, DL);
14708     Op1 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
14709                       DAG.getUNDEF(MVT::v8i1), Op1, zeroConst);
14710     Op2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
14711                       DAG.getUNDEF(MVT::v8i1), Op2, zeroConst);
14712     SDValue newSelect = DAG.getNode(ISD::SELECT, DL, MVT::v8i1,
14713                                     Cond, Op1, Op2);
14714     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, newSelect, zeroConst);
14715   }
14716
14717   if (Cond.getOpcode() == ISD::SETCC) {
14718     SDValue NewCond = LowerSETCC(Cond, DAG);
14719     if (NewCond.getNode())
14720       Cond = NewCond;
14721   }
14722
14723   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
14724   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
14725   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
14726   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
14727   if (Cond.getOpcode() == X86ISD::SETCC &&
14728       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
14729       isZero(Cond.getOperand(1).getOperand(1))) {
14730     SDValue Cmp = Cond.getOperand(1);
14731
14732     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
14733
14734     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
14735         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
14736       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
14737
14738       SDValue CmpOp0 = Cmp.getOperand(0);
14739       // Apply further optimizations for special cases
14740       // (select (x != 0), -1, 0) -> neg & sbb
14741       // (select (x == 0), 0, -1) -> neg & sbb
14742       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
14743         if (YC->isNullValue() &&
14744             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
14745           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
14746           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
14747                                     DAG.getConstant(0, DL,
14748                                                     CmpOp0.getValueType()),
14749                                     CmpOp0);
14750           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14751                                     DAG.getConstant(X86::COND_B, DL, MVT::i8),
14752                                     SDValue(Neg.getNode(), 1));
14753           return Res;
14754         }
14755
14756       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
14757                         CmpOp0, DAG.getConstant(1, DL, CmpOp0.getValueType()));
14758       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14759
14760       SDValue Res =   // Res = 0 or -1.
14761         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14762                     DAG.getConstant(X86::COND_B, DL, MVT::i8), Cmp);
14763
14764       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
14765         Res = DAG.getNOT(DL, Res, Res.getValueType());
14766
14767       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
14768       if (!N2C || !N2C->isNullValue())
14769         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
14770       return Res;
14771     }
14772   }
14773
14774   // Look past (and (setcc_carry (cmp ...)), 1).
14775   if (Cond.getOpcode() == ISD::AND &&
14776       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
14777     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
14778     if (C && C->getAPIntValue() == 1)
14779       Cond = Cond.getOperand(0);
14780   }
14781
14782   // If condition flag is set by a X86ISD::CMP, then use it as the condition
14783   // setting operand in place of the X86ISD::SETCC.
14784   unsigned CondOpcode = Cond.getOpcode();
14785   if (CondOpcode == X86ISD::SETCC ||
14786       CondOpcode == X86ISD::SETCC_CARRY) {
14787     CC = Cond.getOperand(0);
14788
14789     SDValue Cmp = Cond.getOperand(1);
14790     unsigned Opc = Cmp.getOpcode();
14791     MVT VT = Op.getSimpleValueType();
14792
14793     bool IllegalFPCMov = false;
14794     if (VT.isFloatingPoint() && !VT.isVector() &&
14795         !isScalarFPTypeInSSEReg(VT))  // FPStack?
14796       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
14797
14798     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
14799         Opc == X86ISD::BT) { // FIXME
14800       Cond = Cmp;
14801       addTest = false;
14802     }
14803   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
14804              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
14805              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
14806               Cond.getOperand(0).getValueType() != MVT::i8)) {
14807     SDValue LHS = Cond.getOperand(0);
14808     SDValue RHS = Cond.getOperand(1);
14809     unsigned X86Opcode;
14810     unsigned X86Cond;
14811     SDVTList VTs;
14812     switch (CondOpcode) {
14813     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
14814     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
14815     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
14816     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
14817     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
14818     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
14819     default: llvm_unreachable("unexpected overflowing operator");
14820     }
14821     if (CondOpcode == ISD::UMULO)
14822       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
14823                           MVT::i32);
14824     else
14825       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14826
14827     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
14828
14829     if (CondOpcode == ISD::UMULO)
14830       Cond = X86Op.getValue(2);
14831     else
14832       Cond = X86Op.getValue(1);
14833
14834     CC = DAG.getConstant(X86Cond, DL, MVT::i8);
14835     addTest = false;
14836   }
14837
14838   if (addTest) {
14839     // Look past the truncate if the high bits are known zero.
14840     if (isTruncWithZeroHighBitsInput(Cond, DAG))
14841       Cond = Cond.getOperand(0);
14842
14843     // We know the result of AND is compared against zero. Try to match
14844     // it to BT.
14845     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
14846       if (SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG)) {
14847         CC = NewSetCC.getOperand(0);
14848         Cond = NewSetCC.getOperand(1);
14849         addTest = false;
14850       }
14851     }
14852   }
14853
14854   if (addTest) {
14855     CC = DAG.getConstant(X86::COND_NE, DL, MVT::i8);
14856     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
14857   }
14858
14859   // a <  b ? -1 :  0 -> RES = ~setcc_carry
14860   // a <  b ?  0 : -1 -> RES = setcc_carry
14861   // a >= b ? -1 :  0 -> RES = setcc_carry
14862   // a >= b ?  0 : -1 -> RES = ~setcc_carry
14863   if (Cond.getOpcode() == X86ISD::SUB) {
14864     Cond = ConvertCmpIfNecessary(Cond, DAG);
14865     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
14866
14867     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
14868         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
14869       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14870                                 DAG.getConstant(X86::COND_B, DL, MVT::i8),
14871                                 Cond);
14872       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
14873         return DAG.getNOT(DL, Res, Res.getValueType());
14874       return Res;
14875     }
14876   }
14877
14878   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
14879   // widen the cmov and push the truncate through. This avoids introducing a new
14880   // branch during isel and doesn't add any extensions.
14881   if (Op.getValueType() == MVT::i8 &&
14882       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
14883     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
14884     if (T1.getValueType() == T2.getValueType() &&
14885         // Blacklist CopyFromReg to avoid partial register stalls.
14886         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
14887       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
14888       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
14889       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
14890     }
14891   }
14892
14893   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
14894   // condition is true.
14895   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
14896   SDValue Ops[] = { Op2, Op1, CC, Cond };
14897   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
14898 }
14899
14900 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op,
14901                                        const X86Subtarget *Subtarget,
14902                                        SelectionDAG &DAG) {
14903   MVT VT = Op->getSimpleValueType(0);
14904   SDValue In = Op->getOperand(0);
14905   MVT InVT = In.getSimpleValueType();
14906   MVT VTElt = VT.getVectorElementType();
14907   MVT InVTElt = InVT.getVectorElementType();
14908   SDLoc dl(Op);
14909
14910   // SKX processor
14911   if ((InVTElt == MVT::i1) &&
14912       (((Subtarget->hasBWI() && Subtarget->hasVLX() &&
14913         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() <= 16)) ||
14914
14915        ((Subtarget->hasBWI() && VT.is512BitVector() &&
14916         VTElt.getSizeInBits() <= 16)) ||
14917
14918        ((Subtarget->hasDQI() && Subtarget->hasVLX() &&
14919         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() >= 32)) ||
14920
14921        ((Subtarget->hasDQI() && VT.is512BitVector() &&
14922         VTElt.getSizeInBits() >= 32))))
14923     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14924
14925   unsigned int NumElts = VT.getVectorNumElements();
14926
14927   if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
14928     return SDValue();
14929
14930   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1) {
14931     if (In.getOpcode() == X86ISD::VSEXT || In.getOpcode() == X86ISD::VZEXT)
14932       return DAG.getNode(In.getOpcode(), dl, VT, In.getOperand(0));
14933     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14934   }
14935
14936   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
14937   MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
14938   SDValue NegOne =
14939    DAG.getConstant(APInt::getAllOnesValue(ExtVT.getScalarSizeInBits()), dl,
14940                    ExtVT);
14941   SDValue Zero =
14942    DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), dl, ExtVT);
14943
14944   SDValue V = DAG.getNode(ISD::VSELECT, dl, ExtVT, In, NegOne, Zero);
14945   if (VT.is512BitVector())
14946     return V;
14947   return DAG.getNode(X86ISD::VTRUNC, dl, VT, V);
14948 }
14949
14950 static SDValue LowerSIGN_EXTEND_VECTOR_INREG(SDValue Op,
14951                                              const X86Subtarget *Subtarget,
14952                                              SelectionDAG &DAG) {
14953   SDValue In = Op->getOperand(0);
14954   MVT VT = Op->getSimpleValueType(0);
14955   MVT InVT = In.getSimpleValueType();
14956   assert(VT.getSizeInBits() == InVT.getSizeInBits());
14957
14958   MVT InSVT = InVT.getVectorElementType();
14959   assert(VT.getVectorElementType().getSizeInBits() > InSVT.getSizeInBits());
14960
14961   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
14962     return SDValue();
14963   if (InSVT != MVT::i32 && InSVT != MVT::i16 && InSVT != MVT::i8)
14964     return SDValue();
14965
14966   SDLoc dl(Op);
14967
14968   // SSE41 targets can use the pmovsx* instructions directly.
14969   if (Subtarget->hasSSE41())
14970     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14971
14972   // pre-SSE41 targets unpack lower lanes and then sign-extend using SRAI.
14973   SDValue Curr = In;
14974   MVT CurrVT = InVT;
14975
14976   // As SRAI is only available on i16/i32 types, we expand only up to i32
14977   // and handle i64 separately.
14978   while (CurrVT != VT && CurrVT.getVectorElementType() != MVT::i32) {
14979     Curr = DAG.getNode(X86ISD::UNPCKL, dl, CurrVT, DAG.getUNDEF(CurrVT), Curr);
14980     MVT CurrSVT = MVT::getIntegerVT(CurrVT.getScalarSizeInBits() * 2);
14981     CurrVT = MVT::getVectorVT(CurrSVT, CurrVT.getVectorNumElements() / 2);
14982     Curr = DAG.getBitcast(CurrVT, Curr);
14983   }
14984
14985   SDValue SignExt = Curr;
14986   if (CurrVT != InVT) {
14987     unsigned SignExtShift =
14988         CurrVT.getVectorElementType().getSizeInBits() - InSVT.getSizeInBits();
14989     SignExt = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
14990                           DAG.getConstant(SignExtShift, dl, MVT::i8));
14991   }
14992
14993   if (CurrVT == VT)
14994     return SignExt;
14995
14996   if (VT == MVT::v2i64 && CurrVT == MVT::v4i32) {
14997     SDValue Sign = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
14998                                DAG.getConstant(31, dl, MVT::i8));
14999     SDValue Ext = DAG.getVectorShuffle(CurrVT, dl, SignExt, Sign, {0, 4, 1, 5});
15000     return DAG.getBitcast(VT, Ext);
15001   }
15002
15003   return SDValue();
15004 }
15005
15006 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
15007                                 SelectionDAG &DAG) {
15008   MVT VT = Op->getSimpleValueType(0);
15009   SDValue In = Op->getOperand(0);
15010   MVT InVT = In.getSimpleValueType();
15011   SDLoc dl(Op);
15012
15013   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
15014     return LowerSIGN_EXTEND_AVX512(Op, Subtarget, DAG);
15015
15016   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
15017       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
15018       (VT != MVT::v16i16 || InVT != MVT::v16i8))
15019     return SDValue();
15020
15021   if (Subtarget->hasInt256())
15022     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
15023
15024   // Optimize vectors in AVX mode
15025   // Sign extend  v8i16 to v8i32 and
15026   //              v4i32 to v4i64
15027   //
15028   // Divide input vector into two parts
15029   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
15030   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
15031   // concat the vectors to original VT
15032
15033   unsigned NumElems = InVT.getVectorNumElements();
15034   SDValue Undef = DAG.getUNDEF(InVT);
15035
15036   SmallVector<int,8> ShufMask1(NumElems, -1);
15037   for (unsigned i = 0; i != NumElems/2; ++i)
15038     ShufMask1[i] = i;
15039
15040   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
15041
15042   SmallVector<int,8> ShufMask2(NumElems, -1);
15043   for (unsigned i = 0; i != NumElems/2; ++i)
15044     ShufMask2[i] = i + NumElems/2;
15045
15046   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
15047
15048   MVT HalfVT = MVT::getVectorVT(VT.getVectorElementType(),
15049                                 VT.getVectorNumElements()/2);
15050
15051   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
15052   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
15053
15054   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
15055 }
15056
15057 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
15058 // may emit an illegal shuffle but the expansion is still better than scalar
15059 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
15060 // we'll emit a shuffle and a arithmetic shift.
15061 // FIXME: Is the expansion actually better than scalar code? It doesn't seem so.
15062 // TODO: It is possible to support ZExt by zeroing the undef values during
15063 // the shuffle phase or after the shuffle.
15064 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
15065                                  SelectionDAG &DAG) {
15066   MVT RegVT = Op.getSimpleValueType();
15067   assert(RegVT.isVector() && "We only custom lower vector sext loads.");
15068   assert(RegVT.isInteger() &&
15069          "We only custom lower integer vector sext loads.");
15070
15071   // Nothing useful we can do without SSE2 shuffles.
15072   assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
15073
15074   LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
15075   SDLoc dl(Ld);
15076   EVT MemVT = Ld->getMemoryVT();
15077   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15078   unsigned RegSz = RegVT.getSizeInBits();
15079
15080   ISD::LoadExtType Ext = Ld->getExtensionType();
15081
15082   assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
15083          && "Only anyext and sext are currently implemented.");
15084   assert(MemVT != RegVT && "Cannot extend to the same type");
15085   assert(MemVT.isVector() && "Must load a vector from memory");
15086
15087   unsigned NumElems = RegVT.getVectorNumElements();
15088   unsigned MemSz = MemVT.getSizeInBits();
15089   assert(RegSz > MemSz && "Register size must be greater than the mem size");
15090
15091   if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
15092     // The only way in which we have a legal 256-bit vector result but not the
15093     // integer 256-bit operations needed to directly lower a sextload is if we
15094     // have AVX1 but not AVX2. In that case, we can always emit a sextload to
15095     // a 128-bit vector and a normal sign_extend to 256-bits that should get
15096     // correctly legalized. We do this late to allow the canonical form of
15097     // sextload to persist throughout the rest of the DAG combiner -- it wants
15098     // to fold together any extensions it can, and so will fuse a sign_extend
15099     // of an sextload into a sextload targeting a wider value.
15100     SDValue Load;
15101     if (MemSz == 128) {
15102       // Just switch this to a normal load.
15103       assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
15104                                        "it must be a legal 128-bit vector "
15105                                        "type!");
15106       Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
15107                   Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
15108                   Ld->isInvariant(), Ld->getAlignment());
15109     } else {
15110       assert(MemSz < 128 &&
15111              "Can't extend a type wider than 128 bits to a 256 bit vector!");
15112       // Do an sext load to a 128-bit vector type. We want to use the same
15113       // number of elements, but elements half as wide. This will end up being
15114       // recursively lowered by this routine, but will succeed as we definitely
15115       // have all the necessary features if we're using AVX1.
15116       EVT HalfEltVT =
15117           EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
15118       EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
15119       Load =
15120           DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
15121                          Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
15122                          Ld->isNonTemporal(), Ld->isInvariant(),
15123                          Ld->getAlignment());
15124     }
15125
15126     // Replace chain users with the new chain.
15127     assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
15128     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
15129
15130     // Finally, do a normal sign-extend to the desired register.
15131     return DAG.getSExtOrTrunc(Load, dl, RegVT);
15132   }
15133
15134   // All sizes must be a power of two.
15135   assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
15136          "Non-power-of-two elements are not custom lowered!");
15137
15138   // Attempt to load the original value using scalar loads.
15139   // Find the largest scalar type that divides the total loaded size.
15140   MVT SclrLoadTy = MVT::i8;
15141   for (MVT Tp : MVT::integer_valuetypes()) {
15142     if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
15143       SclrLoadTy = Tp;
15144     }
15145   }
15146
15147   // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
15148   if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
15149       (64 <= MemSz))
15150     SclrLoadTy = MVT::f64;
15151
15152   // Calculate the number of scalar loads that we need to perform
15153   // in order to load our vector from memory.
15154   unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
15155
15156   assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
15157          "Can only lower sext loads with a single scalar load!");
15158
15159   unsigned loadRegZize = RegSz;
15160   if (Ext == ISD::SEXTLOAD && RegSz >= 256)
15161     loadRegZize = 128;
15162
15163   // Represent our vector as a sequence of elements which are the
15164   // largest scalar that we can load.
15165   EVT LoadUnitVecVT = EVT::getVectorVT(
15166       *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
15167
15168   // Represent the data using the same element type that is stored in
15169   // memory. In practice, we ''widen'' MemVT.
15170   EVT WideVecVT =
15171       EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
15172                        loadRegZize / MemVT.getScalarSizeInBits());
15173
15174   assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
15175          "Invalid vector type");
15176
15177   // We can't shuffle using an illegal type.
15178   assert(TLI.isTypeLegal(WideVecVT) &&
15179          "We only lower types that form legal widened vector types");
15180
15181   SmallVector<SDValue, 8> Chains;
15182   SDValue Ptr = Ld->getBasePtr();
15183   SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, dl,
15184                                       TLI.getPointerTy(DAG.getDataLayout()));
15185   SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
15186
15187   for (unsigned i = 0; i < NumLoads; ++i) {
15188     // Perform a single load.
15189     SDValue ScalarLoad =
15190         DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
15191                     Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
15192                     Ld->getAlignment());
15193     Chains.push_back(ScalarLoad.getValue(1));
15194     // Create the first element type using SCALAR_TO_VECTOR in order to avoid
15195     // another round of DAGCombining.
15196     if (i == 0)
15197       Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
15198     else
15199       Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
15200                         ScalarLoad, DAG.getIntPtrConstant(i, dl));
15201
15202     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
15203   }
15204
15205   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
15206
15207   // Bitcast the loaded value to a vector of the original element type, in
15208   // the size of the target vector type.
15209   SDValue SlicedVec = DAG.getBitcast(WideVecVT, Res);
15210   unsigned SizeRatio = RegSz / MemSz;
15211
15212   if (Ext == ISD::SEXTLOAD) {
15213     // If we have SSE4.1, we can directly emit a VSEXT node.
15214     if (Subtarget->hasSSE41()) {
15215       SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
15216       DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
15217       return Sext;
15218     }
15219
15220     // Otherwise we'll use SIGN_EXTEND_VECTOR_INREG to sign extend the lowest
15221     // lanes.
15222     assert(TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND_VECTOR_INREG, RegVT) &&
15223            "We can't implement a sext load without SIGN_EXTEND_VECTOR_INREG!");
15224
15225     SDValue Shuff = DAG.getSignExtendVectorInReg(SlicedVec, dl, RegVT);
15226     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
15227     return Shuff;
15228   }
15229
15230   // Redistribute the loaded elements into the different locations.
15231   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
15232   for (unsigned i = 0; i != NumElems; ++i)
15233     ShuffleVec[i * SizeRatio] = i;
15234
15235   SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
15236                                        DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
15237
15238   // Bitcast to the requested type.
15239   Shuff = DAG.getBitcast(RegVT, Shuff);
15240   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
15241   return Shuff;
15242 }
15243
15244 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
15245 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
15246 // from the AND / OR.
15247 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
15248   Opc = Op.getOpcode();
15249   if (Opc != ISD::OR && Opc != ISD::AND)
15250     return false;
15251   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
15252           Op.getOperand(0).hasOneUse() &&
15253           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
15254           Op.getOperand(1).hasOneUse());
15255 }
15256
15257 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
15258 // 1 and that the SETCC node has a single use.
15259 static bool isXor1OfSetCC(SDValue Op) {
15260   if (Op.getOpcode() != ISD::XOR)
15261     return false;
15262   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
15263   if (N1C && N1C->getAPIntValue() == 1) {
15264     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
15265       Op.getOperand(0).hasOneUse();
15266   }
15267   return false;
15268 }
15269
15270 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
15271   bool addTest = true;
15272   SDValue Chain = Op.getOperand(0);
15273   SDValue Cond  = Op.getOperand(1);
15274   SDValue Dest  = Op.getOperand(2);
15275   SDLoc dl(Op);
15276   SDValue CC;
15277   bool Inverted = false;
15278
15279   if (Cond.getOpcode() == ISD::SETCC) {
15280     // Check for setcc([su]{add,sub,mul}o == 0).
15281     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
15282         isa<ConstantSDNode>(Cond.getOperand(1)) &&
15283         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
15284         Cond.getOperand(0).getResNo() == 1 &&
15285         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
15286          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
15287          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
15288          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
15289          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
15290          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
15291       Inverted = true;
15292       Cond = Cond.getOperand(0);
15293     } else {
15294       SDValue NewCond = LowerSETCC(Cond, DAG);
15295       if (NewCond.getNode())
15296         Cond = NewCond;
15297     }
15298   }
15299 #if 0
15300   // FIXME: LowerXALUO doesn't handle these!!
15301   else if (Cond.getOpcode() == X86ISD::ADD  ||
15302            Cond.getOpcode() == X86ISD::SUB  ||
15303            Cond.getOpcode() == X86ISD::SMUL ||
15304            Cond.getOpcode() == X86ISD::UMUL)
15305     Cond = LowerXALUO(Cond, DAG);
15306 #endif
15307
15308   // Look pass (and (setcc_carry (cmp ...)), 1).
15309   if (Cond.getOpcode() == ISD::AND &&
15310       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
15311     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
15312     if (C && C->getAPIntValue() == 1)
15313       Cond = Cond.getOperand(0);
15314   }
15315
15316   // If condition flag is set by a X86ISD::CMP, then use it as the condition
15317   // setting operand in place of the X86ISD::SETCC.
15318   unsigned CondOpcode = Cond.getOpcode();
15319   if (CondOpcode == X86ISD::SETCC ||
15320       CondOpcode == X86ISD::SETCC_CARRY) {
15321     CC = Cond.getOperand(0);
15322
15323     SDValue Cmp = Cond.getOperand(1);
15324     unsigned Opc = Cmp.getOpcode();
15325     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
15326     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
15327       Cond = Cmp;
15328       addTest = false;
15329     } else {
15330       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
15331       default: break;
15332       case X86::COND_O:
15333       case X86::COND_B:
15334         // These can only come from an arithmetic instruction with overflow,
15335         // e.g. SADDO, UADDO.
15336         Cond = Cond.getNode()->getOperand(1);
15337         addTest = false;
15338         break;
15339       }
15340     }
15341   }
15342   CondOpcode = Cond.getOpcode();
15343   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
15344       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
15345       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
15346        Cond.getOperand(0).getValueType() != MVT::i8)) {
15347     SDValue LHS = Cond.getOperand(0);
15348     SDValue RHS = Cond.getOperand(1);
15349     unsigned X86Opcode;
15350     unsigned X86Cond;
15351     SDVTList VTs;
15352     // Keep this in sync with LowerXALUO, otherwise we might create redundant
15353     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
15354     // X86ISD::INC).
15355     switch (CondOpcode) {
15356     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
15357     case ISD::SADDO:
15358       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
15359         if (C->isOne()) {
15360           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
15361           break;
15362         }
15363       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
15364     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
15365     case ISD::SSUBO:
15366       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
15367         if (C->isOne()) {
15368           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
15369           break;
15370         }
15371       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
15372     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
15373     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
15374     default: llvm_unreachable("unexpected overflowing operator");
15375     }
15376     if (Inverted)
15377       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
15378     if (CondOpcode == ISD::UMULO)
15379       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
15380                           MVT::i32);
15381     else
15382       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
15383
15384     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
15385
15386     if (CondOpcode == ISD::UMULO)
15387       Cond = X86Op.getValue(2);
15388     else
15389       Cond = X86Op.getValue(1);
15390
15391     CC = DAG.getConstant(X86Cond, dl, MVT::i8);
15392     addTest = false;
15393   } else {
15394     unsigned CondOpc;
15395     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
15396       SDValue Cmp = Cond.getOperand(0).getOperand(1);
15397       if (CondOpc == ISD::OR) {
15398         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
15399         // two branches instead of an explicit OR instruction with a
15400         // separate test.
15401         if (Cmp == Cond.getOperand(1).getOperand(1) &&
15402             isX86LogicalCmp(Cmp)) {
15403           CC = Cond.getOperand(0).getOperand(0);
15404           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15405                               Chain, Dest, CC, Cmp);
15406           CC = Cond.getOperand(1).getOperand(0);
15407           Cond = Cmp;
15408           addTest = false;
15409         }
15410       } else { // ISD::AND
15411         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
15412         // two branches instead of an explicit AND instruction with a
15413         // separate test. However, we only do this if this block doesn't
15414         // have a fall-through edge, because this requires an explicit
15415         // jmp when the condition is false.
15416         if (Cmp == Cond.getOperand(1).getOperand(1) &&
15417             isX86LogicalCmp(Cmp) &&
15418             Op.getNode()->hasOneUse()) {
15419           X86::CondCode CCode =
15420             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
15421           CCode = X86::GetOppositeBranchCondition(CCode);
15422           CC = DAG.getConstant(CCode, dl, MVT::i8);
15423           SDNode *User = *Op.getNode()->use_begin();
15424           // Look for an unconditional branch following this conditional branch.
15425           // We need this because we need to reverse the successors in order
15426           // to implement FCMP_OEQ.
15427           if (User->getOpcode() == ISD::BR) {
15428             SDValue FalseBB = User->getOperand(1);
15429             SDNode *NewBR =
15430               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
15431             assert(NewBR == User);
15432             (void)NewBR;
15433             Dest = FalseBB;
15434
15435             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15436                                 Chain, Dest, CC, Cmp);
15437             X86::CondCode CCode =
15438               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
15439             CCode = X86::GetOppositeBranchCondition(CCode);
15440             CC = DAG.getConstant(CCode, dl, MVT::i8);
15441             Cond = Cmp;
15442             addTest = false;
15443           }
15444         }
15445       }
15446     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
15447       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
15448       // It should be transformed during dag combiner except when the condition
15449       // is set by a arithmetics with overflow node.
15450       X86::CondCode CCode =
15451         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
15452       CCode = X86::GetOppositeBranchCondition(CCode);
15453       CC = DAG.getConstant(CCode, dl, MVT::i8);
15454       Cond = Cond.getOperand(0).getOperand(1);
15455       addTest = false;
15456     } else if (Cond.getOpcode() == ISD::SETCC &&
15457                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
15458       // For FCMP_OEQ, we can emit
15459       // two branches instead of an explicit AND instruction with a
15460       // separate test. However, we only do this if this block doesn't
15461       // have a fall-through edge, because this requires an explicit
15462       // jmp when the condition is false.
15463       if (Op.getNode()->hasOneUse()) {
15464         SDNode *User = *Op.getNode()->use_begin();
15465         // Look for an unconditional branch following this conditional branch.
15466         // We need this because we need to reverse the successors in order
15467         // to implement FCMP_OEQ.
15468         if (User->getOpcode() == ISD::BR) {
15469           SDValue FalseBB = User->getOperand(1);
15470           SDNode *NewBR =
15471             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
15472           assert(NewBR == User);
15473           (void)NewBR;
15474           Dest = FalseBB;
15475
15476           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
15477                                     Cond.getOperand(0), Cond.getOperand(1));
15478           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
15479           CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
15480           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15481                               Chain, Dest, CC, Cmp);
15482           CC = DAG.getConstant(X86::COND_P, dl, MVT::i8);
15483           Cond = Cmp;
15484           addTest = false;
15485         }
15486       }
15487     } else if (Cond.getOpcode() == ISD::SETCC &&
15488                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
15489       // For FCMP_UNE, we can emit
15490       // two branches instead of an explicit AND instruction with a
15491       // separate test. However, we only do this if this block doesn't
15492       // have a fall-through edge, because this requires an explicit
15493       // jmp when the condition is false.
15494       if (Op.getNode()->hasOneUse()) {
15495         SDNode *User = *Op.getNode()->use_begin();
15496         // Look for an unconditional branch following this conditional branch.
15497         // We need this because we need to reverse the successors in order
15498         // to implement FCMP_UNE.
15499         if (User->getOpcode() == ISD::BR) {
15500           SDValue FalseBB = User->getOperand(1);
15501           SDNode *NewBR =
15502             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
15503           assert(NewBR == User);
15504           (void)NewBR;
15505
15506           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
15507                                     Cond.getOperand(0), Cond.getOperand(1));
15508           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
15509           CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
15510           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15511                               Chain, Dest, CC, Cmp);
15512           CC = DAG.getConstant(X86::COND_NP, dl, MVT::i8);
15513           Cond = Cmp;
15514           addTest = false;
15515           Dest = FalseBB;
15516         }
15517       }
15518     }
15519   }
15520
15521   if (addTest) {
15522     // Look pass the truncate if the high bits are known zero.
15523     if (isTruncWithZeroHighBitsInput(Cond, DAG))
15524         Cond = Cond.getOperand(0);
15525
15526     // We know the result of AND is compared against zero. Try to match
15527     // it to BT.
15528     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
15529       if (SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG)) {
15530         CC = NewSetCC.getOperand(0);
15531         Cond = NewSetCC.getOperand(1);
15532         addTest = false;
15533       }
15534     }
15535   }
15536
15537   if (addTest) {
15538     X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
15539     CC = DAG.getConstant(X86Cond, dl, MVT::i8);
15540     Cond = EmitTest(Cond, X86Cond, dl, DAG);
15541   }
15542   Cond = ConvertCmpIfNecessary(Cond, DAG);
15543   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15544                      Chain, Dest, CC, Cond);
15545 }
15546
15547 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
15548 // Calls to _alloca are needed to probe the stack when allocating more than 4k
15549 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
15550 // that the guard pages used by the OS virtual memory manager are allocated in
15551 // correct sequence.
15552 SDValue
15553 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
15554                                            SelectionDAG &DAG) const {
15555   MachineFunction &MF = DAG.getMachineFunction();
15556   bool SplitStack = MF.shouldSplitStack();
15557   bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMachO()) ||
15558                SplitStack;
15559   SDLoc dl(Op);
15560
15561   if (!Lower) {
15562     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15563     SDNode* Node = Op.getNode();
15564
15565     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
15566     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
15567         " not tell us which reg is the stack pointer!");
15568     EVT VT = Node->getValueType(0);
15569     SDValue Tmp1 = SDValue(Node, 0);
15570     SDValue Tmp2 = SDValue(Node, 1);
15571     SDValue Tmp3 = Node->getOperand(2);
15572     SDValue Chain = Tmp1.getOperand(0);
15573
15574     // Chain the dynamic stack allocation so that it doesn't modify the stack
15575     // pointer when other instructions are using the stack.
15576     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, dl, true),
15577         SDLoc(Node));
15578
15579     SDValue Size = Tmp2.getOperand(1);
15580     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
15581     Chain = SP.getValue(1);
15582     unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
15583     const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
15584     unsigned StackAlign = TFI.getStackAlignment();
15585     Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
15586     if (Align > StackAlign)
15587       Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
15588           DAG.getConstant(-(uint64_t)Align, dl, VT));
15589     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
15590
15591     Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
15592         DAG.getIntPtrConstant(0, dl, true), SDValue(),
15593         SDLoc(Node));
15594
15595     SDValue Ops[2] = { Tmp1, Tmp2 };
15596     return DAG.getMergeValues(Ops, dl);
15597   }
15598
15599   // Get the inputs.
15600   SDValue Chain = Op.getOperand(0);
15601   SDValue Size  = Op.getOperand(1);
15602   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
15603   EVT VT = Op.getNode()->getValueType(0);
15604
15605   bool Is64Bit = Subtarget->is64Bit();
15606   MVT SPTy = getPointerTy(DAG.getDataLayout());
15607
15608   if (SplitStack) {
15609     MachineRegisterInfo &MRI = MF.getRegInfo();
15610
15611     if (Is64Bit) {
15612       // The 64 bit implementation of segmented stacks needs to clobber both r10
15613       // r11. This makes it impossible to use it along with nested parameters.
15614       const Function *F = MF.getFunction();
15615
15616       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
15617            I != E; ++I)
15618         if (I->hasNestAttr())
15619           report_fatal_error("Cannot use segmented stacks with functions that "
15620                              "have nested arguments.");
15621     }
15622
15623     const TargetRegisterClass *AddrRegClass = getRegClassFor(SPTy);
15624     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
15625     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
15626     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
15627                                 DAG.getRegister(Vreg, SPTy));
15628     SDValue Ops1[2] = { Value, Chain };
15629     return DAG.getMergeValues(Ops1, dl);
15630   } else {
15631     SDValue Flag;
15632     const unsigned Reg = (Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX);
15633
15634     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
15635     Flag = Chain.getValue(1);
15636     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
15637
15638     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
15639
15640     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15641     unsigned SPReg = RegInfo->getStackRegister();
15642     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
15643     Chain = SP.getValue(1);
15644
15645     if (Align) {
15646       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
15647                        DAG.getConstant(-(uint64_t)Align, dl, VT));
15648       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
15649     }
15650
15651     SDValue Ops1[2] = { SP, Chain };
15652     return DAG.getMergeValues(Ops1, dl);
15653   }
15654 }
15655
15656 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
15657   MachineFunction &MF = DAG.getMachineFunction();
15658   auto PtrVT = getPointerTy(MF.getDataLayout());
15659   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
15660
15661   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
15662   SDLoc DL(Op);
15663
15664   if (!Subtarget->is64Bit() ||
15665       Subtarget->isCallingConvWin64(MF.getFunction()->getCallingConv())) {
15666     // vastart just stores the address of the VarArgsFrameIndex slot into the
15667     // memory location argument.
15668     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
15669     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
15670                         MachinePointerInfo(SV), false, false, 0);
15671   }
15672
15673   // __va_list_tag:
15674   //   gp_offset         (0 - 6 * 8)
15675   //   fp_offset         (48 - 48 + 8 * 16)
15676   //   overflow_arg_area (point to parameters coming in memory).
15677   //   reg_save_area
15678   SmallVector<SDValue, 8> MemOps;
15679   SDValue FIN = Op.getOperand(1);
15680   // Store gp_offset
15681   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
15682                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
15683                                                DL, MVT::i32),
15684                                FIN, MachinePointerInfo(SV), false, false, 0);
15685   MemOps.push_back(Store);
15686
15687   // Store fp_offset
15688   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
15689   Store = DAG.getStore(Op.getOperand(0), DL,
15690                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(), DL,
15691                                        MVT::i32),
15692                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
15693   MemOps.push_back(Store);
15694
15695   // Store ptr to overflow_arg_area
15696   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
15697   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
15698   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
15699                        MachinePointerInfo(SV, 8),
15700                        false, false, 0);
15701   MemOps.push_back(Store);
15702
15703   // Store ptr to reg_save_area.
15704   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(
15705       Subtarget->isTarget64BitLP64() ? 8 : 4, DL));
15706   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), PtrVT);
15707   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN, MachinePointerInfo(
15708       SV, Subtarget->isTarget64BitLP64() ? 16 : 12), false, false, 0);
15709   MemOps.push_back(Store);
15710   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
15711 }
15712
15713 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
15714   assert(Subtarget->is64Bit() &&
15715          "LowerVAARG only handles 64-bit va_arg!");
15716   assert(Op.getNode()->getNumOperands() == 4);
15717
15718   MachineFunction &MF = DAG.getMachineFunction();
15719   if (Subtarget->isCallingConvWin64(MF.getFunction()->getCallingConv()))
15720     // The Win64 ABI uses char* instead of a structure.
15721     return DAG.expandVAArg(Op.getNode());
15722
15723   SDValue Chain = Op.getOperand(0);
15724   SDValue SrcPtr = Op.getOperand(1);
15725   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
15726   unsigned Align = Op.getConstantOperandVal(3);
15727   SDLoc dl(Op);
15728
15729   EVT ArgVT = Op.getNode()->getValueType(0);
15730   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
15731   uint32_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
15732   uint8_t ArgMode;
15733
15734   // Decide which area this value should be read from.
15735   // TODO: Implement the AMD64 ABI in its entirety. This simple
15736   // selection mechanism works only for the basic types.
15737   if (ArgVT == MVT::f80) {
15738     llvm_unreachable("va_arg for f80 not yet implemented");
15739   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
15740     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
15741   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
15742     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
15743   } else {
15744     llvm_unreachable("Unhandled argument type in LowerVAARG");
15745   }
15746
15747   if (ArgMode == 2) {
15748     // Sanity Check: Make sure using fp_offset makes sense.
15749     assert(!Subtarget->useSoftFloat() &&
15750            !(MF.getFunction()->hasFnAttribute(Attribute::NoImplicitFloat)) &&
15751            Subtarget->hasSSE1());
15752   }
15753
15754   // Insert VAARG_64 node into the DAG
15755   // VAARG_64 returns two values: Variable Argument Address, Chain
15756   SDValue InstOps[] = {Chain, SrcPtr, DAG.getConstant(ArgSize, dl, MVT::i32),
15757                        DAG.getConstant(ArgMode, dl, MVT::i8),
15758                        DAG.getConstant(Align, dl, MVT::i32)};
15759   SDVTList VTs = DAG.getVTList(getPointerTy(DAG.getDataLayout()), MVT::Other);
15760   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
15761                                           VTs, InstOps, MVT::i64,
15762                                           MachinePointerInfo(SV),
15763                                           /*Align=*/0,
15764                                           /*Volatile=*/false,
15765                                           /*ReadMem=*/true,
15766                                           /*WriteMem=*/true);
15767   Chain = VAARG.getValue(1);
15768
15769   // Load the next argument and return it
15770   return DAG.getLoad(ArgVT, dl,
15771                      Chain,
15772                      VAARG,
15773                      MachinePointerInfo(),
15774                      false, false, false, 0);
15775 }
15776
15777 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
15778                            SelectionDAG &DAG) {
15779   // X86-64 va_list is a struct { i32, i32, i8*, i8* }, except on Windows,
15780   // where a va_list is still an i8*.
15781   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
15782   if (Subtarget->isCallingConvWin64(
15783         DAG.getMachineFunction().getFunction()->getCallingConv()))
15784     // Probably a Win64 va_copy.
15785     return DAG.expandVACopy(Op.getNode());
15786
15787   SDValue Chain = Op.getOperand(0);
15788   SDValue DstPtr = Op.getOperand(1);
15789   SDValue SrcPtr = Op.getOperand(2);
15790   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
15791   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
15792   SDLoc DL(Op);
15793
15794   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
15795                        DAG.getIntPtrConstant(24, DL), 8, /*isVolatile*/false,
15796                        false, false,
15797                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
15798 }
15799
15800 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
15801 // amount is a constant. Takes immediate version of shift as input.
15802 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
15803                                           SDValue SrcOp, uint64_t ShiftAmt,
15804                                           SelectionDAG &DAG) {
15805   MVT ElementType = VT.getVectorElementType();
15806
15807   // Fold this packed shift into its first operand if ShiftAmt is 0.
15808   if (ShiftAmt == 0)
15809     return SrcOp;
15810
15811   // Check for ShiftAmt >= element width
15812   if (ShiftAmt >= ElementType.getSizeInBits()) {
15813     if (Opc == X86ISD::VSRAI)
15814       ShiftAmt = ElementType.getSizeInBits() - 1;
15815     else
15816       return DAG.getConstant(0, dl, VT);
15817   }
15818
15819   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
15820          && "Unknown target vector shift-by-constant node");
15821
15822   // Fold this packed vector shift into a build vector if SrcOp is a
15823   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
15824   if (VT == SrcOp.getSimpleValueType() &&
15825       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
15826     SmallVector<SDValue, 8> Elts;
15827     unsigned NumElts = SrcOp->getNumOperands();
15828     ConstantSDNode *ND;
15829
15830     switch(Opc) {
15831     default: llvm_unreachable(nullptr);
15832     case X86ISD::VSHLI:
15833       for (unsigned i=0; i!=NumElts; ++i) {
15834         SDValue CurrentOp = SrcOp->getOperand(i);
15835         if (CurrentOp->getOpcode() == ISD::UNDEF) {
15836           Elts.push_back(CurrentOp);
15837           continue;
15838         }
15839         ND = cast<ConstantSDNode>(CurrentOp);
15840         const APInt &C = ND->getAPIntValue();
15841         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), dl, ElementType));
15842       }
15843       break;
15844     case X86ISD::VSRLI:
15845       for (unsigned i=0; i!=NumElts; ++i) {
15846         SDValue CurrentOp = SrcOp->getOperand(i);
15847         if (CurrentOp->getOpcode() == ISD::UNDEF) {
15848           Elts.push_back(CurrentOp);
15849           continue;
15850         }
15851         ND = cast<ConstantSDNode>(CurrentOp);
15852         const APInt &C = ND->getAPIntValue();
15853         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), dl, ElementType));
15854       }
15855       break;
15856     case X86ISD::VSRAI:
15857       for (unsigned i=0; i!=NumElts; ++i) {
15858         SDValue CurrentOp = SrcOp->getOperand(i);
15859         if (CurrentOp->getOpcode() == ISD::UNDEF) {
15860           Elts.push_back(CurrentOp);
15861           continue;
15862         }
15863         ND = cast<ConstantSDNode>(CurrentOp);
15864         const APInt &C = ND->getAPIntValue();
15865         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), dl, ElementType));
15866       }
15867       break;
15868     }
15869
15870     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
15871   }
15872
15873   return DAG.getNode(Opc, dl, VT, SrcOp,
15874                      DAG.getConstant(ShiftAmt, dl, MVT::i8));
15875 }
15876
15877 // getTargetVShiftNode - Handle vector element shifts where the shift amount
15878 // may or may not be a constant. Takes immediate version of shift as input.
15879 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
15880                                    SDValue SrcOp, SDValue ShAmt,
15881                                    SelectionDAG &DAG) {
15882   MVT SVT = ShAmt.getSimpleValueType();
15883   assert((SVT == MVT::i32 || SVT == MVT::i64) && "Unexpected value type!");
15884
15885   // Catch shift-by-constant.
15886   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
15887     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
15888                                       CShAmt->getZExtValue(), DAG);
15889
15890   // Change opcode to non-immediate version
15891   switch (Opc) {
15892     default: llvm_unreachable("Unknown target vector shift node");
15893     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
15894     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
15895     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
15896   }
15897
15898   const X86Subtarget &Subtarget =
15899       static_cast<const X86Subtarget &>(DAG.getSubtarget());
15900   if (Subtarget.hasSSE41() && ShAmt.getOpcode() == ISD::ZERO_EXTEND &&
15901       ShAmt.getOperand(0).getSimpleValueType() == MVT::i16) {
15902     // Let the shuffle legalizer expand this shift amount node.
15903     SDValue Op0 = ShAmt.getOperand(0);
15904     Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(Op0), MVT::v8i16, Op0);
15905     ShAmt = getShuffleVectorZeroOrUndef(Op0, 0, true, &Subtarget, DAG);
15906   } else {
15907     // Need to build a vector containing shift amount.
15908     // SSE/AVX packed shifts only use the lower 64-bit of the shift count.
15909     SmallVector<SDValue, 4> ShOps;
15910     ShOps.push_back(ShAmt);
15911     if (SVT == MVT::i32) {
15912       ShOps.push_back(DAG.getConstant(0, dl, SVT));
15913       ShOps.push_back(DAG.getUNDEF(SVT));
15914     }
15915     ShOps.push_back(DAG.getUNDEF(SVT));
15916
15917     MVT BVT = SVT == MVT::i32 ? MVT::v4i32 : MVT::v2i64;
15918     ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, BVT, ShOps);
15919   }
15920
15921   // The return type has to be a 128-bit type with the same element
15922   // type as the input type.
15923   MVT EltVT = VT.getVectorElementType();
15924   MVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
15925
15926   ShAmt = DAG.getBitcast(ShVT, ShAmt);
15927   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
15928 }
15929
15930 /// \brief Return (and \p Op, \p Mask) for compare instructions or
15931 /// (vselect \p Mask, \p Op, \p PreservedSrc) for others along with the
15932 /// necessary casting or extending for \p Mask when lowering masking intrinsics
15933 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
15934                                     SDValue PreservedSrc,
15935                                     const X86Subtarget *Subtarget,
15936                                     SelectionDAG &DAG) {
15937     MVT VT = Op.getSimpleValueType();
15938     MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
15939     SDValue VMask;
15940     unsigned OpcodeSelect = ISD::VSELECT;
15941     SDLoc dl(Op);
15942
15943     if (isAllOnes(Mask))
15944       return Op;
15945
15946     if (MaskVT.bitsGT(Mask.getSimpleValueType())) {
15947       MVT newMaskVT = MVT::getIntegerVT(MaskVT.getSizeInBits());
15948       VMask = DAG.getBitcast(MaskVT,
15949                              DAG.getNode(ISD::ANY_EXTEND, dl, newMaskVT, Mask));
15950     } else {
15951       MVT BitcastVT = MVT::getVectorVT(MVT::i1,
15952                                        Mask.getSimpleValueType().getSizeInBits());
15953       // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
15954       // are extracted by EXTRACT_SUBVECTOR.
15955       VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15956                           DAG.getBitcast(BitcastVT, Mask),
15957                           DAG.getIntPtrConstant(0, dl));
15958     }
15959
15960     switch (Op.getOpcode()) {
15961     default: break;
15962     case X86ISD::PCMPEQM:
15963     case X86ISD::PCMPGTM:
15964     case X86ISD::CMPM:
15965     case X86ISD::CMPMU:
15966       return DAG.getNode(ISD::AND, dl, VT, Op, VMask);
15967     case X86ISD::VFPCLASS:
15968       return DAG.getNode(ISD::OR, dl, VT, Op, VMask);
15969     case X86ISD::VTRUNC:
15970     case X86ISD::VTRUNCS:
15971     case X86ISD::VTRUNCUS:
15972       // We can't use ISD::VSELECT here because it is not always "Legal"
15973       // for the destination type. For example vpmovqb require only AVX512
15974       // and vselect that can operate on byte element type require BWI
15975       OpcodeSelect = X86ISD::SELECT;
15976       break;
15977     }
15978     if (PreservedSrc.getOpcode() == ISD::UNDEF)
15979       PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
15980     return DAG.getNode(OpcodeSelect, dl, VT, VMask, Op, PreservedSrc);
15981 }
15982
15983 /// \brief Creates an SDNode for a predicated scalar operation.
15984 /// \returns (X86vselect \p Mask, \p Op, \p PreservedSrc).
15985 /// The mask is coming as MVT::i8 and it should be truncated
15986 /// to MVT::i1 while lowering masking intrinsics.
15987 /// The main difference between ScalarMaskingNode and VectorMaskingNode is using
15988 /// "X86select" instead of "vselect". We just can't create the "vselect" node
15989 /// for a scalar instruction.
15990 static SDValue getScalarMaskingNode(SDValue Op, SDValue Mask,
15991                                     SDValue PreservedSrc,
15992                                     const X86Subtarget *Subtarget,
15993                                     SelectionDAG &DAG) {
15994   if (isAllOnes(Mask))
15995     return Op;
15996
15997   MVT VT = Op.getSimpleValueType();
15998   SDLoc dl(Op);
15999   // The mask should be of type MVT::i1
16000   SDValue IMask = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Mask);
16001
16002   if (Op.getOpcode() == X86ISD::FSETCC)
16003     return DAG.getNode(ISD::AND, dl, VT, Op, IMask);
16004   if (Op.getOpcode() == X86ISD::VFPCLASS)
16005     return DAG.getNode(ISD::OR, dl, VT, Op, IMask);
16006
16007   if (PreservedSrc.getOpcode() == ISD::UNDEF)
16008     PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
16009   return DAG.getNode(X86ISD::SELECT, dl, VT, IMask, Op, PreservedSrc);
16010 }
16011
16012 static int getSEHRegistrationNodeSize(const Function *Fn) {
16013   if (!Fn->hasPersonalityFn())
16014     report_fatal_error(
16015         "querying registration node size for function without personality");
16016   // The RegNodeSize is 6 32-bit words for SEH and 4 for C++ EH. See
16017   // WinEHStatePass for the full struct definition.
16018   switch (classifyEHPersonality(Fn->getPersonalityFn())) {
16019   case EHPersonality::MSVC_X86SEH: return 24;
16020   case EHPersonality::MSVC_CXX: return 16;
16021   default: break;
16022   }
16023   report_fatal_error("can only recover FP for MSVC EH personality functions");
16024 }
16025
16026 /// When the 32-bit MSVC runtime transfers control to us, either to an outlined
16027 /// function or when returning to a parent frame after catching an exception, we
16028 /// recover the parent frame pointer by doing arithmetic on the incoming EBP.
16029 /// Here's the math:
16030 ///   RegNodeBase = EntryEBP - RegNodeSize
16031 ///   ParentFP = RegNodeBase - RegNodeFrameOffset
16032 /// Subtracting RegNodeSize takes us to the offset of the registration node, and
16033 /// subtracting the offset (negative on x86) takes us back to the parent FP.
16034 static SDValue recoverFramePointer(SelectionDAG &DAG, const Function *Fn,
16035                                    SDValue EntryEBP) {
16036   MachineFunction &MF = DAG.getMachineFunction();
16037   SDLoc dl;
16038
16039   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16040   MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
16041
16042   // It's possible that the parent function no longer has a personality function
16043   // if the exceptional code was optimized away, in which case we just return
16044   // the incoming EBP.
16045   if (!Fn->hasPersonalityFn())
16046     return EntryEBP;
16047
16048   int RegNodeSize = getSEHRegistrationNodeSize(Fn);
16049
16050   // Get an MCSymbol that will ultimately resolve to the frame offset of the EH
16051   // registration.
16052   MCSymbol *OffsetSym =
16053       MF.getMMI().getContext().getOrCreateParentFrameOffsetSymbol(
16054           GlobalValue::getRealLinkageName(Fn->getName()));
16055   SDValue OffsetSymVal = DAG.getMCSymbol(OffsetSym, PtrVT);
16056   SDValue RegNodeFrameOffset =
16057       DAG.getNode(ISD::LOCAL_RECOVER, dl, PtrVT, OffsetSymVal);
16058
16059   // RegNodeBase = EntryEBP - RegNodeSize
16060   // ParentFP = RegNodeBase - RegNodeFrameOffset
16061   SDValue RegNodeBase = DAG.getNode(ISD::SUB, dl, PtrVT, EntryEBP,
16062                                     DAG.getConstant(RegNodeSize, dl, PtrVT));
16063   return DAG.getNode(ISD::SUB, dl, PtrVT, RegNodeBase, RegNodeFrameOffset);
16064 }
16065
16066 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
16067                                        SelectionDAG &DAG) {
16068   SDLoc dl(Op);
16069   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16070   MVT VT = Op.getSimpleValueType();
16071   const IntrinsicData* IntrData = getIntrinsicWithoutChain(IntNo);
16072   if (IntrData) {
16073     switch(IntrData->Type) {
16074     case INTR_TYPE_1OP:
16075       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1));
16076     case INTR_TYPE_2OP:
16077       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
16078         Op.getOperand(2));
16079     case INTR_TYPE_2OP_IMM8:
16080       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
16081                          DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op.getOperand(2)));
16082     case INTR_TYPE_3OP:
16083       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
16084         Op.getOperand(2), Op.getOperand(3));
16085     case INTR_TYPE_4OP:
16086       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
16087         Op.getOperand(2), Op.getOperand(3), Op.getOperand(4));
16088     case INTR_TYPE_1OP_MASK_RM: {
16089       SDValue Src = Op.getOperand(1);
16090       SDValue PassThru = Op.getOperand(2);
16091       SDValue Mask = Op.getOperand(3);
16092       SDValue RoundingMode;
16093       // We allways add rounding mode to the Node.
16094       // If the rounding mode is not specified, we add the
16095       // "current direction" mode.
16096       if (Op.getNumOperands() == 4)
16097         RoundingMode =
16098           DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
16099       else
16100         RoundingMode = Op.getOperand(4);
16101       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16102       if (IntrWithRoundingModeOpcode != 0)
16103         if (cast<ConstantSDNode>(RoundingMode)->getZExtValue() !=
16104             X86::STATIC_ROUNDING::CUR_DIRECTION)
16105           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16106                                       dl, Op.getValueType(), Src, RoundingMode),
16107                                       Mask, PassThru, Subtarget, DAG);
16108       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src,
16109                                               RoundingMode),
16110                                   Mask, PassThru, Subtarget, DAG);
16111     }
16112     case INTR_TYPE_1OP_MASK: {
16113       SDValue Src = Op.getOperand(1);
16114       SDValue PassThru = Op.getOperand(2);
16115       SDValue Mask = Op.getOperand(3);
16116       // We add rounding mode to the Node when
16117       //   - RM Opcode is specified and
16118       //   - RM is not "current direction".
16119       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16120       if (IntrWithRoundingModeOpcode != 0) {
16121         SDValue Rnd = Op.getOperand(4);
16122         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
16123         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
16124           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16125                                       dl, Op.getValueType(),
16126                                       Src, Rnd),
16127                                       Mask, PassThru, Subtarget, DAG);
16128         }
16129       }
16130       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src),
16131                                   Mask, PassThru, Subtarget, DAG);
16132     }
16133     case INTR_TYPE_SCALAR_MASK: {
16134       SDValue Src1 = Op.getOperand(1);
16135       SDValue Src2 = Op.getOperand(2);
16136       SDValue passThru = Op.getOperand(3);
16137       SDValue Mask = Op.getOperand(4);
16138       return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2),
16139                                   Mask, passThru, Subtarget, DAG);
16140     }
16141     case INTR_TYPE_SCALAR_MASK_RM: {
16142       SDValue Src1 = Op.getOperand(1);
16143       SDValue Src2 = Op.getOperand(2);
16144       SDValue Src0 = Op.getOperand(3);
16145       SDValue Mask = Op.getOperand(4);
16146       // There are 2 kinds of intrinsics in this group:
16147       // (1) With suppress-all-exceptions (sae) or rounding mode- 6 operands
16148       // (2) With rounding mode and sae - 7 operands.
16149       if (Op.getNumOperands() == 6) {
16150         SDValue Sae  = Op.getOperand(5);
16151         unsigned Opc = IntrData->Opc1 ? IntrData->Opc1 : IntrData->Opc0;
16152         return getScalarMaskingNode(DAG.getNode(Opc, dl, VT, Src1, Src2,
16153                                                 Sae),
16154                                     Mask, Src0, Subtarget, DAG);
16155       }
16156       assert(Op.getNumOperands() == 7 && "Unexpected intrinsic form");
16157       SDValue RoundingMode  = Op.getOperand(5);
16158       SDValue Sae  = Op.getOperand(6);
16159       return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
16160                                               RoundingMode, Sae),
16161                                   Mask, Src0, Subtarget, DAG);
16162     }
16163     case INTR_TYPE_2OP_MASK:
16164     case INTR_TYPE_2OP_IMM8_MASK: {
16165       SDValue Src1 = Op.getOperand(1);
16166       SDValue Src2 = Op.getOperand(2);
16167       SDValue PassThru = Op.getOperand(3);
16168       SDValue Mask = Op.getOperand(4);
16169
16170       if (IntrData->Type == INTR_TYPE_2OP_IMM8_MASK)
16171         Src2 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Src2);
16172
16173       // We specify 2 possible opcodes for intrinsics with rounding modes.
16174       // First, we check if the intrinsic may have non-default rounding mode,
16175       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
16176       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16177       if (IntrWithRoundingModeOpcode != 0) {
16178         SDValue Rnd = Op.getOperand(5);
16179         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
16180         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
16181           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16182                                       dl, Op.getValueType(),
16183                                       Src1, Src2, Rnd),
16184                                       Mask, PassThru, Subtarget, DAG);
16185         }
16186       }
16187       // TODO: Intrinsics should have fast-math-flags to propagate.
16188       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,Src1,Src2),
16189                                   Mask, PassThru, Subtarget, DAG);
16190     }
16191     case INTR_TYPE_2OP_MASK_RM: {
16192       SDValue Src1 = Op.getOperand(1);
16193       SDValue Src2 = Op.getOperand(2);
16194       SDValue PassThru = Op.getOperand(3);
16195       SDValue Mask = Op.getOperand(4);
16196       // We specify 2 possible modes for intrinsics, with/without rounding
16197       // modes.
16198       // First, we check if the intrinsic have rounding mode (6 operands),
16199       // if not, we set rounding mode to "current".
16200       SDValue Rnd;
16201       if (Op.getNumOperands() == 6)
16202         Rnd = Op.getOperand(5);
16203       else
16204         Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
16205       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16206                                               Src1, Src2, Rnd),
16207                                   Mask, PassThru, Subtarget, DAG);
16208     }
16209     case INTR_TYPE_3OP_SCALAR_MASK_RM: {
16210       SDValue Src1 = Op.getOperand(1);
16211       SDValue Src2 = Op.getOperand(2);
16212       SDValue Src3 = Op.getOperand(3);
16213       SDValue PassThru = Op.getOperand(4);
16214       SDValue Mask = Op.getOperand(5);
16215       SDValue Sae  = Op.getOperand(6);
16216
16217       return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1,
16218                                               Src2, Src3, Sae),
16219                                   Mask, PassThru, Subtarget, DAG);
16220     }
16221     case INTR_TYPE_3OP_MASK_RM: {
16222       SDValue Src1 = Op.getOperand(1);
16223       SDValue Src2 = Op.getOperand(2);
16224       SDValue Imm = Op.getOperand(3);
16225       SDValue PassThru = Op.getOperand(4);
16226       SDValue Mask = Op.getOperand(5);
16227       // We specify 2 possible modes for intrinsics, with/without rounding
16228       // modes.
16229       // First, we check if the intrinsic have rounding mode (7 operands),
16230       // if not, we set rounding mode to "current".
16231       SDValue Rnd;
16232       if (Op.getNumOperands() == 7)
16233         Rnd = Op.getOperand(6);
16234       else
16235         Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
16236       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16237         Src1, Src2, Imm, Rnd),
16238         Mask, PassThru, Subtarget, DAG);
16239     }
16240     case INTR_TYPE_3OP_IMM8_MASK:
16241     case INTR_TYPE_3OP_MASK:
16242     case INSERT_SUBVEC: {
16243       SDValue Src1 = Op.getOperand(1);
16244       SDValue Src2 = Op.getOperand(2);
16245       SDValue Src3 = Op.getOperand(3);
16246       SDValue PassThru = Op.getOperand(4);
16247       SDValue Mask = Op.getOperand(5);
16248
16249       if (IntrData->Type == INTR_TYPE_3OP_IMM8_MASK)
16250         Src3 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Src3);
16251       else if (IntrData->Type == INSERT_SUBVEC) {
16252         // imm should be adapted to ISD::INSERT_SUBVECTOR behavior
16253         assert(isa<ConstantSDNode>(Src3) && "Expected a ConstantSDNode here!");
16254         unsigned Imm = cast<ConstantSDNode>(Src3)->getZExtValue();
16255         Imm *= Src2.getSimpleValueType().getVectorNumElements();
16256         Src3 = DAG.getTargetConstant(Imm, dl, MVT::i32);
16257       }
16258
16259       // We specify 2 possible opcodes for intrinsics with rounding modes.
16260       // First, we check if the intrinsic may have non-default rounding mode,
16261       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
16262       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16263       if (IntrWithRoundingModeOpcode != 0) {
16264         SDValue Rnd = Op.getOperand(6);
16265         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
16266         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
16267           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16268                                       dl, Op.getValueType(),
16269                                       Src1, Src2, Src3, Rnd),
16270                                       Mask, PassThru, Subtarget, DAG);
16271         }
16272       }
16273       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16274                                               Src1, Src2, Src3),
16275                                   Mask, PassThru, Subtarget, DAG);
16276     }
16277     case VPERM_3OP_MASKZ:
16278     case VPERM_3OP_MASK:
16279     case FMA_OP_MASK3:
16280     case FMA_OP_MASKZ:
16281     case FMA_OP_MASK: {
16282       SDValue Src1 = Op.getOperand(1);
16283       SDValue Src2 = Op.getOperand(2);
16284       SDValue Src3 = Op.getOperand(3);
16285       SDValue Mask = Op.getOperand(4);
16286       MVT VT = Op.getSimpleValueType();
16287       SDValue PassThru = SDValue();
16288
16289       // set PassThru element
16290       if (IntrData->Type == VPERM_3OP_MASKZ || IntrData->Type == FMA_OP_MASKZ)
16291         PassThru = getZeroVector(VT, Subtarget, DAG, dl);
16292       else if (IntrData->Type == FMA_OP_MASK3)
16293         PassThru = Src3;
16294       else
16295         PassThru = Src1;
16296
16297       // We specify 2 possible opcodes for intrinsics with rounding modes.
16298       // First, we check if the intrinsic may have non-default rounding mode,
16299       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
16300       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16301       if (IntrWithRoundingModeOpcode != 0) {
16302         SDValue Rnd = Op.getOperand(5);
16303         if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
16304             X86::STATIC_ROUNDING::CUR_DIRECTION)
16305           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16306                                                   dl, Op.getValueType(),
16307                                                   Src1, Src2, Src3, Rnd),
16308                                       Mask, PassThru, Subtarget, DAG);
16309       }
16310       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0,
16311                                               dl, Op.getValueType(),
16312                                               Src1, Src2, Src3),
16313                                   Mask, PassThru, Subtarget, DAG);
16314     }
16315     case TERLOG_OP_MASK:
16316     case TERLOG_OP_MASKZ: {
16317       SDValue Src1 = Op.getOperand(1);
16318       SDValue Src2 = Op.getOperand(2);
16319       SDValue Src3 = Op.getOperand(3);
16320       SDValue Src4 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op.getOperand(4));
16321       SDValue Mask = Op.getOperand(5);
16322       MVT VT = Op.getSimpleValueType();
16323       SDValue PassThru = Src1;
16324       // Set PassThru element.
16325       if (IntrData->Type == TERLOG_OP_MASKZ)
16326         PassThru = getZeroVector(VT, Subtarget, DAG, dl);
16327
16328       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16329                                               Src1, Src2, Src3, Src4),
16330                                   Mask, PassThru, Subtarget, DAG);
16331     }
16332     case FPCLASS: {
16333       // FPclass intrinsics with mask
16334        SDValue Src1 = Op.getOperand(1);
16335        MVT VT = Src1.getSimpleValueType();
16336        MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
16337        SDValue Imm = Op.getOperand(2);
16338        SDValue Mask = Op.getOperand(3);
16339        MVT BitcastVT = MVT::getVectorVT(MVT::i1,
16340                                      Mask.getSimpleValueType().getSizeInBits());
16341        SDValue FPclass = DAG.getNode(IntrData->Opc0, dl, MaskVT, Src1, Imm);
16342        SDValue FPclassMask = getVectorMaskingNode(FPclass, Mask,
16343                                                  DAG.getTargetConstant(0, dl, MaskVT),
16344                                                  Subtarget, DAG);
16345        SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
16346                                  DAG.getUNDEF(BitcastVT), FPclassMask,
16347                                  DAG.getIntPtrConstant(0, dl));
16348        return DAG.getBitcast(Op.getValueType(), Res);
16349     }
16350     case FPCLASSS: {
16351       SDValue Src1 = Op.getOperand(1);
16352       SDValue Imm = Op.getOperand(2);
16353       SDValue Mask = Op.getOperand(3);
16354       SDValue FPclass = DAG.getNode(IntrData->Opc0, dl, MVT::i1, Src1, Imm);
16355       SDValue FPclassMask = getScalarMaskingNode(FPclass, Mask,
16356         DAG.getTargetConstant(0, dl, MVT::i1), Subtarget, DAG);
16357       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i8, FPclassMask);
16358     }
16359     case CMP_MASK:
16360     case CMP_MASK_CC: {
16361       // Comparison intrinsics with masks.
16362       // Example of transformation:
16363       // (i8 (int_x86_avx512_mask_pcmpeq_q_128
16364       //             (v2i64 %a), (v2i64 %b), (i8 %mask))) ->
16365       // (i8 (bitcast
16366       //   (v8i1 (insert_subvector undef,
16367       //           (v2i1 (and (PCMPEQM %a, %b),
16368       //                      (extract_subvector
16369       //                         (v8i1 (bitcast %mask)), 0))), 0))))
16370       MVT VT = Op.getOperand(1).getSimpleValueType();
16371       MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
16372       SDValue Mask = Op.getOperand((IntrData->Type == CMP_MASK_CC) ? 4 : 3);
16373       MVT BitcastVT = MVT::getVectorVT(MVT::i1,
16374                                        Mask.getSimpleValueType().getSizeInBits());
16375       SDValue Cmp;
16376       if (IntrData->Type == CMP_MASK_CC) {
16377         SDValue CC = Op.getOperand(3);
16378         CC = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, CC);
16379         // We specify 2 possible opcodes for intrinsics with rounding modes.
16380         // First, we check if the intrinsic may have non-default rounding mode,
16381         // (IntrData->Opc1 != 0), then we check the rounding mode operand.
16382         if (IntrData->Opc1 != 0) {
16383           SDValue Rnd = Op.getOperand(5);
16384           if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
16385               X86::STATIC_ROUNDING::CUR_DIRECTION)
16386             Cmp = DAG.getNode(IntrData->Opc1, dl, MaskVT, Op.getOperand(1),
16387                               Op.getOperand(2), CC, Rnd);
16388         }
16389         //default rounding mode
16390         if(!Cmp.getNode())
16391             Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
16392                               Op.getOperand(2), CC);
16393
16394       } else {
16395         assert(IntrData->Type == CMP_MASK && "Unexpected intrinsic type!");
16396         Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
16397                           Op.getOperand(2));
16398       }
16399       SDValue CmpMask = getVectorMaskingNode(Cmp, Mask,
16400                                              DAG.getTargetConstant(0, dl,
16401                                                                    MaskVT),
16402                                              Subtarget, DAG);
16403       SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
16404                                 DAG.getUNDEF(BitcastVT), CmpMask,
16405                                 DAG.getIntPtrConstant(0, dl));
16406       return DAG.getBitcast(Op.getValueType(), Res);
16407     }
16408     case CMP_MASK_SCALAR_CC: {
16409       SDValue Src1 = Op.getOperand(1);
16410       SDValue Src2 = Op.getOperand(2);
16411       SDValue CC = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op.getOperand(3));
16412       SDValue Mask = Op.getOperand(4);
16413
16414       SDValue Cmp;
16415       if (IntrData->Opc1 != 0) {
16416         SDValue Rnd = Op.getOperand(5);
16417         if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
16418             X86::STATIC_ROUNDING::CUR_DIRECTION)
16419           Cmp = DAG.getNode(IntrData->Opc1, dl, MVT::i1, Src1, Src2, CC, Rnd);
16420       }
16421       //default rounding mode
16422       if(!Cmp.getNode())
16423         Cmp = DAG.getNode(IntrData->Opc0, dl, MVT::i1, Src1, Src2, CC);
16424
16425       SDValue CmpMask = getScalarMaskingNode(Cmp, Mask,
16426                                              DAG.getTargetConstant(0, dl,
16427                                                                    MVT::i1),
16428                                              Subtarget, DAG);
16429
16430       return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::i8,
16431                          DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i8, CmpMask),
16432                          DAG.getValueType(MVT::i1));
16433     }
16434     case COMI: { // Comparison intrinsics
16435       ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
16436       SDValue LHS = Op.getOperand(1);
16437       SDValue RHS = Op.getOperand(2);
16438       unsigned X86CC = TranslateX86CC(CC, dl, true, LHS, RHS, DAG);
16439       assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
16440       SDValue Cond = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
16441       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16442                                   DAG.getConstant(X86CC, dl, MVT::i8), Cond);
16443       return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16444     }
16445     case VSHIFT:
16446       return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
16447                                  Op.getOperand(1), Op.getOperand(2), DAG);
16448     case VSHIFT_MASK:
16449       return getVectorMaskingNode(getTargetVShiftNode(IntrData->Opc0, dl,
16450                                                       Op.getSimpleValueType(),
16451                                                       Op.getOperand(1),
16452                                                       Op.getOperand(2), DAG),
16453                                   Op.getOperand(4), Op.getOperand(3), Subtarget,
16454                                   DAG);
16455     case COMPRESS_EXPAND_IN_REG: {
16456       SDValue Mask = Op.getOperand(3);
16457       SDValue DataToCompress = Op.getOperand(1);
16458       SDValue PassThru = Op.getOperand(2);
16459       if (isAllOnes(Mask)) // return data as is
16460         return Op.getOperand(1);
16461
16462       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16463                                               DataToCompress),
16464                                   Mask, PassThru, Subtarget, DAG);
16465     }
16466     case BLEND: {
16467       SDValue Mask = Op.getOperand(3);
16468       MVT VT = Op.getSimpleValueType();
16469       MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
16470       MVT BitcastVT = MVT::getVectorVT(MVT::i1,
16471                                        Mask.getSimpleValueType().getSizeInBits());
16472       SDLoc dl(Op);
16473       SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16474                                   DAG.getBitcast(BitcastVT, Mask),
16475                                   DAG.getIntPtrConstant(0, dl));
16476       return DAG.getNode(IntrData->Opc0, dl, VT, VMask, Op.getOperand(1),
16477                          Op.getOperand(2));
16478     }
16479     default:
16480       break;
16481     }
16482   }
16483
16484   switch (IntNo) {
16485   default: return SDValue();    // Don't custom lower most intrinsics.
16486
16487   case Intrinsic::x86_avx2_permd:
16488   case Intrinsic::x86_avx2_permps:
16489     // Operands intentionally swapped. Mask is last operand to intrinsic,
16490     // but second operand for node/instruction.
16491     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
16492                        Op.getOperand(2), Op.getOperand(1));
16493
16494   // ptest and testp intrinsics. The intrinsic these come from are designed to
16495   // return an integer value, not just an instruction so lower it to the ptest
16496   // or testp pattern and a setcc for the result.
16497   case Intrinsic::x86_sse41_ptestz:
16498   case Intrinsic::x86_sse41_ptestc:
16499   case Intrinsic::x86_sse41_ptestnzc:
16500   case Intrinsic::x86_avx_ptestz_256:
16501   case Intrinsic::x86_avx_ptestc_256:
16502   case Intrinsic::x86_avx_ptestnzc_256:
16503   case Intrinsic::x86_avx_vtestz_ps:
16504   case Intrinsic::x86_avx_vtestc_ps:
16505   case Intrinsic::x86_avx_vtestnzc_ps:
16506   case Intrinsic::x86_avx_vtestz_pd:
16507   case Intrinsic::x86_avx_vtestc_pd:
16508   case Intrinsic::x86_avx_vtestnzc_pd:
16509   case Intrinsic::x86_avx_vtestz_ps_256:
16510   case Intrinsic::x86_avx_vtestc_ps_256:
16511   case Intrinsic::x86_avx_vtestnzc_ps_256:
16512   case Intrinsic::x86_avx_vtestz_pd_256:
16513   case Intrinsic::x86_avx_vtestc_pd_256:
16514   case Intrinsic::x86_avx_vtestnzc_pd_256: {
16515     bool IsTestPacked = false;
16516     unsigned X86CC;
16517     switch (IntNo) {
16518     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
16519     case Intrinsic::x86_avx_vtestz_ps:
16520     case Intrinsic::x86_avx_vtestz_pd:
16521     case Intrinsic::x86_avx_vtestz_ps_256:
16522     case Intrinsic::x86_avx_vtestz_pd_256:
16523       IsTestPacked = true; // Fallthrough
16524     case Intrinsic::x86_sse41_ptestz:
16525     case Intrinsic::x86_avx_ptestz_256:
16526       // ZF = 1
16527       X86CC = X86::COND_E;
16528       break;
16529     case Intrinsic::x86_avx_vtestc_ps:
16530     case Intrinsic::x86_avx_vtestc_pd:
16531     case Intrinsic::x86_avx_vtestc_ps_256:
16532     case Intrinsic::x86_avx_vtestc_pd_256:
16533       IsTestPacked = true; // Fallthrough
16534     case Intrinsic::x86_sse41_ptestc:
16535     case Intrinsic::x86_avx_ptestc_256:
16536       // CF = 1
16537       X86CC = X86::COND_B;
16538       break;
16539     case Intrinsic::x86_avx_vtestnzc_ps:
16540     case Intrinsic::x86_avx_vtestnzc_pd:
16541     case Intrinsic::x86_avx_vtestnzc_ps_256:
16542     case Intrinsic::x86_avx_vtestnzc_pd_256:
16543       IsTestPacked = true; // Fallthrough
16544     case Intrinsic::x86_sse41_ptestnzc:
16545     case Intrinsic::x86_avx_ptestnzc_256:
16546       // ZF and CF = 0
16547       X86CC = X86::COND_A;
16548       break;
16549     }
16550
16551     SDValue LHS = Op.getOperand(1);
16552     SDValue RHS = Op.getOperand(2);
16553     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
16554     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
16555     SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
16556     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
16557     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16558   }
16559   case Intrinsic::x86_avx512_kortestz_w:
16560   case Intrinsic::x86_avx512_kortestc_w: {
16561     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
16562     SDValue LHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(1));
16563     SDValue RHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(2));
16564     SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
16565     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
16566     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
16567     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16568   }
16569
16570   case Intrinsic::x86_sse42_pcmpistria128:
16571   case Intrinsic::x86_sse42_pcmpestria128:
16572   case Intrinsic::x86_sse42_pcmpistric128:
16573   case Intrinsic::x86_sse42_pcmpestric128:
16574   case Intrinsic::x86_sse42_pcmpistrio128:
16575   case Intrinsic::x86_sse42_pcmpestrio128:
16576   case Intrinsic::x86_sse42_pcmpistris128:
16577   case Intrinsic::x86_sse42_pcmpestris128:
16578   case Intrinsic::x86_sse42_pcmpistriz128:
16579   case Intrinsic::x86_sse42_pcmpestriz128: {
16580     unsigned Opcode;
16581     unsigned X86CC;
16582     switch (IntNo) {
16583     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
16584     case Intrinsic::x86_sse42_pcmpistria128:
16585       Opcode = X86ISD::PCMPISTRI;
16586       X86CC = X86::COND_A;
16587       break;
16588     case Intrinsic::x86_sse42_pcmpestria128:
16589       Opcode = X86ISD::PCMPESTRI;
16590       X86CC = X86::COND_A;
16591       break;
16592     case Intrinsic::x86_sse42_pcmpistric128:
16593       Opcode = X86ISD::PCMPISTRI;
16594       X86CC = X86::COND_B;
16595       break;
16596     case Intrinsic::x86_sse42_pcmpestric128:
16597       Opcode = X86ISD::PCMPESTRI;
16598       X86CC = X86::COND_B;
16599       break;
16600     case Intrinsic::x86_sse42_pcmpistrio128:
16601       Opcode = X86ISD::PCMPISTRI;
16602       X86CC = X86::COND_O;
16603       break;
16604     case Intrinsic::x86_sse42_pcmpestrio128:
16605       Opcode = X86ISD::PCMPESTRI;
16606       X86CC = X86::COND_O;
16607       break;
16608     case Intrinsic::x86_sse42_pcmpistris128:
16609       Opcode = X86ISD::PCMPISTRI;
16610       X86CC = X86::COND_S;
16611       break;
16612     case Intrinsic::x86_sse42_pcmpestris128:
16613       Opcode = X86ISD::PCMPESTRI;
16614       X86CC = X86::COND_S;
16615       break;
16616     case Intrinsic::x86_sse42_pcmpistriz128:
16617       Opcode = X86ISD::PCMPISTRI;
16618       X86CC = X86::COND_E;
16619       break;
16620     case Intrinsic::x86_sse42_pcmpestriz128:
16621       Opcode = X86ISD::PCMPESTRI;
16622       X86CC = X86::COND_E;
16623       break;
16624     }
16625     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
16626     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
16627     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
16628     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16629                                 DAG.getConstant(X86CC, dl, MVT::i8),
16630                                 SDValue(PCMP.getNode(), 1));
16631     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16632   }
16633
16634   case Intrinsic::x86_sse42_pcmpistri128:
16635   case Intrinsic::x86_sse42_pcmpestri128: {
16636     unsigned Opcode;
16637     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
16638       Opcode = X86ISD::PCMPISTRI;
16639     else
16640       Opcode = X86ISD::PCMPESTRI;
16641
16642     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
16643     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
16644     return DAG.getNode(Opcode, dl, VTs, NewOps);
16645   }
16646
16647   case Intrinsic::x86_seh_lsda: {
16648     // Compute the symbol for the LSDA. We know it'll get emitted later.
16649     MachineFunction &MF = DAG.getMachineFunction();
16650     SDValue Op1 = Op.getOperand(1);
16651     auto *Fn = cast<Function>(cast<GlobalAddressSDNode>(Op1)->getGlobal());
16652     MCSymbol *LSDASym = MF.getMMI().getContext().getOrCreateLSDASymbol(
16653         GlobalValue::getRealLinkageName(Fn->getName()));
16654
16655     // Generate a simple absolute symbol reference. This intrinsic is only
16656     // supported on 32-bit Windows, which isn't PIC.
16657     SDValue Result = DAG.getMCSymbol(LSDASym, VT);
16658     return DAG.getNode(X86ISD::Wrapper, dl, VT, Result);
16659   }
16660
16661   case Intrinsic::x86_seh_recoverfp: {
16662     SDValue FnOp = Op.getOperand(1);
16663     SDValue IncomingFPOp = Op.getOperand(2);
16664     GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(FnOp);
16665     auto *Fn = dyn_cast_or_null<Function>(GSD ? GSD->getGlobal() : nullptr);
16666     if (!Fn)
16667       report_fatal_error(
16668           "llvm.x86.seh.recoverfp must take a function as the first argument");
16669     return recoverFramePointer(DAG, Fn, IncomingFPOp);
16670   }
16671
16672   case Intrinsic::localaddress: {
16673     // Returns one of the stack, base, or frame pointer registers, depending on
16674     // which is used to reference local variables.
16675     MachineFunction &MF = DAG.getMachineFunction();
16676     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16677     unsigned Reg;
16678     if (RegInfo->hasBasePointer(MF))
16679       Reg = RegInfo->getBaseRegister();
16680     else // This function handles the SP or FP case.
16681       Reg = RegInfo->getPtrSizedFrameRegister(MF);
16682     return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
16683   }
16684   }
16685 }
16686
16687 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
16688                               SDValue Src, SDValue Mask, SDValue Base,
16689                               SDValue Index, SDValue ScaleOp, SDValue Chain,
16690                               const X86Subtarget * Subtarget) {
16691   SDLoc dl(Op);
16692   auto *C = cast<ConstantSDNode>(ScaleOp);
16693   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
16694   MVT MaskVT = MVT::getVectorVT(MVT::i1,
16695                              Index.getSimpleValueType().getVectorNumElements());
16696   SDValue MaskInReg;
16697   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
16698   if (MaskC)
16699     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
16700   else {
16701     MVT BitcastVT = MVT::getVectorVT(MVT::i1,
16702                                      Mask.getSimpleValueType().getSizeInBits());
16703
16704     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
16705     // are extracted by EXTRACT_SUBVECTOR.
16706     MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16707                             DAG.getBitcast(BitcastVT, Mask),
16708                             DAG.getIntPtrConstant(0, dl));
16709   }
16710   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
16711   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
16712   SDValue Segment = DAG.getRegister(0, MVT::i32);
16713   if (Src.getOpcode() == ISD::UNDEF)
16714     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
16715   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
16716   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
16717   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
16718   return DAG.getMergeValues(RetOps, dl);
16719 }
16720
16721 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
16722                                SDValue Src, SDValue Mask, SDValue Base,
16723                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
16724   SDLoc dl(Op);
16725   auto *C = cast<ConstantSDNode>(ScaleOp);
16726   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
16727   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
16728   SDValue Segment = DAG.getRegister(0, MVT::i32);
16729   MVT MaskVT = MVT::getVectorVT(MVT::i1,
16730                              Index.getSimpleValueType().getVectorNumElements());
16731   SDValue MaskInReg;
16732   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
16733   if (MaskC)
16734     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
16735   else {
16736     MVT BitcastVT = MVT::getVectorVT(MVT::i1,
16737                                      Mask.getSimpleValueType().getSizeInBits());
16738
16739     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
16740     // are extracted by EXTRACT_SUBVECTOR.
16741     MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16742                             DAG.getBitcast(BitcastVT, Mask),
16743                             DAG.getIntPtrConstant(0, dl));
16744   }
16745   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
16746   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
16747   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
16748   return SDValue(Res, 1);
16749 }
16750
16751 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
16752                                SDValue Mask, SDValue Base, SDValue Index,
16753                                SDValue ScaleOp, SDValue Chain) {
16754   SDLoc dl(Op);
16755   auto *C = cast<ConstantSDNode>(ScaleOp);
16756   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
16757   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
16758   SDValue Segment = DAG.getRegister(0, MVT::i32);
16759   MVT MaskVT =
16760     MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
16761   SDValue MaskInReg;
16762   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
16763   if (MaskC)
16764     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
16765   else
16766     MaskInReg = DAG.getBitcast(MaskVT, Mask);
16767   //SDVTList VTs = DAG.getVTList(MVT::Other);
16768   SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
16769   SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
16770   return SDValue(Res, 0);
16771 }
16772
16773 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
16774 // read performance monitor counters (x86_rdpmc).
16775 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
16776                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
16777                               SmallVectorImpl<SDValue> &Results) {
16778   assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
16779   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16780   SDValue LO, HI;
16781
16782   // The ECX register is used to select the index of the performance counter
16783   // to read.
16784   SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
16785                                    N->getOperand(2));
16786   SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
16787
16788   // Reads the content of a 64-bit performance counter and returns it in the
16789   // registers EDX:EAX.
16790   if (Subtarget->is64Bit()) {
16791     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
16792     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
16793                             LO.getValue(2));
16794   } else {
16795     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
16796     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
16797                             LO.getValue(2));
16798   }
16799   Chain = HI.getValue(1);
16800
16801   if (Subtarget->is64Bit()) {
16802     // The EAX register is loaded with the low-order 32 bits. The EDX register
16803     // is loaded with the supported high-order bits of the counter.
16804     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
16805                               DAG.getConstant(32, DL, MVT::i8));
16806     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
16807     Results.push_back(Chain);
16808     return;
16809   }
16810
16811   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
16812   SDValue Ops[] = { LO, HI };
16813   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
16814   Results.push_back(Pair);
16815   Results.push_back(Chain);
16816 }
16817
16818 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
16819 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
16820 // also used to custom lower READCYCLECOUNTER nodes.
16821 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
16822                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
16823                               SmallVectorImpl<SDValue> &Results) {
16824   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16825   SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
16826   SDValue LO, HI;
16827
16828   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
16829   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
16830   // and the EAX register is loaded with the low-order 32 bits.
16831   if (Subtarget->is64Bit()) {
16832     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
16833     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
16834                             LO.getValue(2));
16835   } else {
16836     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
16837     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
16838                             LO.getValue(2));
16839   }
16840   SDValue Chain = HI.getValue(1);
16841
16842   if (Opcode == X86ISD::RDTSCP_DAG) {
16843     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
16844
16845     // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
16846     // the ECX register. Add 'ecx' explicitly to the chain.
16847     SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
16848                                      HI.getValue(2));
16849     // Explicitly store the content of ECX at the location passed in input
16850     // to the 'rdtscp' intrinsic.
16851     Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
16852                          MachinePointerInfo(), false, false, 0);
16853   }
16854
16855   if (Subtarget->is64Bit()) {
16856     // The EDX register is loaded with the high-order 32 bits of the MSR, and
16857     // the EAX register is loaded with the low-order 32 bits.
16858     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
16859                               DAG.getConstant(32, DL, MVT::i8));
16860     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
16861     Results.push_back(Chain);
16862     return;
16863   }
16864
16865   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
16866   SDValue Ops[] = { LO, HI };
16867   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
16868   Results.push_back(Pair);
16869   Results.push_back(Chain);
16870 }
16871
16872 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
16873                                      SelectionDAG &DAG) {
16874   SmallVector<SDValue, 2> Results;
16875   SDLoc DL(Op);
16876   getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
16877                           Results);
16878   return DAG.getMergeValues(Results, DL);
16879 }
16880
16881 static SDValue LowerSEHRESTOREFRAME(SDValue Op, const X86Subtarget *Subtarget,
16882                                     SelectionDAG &DAG) {
16883   MachineFunction &MF = DAG.getMachineFunction();
16884   const Function *Fn = MF.getFunction();
16885   SDLoc dl(Op);
16886   SDValue Chain = Op.getOperand(0);
16887
16888   assert(Subtarget->getFrameLowering()->hasFP(MF) &&
16889          "using llvm.x86.seh.restoreframe requires a frame pointer");
16890
16891   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16892   MVT VT = TLI.getPointerTy(DAG.getDataLayout());
16893
16894   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16895   unsigned FrameReg =
16896       RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
16897   unsigned SPReg = RegInfo->getStackRegister();
16898   unsigned SlotSize = RegInfo->getSlotSize();
16899
16900   // Get incoming EBP.
16901   SDValue IncomingEBP =
16902       DAG.getCopyFromReg(Chain, dl, FrameReg, VT);
16903
16904   // SP is saved in the first field of every registration node, so load
16905   // [EBP-RegNodeSize] into SP.
16906   int RegNodeSize = getSEHRegistrationNodeSize(Fn);
16907   SDValue SPAddr = DAG.getNode(ISD::ADD, dl, VT, IncomingEBP,
16908                                DAG.getConstant(-RegNodeSize, dl, VT));
16909   SDValue NewSP =
16910       DAG.getLoad(VT, dl, Chain, SPAddr, MachinePointerInfo(), false, false,
16911                   false, VT.getScalarSizeInBits() / 8);
16912   Chain = DAG.getCopyToReg(Chain, dl, SPReg, NewSP);
16913
16914   if (!RegInfo->needsStackRealignment(MF)) {
16915     // Adjust EBP to point back to the original frame position.
16916     SDValue NewFP = recoverFramePointer(DAG, Fn, IncomingEBP);
16917     Chain = DAG.getCopyToReg(Chain, dl, FrameReg, NewFP);
16918   } else {
16919     assert(RegInfo->hasBasePointer(MF) &&
16920            "functions with Win32 EH must use frame or base pointer register");
16921
16922     // Reload the base pointer (ESI) with the adjusted incoming EBP.
16923     SDValue NewBP = recoverFramePointer(DAG, Fn, IncomingEBP);
16924     Chain = DAG.getCopyToReg(Chain, dl, RegInfo->getBaseRegister(), NewBP);
16925
16926     // Reload the spilled EBP value, now that the stack and base pointers are
16927     // set up.
16928     X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
16929     X86FI->setHasSEHFramePtrSave(true);
16930     int FI = MF.getFrameInfo()->CreateSpillStackObject(SlotSize, SlotSize);
16931     X86FI->setSEHFramePtrSaveIndex(FI);
16932     SDValue NewFP = DAG.getLoad(VT, dl, Chain, DAG.getFrameIndex(FI, VT),
16933                                 MachinePointerInfo(), false, false, false,
16934                                 VT.getScalarSizeInBits() / 8);
16935     Chain = DAG.getCopyToReg(NewFP, dl, FrameReg, NewFP);
16936   }
16937
16938   return Chain;
16939 }
16940
16941 static SDValue MarkEHRegistrationNode(SDValue Op, SelectionDAG &DAG) {
16942   MachineFunction &MF = DAG.getMachineFunction();
16943   SDValue Chain = Op.getOperand(0);
16944   SDValue RegNode = Op.getOperand(2);
16945   WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo();
16946   if (!EHInfo)
16947     report_fatal_error("EH registrations only live in functions using WinEH");
16948
16949   // Cast the operand to an alloca, and remember the frame index.
16950   auto *FINode = dyn_cast<FrameIndexSDNode>(RegNode);
16951   if (!FINode)
16952     report_fatal_error("llvm.x86.seh.ehregnode expects a static alloca");
16953   EHInfo->EHRegNodeFrameIndex = FINode->getIndex();
16954
16955   // Return the chain operand without making any DAG nodes.
16956   return Chain;
16957 }
16958
16959 /// \brief Lower intrinsics for TRUNCATE_TO_MEM case
16960 /// return truncate Store/MaskedStore Node
16961 static SDValue LowerINTRINSIC_TRUNCATE_TO_MEM(const SDValue & Op,
16962                                                SelectionDAG &DAG,
16963                                                MVT ElementType) {
16964   SDLoc dl(Op);
16965   SDValue Mask = Op.getOperand(4);
16966   SDValue DataToTruncate = Op.getOperand(3);
16967   SDValue Addr = Op.getOperand(2);
16968   SDValue Chain = Op.getOperand(0);
16969
16970   MVT VT  = DataToTruncate.getSimpleValueType();
16971   MVT SVT = MVT::getVectorVT(ElementType, VT.getVectorNumElements());
16972
16973   if (isAllOnes(Mask)) // return just a truncate store
16974     return DAG.getTruncStore(Chain, dl, DataToTruncate, Addr,
16975                              MachinePointerInfo(), SVT, false, false,
16976                              SVT.getScalarSizeInBits()/8);
16977
16978   MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
16979   MVT BitcastVT = MVT::getVectorVT(MVT::i1,
16980                                    Mask.getSimpleValueType().getSizeInBits());
16981   // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
16982   // are extracted by EXTRACT_SUBVECTOR.
16983   SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16984                               DAG.getBitcast(BitcastVT, Mask),
16985                               DAG.getIntPtrConstant(0, dl));
16986
16987   MachineMemOperand *MMO = DAG.getMachineFunction().
16988     getMachineMemOperand(MachinePointerInfo(),
16989                          MachineMemOperand::MOStore, SVT.getStoreSize(),
16990                          SVT.getScalarSizeInBits()/8);
16991
16992   return DAG.getMaskedStore(Chain, dl, DataToTruncate, Addr,
16993                             VMask, SVT, MMO, true);
16994 }
16995
16996 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
16997                                       SelectionDAG &DAG) {
16998   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
16999
17000   const IntrinsicData* IntrData = getIntrinsicWithChain(IntNo);
17001   if (!IntrData) {
17002     if (IntNo == llvm::Intrinsic::x86_seh_restoreframe)
17003       return LowerSEHRESTOREFRAME(Op, Subtarget, DAG);
17004     else if (IntNo == llvm::Intrinsic::x86_seh_ehregnode)
17005       return MarkEHRegistrationNode(Op, DAG);
17006     return SDValue();
17007   }
17008
17009   SDLoc dl(Op);
17010   switch(IntrData->Type) {
17011   default: llvm_unreachable("Unknown Intrinsic Type");
17012   case RDSEED:
17013   case RDRAND: {
17014     // Emit the node with the right value type.
17015     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
17016     SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
17017
17018     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
17019     // Otherwise return the value from Rand, which is always 0, casted to i32.
17020     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
17021                       DAG.getConstant(1, dl, Op->getValueType(1)),
17022                       DAG.getConstant(X86::COND_B, dl, MVT::i32),
17023                       SDValue(Result.getNode(), 1) };
17024     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
17025                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
17026                                   Ops);
17027
17028     // Return { result, isValid, chain }.
17029     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
17030                        SDValue(Result.getNode(), 2));
17031   }
17032   case GATHER: {
17033   //gather(v1, mask, index, base, scale);
17034     SDValue Chain = Op.getOperand(0);
17035     SDValue Src   = Op.getOperand(2);
17036     SDValue Base  = Op.getOperand(3);
17037     SDValue Index = Op.getOperand(4);
17038     SDValue Mask  = Op.getOperand(5);
17039     SDValue Scale = Op.getOperand(6);
17040     return getGatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale,
17041                          Chain, Subtarget);
17042   }
17043   case SCATTER: {
17044   //scatter(base, mask, index, v1, scale);
17045     SDValue Chain = Op.getOperand(0);
17046     SDValue Base  = Op.getOperand(2);
17047     SDValue Mask  = Op.getOperand(3);
17048     SDValue Index = Op.getOperand(4);
17049     SDValue Src   = Op.getOperand(5);
17050     SDValue Scale = Op.getOperand(6);
17051     return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index,
17052                           Scale, Chain);
17053   }
17054   case PREFETCH: {
17055     SDValue Hint = Op.getOperand(6);
17056     unsigned HintVal = cast<ConstantSDNode>(Hint)->getZExtValue();
17057     assert(HintVal < 2 && "Wrong prefetch hint in intrinsic: should be 0 or 1");
17058     unsigned Opcode = (HintVal ? IntrData->Opc1 : IntrData->Opc0);
17059     SDValue Chain = Op.getOperand(0);
17060     SDValue Mask  = Op.getOperand(2);
17061     SDValue Index = Op.getOperand(3);
17062     SDValue Base  = Op.getOperand(4);
17063     SDValue Scale = Op.getOperand(5);
17064     return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
17065   }
17066   // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
17067   case RDTSC: {
17068     SmallVector<SDValue, 2> Results;
17069     getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget,
17070                             Results);
17071     return DAG.getMergeValues(Results, dl);
17072   }
17073   // Read Performance Monitoring Counters.
17074   case RDPMC: {
17075     SmallVector<SDValue, 2> Results;
17076     getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
17077     return DAG.getMergeValues(Results, dl);
17078   }
17079   // XTEST intrinsics.
17080   case XTEST: {
17081     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
17082     SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
17083     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17084                                 DAG.getConstant(X86::COND_NE, dl, MVT::i8),
17085                                 InTrans);
17086     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
17087     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
17088                        Ret, SDValue(InTrans.getNode(), 1));
17089   }
17090   // ADC/ADCX/SBB
17091   case ADX: {
17092     SmallVector<SDValue, 2> Results;
17093     SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
17094     SDVTList VTs = DAG.getVTList(Op.getOperand(3)->getValueType(0), MVT::Other);
17095     SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(2),
17096                                 DAG.getConstant(-1, dl, MVT::i8));
17097     SDValue Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(3),
17098                               Op.getOperand(4), GenCF.getValue(1));
17099     SDValue Store = DAG.getStore(Op.getOperand(0), dl, Res.getValue(0),
17100                                  Op.getOperand(5), MachinePointerInfo(),
17101                                  false, false, 0);
17102     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17103                                 DAG.getConstant(X86::COND_B, dl, MVT::i8),
17104                                 Res.getValue(1));
17105     Results.push_back(SetCC);
17106     Results.push_back(Store);
17107     return DAG.getMergeValues(Results, dl);
17108   }
17109   case COMPRESS_TO_MEM: {
17110     SDLoc dl(Op);
17111     SDValue Mask = Op.getOperand(4);
17112     SDValue DataToCompress = Op.getOperand(3);
17113     SDValue Addr = Op.getOperand(2);
17114     SDValue Chain = Op.getOperand(0);
17115
17116     MVT VT = DataToCompress.getSimpleValueType();
17117     if (isAllOnes(Mask)) // return just a store
17118       return DAG.getStore(Chain, dl, DataToCompress, Addr,
17119                           MachinePointerInfo(), false, false,
17120                           VT.getScalarSizeInBits()/8);
17121
17122     SDValue Compressed =
17123       getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToCompress),
17124                            Mask, DAG.getUNDEF(VT), Subtarget, DAG);
17125     return DAG.getStore(Chain, dl, Compressed, Addr,
17126                         MachinePointerInfo(), false, false,
17127                         VT.getScalarSizeInBits()/8);
17128   }
17129   case TRUNCATE_TO_MEM_VI8:
17130     return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i8);
17131   case TRUNCATE_TO_MEM_VI16:
17132     return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i16);
17133   case TRUNCATE_TO_MEM_VI32:
17134     return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i32);
17135   case EXPAND_FROM_MEM: {
17136     SDLoc dl(Op);
17137     SDValue Mask = Op.getOperand(4);
17138     SDValue PassThru = Op.getOperand(3);
17139     SDValue Addr = Op.getOperand(2);
17140     SDValue Chain = Op.getOperand(0);
17141     MVT VT = Op.getSimpleValueType();
17142
17143     if (isAllOnes(Mask)) // return just a load
17144       return DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(), false, false,
17145                          false, VT.getScalarSizeInBits()/8);
17146
17147     SDValue DataToExpand = DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(),
17148                                        false, false, false,
17149                                        VT.getScalarSizeInBits()/8);
17150
17151     SDValue Results[] = {
17152       getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToExpand),
17153                            Mask, PassThru, Subtarget, DAG), Chain};
17154     return DAG.getMergeValues(Results, dl);
17155   }
17156   }
17157 }
17158
17159 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
17160                                            SelectionDAG &DAG) const {
17161   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
17162   MFI->setReturnAddressIsTaken(true);
17163
17164   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
17165     return SDValue();
17166
17167   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
17168   SDLoc dl(Op);
17169   EVT PtrVT = getPointerTy(DAG.getDataLayout());
17170
17171   if (Depth > 0) {
17172     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
17173     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17174     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), dl, PtrVT);
17175     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
17176                        DAG.getNode(ISD::ADD, dl, PtrVT,
17177                                    FrameAddr, Offset),
17178                        MachinePointerInfo(), false, false, false, 0);
17179   }
17180
17181   // Just load the return address.
17182   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
17183   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
17184                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
17185 }
17186
17187 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
17188   MachineFunction &MF = DAG.getMachineFunction();
17189   MachineFrameInfo *MFI = MF.getFrameInfo();
17190   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
17191   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17192   EVT VT = Op.getValueType();
17193
17194   MFI->setFrameAddressIsTaken(true);
17195
17196   if (MF.getTarget().getMCAsmInfo()->usesWindowsCFI()) {
17197     // Depth > 0 makes no sense on targets which use Windows unwind codes.  It
17198     // is not possible to crawl up the stack without looking at the unwind codes
17199     // simultaneously.
17200     int FrameAddrIndex = FuncInfo->getFAIndex();
17201     if (!FrameAddrIndex) {
17202       // Set up a frame object for the return address.
17203       unsigned SlotSize = RegInfo->getSlotSize();
17204       FrameAddrIndex = MF.getFrameInfo()->CreateFixedObject(
17205           SlotSize, /*Offset=*/0, /*IsImmutable=*/false);
17206       FuncInfo->setFAIndex(FrameAddrIndex);
17207     }
17208     return DAG.getFrameIndex(FrameAddrIndex, VT);
17209   }
17210
17211   unsigned FrameReg =
17212       RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
17213   SDLoc dl(Op);  // FIXME probably not meaningful
17214   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
17215   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
17216           (FrameReg == X86::EBP && VT == MVT::i32)) &&
17217          "Invalid Frame Register!");
17218   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
17219   while (Depth--)
17220     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
17221                             MachinePointerInfo(),
17222                             false, false, false, 0);
17223   return FrameAddr;
17224 }
17225
17226 // FIXME? Maybe this could be a TableGen attribute on some registers and
17227 // this table could be generated automatically from RegInfo.
17228 unsigned X86TargetLowering::getRegisterByName(const char* RegName, EVT VT,
17229                                               SelectionDAG &DAG) const {
17230   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
17231   const MachineFunction &MF = DAG.getMachineFunction();
17232
17233   unsigned Reg = StringSwitch<unsigned>(RegName)
17234                        .Case("esp", X86::ESP)
17235                        .Case("rsp", X86::RSP)
17236                        .Case("ebp", X86::EBP)
17237                        .Case("rbp", X86::RBP)
17238                        .Default(0);
17239
17240   if (Reg == X86::EBP || Reg == X86::RBP) {
17241     if (!TFI.hasFP(MF))
17242       report_fatal_error("register " + StringRef(RegName) +
17243                          " is allocatable: function has no frame pointer");
17244 #ifndef NDEBUG
17245     else {
17246       const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17247       unsigned FrameReg =
17248           RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
17249       assert((FrameReg == X86::EBP || FrameReg == X86::RBP) &&
17250              "Invalid Frame Register!");
17251     }
17252 #endif
17253   }
17254
17255   if (Reg)
17256     return Reg;
17257
17258   report_fatal_error("Invalid register name global variable");
17259 }
17260
17261 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
17262                                                      SelectionDAG &DAG) const {
17263   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17264   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize(), SDLoc(Op));
17265 }
17266
17267 unsigned X86TargetLowering::getExceptionPointerRegister(
17268     const Constant *PersonalityFn) const {
17269   if (classifyEHPersonality(PersonalityFn) == EHPersonality::CoreCLR)
17270     return Subtarget->isTarget64BitLP64() ? X86::RDX : X86::EDX;
17271
17272   return Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX;
17273 }
17274
17275 unsigned X86TargetLowering::getExceptionSelectorRegister(
17276     const Constant *PersonalityFn) const {
17277   // Funclet personalities don't use selectors (the runtime does the selection).
17278   assert(!isFuncletEHPersonality(classifyEHPersonality(PersonalityFn)));
17279   return Subtarget->isTarget64BitLP64() ? X86::RDX : X86::EDX;
17280 }
17281
17282 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
17283   SDValue Chain     = Op.getOperand(0);
17284   SDValue Offset    = Op.getOperand(1);
17285   SDValue Handler   = Op.getOperand(2);
17286   SDLoc dl      (Op);
17287
17288   EVT PtrVT = getPointerTy(DAG.getDataLayout());
17289   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17290   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
17291   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
17292           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
17293          "Invalid Frame Register!");
17294   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
17295   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
17296
17297   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
17298                                  DAG.getIntPtrConstant(RegInfo->getSlotSize(),
17299                                                        dl));
17300   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
17301   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
17302                        false, false, 0);
17303   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
17304
17305   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
17306                      DAG.getRegister(StoreAddrReg, PtrVT));
17307 }
17308
17309 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
17310                                                SelectionDAG &DAG) const {
17311   SDLoc DL(Op);
17312   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
17313                      DAG.getVTList(MVT::i32, MVT::Other),
17314                      Op.getOperand(0), Op.getOperand(1));
17315 }
17316
17317 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
17318                                                 SelectionDAG &DAG) const {
17319   SDLoc DL(Op);
17320   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
17321                      Op.getOperand(0), Op.getOperand(1));
17322 }
17323
17324 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
17325   return Op.getOperand(0);
17326 }
17327
17328 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
17329                                                 SelectionDAG &DAG) const {
17330   SDValue Root = Op.getOperand(0);
17331   SDValue Trmp = Op.getOperand(1); // trampoline
17332   SDValue FPtr = Op.getOperand(2); // nested function
17333   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
17334   SDLoc dl (Op);
17335
17336   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
17337   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
17338
17339   if (Subtarget->is64Bit()) {
17340     SDValue OutChains[6];
17341
17342     // Large code-model.
17343     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
17344     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
17345
17346     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
17347     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
17348
17349     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
17350
17351     // Load the pointer to the nested function into R11.
17352     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
17353     SDValue Addr = Trmp;
17354     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
17355                                 Addr, MachinePointerInfo(TrmpAddr),
17356                                 false, false, 0);
17357
17358     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17359                        DAG.getConstant(2, dl, MVT::i64));
17360     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
17361                                 MachinePointerInfo(TrmpAddr, 2),
17362                                 false, false, 2);
17363
17364     // Load the 'nest' parameter value into R10.
17365     // R10 is specified in X86CallingConv.td
17366     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
17367     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17368                        DAG.getConstant(10, dl, MVT::i64));
17369     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
17370                                 Addr, MachinePointerInfo(TrmpAddr, 10),
17371                                 false, false, 0);
17372
17373     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17374                        DAG.getConstant(12, dl, MVT::i64));
17375     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
17376                                 MachinePointerInfo(TrmpAddr, 12),
17377                                 false, false, 2);
17378
17379     // Jump to the nested function.
17380     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
17381     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17382                        DAG.getConstant(20, dl, MVT::i64));
17383     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
17384                                 Addr, MachinePointerInfo(TrmpAddr, 20),
17385                                 false, false, 0);
17386
17387     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
17388     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17389                        DAG.getConstant(22, dl, MVT::i64));
17390     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, dl, MVT::i8),
17391                                 Addr, MachinePointerInfo(TrmpAddr, 22),
17392                                 false, false, 0);
17393
17394     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
17395   } else {
17396     const Function *Func =
17397       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
17398     CallingConv::ID CC = Func->getCallingConv();
17399     unsigned NestReg;
17400
17401     switch (CC) {
17402     default:
17403       llvm_unreachable("Unsupported calling convention");
17404     case CallingConv::C:
17405     case CallingConv::X86_StdCall: {
17406       // Pass 'nest' parameter in ECX.
17407       // Must be kept in sync with X86CallingConv.td
17408       NestReg = X86::ECX;
17409
17410       // Check that ECX wasn't needed by an 'inreg' parameter.
17411       FunctionType *FTy = Func->getFunctionType();
17412       const AttributeSet &Attrs = Func->getAttributes();
17413
17414       if (!Attrs.isEmpty() && !Func->isVarArg()) {
17415         unsigned InRegCount = 0;
17416         unsigned Idx = 1;
17417
17418         for (FunctionType::param_iterator I = FTy->param_begin(),
17419              E = FTy->param_end(); I != E; ++I, ++Idx)
17420           if (Attrs.hasAttribute(Idx, Attribute::InReg)) {
17421             auto &DL = DAG.getDataLayout();
17422             // FIXME: should only count parameters that are lowered to integers.
17423             InRegCount += (DL.getTypeSizeInBits(*I) + 31) / 32;
17424           }
17425
17426         if (InRegCount > 2) {
17427           report_fatal_error("Nest register in use - reduce number of inreg"
17428                              " parameters!");
17429         }
17430       }
17431       break;
17432     }
17433     case CallingConv::X86_FastCall:
17434     case CallingConv::X86_ThisCall:
17435     case CallingConv::Fast:
17436       // Pass 'nest' parameter in EAX.
17437       // Must be kept in sync with X86CallingConv.td
17438       NestReg = X86::EAX;
17439       break;
17440     }
17441
17442     SDValue OutChains[4];
17443     SDValue Addr, Disp;
17444
17445     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17446                        DAG.getConstant(10, dl, MVT::i32));
17447     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
17448
17449     // This is storing the opcode for MOV32ri.
17450     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
17451     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
17452     OutChains[0] = DAG.getStore(Root, dl,
17453                                 DAG.getConstant(MOV32ri|N86Reg, dl, MVT::i8),
17454                                 Trmp, MachinePointerInfo(TrmpAddr),
17455                                 false, false, 0);
17456
17457     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17458                        DAG.getConstant(1, dl, MVT::i32));
17459     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
17460                                 MachinePointerInfo(TrmpAddr, 1),
17461                                 false, false, 1);
17462
17463     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
17464     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17465                        DAG.getConstant(5, dl, MVT::i32));
17466     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, dl, MVT::i8),
17467                                 Addr, MachinePointerInfo(TrmpAddr, 5),
17468                                 false, false, 1);
17469
17470     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17471                        DAG.getConstant(6, dl, MVT::i32));
17472     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
17473                                 MachinePointerInfo(TrmpAddr, 6),
17474                                 false, false, 1);
17475
17476     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
17477   }
17478 }
17479
17480 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
17481                                             SelectionDAG &DAG) const {
17482   /*
17483    The rounding mode is in bits 11:10 of FPSR, and has the following
17484    settings:
17485      00 Round to nearest
17486      01 Round to -inf
17487      10 Round to +inf
17488      11 Round to 0
17489
17490   FLT_ROUNDS, on the other hand, expects the following:
17491     -1 Undefined
17492      0 Round to 0
17493      1 Round to nearest
17494      2 Round to +inf
17495      3 Round to -inf
17496
17497   To perform the conversion, we do:
17498     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
17499   */
17500
17501   MachineFunction &MF = DAG.getMachineFunction();
17502   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
17503   unsigned StackAlignment = TFI.getStackAlignment();
17504   MVT VT = Op.getSimpleValueType();
17505   SDLoc DL(Op);
17506
17507   // Save FP Control Word to stack slot
17508   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
17509   SDValue StackSlot =
17510       DAG.getFrameIndex(SSFI, getPointerTy(DAG.getDataLayout()));
17511
17512   MachineMemOperand *MMO =
17513       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
17514                               MachineMemOperand::MOStore, 2, 2);
17515
17516   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
17517   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
17518                                           DAG.getVTList(MVT::Other),
17519                                           Ops, MVT::i16, MMO);
17520
17521   // Load FP Control Word from stack slot
17522   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
17523                             MachinePointerInfo(), false, false, false, 0);
17524
17525   // Transform as necessary
17526   SDValue CWD1 =
17527     DAG.getNode(ISD::SRL, DL, MVT::i16,
17528                 DAG.getNode(ISD::AND, DL, MVT::i16,
17529                             CWD, DAG.getConstant(0x800, DL, MVT::i16)),
17530                 DAG.getConstant(11, DL, MVT::i8));
17531   SDValue CWD2 =
17532     DAG.getNode(ISD::SRL, DL, MVT::i16,
17533                 DAG.getNode(ISD::AND, DL, MVT::i16,
17534                             CWD, DAG.getConstant(0x400, DL, MVT::i16)),
17535                 DAG.getConstant(9, DL, MVT::i8));
17536
17537   SDValue RetVal =
17538     DAG.getNode(ISD::AND, DL, MVT::i16,
17539                 DAG.getNode(ISD::ADD, DL, MVT::i16,
17540                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
17541                             DAG.getConstant(1, DL, MVT::i16)),
17542                 DAG.getConstant(3, DL, MVT::i16));
17543
17544   return DAG.getNode((VT.getSizeInBits() < 16 ?
17545                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
17546 }
17547
17548 /// \brief Lower a vector CTLZ using native supported vector CTLZ instruction.
17549 //
17550 // 1. i32/i64 128/256-bit vector (native support require VLX) are expended
17551 //    to 512-bit vector.
17552 // 2. i8/i16 vector implemented using dword LZCNT vector instruction
17553 //    ( sub(trunc(lzcnt(zext32(x)))) ). In case zext32(x) is illegal,
17554 //    split the vector, perform operation on it's Lo a Hi part and
17555 //    concatenate the results.
17556 static SDValue LowerVectorCTLZ_AVX512(SDValue Op, SelectionDAG &DAG) {
17557   SDLoc dl(Op);
17558   MVT VT = Op.getSimpleValueType();
17559   MVT EltVT = VT.getVectorElementType();
17560   unsigned NumElems = VT.getVectorNumElements();
17561
17562   if (EltVT == MVT::i64 || EltVT == MVT::i32) {
17563     // Extend to 512 bit vector.
17564     assert((VT.is256BitVector() || VT.is128BitVector()) &&
17565               "Unsupported value type for operation");
17566
17567     MVT NewVT = MVT::getVectorVT(EltVT, 512 / VT.getScalarSizeInBits());
17568     SDValue Vec512 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, NewVT,
17569                                  DAG.getUNDEF(NewVT),
17570                                  Op.getOperand(0),
17571                                  DAG.getIntPtrConstant(0, dl));
17572     SDValue CtlzNode = DAG.getNode(ISD::CTLZ, dl, NewVT, Vec512);
17573
17574     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, CtlzNode,
17575                        DAG.getIntPtrConstant(0, dl));
17576   }
17577
17578   assert((EltVT == MVT::i8 || EltVT == MVT::i16) &&
17579           "Unsupported element type");
17580
17581   if (16 < NumElems) {
17582     // Split vector, it's Lo and Hi parts will be handled in next iteration.
17583     SDValue Lo, Hi;
17584     std::tie(Lo, Hi) = DAG.SplitVector(Op.getOperand(0), dl);
17585     MVT OutVT = MVT::getVectorVT(EltVT, NumElems/2);
17586
17587     Lo = DAG.getNode(Op.getOpcode(), dl, OutVT, Lo);
17588     Hi = DAG.getNode(Op.getOpcode(), dl, OutVT, Hi);
17589
17590     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lo, Hi);
17591   }
17592
17593   MVT NewVT = MVT::getVectorVT(MVT::i32, NumElems);
17594
17595   assert((NewVT.is256BitVector() || NewVT.is512BitVector()) &&
17596           "Unsupported value type for operation");
17597
17598   // Use native supported vector instruction vplzcntd.
17599   Op = DAG.getNode(ISD::ZERO_EXTEND, dl, NewVT, Op.getOperand(0));
17600   SDValue CtlzNode = DAG.getNode(ISD::CTLZ, dl, NewVT, Op);
17601   SDValue TruncNode = DAG.getNode(ISD::TRUNCATE, dl, VT, CtlzNode);
17602   SDValue Delta = DAG.getConstant(32 - EltVT.getSizeInBits(), dl, VT);
17603
17604   return DAG.getNode(ISD::SUB, dl, VT, TruncNode, Delta);
17605 }
17606
17607 static SDValue LowerCTLZ(SDValue Op, const X86Subtarget *Subtarget,
17608                          SelectionDAG &DAG) {
17609   MVT VT = Op.getSimpleValueType();
17610   MVT OpVT = VT;
17611   unsigned NumBits = VT.getSizeInBits();
17612   SDLoc dl(Op);
17613
17614   if (VT.isVector() && Subtarget->hasAVX512())
17615     return LowerVectorCTLZ_AVX512(Op, DAG);
17616
17617   Op = Op.getOperand(0);
17618   if (VT == MVT::i8) {
17619     // Zero extend to i32 since there is not an i8 bsr.
17620     OpVT = MVT::i32;
17621     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
17622   }
17623
17624   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
17625   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
17626   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
17627
17628   // If src is zero (i.e. bsr sets ZF), returns NumBits.
17629   SDValue Ops[] = {
17630     Op,
17631     DAG.getConstant(NumBits + NumBits - 1, dl, OpVT),
17632     DAG.getConstant(X86::COND_E, dl, MVT::i8),
17633     Op.getValue(1)
17634   };
17635   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
17636
17637   // Finally xor with NumBits-1.
17638   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
17639                    DAG.getConstant(NumBits - 1, dl, OpVT));
17640
17641   if (VT == MVT::i8)
17642     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
17643   return Op;
17644 }
17645
17646 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, const X86Subtarget *Subtarget,
17647                                     SelectionDAG &DAG) {
17648   MVT VT = Op.getSimpleValueType();
17649   EVT OpVT = VT;
17650   unsigned NumBits = VT.getSizeInBits();
17651   SDLoc dl(Op);
17652
17653   if (VT.isVector() && Subtarget->hasAVX512())
17654     return LowerVectorCTLZ_AVX512(Op, DAG);
17655
17656   Op = Op.getOperand(0);
17657   if (VT == MVT::i8) {
17658     // Zero extend to i32 since there is not an i8 bsr.
17659     OpVT = MVT::i32;
17660     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
17661   }
17662
17663   // Issue a bsr (scan bits in reverse).
17664   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
17665   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
17666
17667   // And xor with NumBits-1.
17668   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
17669                    DAG.getConstant(NumBits - 1, dl, OpVT));
17670
17671   if (VT == MVT::i8)
17672     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
17673   return Op;
17674 }
17675
17676 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
17677   MVT VT = Op.getSimpleValueType();
17678   unsigned NumBits = VT.getScalarSizeInBits();
17679   SDLoc dl(Op);
17680
17681   if (VT.isVector()) {
17682     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17683
17684     SDValue N0 = Op.getOperand(0);
17685     SDValue Zero = DAG.getConstant(0, dl, VT);
17686
17687     // lsb(x) = (x & -x)
17688     SDValue LSB = DAG.getNode(ISD::AND, dl, VT, N0,
17689                               DAG.getNode(ISD::SUB, dl, VT, Zero, N0));
17690
17691     // cttz_undef(x) = (width - 1) - ctlz(lsb)
17692     if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF &&
17693         TLI.isOperationLegal(ISD::CTLZ, VT)) {
17694       SDValue WidthMinusOne = DAG.getConstant(NumBits - 1, dl, VT);
17695       return DAG.getNode(ISD::SUB, dl, VT, WidthMinusOne,
17696                          DAG.getNode(ISD::CTLZ, dl, VT, LSB));
17697     }
17698
17699     // cttz(x) = ctpop(lsb - 1)
17700     SDValue One = DAG.getConstant(1, dl, VT);
17701     return DAG.getNode(ISD::CTPOP, dl, VT,
17702                        DAG.getNode(ISD::SUB, dl, VT, LSB, One));
17703   }
17704
17705   assert(Op.getOpcode() == ISD::CTTZ &&
17706          "Only scalar CTTZ requires custom lowering");
17707
17708   // Issue a bsf (scan bits forward) which also sets EFLAGS.
17709   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
17710   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op.getOperand(0));
17711
17712   // If src is zero (i.e. bsf sets ZF), returns NumBits.
17713   SDValue Ops[] = {
17714     Op,
17715     DAG.getConstant(NumBits, dl, VT),
17716     DAG.getConstant(X86::COND_E, dl, MVT::i8),
17717     Op.getValue(1)
17718   };
17719   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
17720 }
17721
17722 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
17723 // ones, and then concatenate the result back.
17724 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
17725   MVT VT = Op.getSimpleValueType();
17726
17727   assert(VT.is256BitVector() && VT.isInteger() &&
17728          "Unsupported value type for operation");
17729
17730   unsigned NumElems = VT.getVectorNumElements();
17731   SDLoc dl(Op);
17732
17733   // Extract the LHS vectors
17734   SDValue LHS = Op.getOperand(0);
17735   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
17736   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
17737
17738   // Extract the RHS vectors
17739   SDValue RHS = Op.getOperand(1);
17740   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
17741   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
17742
17743   MVT EltVT = VT.getVectorElementType();
17744   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
17745
17746   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
17747                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
17748                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
17749 }
17750
17751 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
17752   if (Op.getValueType() == MVT::i1)
17753     return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
17754                        Op.getOperand(0), Op.getOperand(1));
17755   assert(Op.getSimpleValueType().is256BitVector() &&
17756          Op.getSimpleValueType().isInteger() &&
17757          "Only handle AVX 256-bit vector integer operation");
17758   return Lower256IntArith(Op, DAG);
17759 }
17760
17761 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
17762   if (Op.getValueType() == MVT::i1)
17763     return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
17764                        Op.getOperand(0), Op.getOperand(1));
17765   assert(Op.getSimpleValueType().is256BitVector() &&
17766          Op.getSimpleValueType().isInteger() &&
17767          "Only handle AVX 256-bit vector integer operation");
17768   return Lower256IntArith(Op, DAG);
17769 }
17770
17771 static SDValue LowerMINMAX(SDValue Op, SelectionDAG &DAG) {
17772   assert(Op.getSimpleValueType().is256BitVector() &&
17773          Op.getSimpleValueType().isInteger() &&
17774          "Only handle AVX 256-bit vector integer operation");
17775   return Lower256IntArith(Op, DAG);
17776 }
17777
17778 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
17779                         SelectionDAG &DAG) {
17780   SDLoc dl(Op);
17781   MVT VT = Op.getSimpleValueType();
17782
17783   if (VT == MVT::i1)
17784     return DAG.getNode(ISD::AND, dl, VT, Op.getOperand(0), Op.getOperand(1));
17785
17786   // Decompose 256-bit ops into smaller 128-bit ops.
17787   if (VT.is256BitVector() && !Subtarget->hasInt256())
17788     return Lower256IntArith(Op, DAG);
17789
17790   SDValue A = Op.getOperand(0);
17791   SDValue B = Op.getOperand(1);
17792
17793   // Lower v16i8/v32i8 mul as promotion to v8i16/v16i16 vector
17794   // pairs, multiply and truncate.
17795   if (VT == MVT::v16i8 || VT == MVT::v32i8) {
17796     if (Subtarget->hasInt256()) {
17797       if (VT == MVT::v32i8) {
17798         MVT SubVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() / 2);
17799         SDValue Lo = DAG.getIntPtrConstant(0, dl);
17800         SDValue Hi = DAG.getIntPtrConstant(VT.getVectorNumElements() / 2, dl);
17801         SDValue ALo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Lo);
17802         SDValue BLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Lo);
17803         SDValue AHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Hi);
17804         SDValue BHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Hi);
17805         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
17806                            DAG.getNode(ISD::MUL, dl, SubVT, ALo, BLo),
17807                            DAG.getNode(ISD::MUL, dl, SubVT, AHi, BHi));
17808       }
17809
17810       MVT ExVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements());
17811       return DAG.getNode(
17812           ISD::TRUNCATE, dl, VT,
17813           DAG.getNode(ISD::MUL, dl, ExVT,
17814                       DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, A),
17815                       DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, B)));
17816     }
17817
17818     assert(VT == MVT::v16i8 &&
17819            "Pre-AVX2 support only supports v16i8 multiplication");
17820     MVT ExVT = MVT::v8i16;
17821
17822     // Extract the lo parts and sign extend to i16
17823     SDValue ALo, BLo;
17824     if (Subtarget->hasSSE41()) {
17825       ALo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, A);
17826       BLo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, B);
17827     } else {
17828       const int ShufMask[] = {-1, 0, -1, 1, -1, 2, -1, 3,
17829                               -1, 4, -1, 5, -1, 6, -1, 7};
17830       ALo = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
17831       BLo = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
17832       ALo = DAG.getBitcast(ExVT, ALo);
17833       BLo = DAG.getBitcast(ExVT, BLo);
17834       ALo = DAG.getNode(ISD::SRA, dl, ExVT, ALo, DAG.getConstant(8, dl, ExVT));
17835       BLo = DAG.getNode(ISD::SRA, dl, ExVT, BLo, DAG.getConstant(8, dl, ExVT));
17836     }
17837
17838     // Extract the hi parts and sign extend to i16
17839     SDValue AHi, BHi;
17840     if (Subtarget->hasSSE41()) {
17841       const int ShufMask[] = {8,  9,  10, 11, 12, 13, 14, 15,
17842                               -1, -1, -1, -1, -1, -1, -1, -1};
17843       AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
17844       BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
17845       AHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, AHi);
17846       BHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, BHi);
17847     } else {
17848       const int ShufMask[] = {-1, 8,  -1, 9,  -1, 10, -1, 11,
17849                               -1, 12, -1, 13, -1, 14, -1, 15};
17850       AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
17851       BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
17852       AHi = DAG.getBitcast(ExVT, AHi);
17853       BHi = DAG.getBitcast(ExVT, BHi);
17854       AHi = DAG.getNode(ISD::SRA, dl, ExVT, AHi, DAG.getConstant(8, dl, ExVT));
17855       BHi = DAG.getNode(ISD::SRA, dl, ExVT, BHi, DAG.getConstant(8, dl, ExVT));
17856     }
17857
17858     // Multiply, mask the lower 8bits of the lo/hi results and pack
17859     SDValue RLo = DAG.getNode(ISD::MUL, dl, ExVT, ALo, BLo);
17860     SDValue RHi = DAG.getNode(ISD::MUL, dl, ExVT, AHi, BHi);
17861     RLo = DAG.getNode(ISD::AND, dl, ExVT, RLo, DAG.getConstant(255, dl, ExVT));
17862     RHi = DAG.getNode(ISD::AND, dl, ExVT, RHi, DAG.getConstant(255, dl, ExVT));
17863     return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
17864   }
17865
17866   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
17867   if (VT == MVT::v4i32) {
17868     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
17869            "Should not custom lower when pmuldq is available!");
17870
17871     // Extract the odd parts.
17872     static const int UnpackMask[] = { 1, -1, 3, -1 };
17873     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
17874     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
17875
17876     // Multiply the even parts.
17877     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
17878     // Now multiply odd parts.
17879     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
17880
17881     Evens = DAG.getBitcast(VT, Evens);
17882     Odds = DAG.getBitcast(VT, Odds);
17883
17884     // Merge the two vectors back together with a shuffle. This expands into 2
17885     // shuffles.
17886     static const int ShufMask[] = { 0, 4, 2, 6 };
17887     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
17888   }
17889
17890   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
17891          "Only know how to lower V2I64/V4I64/V8I64 multiply");
17892
17893   //  Ahi = psrlqi(a, 32);
17894   //  Bhi = psrlqi(b, 32);
17895   //
17896   //  AloBlo = pmuludq(a, b);
17897   //  AloBhi = pmuludq(a, Bhi);
17898   //  AhiBlo = pmuludq(Ahi, b);
17899
17900   //  AloBhi = psllqi(AloBhi, 32);
17901   //  AhiBlo = psllqi(AhiBlo, 32);
17902   //  return AloBlo + AloBhi + AhiBlo;
17903
17904   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
17905   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
17906
17907   SDValue AhiBlo = Ahi;
17908   SDValue AloBhi = Bhi;
17909   // Bit cast to 32-bit vectors for MULUDQ
17910   MVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
17911                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
17912   A = DAG.getBitcast(MulVT, A);
17913   B = DAG.getBitcast(MulVT, B);
17914   Ahi = DAG.getBitcast(MulVT, Ahi);
17915   Bhi = DAG.getBitcast(MulVT, Bhi);
17916
17917   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
17918   // After shifting right const values the result may be all-zero.
17919   if (!ISD::isBuildVectorAllZeros(Ahi.getNode())) {
17920     AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
17921     AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
17922   }
17923   if (!ISD::isBuildVectorAllZeros(Bhi.getNode())) {
17924     AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
17925     AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
17926   }
17927
17928   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
17929   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
17930 }
17931
17932 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
17933   assert(Subtarget->isTargetWin64() && "Unexpected target");
17934   EVT VT = Op.getValueType();
17935   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
17936          "Unexpected return type for lowering");
17937
17938   RTLIB::Libcall LC;
17939   bool isSigned;
17940   switch (Op->getOpcode()) {
17941   default: llvm_unreachable("Unexpected request for libcall!");
17942   case ISD::SDIV:      isSigned = true;  LC = RTLIB::SDIV_I128;    break;
17943   case ISD::UDIV:      isSigned = false; LC = RTLIB::UDIV_I128;    break;
17944   case ISD::SREM:      isSigned = true;  LC = RTLIB::SREM_I128;    break;
17945   case ISD::UREM:      isSigned = false; LC = RTLIB::UREM_I128;    break;
17946   case ISD::SDIVREM:   isSigned = true;  LC = RTLIB::SDIVREM_I128; break;
17947   case ISD::UDIVREM:   isSigned = false; LC = RTLIB::UDIVREM_I128; break;
17948   }
17949
17950   SDLoc dl(Op);
17951   SDValue InChain = DAG.getEntryNode();
17952
17953   TargetLowering::ArgListTy Args;
17954   TargetLowering::ArgListEntry Entry;
17955   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
17956     EVT ArgVT = Op->getOperand(i).getValueType();
17957     assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
17958            "Unexpected argument type for lowering");
17959     SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
17960     Entry.Node = StackPtr;
17961     InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
17962                            false, false, 16);
17963     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
17964     Entry.Ty = PointerType::get(ArgTy,0);
17965     Entry.isSExt = false;
17966     Entry.isZExt = false;
17967     Args.push_back(Entry);
17968   }
17969
17970   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
17971                                          getPointerTy(DAG.getDataLayout()));
17972
17973   TargetLowering::CallLoweringInfo CLI(DAG);
17974   CLI.setDebugLoc(dl).setChain(InChain)
17975     .setCallee(getLibcallCallingConv(LC),
17976                static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
17977                Callee, std::move(Args), 0)
17978     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
17979
17980   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
17981   return DAG.getBitcast(VT, CallInfo.first);
17982 }
17983
17984 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
17985                              SelectionDAG &DAG) {
17986   SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
17987   MVT VT = Op0.getSimpleValueType();
17988   SDLoc dl(Op);
17989
17990   assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
17991          (VT == MVT::v8i32 && Subtarget->hasInt256()));
17992
17993   // PMULxD operations multiply each even value (starting at 0) of LHS with
17994   // the related value of RHS and produce a widen result.
17995   // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
17996   // => <2 x i64> <ae|cg>
17997   //
17998   // In other word, to have all the results, we need to perform two PMULxD:
17999   // 1. one with the even values.
18000   // 2. one with the odd values.
18001   // To achieve #2, with need to place the odd values at an even position.
18002   //
18003   // Place the odd value at an even position (basically, shift all values 1
18004   // step to the left):
18005   const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
18006   // <a|b|c|d> => <b|undef|d|undef>
18007   SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
18008   // <e|f|g|h> => <f|undef|h|undef>
18009   SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
18010
18011   // Emit two multiplies, one for the lower 2 ints and one for the higher 2
18012   // ints.
18013   MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
18014   bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
18015   unsigned Opcode =
18016       (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
18017   // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
18018   // => <2 x i64> <ae|cg>
18019   SDValue Mul1 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
18020   // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
18021   // => <2 x i64> <bf|dh>
18022   SDValue Mul2 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
18023
18024   // Shuffle it back into the right order.
18025   SDValue Highs, Lows;
18026   if (VT == MVT::v8i32) {
18027     const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
18028     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
18029     const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
18030     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
18031   } else {
18032     const int HighMask[] = {1, 5, 3, 7};
18033     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
18034     const int LowMask[] = {0, 4, 2, 6};
18035     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
18036   }
18037
18038   // If we have a signed multiply but no PMULDQ fix up the high parts of a
18039   // unsigned multiply.
18040   if (IsSigned && !Subtarget->hasSSE41()) {
18041     SDValue ShAmt = DAG.getConstant(
18042         31, dl,
18043         DAG.getTargetLoweringInfo().getShiftAmountTy(VT, DAG.getDataLayout()));
18044     SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
18045                              DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
18046     SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
18047                              DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
18048
18049     SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
18050     Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
18051   }
18052
18053   // The first result of MUL_LOHI is actually the low value, followed by the
18054   // high value.
18055   SDValue Ops[] = {Lows, Highs};
18056   return DAG.getMergeValues(Ops, dl);
18057 }
18058
18059 // Return true if the required (according to Opcode) shift-imm form is natively
18060 // supported by the Subtarget
18061 static bool SupportedVectorShiftWithImm(MVT VT, const X86Subtarget *Subtarget,
18062                                         unsigned Opcode) {
18063   if (VT.getScalarSizeInBits() < 16)
18064     return false;
18065
18066   if (VT.is512BitVector() &&
18067       (VT.getScalarSizeInBits() > 16 || Subtarget->hasBWI()))
18068     return true;
18069
18070   bool LShift = VT.is128BitVector() ||
18071     (VT.is256BitVector() && Subtarget->hasInt256());
18072
18073   bool AShift = LShift && (Subtarget->hasVLX() ||
18074     (VT != MVT::v2i64 && VT != MVT::v4i64));
18075   return (Opcode == ISD::SRA) ? AShift : LShift;
18076 }
18077
18078 // The shift amount is a variable, but it is the same for all vector lanes.
18079 // These instructions are defined together with shift-immediate.
18080 static
18081 bool SupportedVectorShiftWithBaseAmnt(MVT VT, const X86Subtarget *Subtarget,
18082                                       unsigned Opcode) {
18083   return SupportedVectorShiftWithImm(VT, Subtarget, Opcode);
18084 }
18085
18086 // Return true if the required (according to Opcode) variable-shift form is
18087 // natively supported by the Subtarget
18088 static bool SupportedVectorVarShift(MVT VT, const X86Subtarget *Subtarget,
18089                                     unsigned Opcode) {
18090
18091   if (!Subtarget->hasInt256() || VT.getScalarSizeInBits() < 16)
18092     return false;
18093
18094   // vXi16 supported only on AVX-512, BWI
18095   if (VT.getScalarSizeInBits() == 16 && !Subtarget->hasBWI())
18096     return false;
18097
18098   if (VT.is512BitVector() || Subtarget->hasVLX())
18099     return true;
18100
18101   bool LShift = VT.is128BitVector() || VT.is256BitVector();
18102   bool AShift = LShift &&  VT != MVT::v2i64 && VT != MVT::v4i64;
18103   return (Opcode == ISD::SRA) ? AShift : LShift;
18104 }
18105
18106 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
18107                                          const X86Subtarget *Subtarget) {
18108   MVT VT = Op.getSimpleValueType();
18109   SDLoc dl(Op);
18110   SDValue R = Op.getOperand(0);
18111   SDValue Amt = Op.getOperand(1);
18112
18113   unsigned X86Opc = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
18114     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
18115
18116   auto ArithmeticShiftRight64 = [&](uint64_t ShiftAmt) {
18117     assert((VT == MVT::v2i64 || VT == MVT::v4i64) && "Unexpected SRA type");
18118     MVT ExVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() * 2);
18119     SDValue Ex = DAG.getBitcast(ExVT, R);
18120
18121     if (ShiftAmt >= 32) {
18122       // Splat sign to upper i32 dst, and SRA upper i32 src to lower i32.
18123       SDValue Upper =
18124           getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex, 31, DAG);
18125       SDValue Lower = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
18126                                                  ShiftAmt - 32, DAG);
18127       if (VT == MVT::v2i64)
18128         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {5, 1, 7, 3});
18129       if (VT == MVT::v4i64)
18130         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
18131                                   {9, 1, 11, 3, 13, 5, 15, 7});
18132     } else {
18133       // SRA upper i32, SHL whole i64 and select lower i32.
18134       SDValue Upper = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
18135                                                  ShiftAmt, DAG);
18136       SDValue Lower =
18137           getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt, DAG);
18138       Lower = DAG.getBitcast(ExVT, Lower);
18139       if (VT == MVT::v2i64)
18140         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {4, 1, 6, 3});
18141       if (VT == MVT::v4i64)
18142         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
18143                                   {8, 1, 10, 3, 12, 5, 14, 7});
18144     }
18145     return DAG.getBitcast(VT, Ex);
18146   };
18147
18148   // Optimize shl/srl/sra with constant shift amount.
18149   if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
18150     if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
18151       uint64_t ShiftAmt = ShiftConst->getZExtValue();
18152
18153       if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
18154         return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
18155
18156       // i64 SRA needs to be performed as partial shifts.
18157       if ((VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
18158           Op.getOpcode() == ISD::SRA && !Subtarget->hasXOP())
18159         return ArithmeticShiftRight64(ShiftAmt);
18160
18161       if (VT == MVT::v16i8 || (Subtarget->hasInt256() && VT == MVT::v32i8)) {
18162         unsigned NumElts = VT.getVectorNumElements();
18163         MVT ShiftVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
18164
18165         // Simple i8 add case
18166         if (Op.getOpcode() == ISD::SHL && ShiftAmt == 1)
18167           return DAG.getNode(ISD::ADD, dl, VT, R, R);
18168
18169         // ashr(R, 7)  === cmp_slt(R, 0)
18170         if (Op.getOpcode() == ISD::SRA && ShiftAmt == 7) {
18171           SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
18172           return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
18173         }
18174
18175         // XOP can shift v16i8 directly instead of as shift v8i16 + mask.
18176         if (VT == MVT::v16i8 && Subtarget->hasXOP())
18177           return SDValue();
18178
18179         if (Op.getOpcode() == ISD::SHL) {
18180           // Make a large shift.
18181           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ShiftVT,
18182                                                    R, ShiftAmt, DAG);
18183           SHL = DAG.getBitcast(VT, SHL);
18184           // Zero out the rightmost bits.
18185           SmallVector<SDValue, 32> V(
18186               NumElts, DAG.getConstant(uint8_t(-1U << ShiftAmt), dl, MVT::i8));
18187           return DAG.getNode(ISD::AND, dl, VT, SHL,
18188                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
18189         }
18190         if (Op.getOpcode() == ISD::SRL) {
18191           // Make a large shift.
18192           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ShiftVT,
18193                                                    R, ShiftAmt, DAG);
18194           SRL = DAG.getBitcast(VT, SRL);
18195           // Zero out the leftmost bits.
18196           SmallVector<SDValue, 32> V(
18197               NumElts, DAG.getConstant(uint8_t(-1U) >> ShiftAmt, dl, MVT::i8));
18198           return DAG.getNode(ISD::AND, dl, VT, SRL,
18199                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
18200         }
18201         if (Op.getOpcode() == ISD::SRA) {
18202           // ashr(R, Amt) === sub(xor(lshr(R, Amt), Mask), Mask)
18203           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
18204           SmallVector<SDValue, 32> V(NumElts,
18205                                      DAG.getConstant(128 >> ShiftAmt, dl,
18206                                                      MVT::i8));
18207           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
18208           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
18209           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
18210           return Res;
18211         }
18212         llvm_unreachable("Unknown shift opcode.");
18213       }
18214     }
18215   }
18216
18217   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
18218   if (!Subtarget->is64Bit() && !Subtarget->hasXOP() &&
18219       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64))) {
18220
18221     // Peek through any splat that was introduced for i64 shift vectorization.
18222     int SplatIndex = -1;
18223     if (ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt.getNode()))
18224       if (SVN->isSplat()) {
18225         SplatIndex = SVN->getSplatIndex();
18226         Amt = Amt.getOperand(0);
18227         assert(SplatIndex < (int)VT.getVectorNumElements() &&
18228                "Splat shuffle referencing second operand");
18229       }
18230
18231     if (Amt.getOpcode() != ISD::BITCAST ||
18232         Amt.getOperand(0).getOpcode() != ISD::BUILD_VECTOR)
18233       return SDValue();
18234
18235     Amt = Amt.getOperand(0);
18236     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
18237                      VT.getVectorNumElements();
18238     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
18239     uint64_t ShiftAmt = 0;
18240     unsigned BaseOp = (SplatIndex < 0 ? 0 : SplatIndex * Ratio);
18241     for (unsigned i = 0; i != Ratio; ++i) {
18242       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i + BaseOp));
18243       if (!C)
18244         return SDValue();
18245       // 6 == Log2(64)
18246       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
18247     }
18248
18249     // Check remaining shift amounts (if not a splat).
18250     if (SplatIndex < 0) {
18251       for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
18252         uint64_t ShAmt = 0;
18253         for (unsigned j = 0; j != Ratio; ++j) {
18254           ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
18255           if (!C)
18256             return SDValue();
18257           // 6 == Log2(64)
18258           ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
18259         }
18260         if (ShAmt != ShiftAmt)
18261           return SDValue();
18262       }
18263     }
18264
18265     if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
18266       return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
18267
18268     if (Op.getOpcode() == ISD::SRA)
18269       return ArithmeticShiftRight64(ShiftAmt);
18270   }
18271
18272   return SDValue();
18273 }
18274
18275 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
18276                                         const X86Subtarget* Subtarget) {
18277   MVT VT = Op.getSimpleValueType();
18278   SDLoc dl(Op);
18279   SDValue R = Op.getOperand(0);
18280   SDValue Amt = Op.getOperand(1);
18281
18282   unsigned X86OpcI = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
18283     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
18284
18285   unsigned X86OpcV = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHL :
18286     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRL : X86ISD::VSRA;
18287
18288   if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode())) {
18289     SDValue BaseShAmt;
18290     MVT EltVT = VT.getVectorElementType();
18291
18292     if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Amt)) {
18293       // Check if this build_vector node is doing a splat.
18294       // If so, then set BaseShAmt equal to the splat value.
18295       BaseShAmt = BV->getSplatValue();
18296       if (BaseShAmt && BaseShAmt.getOpcode() == ISD::UNDEF)
18297         BaseShAmt = SDValue();
18298     } else {
18299       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
18300         Amt = Amt.getOperand(0);
18301
18302       ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt);
18303       if (SVN && SVN->isSplat()) {
18304         unsigned SplatIdx = (unsigned)SVN->getSplatIndex();
18305         SDValue InVec = Amt.getOperand(0);
18306         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
18307           assert((SplatIdx < InVec.getSimpleValueType().getVectorNumElements()) &&
18308                  "Unexpected shuffle index found!");
18309           BaseShAmt = InVec.getOperand(SplatIdx);
18310         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
18311            if (ConstantSDNode *C =
18312                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
18313              if (C->getZExtValue() == SplatIdx)
18314                BaseShAmt = InVec.getOperand(1);
18315            }
18316         }
18317
18318         if (!BaseShAmt)
18319           // Avoid introducing an extract element from a shuffle.
18320           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InVec,
18321                                   DAG.getIntPtrConstant(SplatIdx, dl));
18322       }
18323     }
18324
18325     if (BaseShAmt.getNode()) {
18326       assert(EltVT.bitsLE(MVT::i64) && "Unexpected element type!");
18327       if (EltVT != MVT::i64 && EltVT.bitsGT(MVT::i32))
18328         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, BaseShAmt);
18329       else if (EltVT.bitsLT(MVT::i32))
18330         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
18331
18332       return getTargetVShiftNode(X86OpcI, dl, VT, R, BaseShAmt, DAG);
18333     }
18334   }
18335
18336   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
18337   if (!Subtarget->is64Bit() && VT == MVT::v2i64  &&
18338       Amt.getOpcode() == ISD::BITCAST &&
18339       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
18340     Amt = Amt.getOperand(0);
18341     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
18342                      VT.getVectorNumElements();
18343     std::vector<SDValue> Vals(Ratio);
18344     for (unsigned i = 0; i != Ratio; ++i)
18345       Vals[i] = Amt.getOperand(i);
18346     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
18347       for (unsigned j = 0; j != Ratio; ++j)
18348         if (Vals[j] != Amt.getOperand(i + j))
18349           return SDValue();
18350     }
18351
18352     if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode()))
18353       return DAG.getNode(X86OpcV, dl, VT, R, Op.getOperand(1));
18354   }
18355   return SDValue();
18356 }
18357
18358 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
18359                           SelectionDAG &DAG) {
18360   MVT VT = Op.getSimpleValueType();
18361   SDLoc dl(Op);
18362   SDValue R = Op.getOperand(0);
18363   SDValue Amt = Op.getOperand(1);
18364
18365   assert(VT.isVector() && "Custom lowering only for vector shifts!");
18366   assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
18367
18368   if (SDValue V = LowerScalarImmediateShift(Op, DAG, Subtarget))
18369     return V;
18370
18371   if (SDValue V = LowerScalarVariableShift(Op, DAG, Subtarget))
18372     return V;
18373
18374   if (SupportedVectorVarShift(VT, Subtarget, Op.getOpcode()))
18375     return Op;
18376
18377   // XOP has 128-bit variable logical/arithmetic shifts.
18378   // +ve/-ve Amt = shift left/right.
18379   if (Subtarget->hasXOP() &&
18380       (VT == MVT::v2i64 || VT == MVT::v4i32 ||
18381        VT == MVT::v8i16 || VT == MVT::v16i8)) {
18382     if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SRA) {
18383       SDValue Zero = getZeroVector(VT, Subtarget, DAG, dl);
18384       Amt = DAG.getNode(ISD::SUB, dl, VT, Zero, Amt);
18385     }
18386     if (Op.getOpcode() == ISD::SHL || Op.getOpcode() == ISD::SRL)
18387       return DAG.getNode(X86ISD::VPSHL, dl, VT, R, Amt);
18388     if (Op.getOpcode() == ISD::SRA)
18389       return DAG.getNode(X86ISD::VPSHA, dl, VT, R, Amt);
18390   }
18391
18392   // 2i64 vector logical shifts can efficiently avoid scalarization - do the
18393   // shifts per-lane and then shuffle the partial results back together.
18394   if (VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) {
18395     // Splat the shift amounts so the scalar shifts above will catch it.
18396     SDValue Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {0, 0});
18397     SDValue Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {1, 1});
18398     SDValue R0 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt0);
18399     SDValue R1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt1);
18400     return DAG.getVectorShuffle(VT, dl, R0, R1, {0, 3});
18401   }
18402
18403   // i64 vector arithmetic shift can be emulated with the transform:
18404   // M = lshr(SIGN_BIT, Amt)
18405   // ashr(R, Amt) === sub(xor(lshr(R, Amt), M), M)
18406   if ((VT == MVT::v2i64 || (VT == MVT::v4i64 && Subtarget->hasInt256())) &&
18407       Op.getOpcode() == ISD::SRA) {
18408     SDValue S = DAG.getConstant(APInt::getSignBit(64), dl, VT);
18409     SDValue M = DAG.getNode(ISD::SRL, dl, VT, S, Amt);
18410     R = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
18411     R = DAG.getNode(ISD::XOR, dl, VT, R, M);
18412     R = DAG.getNode(ISD::SUB, dl, VT, R, M);
18413     return R;
18414   }
18415
18416   // If possible, lower this packed shift into a vector multiply instead of
18417   // expanding it into a sequence of scalar shifts.
18418   // Do this only if the vector shift count is a constant build_vector.
18419   if (Op.getOpcode() == ISD::SHL &&
18420       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
18421        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
18422       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
18423     SmallVector<SDValue, 8> Elts;
18424     MVT SVT = VT.getVectorElementType();
18425     unsigned SVTBits = SVT.getSizeInBits();
18426     APInt One(SVTBits, 1);
18427     unsigned NumElems = VT.getVectorNumElements();
18428
18429     for (unsigned i=0; i !=NumElems; ++i) {
18430       SDValue Op = Amt->getOperand(i);
18431       if (Op->getOpcode() == ISD::UNDEF) {
18432         Elts.push_back(Op);
18433         continue;
18434       }
18435
18436       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
18437       APInt C(SVTBits, ND->getAPIntValue().getZExtValue());
18438       uint64_t ShAmt = C.getZExtValue();
18439       if (ShAmt >= SVTBits) {
18440         Elts.push_back(DAG.getUNDEF(SVT));
18441         continue;
18442       }
18443       Elts.push_back(DAG.getConstant(One.shl(ShAmt), dl, SVT));
18444     }
18445     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
18446     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
18447   }
18448
18449   // Lower SHL with variable shift amount.
18450   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
18451     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, dl, VT));
18452
18453     Op = DAG.getNode(ISD::ADD, dl, VT, Op,
18454                      DAG.getConstant(0x3f800000U, dl, VT));
18455     Op = DAG.getBitcast(MVT::v4f32, Op);
18456     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
18457     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
18458   }
18459
18460   // If possible, lower this shift as a sequence of two shifts by
18461   // constant plus a MOVSS/MOVSD instead of scalarizing it.
18462   // Example:
18463   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
18464   //
18465   // Could be rewritten as:
18466   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
18467   //
18468   // The advantage is that the two shifts from the example would be
18469   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
18470   // the vector shift into four scalar shifts plus four pairs of vector
18471   // insert/extract.
18472   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
18473       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
18474     unsigned TargetOpcode = X86ISD::MOVSS;
18475     bool CanBeSimplified;
18476     // The splat value for the first packed shift (the 'X' from the example).
18477     SDValue Amt1 = Amt->getOperand(0);
18478     // The splat value for the second packed shift (the 'Y' from the example).
18479     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
18480                                         Amt->getOperand(2);
18481
18482     // See if it is possible to replace this node with a sequence of
18483     // two shifts followed by a MOVSS/MOVSD
18484     if (VT == MVT::v4i32) {
18485       // Check if it is legal to use a MOVSS.
18486       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
18487                         Amt2 == Amt->getOperand(3);
18488       if (!CanBeSimplified) {
18489         // Otherwise, check if we can still simplify this node using a MOVSD.
18490         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
18491                           Amt->getOperand(2) == Amt->getOperand(3);
18492         TargetOpcode = X86ISD::MOVSD;
18493         Amt2 = Amt->getOperand(2);
18494       }
18495     } else {
18496       // Do similar checks for the case where the machine value type
18497       // is MVT::v8i16.
18498       CanBeSimplified = Amt1 == Amt->getOperand(1);
18499       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
18500         CanBeSimplified = Amt2 == Amt->getOperand(i);
18501
18502       if (!CanBeSimplified) {
18503         TargetOpcode = X86ISD::MOVSD;
18504         CanBeSimplified = true;
18505         Amt2 = Amt->getOperand(4);
18506         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
18507           CanBeSimplified = Amt1 == Amt->getOperand(i);
18508         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
18509           CanBeSimplified = Amt2 == Amt->getOperand(j);
18510       }
18511     }
18512
18513     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
18514         isa<ConstantSDNode>(Amt2)) {
18515       // Replace this node with two shifts followed by a MOVSS/MOVSD.
18516       MVT CastVT = MVT::v4i32;
18517       SDValue Splat1 =
18518         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), dl, VT);
18519       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
18520       SDValue Splat2 =
18521         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), dl, VT);
18522       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
18523       if (TargetOpcode == X86ISD::MOVSD)
18524         CastVT = MVT::v2i64;
18525       SDValue BitCast1 = DAG.getBitcast(CastVT, Shift1);
18526       SDValue BitCast2 = DAG.getBitcast(CastVT, Shift2);
18527       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
18528                                             BitCast1, DAG);
18529       return DAG.getBitcast(VT, Result);
18530     }
18531   }
18532
18533   // v4i32 Non Uniform Shifts.
18534   // If the shift amount is constant we can shift each lane using the SSE2
18535   // immediate shifts, else we need to zero-extend each lane to the lower i64
18536   // and shift using the SSE2 variable shifts.
18537   // The separate results can then be blended together.
18538   if (VT == MVT::v4i32) {
18539     unsigned Opc = Op.getOpcode();
18540     SDValue Amt0, Amt1, Amt2, Amt3;
18541     if (ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
18542       Amt0 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {0, 0, 0, 0});
18543       Amt1 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {1, 1, 1, 1});
18544       Amt2 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {2, 2, 2, 2});
18545       Amt3 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {3, 3, 3, 3});
18546     } else {
18547       // ISD::SHL is handled above but we include it here for completeness.
18548       switch (Opc) {
18549       default:
18550         llvm_unreachable("Unknown target vector shift node");
18551       case ISD::SHL:
18552         Opc = X86ISD::VSHL;
18553         break;
18554       case ISD::SRL:
18555         Opc = X86ISD::VSRL;
18556         break;
18557       case ISD::SRA:
18558         Opc = X86ISD::VSRA;
18559         break;
18560       }
18561       // The SSE2 shifts use the lower i64 as the same shift amount for
18562       // all lanes and the upper i64 is ignored. These shuffle masks
18563       // optimally zero-extend each lanes on SSE2/SSE41/AVX targets.
18564       SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
18565       Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Z, {0, 4, -1, -1});
18566       Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Z, {1, 5, -1, -1});
18567       Amt2 = DAG.getVectorShuffle(VT, dl, Amt, Z, {2, 6, -1, -1});
18568       Amt3 = DAG.getVectorShuffle(VT, dl, Amt, Z, {3, 7, -1, -1});
18569     }
18570
18571     SDValue R0 = DAG.getNode(Opc, dl, VT, R, Amt0);
18572     SDValue R1 = DAG.getNode(Opc, dl, VT, R, Amt1);
18573     SDValue R2 = DAG.getNode(Opc, dl, VT, R, Amt2);
18574     SDValue R3 = DAG.getNode(Opc, dl, VT, R, Amt3);
18575     SDValue R02 = DAG.getVectorShuffle(VT, dl, R0, R2, {0, -1, 6, -1});
18576     SDValue R13 = DAG.getVectorShuffle(VT, dl, R1, R3, {-1, 1, -1, 7});
18577     return DAG.getVectorShuffle(VT, dl, R02, R13, {0, 5, 2, 7});
18578   }
18579
18580   if (VT == MVT::v16i8 ||
18581       (VT == MVT::v32i8 && Subtarget->hasInt256() && !Subtarget->hasXOP())) {
18582     MVT ExtVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements() / 2);
18583     unsigned ShiftOpcode = Op->getOpcode();
18584
18585     auto SignBitSelect = [&](MVT SelVT, SDValue Sel, SDValue V0, SDValue V1) {
18586       // On SSE41 targets we make use of the fact that VSELECT lowers
18587       // to PBLENDVB which selects bytes based just on the sign bit.
18588       if (Subtarget->hasSSE41()) {
18589         V0 = DAG.getBitcast(VT, V0);
18590         V1 = DAG.getBitcast(VT, V1);
18591         Sel = DAG.getBitcast(VT, Sel);
18592         return DAG.getBitcast(SelVT,
18593                               DAG.getNode(ISD::VSELECT, dl, VT, Sel, V0, V1));
18594       }
18595       // On pre-SSE41 targets we test for the sign bit by comparing to
18596       // zero - a negative value will set all bits of the lanes to true
18597       // and VSELECT uses that in its OR(AND(V0,C),AND(V1,~C)) lowering.
18598       SDValue Z = getZeroVector(SelVT, Subtarget, DAG, dl);
18599       SDValue C = DAG.getNode(X86ISD::PCMPGT, dl, SelVT, Z, Sel);
18600       return DAG.getNode(ISD::VSELECT, dl, SelVT, C, V0, V1);
18601     };
18602
18603     // Turn 'a' into a mask suitable for VSELECT: a = a << 5;
18604     // We can safely do this using i16 shifts as we're only interested in
18605     // the 3 lower bits of each byte.
18606     Amt = DAG.getBitcast(ExtVT, Amt);
18607     Amt = DAG.getNode(ISD::SHL, dl, ExtVT, Amt, DAG.getConstant(5, dl, ExtVT));
18608     Amt = DAG.getBitcast(VT, Amt);
18609
18610     if (Op->getOpcode() == ISD::SHL || Op->getOpcode() == ISD::SRL) {
18611       // r = VSELECT(r, shift(r, 4), a);
18612       SDValue M =
18613           DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
18614       R = SignBitSelect(VT, Amt, M, R);
18615
18616       // a += a
18617       Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18618
18619       // r = VSELECT(r, shift(r, 2), a);
18620       M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
18621       R = SignBitSelect(VT, Amt, M, R);
18622
18623       // a += a
18624       Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18625
18626       // return VSELECT(r, shift(r, 1), a);
18627       M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
18628       R = SignBitSelect(VT, Amt, M, R);
18629       return R;
18630     }
18631
18632     if (Op->getOpcode() == ISD::SRA) {
18633       // For SRA we need to unpack each byte to the higher byte of a i16 vector
18634       // so we can correctly sign extend. We don't care what happens to the
18635       // lower byte.
18636       SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), Amt);
18637       SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), Amt);
18638       SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), R);
18639       SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), R);
18640       ALo = DAG.getBitcast(ExtVT, ALo);
18641       AHi = DAG.getBitcast(ExtVT, AHi);
18642       RLo = DAG.getBitcast(ExtVT, RLo);
18643       RHi = DAG.getBitcast(ExtVT, RHi);
18644
18645       // r = VSELECT(r, shift(r, 4), a);
18646       SDValue MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
18647                                 DAG.getConstant(4, dl, ExtVT));
18648       SDValue MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
18649                                 DAG.getConstant(4, dl, ExtVT));
18650       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
18651       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
18652
18653       // a += a
18654       ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
18655       AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
18656
18657       // r = VSELECT(r, shift(r, 2), a);
18658       MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
18659                         DAG.getConstant(2, dl, ExtVT));
18660       MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
18661                         DAG.getConstant(2, dl, ExtVT));
18662       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
18663       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
18664
18665       // a += a
18666       ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
18667       AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
18668
18669       // r = VSELECT(r, shift(r, 1), a);
18670       MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
18671                         DAG.getConstant(1, dl, ExtVT));
18672       MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
18673                         DAG.getConstant(1, dl, ExtVT));
18674       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
18675       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
18676
18677       // Logical shift the result back to the lower byte, leaving a zero upper
18678       // byte
18679       // meaning that we can safely pack with PACKUSWB.
18680       RLo =
18681           DAG.getNode(ISD::SRL, dl, ExtVT, RLo, DAG.getConstant(8, dl, ExtVT));
18682       RHi =
18683           DAG.getNode(ISD::SRL, dl, ExtVT, RHi, DAG.getConstant(8, dl, ExtVT));
18684       return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
18685     }
18686   }
18687
18688   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
18689   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
18690   // solution better.
18691   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
18692     MVT ExtVT = MVT::v8i32;
18693     unsigned ExtOpc =
18694         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
18695     R = DAG.getNode(ExtOpc, dl, ExtVT, R);
18696     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, ExtVT, Amt);
18697     return DAG.getNode(ISD::TRUNCATE, dl, VT,
18698                        DAG.getNode(Op.getOpcode(), dl, ExtVT, R, Amt));
18699   }
18700
18701   if (Subtarget->hasInt256() && !Subtarget->hasXOP() && VT == MVT::v16i16) {
18702     MVT ExtVT = MVT::v8i32;
18703     SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
18704     SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, Amt, Z);
18705     SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, Amt, Z);
18706     SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, R, R);
18707     SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, R, R);
18708     ALo = DAG.getBitcast(ExtVT, ALo);
18709     AHi = DAG.getBitcast(ExtVT, AHi);
18710     RLo = DAG.getBitcast(ExtVT, RLo);
18711     RHi = DAG.getBitcast(ExtVT, RHi);
18712     SDValue Lo = DAG.getNode(Op.getOpcode(), dl, ExtVT, RLo, ALo);
18713     SDValue Hi = DAG.getNode(Op.getOpcode(), dl, ExtVT, RHi, AHi);
18714     Lo = DAG.getNode(ISD::SRL, dl, ExtVT, Lo, DAG.getConstant(16, dl, ExtVT));
18715     Hi = DAG.getNode(ISD::SRL, dl, ExtVT, Hi, DAG.getConstant(16, dl, ExtVT));
18716     return DAG.getNode(X86ISD::PACKUS, dl, VT, Lo, Hi);
18717   }
18718
18719   if (VT == MVT::v8i16) {
18720     unsigned ShiftOpcode = Op->getOpcode();
18721
18722     auto SignBitSelect = [&](SDValue Sel, SDValue V0, SDValue V1) {
18723       // On SSE41 targets we make use of the fact that VSELECT lowers
18724       // to PBLENDVB which selects bytes based just on the sign bit.
18725       if (Subtarget->hasSSE41()) {
18726         MVT ExtVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() * 2);
18727         V0 = DAG.getBitcast(ExtVT, V0);
18728         V1 = DAG.getBitcast(ExtVT, V1);
18729         Sel = DAG.getBitcast(ExtVT, Sel);
18730         return DAG.getBitcast(
18731             VT, DAG.getNode(ISD::VSELECT, dl, ExtVT, Sel, V0, V1));
18732       }
18733       // On pre-SSE41 targets we splat the sign bit - a negative value will
18734       // set all bits of the lanes to true and VSELECT uses that in
18735       // its OR(AND(V0,C),AND(V1,~C)) lowering.
18736       SDValue C =
18737           DAG.getNode(ISD::SRA, dl, VT, Sel, DAG.getConstant(15, dl, VT));
18738       return DAG.getNode(ISD::VSELECT, dl, VT, C, V0, V1);
18739     };
18740
18741     // Turn 'a' into a mask suitable for VSELECT: a = a << 12;
18742     if (Subtarget->hasSSE41()) {
18743       // On SSE41 targets we need to replicate the shift mask in both
18744       // bytes for PBLENDVB.
18745       Amt = DAG.getNode(
18746           ISD::OR, dl, VT,
18747           DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(4, dl, VT)),
18748           DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT)));
18749     } else {
18750       Amt = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT));
18751     }
18752
18753     // r = VSELECT(r, shift(r, 8), a);
18754     SDValue M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(8, dl, VT));
18755     R = SignBitSelect(Amt, M, R);
18756
18757     // a += a
18758     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18759
18760     // r = VSELECT(r, shift(r, 4), a);
18761     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
18762     R = SignBitSelect(Amt, M, R);
18763
18764     // a += a
18765     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18766
18767     // r = VSELECT(r, shift(r, 2), a);
18768     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
18769     R = SignBitSelect(Amt, M, R);
18770
18771     // a += a
18772     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18773
18774     // return VSELECT(r, shift(r, 1), a);
18775     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
18776     R = SignBitSelect(Amt, M, R);
18777     return R;
18778   }
18779
18780   // Decompose 256-bit shifts into smaller 128-bit shifts.
18781   if (VT.is256BitVector()) {
18782     unsigned NumElems = VT.getVectorNumElements();
18783     MVT EltVT = VT.getVectorElementType();
18784     MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
18785
18786     // Extract the two vectors
18787     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
18788     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
18789
18790     // Recreate the shift amount vectors
18791     SDValue Amt1, Amt2;
18792     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
18793       // Constant shift amount
18794       SmallVector<SDValue, 8> Ops(Amt->op_begin(), Amt->op_begin() + NumElems);
18795       ArrayRef<SDValue> Amt1Csts = makeArrayRef(Ops).slice(0, NumElems / 2);
18796       ArrayRef<SDValue> Amt2Csts = makeArrayRef(Ops).slice(NumElems / 2);
18797
18798       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
18799       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
18800     } else {
18801       // Variable shift amount
18802       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
18803       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
18804     }
18805
18806     // Issue new vector shifts for the smaller types
18807     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
18808     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
18809
18810     // Concatenate the result back
18811     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
18812   }
18813
18814   return SDValue();
18815 }
18816
18817 static SDValue LowerRotate(SDValue Op, const X86Subtarget *Subtarget,
18818                            SelectionDAG &DAG) {
18819   MVT VT = Op.getSimpleValueType();
18820   SDLoc DL(Op);
18821   SDValue R = Op.getOperand(0);
18822   SDValue Amt = Op.getOperand(1);
18823
18824   assert(VT.isVector() && "Custom lowering only for vector rotates!");
18825   assert(Subtarget->hasXOP() && "XOP support required for vector rotates!");
18826   assert((Op.getOpcode() == ISD::ROTL) && "Only ROTL supported");
18827
18828   // XOP has 128-bit vector variable + immediate rotates.
18829   // +ve/-ve Amt = rotate left/right.
18830
18831   // Split 256-bit integers.
18832   if (VT.is256BitVector())
18833     return Lower256IntArith(Op, DAG);
18834
18835   assert(VT.is128BitVector() && "Only rotate 128-bit vectors!");
18836
18837   // Attempt to rotate by immediate.
18838   if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
18839     if (auto *RotateConst = BVAmt->getConstantSplatNode()) {
18840       uint64_t RotateAmt = RotateConst->getAPIntValue().getZExtValue();
18841       assert(RotateAmt < VT.getScalarSizeInBits() && "Rotation out of range");
18842       return DAG.getNode(X86ISD::VPROTI, DL, VT, R,
18843                          DAG.getConstant(RotateAmt, DL, MVT::i8));
18844     }
18845   }
18846
18847   // Use general rotate by variable (per-element).
18848   return DAG.getNode(X86ISD::VPROT, DL, VT, R, Amt);
18849 }
18850
18851 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
18852   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
18853   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
18854   // looks for this combo and may remove the "setcc" instruction if the "setcc"
18855   // has only one use.
18856   SDNode *N = Op.getNode();
18857   SDValue LHS = N->getOperand(0);
18858   SDValue RHS = N->getOperand(1);
18859   unsigned BaseOp = 0;
18860   unsigned Cond = 0;
18861   SDLoc DL(Op);
18862   switch (Op.getOpcode()) {
18863   default: llvm_unreachable("Unknown ovf instruction!");
18864   case ISD::SADDO:
18865     // A subtract of one will be selected as a INC. Note that INC doesn't
18866     // set CF, so we can't do this for UADDO.
18867     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
18868       if (C->isOne()) {
18869         BaseOp = X86ISD::INC;
18870         Cond = X86::COND_O;
18871         break;
18872       }
18873     BaseOp = X86ISD::ADD;
18874     Cond = X86::COND_O;
18875     break;
18876   case ISD::UADDO:
18877     BaseOp = X86ISD::ADD;
18878     Cond = X86::COND_B;
18879     break;
18880   case ISD::SSUBO:
18881     // A subtract of one will be selected as a DEC. Note that DEC doesn't
18882     // set CF, so we can't do this for USUBO.
18883     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
18884       if (C->isOne()) {
18885         BaseOp = X86ISD::DEC;
18886         Cond = X86::COND_O;
18887         break;
18888       }
18889     BaseOp = X86ISD::SUB;
18890     Cond = X86::COND_O;
18891     break;
18892   case ISD::USUBO:
18893     BaseOp = X86ISD::SUB;
18894     Cond = X86::COND_B;
18895     break;
18896   case ISD::SMULO:
18897     BaseOp = N->getValueType(0) == MVT::i8 ? X86ISD::SMUL8 : X86ISD::SMUL;
18898     Cond = X86::COND_O;
18899     break;
18900   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
18901     if (N->getValueType(0) == MVT::i8) {
18902       BaseOp = X86ISD::UMUL8;
18903       Cond = X86::COND_O;
18904       break;
18905     }
18906     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
18907                                  MVT::i32);
18908     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
18909
18910     SDValue SetCC =
18911       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18912                   DAG.getConstant(X86::COND_O, DL, MVT::i32),
18913                   SDValue(Sum.getNode(), 2));
18914
18915     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
18916   }
18917   }
18918
18919   // Also sets EFLAGS.
18920   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
18921   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
18922
18923   SDValue SetCC =
18924     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
18925                 DAG.getConstant(Cond, DL, MVT::i32),
18926                 SDValue(Sum.getNode(), 1));
18927
18928   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
18929 }
18930
18931 /// Returns true if the operand type is exactly twice the native width, and
18932 /// the corresponding cmpxchg8b or cmpxchg16b instruction is available.
18933 /// Used to know whether to use cmpxchg8/16b when expanding atomic operations
18934 /// (otherwise we leave them alone to become __sync_fetch_and_... calls).
18935 bool X86TargetLowering::needsCmpXchgNb(Type *MemType) const {
18936   unsigned OpWidth = MemType->getPrimitiveSizeInBits();
18937
18938   if (OpWidth == 64)
18939     return !Subtarget->is64Bit(); // FIXME this should be Subtarget.hasCmpxchg8b
18940   else if (OpWidth == 128)
18941     return Subtarget->hasCmpxchg16b();
18942   else
18943     return false;
18944 }
18945
18946 bool X86TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
18947   return needsCmpXchgNb(SI->getValueOperand()->getType());
18948 }
18949
18950 // Note: this turns large loads into lock cmpxchg8b/16b.
18951 // FIXME: On 32 bits x86, fild/movq might be faster than lock cmpxchg8b.
18952 TargetLowering::AtomicExpansionKind
18953 X86TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
18954   auto PTy = cast<PointerType>(LI->getPointerOperand()->getType());
18955   return needsCmpXchgNb(PTy->getElementType()) ? AtomicExpansionKind::CmpXChg
18956                                                : AtomicExpansionKind::None;
18957 }
18958
18959 TargetLowering::AtomicExpansionKind
18960 X86TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
18961   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
18962   Type *MemType = AI->getType();
18963
18964   // If the operand is too big, we must see if cmpxchg8/16b is available
18965   // and default to library calls otherwise.
18966   if (MemType->getPrimitiveSizeInBits() > NativeWidth) {
18967     return needsCmpXchgNb(MemType) ? AtomicExpansionKind::CmpXChg
18968                                    : AtomicExpansionKind::None;
18969   }
18970
18971   AtomicRMWInst::BinOp Op = AI->getOperation();
18972   switch (Op) {
18973   default:
18974     llvm_unreachable("Unknown atomic operation");
18975   case AtomicRMWInst::Xchg:
18976   case AtomicRMWInst::Add:
18977   case AtomicRMWInst::Sub:
18978     // It's better to use xadd, xsub or xchg for these in all cases.
18979     return AtomicExpansionKind::None;
18980   case AtomicRMWInst::Or:
18981   case AtomicRMWInst::And:
18982   case AtomicRMWInst::Xor:
18983     // If the atomicrmw's result isn't actually used, we can just add a "lock"
18984     // prefix to a normal instruction for these operations.
18985     return !AI->use_empty() ? AtomicExpansionKind::CmpXChg
18986                             : AtomicExpansionKind::None;
18987   case AtomicRMWInst::Nand:
18988   case AtomicRMWInst::Max:
18989   case AtomicRMWInst::Min:
18990   case AtomicRMWInst::UMax:
18991   case AtomicRMWInst::UMin:
18992     // These always require a non-trivial set of data operations on x86. We must
18993     // use a cmpxchg loop.
18994     return AtomicExpansionKind::CmpXChg;
18995   }
18996 }
18997
18998 static bool hasMFENCE(const X86Subtarget& Subtarget) {
18999   // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
19000   // no-sse2). There isn't any reason to disable it if the target processor
19001   // supports it.
19002   return Subtarget.hasSSE2() || Subtarget.is64Bit();
19003 }
19004
19005 LoadInst *
19006 X86TargetLowering::lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *AI) const {
19007   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
19008   Type *MemType = AI->getType();
19009   // Accesses larger than the native width are turned into cmpxchg/libcalls, so
19010   // there is no benefit in turning such RMWs into loads, and it is actually
19011   // harmful as it introduces a mfence.
19012   if (MemType->getPrimitiveSizeInBits() > NativeWidth)
19013     return nullptr;
19014
19015   auto Builder = IRBuilder<>(AI);
19016   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
19017   auto SynchScope = AI->getSynchScope();
19018   // We must restrict the ordering to avoid generating loads with Release or
19019   // ReleaseAcquire orderings.
19020   auto Order = AtomicCmpXchgInst::getStrongestFailureOrdering(AI->getOrdering());
19021   auto Ptr = AI->getPointerOperand();
19022
19023   // Before the load we need a fence. Here is an example lifted from
19024   // http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf showing why a fence
19025   // is required:
19026   // Thread 0:
19027   //   x.store(1, relaxed);
19028   //   r1 = y.fetch_add(0, release);
19029   // Thread 1:
19030   //   y.fetch_add(42, acquire);
19031   //   r2 = x.load(relaxed);
19032   // r1 = r2 = 0 is impossible, but becomes possible if the idempotent rmw is
19033   // lowered to just a load without a fence. A mfence flushes the store buffer,
19034   // making the optimization clearly correct.
19035   // FIXME: it is required if isAtLeastRelease(Order) but it is not clear
19036   // otherwise, we might be able to be more aggressive on relaxed idempotent
19037   // rmw. In practice, they do not look useful, so we don't try to be
19038   // especially clever.
19039   if (SynchScope == SingleThread)
19040     // FIXME: we could just insert an X86ISD::MEMBARRIER here, except we are at
19041     // the IR level, so we must wrap it in an intrinsic.
19042     return nullptr;
19043
19044   if (!hasMFENCE(*Subtarget))
19045     // FIXME: it might make sense to use a locked operation here but on a
19046     // different cache-line to prevent cache-line bouncing. In practice it
19047     // is probably a small win, and x86 processors without mfence are rare
19048     // enough that we do not bother.
19049     return nullptr;
19050
19051   Function *MFence =
19052       llvm::Intrinsic::getDeclaration(M, Intrinsic::x86_sse2_mfence);
19053   Builder.CreateCall(MFence, {});
19054
19055   // Finally we can emit the atomic load.
19056   LoadInst *Loaded = Builder.CreateAlignedLoad(Ptr,
19057           AI->getType()->getPrimitiveSizeInBits());
19058   Loaded->setAtomic(Order, SynchScope);
19059   AI->replaceAllUsesWith(Loaded);
19060   AI->eraseFromParent();
19061   return Loaded;
19062 }
19063
19064 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
19065                                  SelectionDAG &DAG) {
19066   SDLoc dl(Op);
19067   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
19068     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
19069   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
19070     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
19071
19072   // The only fence that needs an instruction is a sequentially-consistent
19073   // cross-thread fence.
19074   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
19075     if (hasMFENCE(*Subtarget))
19076       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
19077
19078     SDValue Chain = Op.getOperand(0);
19079     SDValue Zero = DAG.getConstant(0, dl, MVT::i32);
19080     SDValue Ops[] = {
19081       DAG.getRegister(X86::ESP, MVT::i32),     // Base
19082       DAG.getTargetConstant(1, dl, MVT::i8),   // Scale
19083       DAG.getRegister(0, MVT::i32),            // Index
19084       DAG.getTargetConstant(0, dl, MVT::i32),  // Disp
19085       DAG.getRegister(0, MVT::i32),            // Segment.
19086       Zero,
19087       Chain
19088     };
19089     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
19090     return SDValue(Res, 0);
19091   }
19092
19093   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
19094   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
19095 }
19096
19097 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
19098                              SelectionDAG &DAG) {
19099   MVT T = Op.getSimpleValueType();
19100   SDLoc DL(Op);
19101   unsigned Reg = 0;
19102   unsigned size = 0;
19103   switch(T.SimpleTy) {
19104   default: llvm_unreachable("Invalid value type!");
19105   case MVT::i8:  Reg = X86::AL;  size = 1; break;
19106   case MVT::i16: Reg = X86::AX;  size = 2; break;
19107   case MVT::i32: Reg = X86::EAX; size = 4; break;
19108   case MVT::i64:
19109     assert(Subtarget->is64Bit() && "Node not type legal!");
19110     Reg = X86::RAX; size = 8;
19111     break;
19112   }
19113   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
19114                                   Op.getOperand(2), SDValue());
19115   SDValue Ops[] = { cpIn.getValue(0),
19116                     Op.getOperand(1),
19117                     Op.getOperand(3),
19118                     DAG.getTargetConstant(size, DL, MVT::i8),
19119                     cpIn.getValue(1) };
19120   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
19121   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
19122   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
19123                                            Ops, T, MMO);
19124
19125   SDValue cpOut =
19126     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
19127   SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
19128                                       MVT::i32, cpOut.getValue(2));
19129   SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
19130                                 DAG.getConstant(X86::COND_E, DL, MVT::i8),
19131                                 EFLAGS);
19132
19133   DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
19134   DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
19135   DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
19136   return SDValue();
19137 }
19138
19139 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
19140                             SelectionDAG &DAG) {
19141   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
19142   MVT DstVT = Op.getSimpleValueType();
19143
19144   if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
19145     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
19146     if (DstVT != MVT::f64)
19147       // This conversion needs to be expanded.
19148       return SDValue();
19149
19150     SDValue InVec = Op->getOperand(0);
19151     SDLoc dl(Op);
19152     unsigned NumElts = SrcVT.getVectorNumElements();
19153     MVT SVT = SrcVT.getVectorElementType();
19154
19155     // Widen the vector in input in the case of MVT::v2i32.
19156     // Example: from MVT::v2i32 to MVT::v4i32.
19157     SmallVector<SDValue, 16> Elts;
19158     for (unsigned i = 0, e = NumElts; i != e; ++i)
19159       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
19160                                  DAG.getIntPtrConstant(i, dl)));
19161
19162     // Explicitly mark the extra elements as Undef.
19163     Elts.append(NumElts, DAG.getUNDEF(SVT));
19164
19165     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
19166     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
19167     SDValue ToV2F64 = DAG.getBitcast(MVT::v2f64, BV);
19168     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
19169                        DAG.getIntPtrConstant(0, dl));
19170   }
19171
19172   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
19173          Subtarget->hasMMX() && "Unexpected custom BITCAST");
19174   assert((DstVT == MVT::i64 ||
19175           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
19176          "Unexpected custom BITCAST");
19177   // i64 <=> MMX conversions are Legal.
19178   if (SrcVT==MVT::i64 && DstVT.isVector())
19179     return Op;
19180   if (DstVT==MVT::i64 && SrcVT.isVector())
19181     return Op;
19182   // MMX <=> MMX conversions are Legal.
19183   if (SrcVT.isVector() && DstVT.isVector())
19184     return Op;
19185   // All other conversions need to be expanded.
19186   return SDValue();
19187 }
19188
19189 /// Compute the horizontal sum of bytes in V for the elements of VT.
19190 ///
19191 /// Requires V to be a byte vector and VT to be an integer vector type with
19192 /// wider elements than V's type. The width of the elements of VT determines
19193 /// how many bytes of V are summed horizontally to produce each element of the
19194 /// result.
19195 static SDValue LowerHorizontalByteSum(SDValue V, MVT VT,
19196                                       const X86Subtarget *Subtarget,
19197                                       SelectionDAG &DAG) {
19198   SDLoc DL(V);
19199   MVT ByteVecVT = V.getSimpleValueType();
19200   MVT EltVT = VT.getVectorElementType();
19201   int NumElts = VT.getVectorNumElements();
19202   assert(ByteVecVT.getVectorElementType() == MVT::i8 &&
19203          "Expected value to have byte element type.");
19204   assert(EltVT != MVT::i8 &&
19205          "Horizontal byte sum only makes sense for wider elements!");
19206   unsigned VecSize = VT.getSizeInBits();
19207   assert(ByteVecVT.getSizeInBits() == VecSize && "Cannot change vector size!");
19208
19209   // PSADBW instruction horizontally add all bytes and leave the result in i64
19210   // chunks, thus directly computes the pop count for v2i64 and v4i64.
19211   if (EltVT == MVT::i64) {
19212     SDValue Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
19213     V = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT, V, Zeros);
19214     return DAG.getBitcast(VT, V);
19215   }
19216
19217   if (EltVT == MVT::i32) {
19218     // We unpack the low half and high half into i32s interleaved with zeros so
19219     // that we can use PSADBW to horizontally sum them. The most useful part of
19220     // this is that it lines up the results of two PSADBW instructions to be
19221     // two v2i64 vectors which concatenated are the 4 population counts. We can
19222     // then use PACKUSWB to shrink and concatenate them into a v4i32 again.
19223     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, DL);
19224     SDValue Low = DAG.getNode(X86ISD::UNPCKL, DL, VT, V, Zeros);
19225     SDValue High = DAG.getNode(X86ISD::UNPCKH, DL, VT, V, Zeros);
19226
19227     // Do the horizontal sums into two v2i64s.
19228     Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
19229     Low = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT,
19230                       DAG.getBitcast(ByteVecVT, Low), Zeros);
19231     High = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT,
19232                        DAG.getBitcast(ByteVecVT, High), Zeros);
19233
19234     // Merge them together.
19235     MVT ShortVecVT = MVT::getVectorVT(MVT::i16, VecSize / 16);
19236     V = DAG.getNode(X86ISD::PACKUS, DL, ByteVecVT,
19237                     DAG.getBitcast(ShortVecVT, Low),
19238                     DAG.getBitcast(ShortVecVT, High));
19239
19240     return DAG.getBitcast(VT, V);
19241   }
19242
19243   // The only element type left is i16.
19244   assert(EltVT == MVT::i16 && "Unknown how to handle type");
19245
19246   // To obtain pop count for each i16 element starting from the pop count for
19247   // i8 elements, shift the i16s left by 8, sum as i8s, and then shift as i16s
19248   // right by 8. It is important to shift as i16s as i8 vector shift isn't
19249   // directly supported.
19250   SmallVector<SDValue, 16> Shifters(NumElts, DAG.getConstant(8, DL, EltVT));
19251   SDValue Shifter = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters);
19252   SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, DAG.getBitcast(VT, V), Shifter);
19253   V = DAG.getNode(ISD::ADD, DL, ByteVecVT, DAG.getBitcast(ByteVecVT, Shl),
19254                   DAG.getBitcast(ByteVecVT, V));
19255   return DAG.getNode(ISD::SRL, DL, VT, DAG.getBitcast(VT, V), Shifter);
19256 }
19257
19258 static SDValue LowerVectorCTPOPInRegLUT(SDValue Op, SDLoc DL,
19259                                         const X86Subtarget *Subtarget,
19260                                         SelectionDAG &DAG) {
19261   MVT VT = Op.getSimpleValueType();
19262   MVT EltVT = VT.getVectorElementType();
19263   unsigned VecSize = VT.getSizeInBits();
19264
19265   // Implement a lookup table in register by using an algorithm based on:
19266   // http://wm.ite.pl/articles/sse-popcount.html
19267   //
19268   // The general idea is that every lower byte nibble in the input vector is an
19269   // index into a in-register pre-computed pop count table. We then split up the
19270   // input vector in two new ones: (1) a vector with only the shifted-right
19271   // higher nibbles for each byte and (2) a vector with the lower nibbles (and
19272   // masked out higher ones) for each byte. PSHUB is used separately with both
19273   // to index the in-register table. Next, both are added and the result is a
19274   // i8 vector where each element contains the pop count for input byte.
19275   //
19276   // To obtain the pop count for elements != i8, we follow up with the same
19277   // approach and use additional tricks as described below.
19278   //
19279   const int LUT[16] = {/* 0 */ 0, /* 1 */ 1, /* 2 */ 1, /* 3 */ 2,
19280                        /* 4 */ 1, /* 5 */ 2, /* 6 */ 2, /* 7 */ 3,
19281                        /* 8 */ 1, /* 9 */ 2, /* a */ 2, /* b */ 3,
19282                        /* c */ 2, /* d */ 3, /* e */ 3, /* f */ 4};
19283
19284   int NumByteElts = VecSize / 8;
19285   MVT ByteVecVT = MVT::getVectorVT(MVT::i8, NumByteElts);
19286   SDValue In = DAG.getBitcast(ByteVecVT, Op);
19287   SmallVector<SDValue, 16> LUTVec;
19288   for (int i = 0; i < NumByteElts; ++i)
19289     LUTVec.push_back(DAG.getConstant(LUT[i % 16], DL, MVT::i8));
19290   SDValue InRegLUT = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, LUTVec);
19291   SmallVector<SDValue, 16> Mask0F(NumByteElts,
19292                                   DAG.getConstant(0x0F, DL, MVT::i8));
19293   SDValue M0F = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Mask0F);
19294
19295   // High nibbles
19296   SmallVector<SDValue, 16> Four(NumByteElts, DAG.getConstant(4, DL, MVT::i8));
19297   SDValue FourV = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Four);
19298   SDValue HighNibbles = DAG.getNode(ISD::SRL, DL, ByteVecVT, In, FourV);
19299
19300   // Low nibbles
19301   SDValue LowNibbles = DAG.getNode(ISD::AND, DL, ByteVecVT, In, M0F);
19302
19303   // The input vector is used as the shuffle mask that index elements into the
19304   // LUT. After counting low and high nibbles, add the vector to obtain the
19305   // final pop count per i8 element.
19306   SDValue HighPopCnt =
19307       DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, HighNibbles);
19308   SDValue LowPopCnt =
19309       DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, LowNibbles);
19310   SDValue PopCnt = DAG.getNode(ISD::ADD, DL, ByteVecVT, HighPopCnt, LowPopCnt);
19311
19312   if (EltVT == MVT::i8)
19313     return PopCnt;
19314
19315   return LowerHorizontalByteSum(PopCnt, VT, Subtarget, DAG);
19316 }
19317
19318 static SDValue LowerVectorCTPOPBitmath(SDValue Op, SDLoc DL,
19319                                        const X86Subtarget *Subtarget,
19320                                        SelectionDAG &DAG) {
19321   MVT VT = Op.getSimpleValueType();
19322   assert(VT.is128BitVector() &&
19323          "Only 128-bit vector bitmath lowering supported.");
19324
19325   int VecSize = VT.getSizeInBits();
19326   MVT EltVT = VT.getVectorElementType();
19327   int Len = EltVT.getSizeInBits();
19328
19329   // This is the vectorized version of the "best" algorithm from
19330   // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
19331   // with a minor tweak to use a series of adds + shifts instead of vector
19332   // multiplications. Implemented for all integer vector types. We only use
19333   // this when we don't have SSSE3 which allows a LUT-based lowering that is
19334   // much faster, even faster than using native popcnt instructions.
19335
19336   auto GetShift = [&](unsigned OpCode, SDValue V, int Shifter) {
19337     MVT VT = V.getSimpleValueType();
19338     SmallVector<SDValue, 32> Shifters(
19339         VT.getVectorNumElements(),
19340         DAG.getConstant(Shifter, DL, VT.getVectorElementType()));
19341     return DAG.getNode(OpCode, DL, VT, V,
19342                        DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters));
19343   };
19344   auto GetMask = [&](SDValue V, APInt Mask) {
19345     MVT VT = V.getSimpleValueType();
19346     SmallVector<SDValue, 32> Masks(
19347         VT.getVectorNumElements(),
19348         DAG.getConstant(Mask, DL, VT.getVectorElementType()));
19349     return DAG.getNode(ISD::AND, DL, VT, V,
19350                        DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Masks));
19351   };
19352
19353   // We don't want to incur the implicit masks required to SRL vNi8 vectors on
19354   // x86, so set the SRL type to have elements at least i16 wide. This is
19355   // correct because all of our SRLs are followed immediately by a mask anyways
19356   // that handles any bits that sneak into the high bits of the byte elements.
19357   MVT SrlVT = Len > 8 ? VT : MVT::getVectorVT(MVT::i16, VecSize / 16);
19358
19359   SDValue V = Op;
19360
19361   // v = v - ((v >> 1) & 0x55555555...)
19362   SDValue Srl =
19363       DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 1));
19364   SDValue And = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x55)));
19365   V = DAG.getNode(ISD::SUB, DL, VT, V, And);
19366
19367   // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
19368   SDValue AndLHS = GetMask(V, APInt::getSplat(Len, APInt(8, 0x33)));
19369   Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 2));
19370   SDValue AndRHS = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x33)));
19371   V = DAG.getNode(ISD::ADD, DL, VT, AndLHS, AndRHS);
19372
19373   // v = (v + (v >> 4)) & 0x0F0F0F0F...
19374   Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 4));
19375   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, V, Srl);
19376   V = GetMask(Add, APInt::getSplat(Len, APInt(8, 0x0F)));
19377
19378   // At this point, V contains the byte-wise population count, and we are
19379   // merely doing a horizontal sum if necessary to get the wider element
19380   // counts.
19381   if (EltVT == MVT::i8)
19382     return V;
19383
19384   return LowerHorizontalByteSum(
19385       DAG.getBitcast(MVT::getVectorVT(MVT::i8, VecSize / 8), V), VT, Subtarget,
19386       DAG);
19387 }
19388
19389 static SDValue LowerVectorCTPOP(SDValue Op, const X86Subtarget *Subtarget,
19390                                 SelectionDAG &DAG) {
19391   MVT VT = Op.getSimpleValueType();
19392   // FIXME: Need to add AVX-512 support here!
19393   assert((VT.is256BitVector() || VT.is128BitVector()) &&
19394          "Unknown CTPOP type to handle");
19395   SDLoc DL(Op.getNode());
19396   SDValue Op0 = Op.getOperand(0);
19397
19398   if (!Subtarget->hasSSSE3()) {
19399     // We can't use the fast LUT approach, so fall back on vectorized bitmath.
19400     assert(VT.is128BitVector() && "Only 128-bit vectors supported in SSE!");
19401     return LowerVectorCTPOPBitmath(Op0, DL, Subtarget, DAG);
19402   }
19403
19404   if (VT.is256BitVector() && !Subtarget->hasInt256()) {
19405     unsigned NumElems = VT.getVectorNumElements();
19406
19407     // Extract each 128-bit vector, compute pop count and concat the result.
19408     SDValue LHS = Extract128BitVector(Op0, 0, DAG, DL);
19409     SDValue RHS = Extract128BitVector(Op0, NumElems/2, DAG, DL);
19410
19411     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT,
19412                        LowerVectorCTPOPInRegLUT(LHS, DL, Subtarget, DAG),
19413                        LowerVectorCTPOPInRegLUT(RHS, DL, Subtarget, DAG));
19414   }
19415
19416   return LowerVectorCTPOPInRegLUT(Op0, DL, Subtarget, DAG);
19417 }
19418
19419 static SDValue LowerCTPOP(SDValue Op, const X86Subtarget *Subtarget,
19420                           SelectionDAG &DAG) {
19421   assert(Op.getSimpleValueType().isVector() &&
19422          "We only do custom lowering for vector population count.");
19423   return LowerVectorCTPOP(Op, Subtarget, DAG);
19424 }
19425
19426 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
19427   SDNode *Node = Op.getNode();
19428   SDLoc dl(Node);
19429   EVT T = Node->getValueType(0);
19430   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
19431                               DAG.getConstant(0, dl, T), Node->getOperand(2));
19432   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
19433                        cast<AtomicSDNode>(Node)->getMemoryVT(),
19434                        Node->getOperand(0),
19435                        Node->getOperand(1), negOp,
19436                        cast<AtomicSDNode>(Node)->getMemOperand(),
19437                        cast<AtomicSDNode>(Node)->getOrdering(),
19438                        cast<AtomicSDNode>(Node)->getSynchScope());
19439 }
19440
19441 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
19442   SDNode *Node = Op.getNode();
19443   SDLoc dl(Node);
19444   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
19445
19446   // Convert seq_cst store -> xchg
19447   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
19448   // FIXME: On 32-bit, store -> fist or movq would be more efficient
19449   //        (The only way to get a 16-byte store is cmpxchg16b)
19450   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
19451   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
19452       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
19453     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
19454                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
19455                                  Node->getOperand(0),
19456                                  Node->getOperand(1), Node->getOperand(2),
19457                                  cast<AtomicSDNode>(Node)->getMemOperand(),
19458                                  cast<AtomicSDNode>(Node)->getOrdering(),
19459                                  cast<AtomicSDNode>(Node)->getSynchScope());
19460     return Swap.getValue(1);
19461   }
19462   // Other atomic stores have a simple pattern.
19463   return Op;
19464 }
19465
19466 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
19467   MVT VT = Op.getNode()->getSimpleValueType(0);
19468
19469   // Let legalize expand this if it isn't a legal type yet.
19470   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
19471     return SDValue();
19472
19473   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
19474
19475   unsigned Opc;
19476   bool ExtraOp = false;
19477   switch (Op.getOpcode()) {
19478   default: llvm_unreachable("Invalid code");
19479   case ISD::ADDC: Opc = X86ISD::ADD; break;
19480   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
19481   case ISD::SUBC: Opc = X86ISD::SUB; break;
19482   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
19483   }
19484
19485   if (!ExtraOp)
19486     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
19487                        Op.getOperand(1));
19488   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
19489                      Op.getOperand(1), Op.getOperand(2));
19490 }
19491
19492 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
19493                             SelectionDAG &DAG) {
19494   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
19495
19496   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
19497   // which returns the values as { float, float } (in XMM0) or
19498   // { double, double } (which is returned in XMM0, XMM1).
19499   SDLoc dl(Op);
19500   SDValue Arg = Op.getOperand(0);
19501   EVT ArgVT = Arg.getValueType();
19502   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
19503
19504   TargetLowering::ArgListTy Args;
19505   TargetLowering::ArgListEntry Entry;
19506
19507   Entry.Node = Arg;
19508   Entry.Ty = ArgTy;
19509   Entry.isSExt = false;
19510   Entry.isZExt = false;
19511   Args.push_back(Entry);
19512
19513   bool isF64 = ArgVT == MVT::f64;
19514   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
19515   // the small struct {f32, f32} is returned in (eax, edx). For f64,
19516   // the results are returned via SRet in memory.
19517   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
19518   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19519   SDValue Callee =
19520       DAG.getExternalSymbol(LibcallName, TLI.getPointerTy(DAG.getDataLayout()));
19521
19522   Type *RetTy = isF64
19523     ? (Type*)StructType::get(ArgTy, ArgTy, nullptr)
19524     : (Type*)VectorType::get(ArgTy, 4);
19525
19526   TargetLowering::CallLoweringInfo CLI(DAG);
19527   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
19528     .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
19529
19530   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
19531
19532   if (isF64)
19533     // Returned in xmm0 and xmm1.
19534     return CallResult.first;
19535
19536   // Returned in bits 0:31 and 32:64 xmm0.
19537   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
19538                                CallResult.first, DAG.getIntPtrConstant(0, dl));
19539   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
19540                                CallResult.first, DAG.getIntPtrConstant(1, dl));
19541   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
19542   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
19543 }
19544
19545 static SDValue LowerMSCATTER(SDValue Op, const X86Subtarget *Subtarget,
19546                              SelectionDAG &DAG) {
19547   assert(Subtarget->hasAVX512() &&
19548          "MGATHER/MSCATTER are supported on AVX-512 arch only");
19549
19550   MaskedScatterSDNode *N = cast<MaskedScatterSDNode>(Op.getNode());
19551   MVT VT = N->getValue().getSimpleValueType();
19552   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported scatter op");
19553   SDLoc dl(Op);
19554
19555   // X86 scatter kills mask register, so its type should be added to
19556   // the list of return values
19557   if (N->getNumValues() == 1) {
19558     SDValue Index = N->getIndex();
19559     if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
19560         !Index.getSimpleValueType().is512BitVector())
19561       Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
19562
19563     SDVTList VTs = DAG.getVTList(N->getMask().getValueType(), MVT::Other);
19564     SDValue Ops[] = { N->getOperand(0), N->getOperand(1),  N->getOperand(2),
19565                       N->getOperand(3), Index };
19566
19567     SDValue NewScatter = DAG.getMaskedScatter(VTs, VT, dl, Ops, N->getMemOperand());
19568     DAG.ReplaceAllUsesWith(Op, SDValue(NewScatter.getNode(), 1));
19569     return SDValue(NewScatter.getNode(), 0);
19570   }
19571   return Op;
19572 }
19573
19574 static SDValue LowerMGATHER(SDValue Op, const X86Subtarget *Subtarget,
19575                             SelectionDAG &DAG) {
19576   assert(Subtarget->hasAVX512() &&
19577          "MGATHER/MSCATTER are supported on AVX-512 arch only");
19578
19579   MaskedGatherSDNode *N = cast<MaskedGatherSDNode>(Op.getNode());
19580   MVT VT = Op.getSimpleValueType();
19581   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported gather op");
19582   SDLoc dl(Op);
19583
19584   SDValue Index = N->getIndex();
19585   if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
19586       !Index.getSimpleValueType().is512BitVector()) {
19587     Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
19588     SDValue Ops[] = { N->getOperand(0), N->getOperand(1),  N->getOperand(2),
19589                       N->getOperand(3), Index };
19590     DAG.UpdateNodeOperands(N, Ops);
19591   }
19592   return Op;
19593 }
19594
19595 SDValue X86TargetLowering::LowerGC_TRANSITION_START(SDValue Op,
19596                                                     SelectionDAG &DAG) const {
19597   // TODO: Eventually, the lowering of these nodes should be informed by or
19598   // deferred to the GC strategy for the function in which they appear. For
19599   // now, however, they must be lowered to something. Since they are logically
19600   // no-ops in the case of a null GC strategy (or a GC strategy which does not
19601   // require special handling for these nodes), lower them as literal NOOPs for
19602   // the time being.
19603   SmallVector<SDValue, 2> Ops;
19604
19605   Ops.push_back(Op.getOperand(0));
19606   if (Op->getGluedNode())
19607     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
19608
19609   SDLoc OpDL(Op);
19610   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
19611   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
19612
19613   return NOOP;
19614 }
19615
19616 SDValue X86TargetLowering::LowerGC_TRANSITION_END(SDValue Op,
19617                                                   SelectionDAG &DAG) const {
19618   // TODO: Eventually, the lowering of these nodes should be informed by or
19619   // deferred to the GC strategy for the function in which they appear. For
19620   // now, however, they must be lowered to something. Since they are logically
19621   // no-ops in the case of a null GC strategy (or a GC strategy which does not
19622   // require special handling for these nodes), lower them as literal NOOPs for
19623   // the time being.
19624   SmallVector<SDValue, 2> Ops;
19625
19626   Ops.push_back(Op.getOperand(0));
19627   if (Op->getGluedNode())
19628     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
19629
19630   SDLoc OpDL(Op);
19631   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
19632   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
19633
19634   return NOOP;
19635 }
19636
19637 /// LowerOperation - Provide custom lowering hooks for some operations.
19638 ///
19639 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
19640   switch (Op.getOpcode()) {
19641   default: llvm_unreachable("Should not custom lower this!");
19642   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
19643   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
19644     return LowerCMP_SWAP(Op, Subtarget, DAG);
19645   case ISD::CTPOP:              return LowerCTPOP(Op, Subtarget, DAG);
19646   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
19647   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
19648   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
19649   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, Subtarget, DAG);
19650   case ISD::VECTOR_SHUFFLE:     return lowerVectorShuffle(Op, Subtarget, DAG);
19651   case ISD::VSELECT:            return LowerVSELECT(Op, DAG);
19652   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
19653   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
19654   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
19655   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
19656   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
19657   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
19658   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
19659   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
19660   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
19661   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
19662   case ISD::SHL_PARTS:
19663   case ISD::SRA_PARTS:
19664   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
19665   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
19666   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
19667   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
19668   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
19669   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
19670   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
19671   case ISD::SIGN_EXTEND_VECTOR_INREG:
19672     return LowerSIGN_EXTEND_VECTOR_INREG(Op, Subtarget, DAG);
19673   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
19674   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
19675   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
19676   case ISD::LOAD:               return LowerExtendedLoad(Op, Subtarget, DAG);
19677   case ISD::FABS:
19678   case ISD::FNEG:               return LowerFABSorFNEG(Op, DAG);
19679   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
19680   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
19681   case ISD::SETCC:              return LowerSETCC(Op, DAG);
19682   case ISD::SELECT:             return LowerSELECT(Op, DAG);
19683   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
19684   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
19685   case ISD::VASTART:            return LowerVASTART(Op, DAG);
19686   case ISD::VAARG:              return LowerVAARG(Op, DAG);
19687   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
19688   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, Subtarget, DAG);
19689   case ISD::INTRINSIC_VOID:
19690   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
19691   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
19692   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
19693   case ISD::FRAME_TO_ARGS_OFFSET:
19694                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
19695   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
19696   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
19697   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
19698   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
19699   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
19700   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
19701   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
19702   case ISD::CTLZ:               return LowerCTLZ(Op, Subtarget, DAG);
19703   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, Subtarget, DAG);
19704   case ISD::CTTZ:
19705   case ISD::CTTZ_ZERO_UNDEF:    return LowerCTTZ(Op, DAG);
19706   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
19707   case ISD::UMUL_LOHI:
19708   case ISD::SMUL_LOHI:          return LowerMUL_LOHI(Op, Subtarget, DAG);
19709   case ISD::ROTL:               return LowerRotate(Op, Subtarget, DAG);
19710   case ISD::SRA:
19711   case ISD::SRL:
19712   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
19713   case ISD::SADDO:
19714   case ISD::UADDO:
19715   case ISD::SSUBO:
19716   case ISD::USUBO:
19717   case ISD::SMULO:
19718   case ISD::UMULO:              return LowerXALUO(Op, DAG);
19719   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
19720   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
19721   case ISD::ADDC:
19722   case ISD::ADDE:
19723   case ISD::SUBC:
19724   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
19725   case ISD::ADD:                return LowerADD(Op, DAG);
19726   case ISD::SUB:                return LowerSUB(Op, DAG);
19727   case ISD::SMAX:
19728   case ISD::SMIN:
19729   case ISD::UMAX:
19730   case ISD::UMIN:               return LowerMINMAX(Op, DAG);
19731   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
19732   case ISD::MGATHER:            return LowerMGATHER(Op, Subtarget, DAG);
19733   case ISD::MSCATTER:           return LowerMSCATTER(Op, Subtarget, DAG);
19734   case ISD::GC_TRANSITION_START:
19735                                 return LowerGC_TRANSITION_START(Op, DAG);
19736   case ISD::GC_TRANSITION_END:  return LowerGC_TRANSITION_END(Op, DAG);
19737   }
19738 }
19739
19740 /// ReplaceNodeResults - Replace a node with an illegal result type
19741 /// with a new node built out of custom code.
19742 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
19743                                            SmallVectorImpl<SDValue>&Results,
19744                                            SelectionDAG &DAG) const {
19745   SDLoc dl(N);
19746   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19747   switch (N->getOpcode()) {
19748   default:
19749     llvm_unreachable("Do not know how to custom type legalize this operation!");
19750   // We might have generated v2f32 FMIN/FMAX operations. Widen them to v4f32.
19751   case X86ISD::FMINC:
19752   case X86ISD::FMIN:
19753   case X86ISD::FMAXC:
19754   case X86ISD::FMAX: {
19755     EVT VT = N->getValueType(0);
19756     assert(VT == MVT::v2f32 && "Unexpected type (!= v2f32) on FMIN/FMAX.");
19757     SDValue UNDEF = DAG.getUNDEF(VT);
19758     SDValue LHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
19759                               N->getOperand(0), UNDEF);
19760     SDValue RHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
19761                               N->getOperand(1), UNDEF);
19762     Results.push_back(DAG.getNode(N->getOpcode(), dl, MVT::v4f32, LHS, RHS));
19763     return;
19764   }
19765   case ISD::SIGN_EXTEND_INREG:
19766   case ISD::ADDC:
19767   case ISD::ADDE:
19768   case ISD::SUBC:
19769   case ISD::SUBE:
19770     // We don't want to expand or promote these.
19771     return;
19772   case ISD::SDIV:
19773   case ISD::UDIV:
19774   case ISD::SREM:
19775   case ISD::UREM:
19776   case ISD::SDIVREM:
19777   case ISD::UDIVREM: {
19778     SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
19779     Results.push_back(V);
19780     return;
19781   }
19782   case ISD::FP_TO_SINT:
19783   case ISD::FP_TO_UINT: {
19784     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
19785
19786     std::pair<SDValue,SDValue> Vals =
19787         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
19788     SDValue FIST = Vals.first, StackSlot = Vals.second;
19789     if (FIST.getNode()) {
19790       EVT VT = N->getValueType(0);
19791       // Return a load from the stack slot.
19792       if (StackSlot.getNode())
19793         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
19794                                       MachinePointerInfo(),
19795                                       false, false, false, 0));
19796       else
19797         Results.push_back(FIST);
19798     }
19799     return;
19800   }
19801   case ISD::UINT_TO_FP: {
19802     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
19803     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
19804         N->getValueType(0) != MVT::v2f32)
19805       return;
19806     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
19807                                  N->getOperand(0));
19808     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
19809                                      MVT::f64);
19810     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
19811     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
19812                              DAG.getBitcast(MVT::v2i64, VBias));
19813     Or = DAG.getBitcast(MVT::v2f64, Or);
19814     // TODO: Are there any fast-math-flags to propagate here?
19815     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
19816     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
19817     return;
19818   }
19819   case ISD::FP_ROUND: {
19820     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
19821         return;
19822     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
19823     Results.push_back(V);
19824     return;
19825   }
19826   case ISD::FP_EXTEND: {
19827     // Right now, only MVT::v2f32 has OperationAction for FP_EXTEND.
19828     // No other ValueType for FP_EXTEND should reach this point.
19829     assert(N->getValueType(0) == MVT::v2f32 &&
19830            "Do not know how to legalize this Node");
19831     return;
19832   }
19833   case ISD::INTRINSIC_W_CHAIN: {
19834     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
19835     switch (IntNo) {
19836     default : llvm_unreachable("Do not know how to custom type "
19837                                "legalize this intrinsic operation!");
19838     case Intrinsic::x86_rdtsc:
19839       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
19840                                      Results);
19841     case Intrinsic::x86_rdtscp:
19842       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
19843                                      Results);
19844     case Intrinsic::x86_rdpmc:
19845       return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
19846     }
19847   }
19848   case ISD::READCYCLECOUNTER: {
19849     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
19850                                    Results);
19851   }
19852   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
19853     EVT T = N->getValueType(0);
19854     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
19855     bool Regs64bit = T == MVT::i128;
19856     MVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
19857     SDValue cpInL, cpInH;
19858     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
19859                         DAG.getConstant(0, dl, HalfT));
19860     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
19861                         DAG.getConstant(1, dl, HalfT));
19862     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
19863                              Regs64bit ? X86::RAX : X86::EAX,
19864                              cpInL, SDValue());
19865     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
19866                              Regs64bit ? X86::RDX : X86::EDX,
19867                              cpInH, cpInL.getValue(1));
19868     SDValue swapInL, swapInH;
19869     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
19870                           DAG.getConstant(0, dl, HalfT));
19871     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
19872                           DAG.getConstant(1, dl, HalfT));
19873     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
19874                                Regs64bit ? X86::RBX : X86::EBX,
19875                                swapInL, cpInH.getValue(1));
19876     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
19877                                Regs64bit ? X86::RCX : X86::ECX,
19878                                swapInH, swapInL.getValue(1));
19879     SDValue Ops[] = { swapInH.getValue(0),
19880                       N->getOperand(1),
19881                       swapInH.getValue(1) };
19882     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
19883     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
19884     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
19885                                   X86ISD::LCMPXCHG8_DAG;
19886     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
19887     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
19888                                         Regs64bit ? X86::RAX : X86::EAX,
19889                                         HalfT, Result.getValue(1));
19890     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
19891                                         Regs64bit ? X86::RDX : X86::EDX,
19892                                         HalfT, cpOutL.getValue(2));
19893     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
19894
19895     SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
19896                                         MVT::i32, cpOutH.getValue(2));
19897     SDValue Success =
19898         DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
19899                     DAG.getConstant(X86::COND_E, dl, MVT::i8), EFLAGS);
19900     Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
19901
19902     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
19903     Results.push_back(Success);
19904     Results.push_back(EFLAGS.getValue(1));
19905     return;
19906   }
19907   case ISD::ATOMIC_SWAP:
19908   case ISD::ATOMIC_LOAD_ADD:
19909   case ISD::ATOMIC_LOAD_SUB:
19910   case ISD::ATOMIC_LOAD_AND:
19911   case ISD::ATOMIC_LOAD_OR:
19912   case ISD::ATOMIC_LOAD_XOR:
19913   case ISD::ATOMIC_LOAD_NAND:
19914   case ISD::ATOMIC_LOAD_MIN:
19915   case ISD::ATOMIC_LOAD_MAX:
19916   case ISD::ATOMIC_LOAD_UMIN:
19917   case ISD::ATOMIC_LOAD_UMAX:
19918   case ISD::ATOMIC_LOAD: {
19919     // Delegate to generic TypeLegalization. Situations we can really handle
19920     // should have already been dealt with by AtomicExpandPass.cpp.
19921     break;
19922   }
19923   case ISD::BITCAST: {
19924     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
19925     EVT DstVT = N->getValueType(0);
19926     EVT SrcVT = N->getOperand(0)->getValueType(0);
19927
19928     if (SrcVT != MVT::f64 ||
19929         (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
19930       return;
19931
19932     unsigned NumElts = DstVT.getVectorNumElements();
19933     EVT SVT = DstVT.getVectorElementType();
19934     EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
19935     SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
19936                                    MVT::v2f64, N->getOperand(0));
19937     SDValue ToVecInt = DAG.getBitcast(WiderVT, Expanded);
19938
19939     if (ExperimentalVectorWideningLegalization) {
19940       // If we are legalizing vectors by widening, we already have the desired
19941       // legal vector type, just return it.
19942       Results.push_back(ToVecInt);
19943       return;
19944     }
19945
19946     SmallVector<SDValue, 8> Elts;
19947     for (unsigned i = 0, e = NumElts; i != e; ++i)
19948       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
19949                                    ToVecInt, DAG.getIntPtrConstant(i, dl)));
19950
19951     Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
19952   }
19953   }
19954 }
19955
19956 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
19957   switch ((X86ISD::NodeType)Opcode) {
19958   case X86ISD::FIRST_NUMBER:       break;
19959   case X86ISD::BSF:                return "X86ISD::BSF";
19960   case X86ISD::BSR:                return "X86ISD::BSR";
19961   case X86ISD::SHLD:               return "X86ISD::SHLD";
19962   case X86ISD::SHRD:               return "X86ISD::SHRD";
19963   case X86ISD::FAND:               return "X86ISD::FAND";
19964   case X86ISD::FANDN:              return "X86ISD::FANDN";
19965   case X86ISD::FOR:                return "X86ISD::FOR";
19966   case X86ISD::FXOR:               return "X86ISD::FXOR";
19967   case X86ISD::FILD:               return "X86ISD::FILD";
19968   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
19969   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
19970   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
19971   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
19972   case X86ISD::FLD:                return "X86ISD::FLD";
19973   case X86ISD::FST:                return "X86ISD::FST";
19974   case X86ISD::CALL:               return "X86ISD::CALL";
19975   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
19976   case X86ISD::RDTSCP_DAG:         return "X86ISD::RDTSCP_DAG";
19977   case X86ISD::RDPMC_DAG:          return "X86ISD::RDPMC_DAG";
19978   case X86ISD::BT:                 return "X86ISD::BT";
19979   case X86ISD::CMP:                return "X86ISD::CMP";
19980   case X86ISD::COMI:               return "X86ISD::COMI";
19981   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
19982   case X86ISD::CMPM:               return "X86ISD::CMPM";
19983   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
19984   case X86ISD::CMPM_RND:           return "X86ISD::CMPM_RND";
19985   case X86ISD::SETCC:              return "X86ISD::SETCC";
19986   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
19987   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
19988   case X86ISD::FGETSIGNx86:        return "X86ISD::FGETSIGNx86";
19989   case X86ISD::CMOV:               return "X86ISD::CMOV";
19990   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
19991   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
19992   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
19993   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
19994   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
19995   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
19996   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
19997   case X86ISD::MOVDQ2Q:            return "X86ISD::MOVDQ2Q";
19998   case X86ISD::MMX_MOVD2W:         return "X86ISD::MMX_MOVD2W";
19999   case X86ISD::MMX_MOVW2D:         return "X86ISD::MMX_MOVW2D";
20000   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
20001   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
20002   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
20003   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
20004   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
20005   case X86ISD::MMX_PINSRW:         return "X86ISD::MMX_PINSRW";
20006   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
20007   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
20008   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
20009   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
20010   case X86ISD::SHRUNKBLEND:        return "X86ISD::SHRUNKBLEND";
20011   case X86ISD::ADDUS:              return "X86ISD::ADDUS";
20012   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
20013   case X86ISD::HADD:               return "X86ISD::HADD";
20014   case X86ISD::HSUB:               return "X86ISD::HSUB";
20015   case X86ISD::FHADD:              return "X86ISD::FHADD";
20016   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
20017   case X86ISD::ABS:                return "X86ISD::ABS";
20018   case X86ISD::CONFLICT:           return "X86ISD::CONFLICT";
20019   case X86ISD::FMAX:               return "X86ISD::FMAX";
20020   case X86ISD::FMAX_RND:           return "X86ISD::FMAX_RND";
20021   case X86ISD::FMIN:               return "X86ISD::FMIN";
20022   case X86ISD::FMIN_RND:           return "X86ISD::FMIN_RND";
20023   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
20024   case X86ISD::FMINC:              return "X86ISD::FMINC";
20025   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
20026   case X86ISD::FRCP:               return "X86ISD::FRCP";
20027   case X86ISD::EXTRQI:             return "X86ISD::EXTRQI";
20028   case X86ISD::INSERTQI:           return "X86ISD::INSERTQI";
20029   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
20030   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
20031   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
20032   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
20033   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
20034   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
20035   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
20036   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
20037   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
20038   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
20039   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
20040   case X86ISD::LCMPXCHG16_DAG:     return "X86ISD::LCMPXCHG16_DAG";
20041   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
20042   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
20043   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
20044   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
20045   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
20046   case X86ISD::VTRUNCS:            return "X86ISD::VTRUNCS";
20047   case X86ISD::VTRUNCUS:           return "X86ISD::VTRUNCUS";
20048   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
20049   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
20050   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
20051   case X86ISD::CVTDQ2PD:           return "X86ISD::CVTDQ2PD";
20052   case X86ISD::CVTUDQ2PD:          return "X86ISD::CVTUDQ2PD";
20053   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
20054   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
20055   case X86ISD::VSHL:               return "X86ISD::VSHL";
20056   case X86ISD::VSRL:               return "X86ISD::VSRL";
20057   case X86ISD::VSRA:               return "X86ISD::VSRA";
20058   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
20059   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
20060   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
20061   case X86ISD::CMPP:               return "X86ISD::CMPP";
20062   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
20063   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
20064   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
20065   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
20066   case X86ISD::ADD:                return "X86ISD::ADD";
20067   case X86ISD::SUB:                return "X86ISD::SUB";
20068   case X86ISD::ADC:                return "X86ISD::ADC";
20069   case X86ISD::SBB:                return "X86ISD::SBB";
20070   case X86ISD::SMUL:               return "X86ISD::SMUL";
20071   case X86ISD::UMUL:               return "X86ISD::UMUL";
20072   case X86ISD::SMUL8:              return "X86ISD::SMUL8";
20073   case X86ISD::UMUL8:              return "X86ISD::UMUL8";
20074   case X86ISD::SDIVREM8_SEXT_HREG: return "X86ISD::SDIVREM8_SEXT_HREG";
20075   case X86ISD::UDIVREM8_ZEXT_HREG: return "X86ISD::UDIVREM8_ZEXT_HREG";
20076   case X86ISD::INC:                return "X86ISD::INC";
20077   case X86ISD::DEC:                return "X86ISD::DEC";
20078   case X86ISD::OR:                 return "X86ISD::OR";
20079   case X86ISD::XOR:                return "X86ISD::XOR";
20080   case X86ISD::AND:                return "X86ISD::AND";
20081   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
20082   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
20083   case X86ISD::PTEST:              return "X86ISD::PTEST";
20084   case X86ISD::TESTP:              return "X86ISD::TESTP";
20085   case X86ISD::TESTM:              return "X86ISD::TESTM";
20086   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
20087   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
20088   case X86ISD::KTEST:              return "X86ISD::KTEST";
20089   case X86ISD::PACKSS:             return "X86ISD::PACKSS";
20090   case X86ISD::PACKUS:             return "X86ISD::PACKUS";
20091   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
20092   case X86ISD::VALIGN:             return "X86ISD::VALIGN";
20093   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
20094   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
20095   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
20096   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
20097   case X86ISD::SHUF128:            return "X86ISD::SHUF128";
20098   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
20099   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
20100   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
20101   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
20102   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
20103   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
20104   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
20105   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
20106   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
20107   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
20108   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
20109   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
20110   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
20111   case X86ISD::SUBV_BROADCAST:     return "X86ISD::SUBV_BROADCAST";
20112   case X86ISD::VEXTRACT:           return "X86ISD::VEXTRACT";
20113   case X86ISD::VPERMILPV:          return "X86ISD::VPERMILPV";
20114   case X86ISD::VPERMILPI:          return "X86ISD::VPERMILPI";
20115   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
20116   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
20117   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
20118   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
20119   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
20120   case X86ISD::VPTERNLOG:          return "X86ISD::VPTERNLOG";
20121   case X86ISD::VFIXUPIMM:          return "X86ISD::VFIXUPIMM";
20122   case X86ISD::VRANGE:             return "X86ISD::VRANGE";
20123   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
20124   case X86ISD::PMULDQ:             return "X86ISD::PMULDQ";
20125   case X86ISD::PSADBW:             return "X86ISD::PSADBW";
20126   case X86ISD::DBPSADBW:           return "X86ISD::DBPSADBW";
20127   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
20128   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
20129   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
20130   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
20131   case X86ISD::MFENCE:             return "X86ISD::MFENCE";
20132   case X86ISD::SFENCE:             return "X86ISD::SFENCE";
20133   case X86ISD::LFENCE:             return "X86ISD::LFENCE";
20134   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
20135   case X86ISD::SAHF:               return "X86ISD::SAHF";
20136   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
20137   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
20138   case X86ISD::VPMADDUBSW:         return "X86ISD::VPMADDUBSW";
20139   case X86ISD::VPMADDWD:           return "X86ISD::VPMADDWD";
20140   case X86ISD::VPROT:              return "X86ISD::VPROT";
20141   case X86ISD::VPROTI:             return "X86ISD::VPROTI";
20142   case X86ISD::VPSHA:              return "X86ISD::VPSHA";
20143   case X86ISD::VPSHL:              return "X86ISD::VPSHL";
20144   case X86ISD::VPCOM:              return "X86ISD::VPCOM";
20145   case X86ISD::VPCOMU:             return "X86ISD::VPCOMU";
20146   case X86ISD::FMADD:              return "X86ISD::FMADD";
20147   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
20148   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
20149   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
20150   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
20151   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
20152   case X86ISD::FMADD_RND:          return "X86ISD::FMADD_RND";
20153   case X86ISD::FNMADD_RND:         return "X86ISD::FNMADD_RND";
20154   case X86ISD::FMSUB_RND:          return "X86ISD::FMSUB_RND";
20155   case X86ISD::FNMSUB_RND:         return "X86ISD::FNMSUB_RND";
20156   case X86ISD::FMADDSUB_RND:       return "X86ISD::FMADDSUB_RND";
20157   case X86ISD::FMSUBADD_RND:       return "X86ISD::FMSUBADD_RND";
20158   case X86ISD::VRNDSCALE:          return "X86ISD::VRNDSCALE";
20159   case X86ISD::VREDUCE:            return "X86ISD::VREDUCE";
20160   case X86ISD::VGETMANT:           return "X86ISD::VGETMANT";
20161   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
20162   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
20163   case X86ISD::XTEST:              return "X86ISD::XTEST";
20164   case X86ISD::COMPRESS:           return "X86ISD::COMPRESS";
20165   case X86ISD::EXPAND:             return "X86ISD::EXPAND";
20166   case X86ISD::SELECT:             return "X86ISD::SELECT";
20167   case X86ISD::ADDSUB:             return "X86ISD::ADDSUB";
20168   case X86ISD::RCP28:              return "X86ISD::RCP28";
20169   case X86ISD::EXP2:               return "X86ISD::EXP2";
20170   case X86ISD::RSQRT28:            return "X86ISD::RSQRT28";
20171   case X86ISD::FADD_RND:           return "X86ISD::FADD_RND";
20172   case X86ISD::FSUB_RND:           return "X86ISD::FSUB_RND";
20173   case X86ISD::FMUL_RND:           return "X86ISD::FMUL_RND";
20174   case X86ISD::FDIV_RND:           return "X86ISD::FDIV_RND";
20175   case X86ISD::FSQRT_RND:          return "X86ISD::FSQRT_RND";
20176   case X86ISD::FGETEXP_RND:        return "X86ISD::FGETEXP_RND";
20177   case X86ISD::SCALEF:             return "X86ISD::SCALEF";
20178   case X86ISD::ADDS:               return "X86ISD::ADDS";
20179   case X86ISD::SUBS:               return "X86ISD::SUBS";
20180   case X86ISD::AVG:                return "X86ISD::AVG";
20181   case X86ISD::MULHRS:             return "X86ISD::MULHRS";
20182   case X86ISD::SINT_TO_FP_RND:     return "X86ISD::SINT_TO_FP_RND";
20183   case X86ISD::UINT_TO_FP_RND:     return "X86ISD::UINT_TO_FP_RND";
20184   case X86ISD::FP_TO_SINT_RND:     return "X86ISD::FP_TO_SINT_RND";
20185   case X86ISD::FP_TO_UINT_RND:     return "X86ISD::FP_TO_UINT_RND";
20186   case X86ISD::VFPCLASS:           return "X86ISD::VFPCLASS";
20187   }
20188   return nullptr;
20189 }
20190
20191 // isLegalAddressingMode - Return true if the addressing mode represented
20192 // by AM is legal for this target, for a load/store of the specified type.
20193 bool X86TargetLowering::isLegalAddressingMode(const DataLayout &DL,
20194                                               const AddrMode &AM, Type *Ty,
20195                                               unsigned AS) const {
20196   // X86 supports extremely general addressing modes.
20197   CodeModel::Model M = getTargetMachine().getCodeModel();
20198   Reloc::Model R = getTargetMachine().getRelocationModel();
20199
20200   // X86 allows a sign-extended 32-bit immediate field as a displacement.
20201   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
20202     return false;
20203
20204   if (AM.BaseGV) {
20205     unsigned GVFlags =
20206       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
20207
20208     // If a reference to this global requires an extra load, we can't fold it.
20209     if (isGlobalStubReference(GVFlags))
20210       return false;
20211
20212     // If BaseGV requires a register for the PIC base, we cannot also have a
20213     // BaseReg specified.
20214     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
20215       return false;
20216
20217     // If lower 4G is not available, then we must use rip-relative addressing.
20218     if ((M != CodeModel::Small || R != Reloc::Static) &&
20219         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
20220       return false;
20221   }
20222
20223   switch (AM.Scale) {
20224   case 0:
20225   case 1:
20226   case 2:
20227   case 4:
20228   case 8:
20229     // These scales always work.
20230     break;
20231   case 3:
20232   case 5:
20233   case 9:
20234     // These scales are formed with basereg+scalereg.  Only accept if there is
20235     // no basereg yet.
20236     if (AM.HasBaseReg)
20237       return false;
20238     break;
20239   default:  // Other stuff never works.
20240     return false;
20241   }
20242
20243   return true;
20244 }
20245
20246 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
20247   unsigned Bits = Ty->getScalarSizeInBits();
20248
20249   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
20250   // particularly cheaper than those without.
20251   if (Bits == 8)
20252     return false;
20253
20254   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
20255   // variable shifts just as cheap as scalar ones.
20256   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
20257     return false;
20258
20259   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
20260   // fully general vector.
20261   return true;
20262 }
20263
20264 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
20265   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
20266     return false;
20267   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
20268   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
20269   return NumBits1 > NumBits2;
20270 }
20271
20272 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
20273   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
20274     return false;
20275
20276   if (!isTypeLegal(EVT::getEVT(Ty1)))
20277     return false;
20278
20279   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
20280
20281   // Assuming the caller doesn't have a zeroext or signext return parameter,
20282   // truncation all the way down to i1 is valid.
20283   return true;
20284 }
20285
20286 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
20287   return isInt<32>(Imm);
20288 }
20289
20290 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
20291   // Can also use sub to handle negated immediates.
20292   return isInt<32>(Imm);
20293 }
20294
20295 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
20296   if (!VT1.isInteger() || !VT2.isInteger())
20297     return false;
20298   unsigned NumBits1 = VT1.getSizeInBits();
20299   unsigned NumBits2 = VT2.getSizeInBits();
20300   return NumBits1 > NumBits2;
20301 }
20302
20303 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
20304   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
20305   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
20306 }
20307
20308 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
20309   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
20310   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
20311 }
20312
20313 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
20314   EVT VT1 = Val.getValueType();
20315   if (isZExtFree(VT1, VT2))
20316     return true;
20317
20318   if (Val.getOpcode() != ISD::LOAD)
20319     return false;
20320
20321   if (!VT1.isSimple() || !VT1.isInteger() ||
20322       !VT2.isSimple() || !VT2.isInteger())
20323     return false;
20324
20325   switch (VT1.getSimpleVT().SimpleTy) {
20326   default: break;
20327   case MVT::i8:
20328   case MVT::i16:
20329   case MVT::i32:
20330     // X86 has 8, 16, and 32-bit zero-extending loads.
20331     return true;
20332   }
20333
20334   return false;
20335 }
20336
20337 bool X86TargetLowering::isVectorLoadExtDesirable(SDValue) const { return true; }
20338
20339 bool
20340 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
20341   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4() || Subtarget->hasAVX512()))
20342     return false;
20343
20344   VT = VT.getScalarType();
20345
20346   if (!VT.isSimple())
20347     return false;
20348
20349   switch (VT.getSimpleVT().SimpleTy) {
20350   case MVT::f32:
20351   case MVT::f64:
20352     return true;
20353   default:
20354     break;
20355   }
20356
20357   return false;
20358 }
20359
20360 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
20361   // i16 instructions are longer (0x66 prefix) and potentially slower.
20362   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
20363 }
20364
20365 /// isShuffleMaskLegal - Targets can use this to indicate that they only
20366 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
20367 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
20368 /// are assumed to be legal.
20369 bool
20370 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
20371                                       EVT VT) const {
20372   if (!VT.isSimple())
20373     return false;
20374
20375   // Not for i1 vectors
20376   if (VT.getSimpleVT().getScalarType() == MVT::i1)
20377     return false;
20378
20379   // Very little shuffling can be done for 64-bit vectors right now.
20380   if (VT.getSimpleVT().getSizeInBits() == 64)
20381     return false;
20382
20383   // We only care that the types being shuffled are legal. The lowering can
20384   // handle any possible shuffle mask that results.
20385   return isTypeLegal(VT.getSimpleVT());
20386 }
20387
20388 bool
20389 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
20390                                           EVT VT) const {
20391   // Just delegate to the generic legality, clear masks aren't special.
20392   return isShuffleMaskLegal(Mask, VT);
20393 }
20394
20395 //===----------------------------------------------------------------------===//
20396 //                           X86 Scheduler Hooks
20397 //===----------------------------------------------------------------------===//
20398
20399 /// Utility function to emit xbegin specifying the start of an RTM region.
20400 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
20401                                      const TargetInstrInfo *TII) {
20402   DebugLoc DL = MI->getDebugLoc();
20403
20404   const BasicBlock *BB = MBB->getBasicBlock();
20405   MachineFunction::iterator I = ++MBB->getIterator();
20406
20407   // For the v = xbegin(), we generate
20408   //
20409   // thisMBB:
20410   //  xbegin sinkMBB
20411   //
20412   // mainMBB:
20413   //  eax = -1
20414   //
20415   // sinkMBB:
20416   //  v = eax
20417
20418   MachineBasicBlock *thisMBB = MBB;
20419   MachineFunction *MF = MBB->getParent();
20420   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
20421   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
20422   MF->insert(I, mainMBB);
20423   MF->insert(I, sinkMBB);
20424
20425   // Transfer the remainder of BB and its successor edges to sinkMBB.
20426   sinkMBB->splice(sinkMBB->begin(), MBB,
20427                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
20428   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
20429
20430   // thisMBB:
20431   //  xbegin sinkMBB
20432   //  # fallthrough to mainMBB
20433   //  # abortion to sinkMBB
20434   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
20435   thisMBB->addSuccessor(mainMBB);
20436   thisMBB->addSuccessor(sinkMBB);
20437
20438   // mainMBB:
20439   //  EAX = -1
20440   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
20441   mainMBB->addSuccessor(sinkMBB);
20442
20443   // sinkMBB:
20444   // EAX is live into the sinkMBB
20445   sinkMBB->addLiveIn(X86::EAX);
20446   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
20447           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
20448     .addReg(X86::EAX);
20449
20450   MI->eraseFromParent();
20451   return sinkMBB;
20452 }
20453
20454 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
20455 // or XMM0_V32I8 in AVX all of this code can be replaced with that
20456 // in the .td file.
20457 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
20458                                        const TargetInstrInfo *TII) {
20459   unsigned Opc;
20460   switch (MI->getOpcode()) {
20461   default: llvm_unreachable("illegal opcode!");
20462   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
20463   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
20464   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
20465   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
20466   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
20467   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
20468   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
20469   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
20470   }
20471
20472   DebugLoc dl = MI->getDebugLoc();
20473   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
20474
20475   unsigned NumArgs = MI->getNumOperands();
20476   for (unsigned i = 1; i < NumArgs; ++i) {
20477     MachineOperand &Op = MI->getOperand(i);
20478     if (!(Op.isReg() && Op.isImplicit()))
20479       MIB.addOperand(Op);
20480   }
20481   if (MI->hasOneMemOperand())
20482     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
20483
20484   BuildMI(*BB, MI, dl,
20485     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
20486     .addReg(X86::XMM0);
20487
20488   MI->eraseFromParent();
20489   return BB;
20490 }
20491
20492 // FIXME: Custom handling because TableGen doesn't support multiple implicit
20493 // defs in an instruction pattern
20494 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
20495                                        const TargetInstrInfo *TII) {
20496   unsigned Opc;
20497   switch (MI->getOpcode()) {
20498   default: llvm_unreachable("illegal opcode!");
20499   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
20500   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
20501   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
20502   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
20503   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
20504   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
20505   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
20506   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
20507   }
20508
20509   DebugLoc dl = MI->getDebugLoc();
20510   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
20511
20512   unsigned NumArgs = MI->getNumOperands(); // remove the results
20513   for (unsigned i = 1; i < NumArgs; ++i) {
20514     MachineOperand &Op = MI->getOperand(i);
20515     if (!(Op.isReg() && Op.isImplicit()))
20516       MIB.addOperand(Op);
20517   }
20518   if (MI->hasOneMemOperand())
20519     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
20520
20521   BuildMI(*BB, MI, dl,
20522     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
20523     .addReg(X86::ECX);
20524
20525   MI->eraseFromParent();
20526   return BB;
20527 }
20528
20529 static MachineBasicBlock *EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
20530                                       const X86Subtarget *Subtarget) {
20531   DebugLoc dl = MI->getDebugLoc();
20532   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20533   // Address into RAX/EAX, other two args into ECX, EDX.
20534   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
20535   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
20536   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
20537   for (int i = 0; i < X86::AddrNumOperands; ++i)
20538     MIB.addOperand(MI->getOperand(i));
20539
20540   unsigned ValOps = X86::AddrNumOperands;
20541   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
20542     .addReg(MI->getOperand(ValOps).getReg());
20543   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
20544     .addReg(MI->getOperand(ValOps+1).getReg());
20545
20546   // The instruction doesn't actually take any operands though.
20547   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
20548
20549   MI->eraseFromParent(); // The pseudo is gone now.
20550   return BB;
20551 }
20552
20553 MachineBasicBlock *
20554 X86TargetLowering::EmitVAARG64WithCustomInserter(MachineInstr *MI,
20555                                                  MachineBasicBlock *MBB) const {
20556   // Emit va_arg instruction on X86-64.
20557
20558   // Operands to this pseudo-instruction:
20559   // 0  ) Output        : destination address (reg)
20560   // 1-5) Input         : va_list address (addr, i64mem)
20561   // 6  ) ArgSize       : Size (in bytes) of vararg type
20562   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
20563   // 8  ) Align         : Alignment of type
20564   // 9  ) EFLAGS (implicit-def)
20565
20566   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
20567   static_assert(X86::AddrNumOperands == 5,
20568                 "VAARG_64 assumes 5 address operands");
20569
20570   unsigned DestReg = MI->getOperand(0).getReg();
20571   MachineOperand &Base = MI->getOperand(1);
20572   MachineOperand &Scale = MI->getOperand(2);
20573   MachineOperand &Index = MI->getOperand(3);
20574   MachineOperand &Disp = MI->getOperand(4);
20575   MachineOperand &Segment = MI->getOperand(5);
20576   unsigned ArgSize = MI->getOperand(6).getImm();
20577   unsigned ArgMode = MI->getOperand(7).getImm();
20578   unsigned Align = MI->getOperand(8).getImm();
20579
20580   // Memory Reference
20581   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
20582   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
20583   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
20584
20585   // Machine Information
20586   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20587   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
20588   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
20589   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
20590   DebugLoc DL = MI->getDebugLoc();
20591
20592   // struct va_list {
20593   //   i32   gp_offset
20594   //   i32   fp_offset
20595   //   i64   overflow_area (address)
20596   //   i64   reg_save_area (address)
20597   // }
20598   // sizeof(va_list) = 24
20599   // alignment(va_list) = 8
20600
20601   unsigned TotalNumIntRegs = 6;
20602   unsigned TotalNumXMMRegs = 8;
20603   bool UseGPOffset = (ArgMode == 1);
20604   bool UseFPOffset = (ArgMode == 2);
20605   unsigned MaxOffset = TotalNumIntRegs * 8 +
20606                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
20607
20608   /* Align ArgSize to a multiple of 8 */
20609   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
20610   bool NeedsAlign = (Align > 8);
20611
20612   MachineBasicBlock *thisMBB = MBB;
20613   MachineBasicBlock *overflowMBB;
20614   MachineBasicBlock *offsetMBB;
20615   MachineBasicBlock *endMBB;
20616
20617   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
20618   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
20619   unsigned OffsetReg = 0;
20620
20621   if (!UseGPOffset && !UseFPOffset) {
20622     // If we only pull from the overflow region, we don't create a branch.
20623     // We don't need to alter control flow.
20624     OffsetDestReg = 0; // unused
20625     OverflowDestReg = DestReg;
20626
20627     offsetMBB = nullptr;
20628     overflowMBB = thisMBB;
20629     endMBB = thisMBB;
20630   } else {
20631     // First emit code to check if gp_offset (or fp_offset) is below the bound.
20632     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
20633     // If not, pull from overflow_area. (branch to overflowMBB)
20634     //
20635     //       thisMBB
20636     //         |     .
20637     //         |        .
20638     //     offsetMBB   overflowMBB
20639     //         |        .
20640     //         |     .
20641     //        endMBB
20642
20643     // Registers for the PHI in endMBB
20644     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
20645     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
20646
20647     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
20648     MachineFunction *MF = MBB->getParent();
20649     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20650     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20651     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20652
20653     MachineFunction::iterator MBBIter = ++MBB->getIterator();
20654
20655     // Insert the new basic blocks
20656     MF->insert(MBBIter, offsetMBB);
20657     MF->insert(MBBIter, overflowMBB);
20658     MF->insert(MBBIter, endMBB);
20659
20660     // Transfer the remainder of MBB and its successor edges to endMBB.
20661     endMBB->splice(endMBB->begin(), thisMBB,
20662                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
20663     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
20664
20665     // Make offsetMBB and overflowMBB successors of thisMBB
20666     thisMBB->addSuccessor(offsetMBB);
20667     thisMBB->addSuccessor(overflowMBB);
20668
20669     // endMBB is a successor of both offsetMBB and overflowMBB
20670     offsetMBB->addSuccessor(endMBB);
20671     overflowMBB->addSuccessor(endMBB);
20672
20673     // Load the offset value into a register
20674     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
20675     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
20676       .addOperand(Base)
20677       .addOperand(Scale)
20678       .addOperand(Index)
20679       .addDisp(Disp, UseFPOffset ? 4 : 0)
20680       .addOperand(Segment)
20681       .setMemRefs(MMOBegin, MMOEnd);
20682
20683     // Check if there is enough room left to pull this argument.
20684     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
20685       .addReg(OffsetReg)
20686       .addImm(MaxOffset + 8 - ArgSizeA8);
20687
20688     // Branch to "overflowMBB" if offset >= max
20689     // Fall through to "offsetMBB" otherwise
20690     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
20691       .addMBB(overflowMBB);
20692   }
20693
20694   // In offsetMBB, emit code to use the reg_save_area.
20695   if (offsetMBB) {
20696     assert(OffsetReg != 0);
20697
20698     // Read the reg_save_area address.
20699     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
20700     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
20701       .addOperand(Base)
20702       .addOperand(Scale)
20703       .addOperand(Index)
20704       .addDisp(Disp, 16)
20705       .addOperand(Segment)
20706       .setMemRefs(MMOBegin, MMOEnd);
20707
20708     // Zero-extend the offset
20709     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
20710       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
20711         .addImm(0)
20712         .addReg(OffsetReg)
20713         .addImm(X86::sub_32bit);
20714
20715     // Add the offset to the reg_save_area to get the final address.
20716     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
20717       .addReg(OffsetReg64)
20718       .addReg(RegSaveReg);
20719
20720     // Compute the offset for the next argument
20721     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
20722     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
20723       .addReg(OffsetReg)
20724       .addImm(UseFPOffset ? 16 : 8);
20725
20726     // Store it back into the va_list.
20727     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
20728       .addOperand(Base)
20729       .addOperand(Scale)
20730       .addOperand(Index)
20731       .addDisp(Disp, UseFPOffset ? 4 : 0)
20732       .addOperand(Segment)
20733       .addReg(NextOffsetReg)
20734       .setMemRefs(MMOBegin, MMOEnd);
20735
20736     // Jump to endMBB
20737     BuildMI(offsetMBB, DL, TII->get(X86::JMP_1))
20738       .addMBB(endMBB);
20739   }
20740
20741   //
20742   // Emit code to use overflow area
20743   //
20744
20745   // Load the overflow_area address into a register.
20746   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
20747   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
20748     .addOperand(Base)
20749     .addOperand(Scale)
20750     .addOperand(Index)
20751     .addDisp(Disp, 8)
20752     .addOperand(Segment)
20753     .setMemRefs(MMOBegin, MMOEnd);
20754
20755   // If we need to align it, do so. Otherwise, just copy the address
20756   // to OverflowDestReg.
20757   if (NeedsAlign) {
20758     // Align the overflow address
20759     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
20760     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
20761
20762     // aligned_addr = (addr + (align-1)) & ~(align-1)
20763     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
20764       .addReg(OverflowAddrReg)
20765       .addImm(Align-1);
20766
20767     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
20768       .addReg(TmpReg)
20769       .addImm(~(uint64_t)(Align-1));
20770   } else {
20771     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
20772       .addReg(OverflowAddrReg);
20773   }
20774
20775   // Compute the next overflow address after this argument.
20776   // (the overflow address should be kept 8-byte aligned)
20777   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
20778   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
20779     .addReg(OverflowDestReg)
20780     .addImm(ArgSizeA8);
20781
20782   // Store the new overflow address.
20783   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
20784     .addOperand(Base)
20785     .addOperand(Scale)
20786     .addOperand(Index)
20787     .addDisp(Disp, 8)
20788     .addOperand(Segment)
20789     .addReg(NextAddrReg)
20790     .setMemRefs(MMOBegin, MMOEnd);
20791
20792   // If we branched, emit the PHI to the front of endMBB.
20793   if (offsetMBB) {
20794     BuildMI(*endMBB, endMBB->begin(), DL,
20795             TII->get(X86::PHI), DestReg)
20796       .addReg(OffsetDestReg).addMBB(offsetMBB)
20797       .addReg(OverflowDestReg).addMBB(overflowMBB);
20798   }
20799
20800   // Erase the pseudo instruction
20801   MI->eraseFromParent();
20802
20803   return endMBB;
20804 }
20805
20806 MachineBasicBlock *
20807 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
20808                                                  MachineInstr *MI,
20809                                                  MachineBasicBlock *MBB) const {
20810   // Emit code to save XMM registers to the stack. The ABI says that the
20811   // number of registers to save is given in %al, so it's theoretically
20812   // possible to do an indirect jump trick to avoid saving all of them,
20813   // however this code takes a simpler approach and just executes all
20814   // of the stores if %al is non-zero. It's less code, and it's probably
20815   // easier on the hardware branch predictor, and stores aren't all that
20816   // expensive anyway.
20817
20818   // Create the new basic blocks. One block contains all the XMM stores,
20819   // and one block is the final destination regardless of whether any
20820   // stores were performed.
20821   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
20822   MachineFunction *F = MBB->getParent();
20823   MachineFunction::iterator MBBIter = ++MBB->getIterator();
20824   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
20825   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
20826   F->insert(MBBIter, XMMSaveMBB);
20827   F->insert(MBBIter, EndMBB);
20828
20829   // Transfer the remainder of MBB and its successor edges to EndMBB.
20830   EndMBB->splice(EndMBB->begin(), MBB,
20831                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
20832   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
20833
20834   // The original block will now fall through to the XMM save block.
20835   MBB->addSuccessor(XMMSaveMBB);
20836   // The XMMSaveMBB will fall through to the end block.
20837   XMMSaveMBB->addSuccessor(EndMBB);
20838
20839   // Now add the instructions.
20840   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20841   DebugLoc DL = MI->getDebugLoc();
20842
20843   unsigned CountReg = MI->getOperand(0).getReg();
20844   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
20845   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
20846
20847   if (!Subtarget->isCallingConvWin64(F->getFunction()->getCallingConv())) {
20848     // If %al is 0, branch around the XMM save block.
20849     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
20850     BuildMI(MBB, DL, TII->get(X86::JE_1)).addMBB(EndMBB);
20851     MBB->addSuccessor(EndMBB);
20852   }
20853
20854   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
20855   // that was just emitted, but clearly shouldn't be "saved".
20856   assert((MI->getNumOperands() <= 3 ||
20857           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
20858           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
20859          && "Expected last argument to be EFLAGS");
20860   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
20861   // In the XMM save block, save all the XMM argument registers.
20862   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
20863     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
20864     MachineMemOperand *MMO = F->getMachineMemOperand(
20865         MachinePointerInfo::getFixedStack(*F, RegSaveFrameIndex, Offset),
20866         MachineMemOperand::MOStore,
20867         /*Size=*/16, /*Align=*/16);
20868     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
20869       .addFrameIndex(RegSaveFrameIndex)
20870       .addImm(/*Scale=*/1)
20871       .addReg(/*IndexReg=*/0)
20872       .addImm(/*Disp=*/Offset)
20873       .addReg(/*Segment=*/0)
20874       .addReg(MI->getOperand(i).getReg())
20875       .addMemOperand(MMO);
20876   }
20877
20878   MI->eraseFromParent();   // The pseudo instruction is gone now.
20879
20880   return EndMBB;
20881 }
20882
20883 // The EFLAGS operand of SelectItr might be missing a kill marker
20884 // because there were multiple uses of EFLAGS, and ISel didn't know
20885 // which to mark. Figure out whether SelectItr should have had a
20886 // kill marker, and set it if it should. Returns the correct kill
20887 // marker value.
20888 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
20889                                      MachineBasicBlock* BB,
20890                                      const TargetRegisterInfo* TRI) {
20891   // Scan forward through BB for a use/def of EFLAGS.
20892   MachineBasicBlock::iterator miI(std::next(SelectItr));
20893   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
20894     const MachineInstr& mi = *miI;
20895     if (mi.readsRegister(X86::EFLAGS))
20896       return false;
20897     if (mi.definesRegister(X86::EFLAGS))
20898       break; // Should have kill-flag - update below.
20899   }
20900
20901   // If we hit the end of the block, check whether EFLAGS is live into a
20902   // successor.
20903   if (miI == BB->end()) {
20904     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
20905                                           sEnd = BB->succ_end();
20906          sItr != sEnd; ++sItr) {
20907       MachineBasicBlock* succ = *sItr;
20908       if (succ->isLiveIn(X86::EFLAGS))
20909         return false;
20910     }
20911   }
20912
20913   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
20914   // out. SelectMI should have a kill flag on EFLAGS.
20915   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
20916   return true;
20917 }
20918
20919 // Return true if it is OK for this CMOV pseudo-opcode to be cascaded
20920 // together with other CMOV pseudo-opcodes into a single basic-block with
20921 // conditional jump around it.
20922 static bool isCMOVPseudo(MachineInstr *MI) {
20923   switch (MI->getOpcode()) {
20924   case X86::CMOV_FR32:
20925   case X86::CMOV_FR64:
20926   case X86::CMOV_GR8:
20927   case X86::CMOV_GR16:
20928   case X86::CMOV_GR32:
20929   case X86::CMOV_RFP32:
20930   case X86::CMOV_RFP64:
20931   case X86::CMOV_RFP80:
20932   case X86::CMOV_V2F64:
20933   case X86::CMOV_V2I64:
20934   case X86::CMOV_V4F32:
20935   case X86::CMOV_V4F64:
20936   case X86::CMOV_V4I64:
20937   case X86::CMOV_V16F32:
20938   case X86::CMOV_V8F32:
20939   case X86::CMOV_V8F64:
20940   case X86::CMOV_V8I64:
20941   case X86::CMOV_V8I1:
20942   case X86::CMOV_V16I1:
20943   case X86::CMOV_V32I1:
20944   case X86::CMOV_V64I1:
20945     return true;
20946
20947   default:
20948     return false;
20949   }
20950 }
20951
20952 MachineBasicBlock *
20953 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
20954                                      MachineBasicBlock *BB) const {
20955   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20956   DebugLoc DL = MI->getDebugLoc();
20957
20958   // To "insert" a SELECT_CC instruction, we actually have to insert the
20959   // diamond control-flow pattern.  The incoming instruction knows the
20960   // destination vreg to set, the condition code register to branch on, the
20961   // true/false values to select between, and a branch opcode to use.
20962   const BasicBlock *LLVM_BB = BB->getBasicBlock();
20963   MachineFunction::iterator It = ++BB->getIterator();
20964
20965   //  thisMBB:
20966   //  ...
20967   //   TrueVal = ...
20968   //   cmpTY ccX, r1, r2
20969   //   bCC copy1MBB
20970   //   fallthrough --> copy0MBB
20971   MachineBasicBlock *thisMBB = BB;
20972   MachineFunction *F = BB->getParent();
20973
20974   // This code lowers all pseudo-CMOV instructions. Generally it lowers these
20975   // as described above, by inserting a BB, and then making a PHI at the join
20976   // point to select the true and false operands of the CMOV in the PHI.
20977   //
20978   // The code also handles two different cases of multiple CMOV opcodes
20979   // in a row.
20980   //
20981   // Case 1:
20982   // In this case, there are multiple CMOVs in a row, all which are based on
20983   // the same condition setting (or the exact opposite condition setting).
20984   // In this case we can lower all the CMOVs using a single inserted BB, and
20985   // then make a number of PHIs at the join point to model the CMOVs. The only
20986   // trickiness here, is that in a case like:
20987   //
20988   // t2 = CMOV cond1 t1, f1
20989   // t3 = CMOV cond1 t2, f2
20990   //
20991   // when rewriting this into PHIs, we have to perform some renaming on the
20992   // temps since you cannot have a PHI operand refer to a PHI result earlier
20993   // in the same block.  The "simple" but wrong lowering would be:
20994   //
20995   // t2 = PHI t1(BB1), f1(BB2)
20996   // t3 = PHI t2(BB1), f2(BB2)
20997   //
20998   // but clearly t2 is not defined in BB1, so that is incorrect. The proper
20999   // renaming is to note that on the path through BB1, t2 is really just a
21000   // copy of t1, and do that renaming, properly generating:
21001   //
21002   // t2 = PHI t1(BB1), f1(BB2)
21003   // t3 = PHI t1(BB1), f2(BB2)
21004   //
21005   // Case 2, we lower cascaded CMOVs such as
21006   //
21007   //   (CMOV (CMOV F, T, cc1), T, cc2)
21008   //
21009   // to two successives branches.  For that, we look for another CMOV as the
21010   // following instruction.
21011   //
21012   // Without this, we would add a PHI between the two jumps, which ends up
21013   // creating a few copies all around. For instance, for
21014   //
21015   //    (sitofp (zext (fcmp une)))
21016   //
21017   // we would generate:
21018   //
21019   //         ucomiss %xmm1, %xmm0
21020   //         movss  <1.0f>, %xmm0
21021   //         movaps  %xmm0, %xmm1
21022   //         jne     .LBB5_2
21023   //         xorps   %xmm1, %xmm1
21024   // .LBB5_2:
21025   //         jp      .LBB5_4
21026   //         movaps  %xmm1, %xmm0
21027   // .LBB5_4:
21028   //         retq
21029   //
21030   // because this custom-inserter would have generated:
21031   //
21032   //   A
21033   //   | \
21034   //   |  B
21035   //   | /
21036   //   C
21037   //   | \
21038   //   |  D
21039   //   | /
21040   //   E
21041   //
21042   // A: X = ...; Y = ...
21043   // B: empty
21044   // C: Z = PHI [X, A], [Y, B]
21045   // D: empty
21046   // E: PHI [X, C], [Z, D]
21047   //
21048   // If we lower both CMOVs in a single step, we can instead generate:
21049   //
21050   //   A
21051   //   | \
21052   //   |  C
21053   //   | /|
21054   //   |/ |
21055   //   |  |
21056   //   |  D
21057   //   | /
21058   //   E
21059   //
21060   // A: X = ...; Y = ...
21061   // D: empty
21062   // E: PHI [X, A], [X, C], [Y, D]
21063   //
21064   // Which, in our sitofp/fcmp example, gives us something like:
21065   //
21066   //         ucomiss %xmm1, %xmm0
21067   //         movss  <1.0f>, %xmm0
21068   //         jne     .LBB5_4
21069   //         jp      .LBB5_4
21070   //         xorps   %xmm0, %xmm0
21071   // .LBB5_4:
21072   //         retq
21073   //
21074   MachineInstr *CascadedCMOV = nullptr;
21075   MachineInstr *LastCMOV = MI;
21076   X86::CondCode CC = X86::CondCode(MI->getOperand(3).getImm());
21077   X86::CondCode OppCC = X86::GetOppositeBranchCondition(CC);
21078   MachineBasicBlock::iterator NextMIIt =
21079       std::next(MachineBasicBlock::iterator(MI));
21080
21081   // Check for case 1, where there are multiple CMOVs with the same condition
21082   // first.  Of the two cases of multiple CMOV lowerings, case 1 reduces the
21083   // number of jumps the most.
21084
21085   if (isCMOVPseudo(MI)) {
21086     // See if we have a string of CMOVS with the same condition.
21087     while (NextMIIt != BB->end() &&
21088            isCMOVPseudo(NextMIIt) &&
21089            (NextMIIt->getOperand(3).getImm() == CC ||
21090             NextMIIt->getOperand(3).getImm() == OppCC)) {
21091       LastCMOV = &*NextMIIt;
21092       ++NextMIIt;
21093     }
21094   }
21095
21096   // This checks for case 2, but only do this if we didn't already find
21097   // case 1, as indicated by LastCMOV == MI.
21098   if (LastCMOV == MI &&
21099       NextMIIt != BB->end() && NextMIIt->getOpcode() == MI->getOpcode() &&
21100       NextMIIt->getOperand(2).getReg() == MI->getOperand(2).getReg() &&
21101       NextMIIt->getOperand(1).getReg() == MI->getOperand(0).getReg()) {
21102     CascadedCMOV = &*NextMIIt;
21103   }
21104
21105   MachineBasicBlock *jcc1MBB = nullptr;
21106
21107   // If we have a cascaded CMOV, we lower it to two successive branches to
21108   // the same block.  EFLAGS is used by both, so mark it as live in the second.
21109   if (CascadedCMOV) {
21110     jcc1MBB = F->CreateMachineBasicBlock(LLVM_BB);
21111     F->insert(It, jcc1MBB);
21112     jcc1MBB->addLiveIn(X86::EFLAGS);
21113   }
21114
21115   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
21116   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
21117   F->insert(It, copy0MBB);
21118   F->insert(It, sinkMBB);
21119
21120   // If the EFLAGS register isn't dead in the terminator, then claim that it's
21121   // live into the sink and copy blocks.
21122   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
21123
21124   MachineInstr *LastEFLAGSUser = CascadedCMOV ? CascadedCMOV : LastCMOV;
21125   if (!LastEFLAGSUser->killsRegister(X86::EFLAGS) &&
21126       !checkAndUpdateEFLAGSKill(LastEFLAGSUser, BB, TRI)) {
21127     copy0MBB->addLiveIn(X86::EFLAGS);
21128     sinkMBB->addLiveIn(X86::EFLAGS);
21129   }
21130
21131   // Transfer the remainder of BB and its successor edges to sinkMBB.
21132   sinkMBB->splice(sinkMBB->begin(), BB,
21133                   std::next(MachineBasicBlock::iterator(LastCMOV)), BB->end());
21134   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
21135
21136   // Add the true and fallthrough blocks as its successors.
21137   if (CascadedCMOV) {
21138     // The fallthrough block may be jcc1MBB, if we have a cascaded CMOV.
21139     BB->addSuccessor(jcc1MBB);
21140
21141     // In that case, jcc1MBB will itself fallthrough the copy0MBB, and
21142     // jump to the sinkMBB.
21143     jcc1MBB->addSuccessor(copy0MBB);
21144     jcc1MBB->addSuccessor(sinkMBB);
21145   } else {
21146     BB->addSuccessor(copy0MBB);
21147   }
21148
21149   // The true block target of the first (or only) branch is always sinkMBB.
21150   BB->addSuccessor(sinkMBB);
21151
21152   // Create the conditional branch instruction.
21153   unsigned Opc = X86::GetCondBranchFromCond(CC);
21154   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
21155
21156   if (CascadedCMOV) {
21157     unsigned Opc2 = X86::GetCondBranchFromCond(
21158         (X86::CondCode)CascadedCMOV->getOperand(3).getImm());
21159     BuildMI(jcc1MBB, DL, TII->get(Opc2)).addMBB(sinkMBB);
21160   }
21161
21162   //  copy0MBB:
21163   //   %FalseValue = ...
21164   //   # fallthrough to sinkMBB
21165   copy0MBB->addSuccessor(sinkMBB);
21166
21167   //  sinkMBB:
21168   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
21169   //  ...
21170   MachineBasicBlock::iterator MIItBegin = MachineBasicBlock::iterator(MI);
21171   MachineBasicBlock::iterator MIItEnd =
21172     std::next(MachineBasicBlock::iterator(LastCMOV));
21173   MachineBasicBlock::iterator SinkInsertionPoint = sinkMBB->begin();
21174   DenseMap<unsigned, std::pair<unsigned, unsigned>> RegRewriteTable;
21175   MachineInstrBuilder MIB;
21176
21177   // As we are creating the PHIs, we have to be careful if there is more than
21178   // one.  Later CMOVs may reference the results of earlier CMOVs, but later
21179   // PHIs have to reference the individual true/false inputs from earlier PHIs.
21180   // That also means that PHI construction must work forward from earlier to
21181   // later, and that the code must maintain a mapping from earlier PHI's
21182   // destination registers, and the registers that went into the PHI.
21183
21184   for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd; ++MIIt) {
21185     unsigned DestReg = MIIt->getOperand(0).getReg();
21186     unsigned Op1Reg = MIIt->getOperand(1).getReg();
21187     unsigned Op2Reg = MIIt->getOperand(2).getReg();
21188
21189     // If this CMOV we are generating is the opposite condition from
21190     // the jump we generated, then we have to swap the operands for the
21191     // PHI that is going to be generated.
21192     if (MIIt->getOperand(3).getImm() == OppCC)
21193         std::swap(Op1Reg, Op2Reg);
21194
21195     if (RegRewriteTable.find(Op1Reg) != RegRewriteTable.end())
21196       Op1Reg = RegRewriteTable[Op1Reg].first;
21197
21198     if (RegRewriteTable.find(Op2Reg) != RegRewriteTable.end())
21199       Op2Reg = RegRewriteTable[Op2Reg].second;
21200
21201     MIB = BuildMI(*sinkMBB, SinkInsertionPoint, DL,
21202                   TII->get(X86::PHI), DestReg)
21203           .addReg(Op1Reg).addMBB(copy0MBB)
21204           .addReg(Op2Reg).addMBB(thisMBB);
21205
21206     // Add this PHI to the rewrite table.
21207     RegRewriteTable[DestReg] = std::make_pair(Op1Reg, Op2Reg);
21208   }
21209
21210   // If we have a cascaded CMOV, the second Jcc provides the same incoming
21211   // value as the first Jcc (the True operand of the SELECT_CC/CMOV nodes).
21212   if (CascadedCMOV) {
21213     MIB.addReg(MI->getOperand(2).getReg()).addMBB(jcc1MBB);
21214     // Copy the PHI result to the register defined by the second CMOV.
21215     BuildMI(*sinkMBB, std::next(MachineBasicBlock::iterator(MIB.getInstr())),
21216             DL, TII->get(TargetOpcode::COPY),
21217             CascadedCMOV->getOperand(0).getReg())
21218         .addReg(MI->getOperand(0).getReg());
21219     CascadedCMOV->eraseFromParent();
21220   }
21221
21222   // Now remove the CMOV(s).
21223   for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd; )
21224     (MIIt++)->eraseFromParent();
21225
21226   return sinkMBB;
21227 }
21228
21229 MachineBasicBlock *
21230 X86TargetLowering::EmitLoweredAtomicFP(MachineInstr *MI,
21231                                        MachineBasicBlock *BB) const {
21232   // Combine the following atomic floating-point modification pattern:
21233   //   a.store(reg OP a.load(acquire), release)
21234   // Transform them into:
21235   //   OPss (%gpr), %xmm
21236   //   movss %xmm, (%gpr)
21237   // Or sd equivalent for 64-bit operations.
21238   unsigned MOp, FOp;
21239   switch (MI->getOpcode()) {
21240   default: llvm_unreachable("unexpected instr type for EmitLoweredAtomicFP");
21241   case X86::RELEASE_FADD32mr: MOp = X86::MOVSSmr; FOp = X86::ADDSSrm; break;
21242   case X86::RELEASE_FADD64mr: MOp = X86::MOVSDmr; FOp = X86::ADDSDrm; break;
21243   }
21244   const X86InstrInfo *TII = Subtarget->getInstrInfo();
21245   DebugLoc DL = MI->getDebugLoc();
21246   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
21247   MachineOperand MSrc = MI->getOperand(0);
21248   unsigned VSrc = MI->getOperand(5).getReg();
21249   const MachineOperand &Disp = MI->getOperand(3);
21250   MachineOperand ZeroDisp = MachineOperand::CreateImm(0);
21251   bool hasDisp = Disp.isGlobal() || Disp.isImm();
21252   if (hasDisp && MSrc.isReg())
21253     MSrc.setIsKill(false);
21254   MachineInstrBuilder MIM = BuildMI(*BB, MI, DL, TII->get(MOp))
21255                                 .addOperand(/*Base=*/MSrc)
21256                                 .addImm(/*Scale=*/1)
21257                                 .addReg(/*Index=*/0)
21258                                 .addDisp(hasDisp ? Disp : ZeroDisp, /*off=*/0)
21259                                 .addReg(0);
21260   MachineInstr *MIO = BuildMI(*BB, (MachineInstr *)MIM, DL, TII->get(FOp),
21261                               MRI.createVirtualRegister(MRI.getRegClass(VSrc)))
21262                           .addReg(VSrc)
21263                           .addOperand(/*Base=*/MSrc)
21264                           .addImm(/*Scale=*/1)
21265                           .addReg(/*Index=*/0)
21266                           .addDisp(hasDisp ? Disp : ZeroDisp, /*off=*/0)
21267                           .addReg(/*Segment=*/0);
21268   MIM.addReg(MIO->getOperand(0).getReg(), RegState::Kill);
21269   MI->eraseFromParent(); // The pseudo instruction is gone now.
21270   return BB;
21271 }
21272
21273 MachineBasicBlock *
21274 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI,
21275                                         MachineBasicBlock *BB) const {
21276   MachineFunction *MF = BB->getParent();
21277   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21278   DebugLoc DL = MI->getDebugLoc();
21279   const BasicBlock *LLVM_BB = BB->getBasicBlock();
21280
21281   assert(MF->shouldSplitStack());
21282
21283   const bool Is64Bit = Subtarget->is64Bit();
21284   const bool IsLP64 = Subtarget->isTarget64BitLP64();
21285
21286   const unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
21287   const unsigned TlsOffset = IsLP64 ? 0x70 : Is64Bit ? 0x40 : 0x30;
21288
21289   // BB:
21290   //  ... [Till the alloca]
21291   // If stacklet is not large enough, jump to mallocMBB
21292   //
21293   // bumpMBB:
21294   //  Allocate by subtracting from RSP
21295   //  Jump to continueMBB
21296   //
21297   // mallocMBB:
21298   //  Allocate by call to runtime
21299   //
21300   // continueMBB:
21301   //  ...
21302   //  [rest of original BB]
21303   //
21304
21305   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
21306   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
21307   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
21308
21309   MachineRegisterInfo &MRI = MF->getRegInfo();
21310   const TargetRegisterClass *AddrRegClass =
21311       getRegClassFor(getPointerTy(MF->getDataLayout()));
21312
21313   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
21314     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
21315     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
21316     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
21317     sizeVReg = MI->getOperand(1).getReg(),
21318     physSPReg = IsLP64 || Subtarget->isTargetNaCl64() ? X86::RSP : X86::ESP;
21319
21320   MachineFunction::iterator MBBIter = ++BB->getIterator();
21321
21322   MF->insert(MBBIter, bumpMBB);
21323   MF->insert(MBBIter, mallocMBB);
21324   MF->insert(MBBIter, continueMBB);
21325
21326   continueMBB->splice(continueMBB->begin(), BB,
21327                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
21328   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
21329
21330   // Add code to the main basic block to check if the stack limit has been hit,
21331   // and if so, jump to mallocMBB otherwise to bumpMBB.
21332   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
21333   BuildMI(BB, DL, TII->get(IsLP64 ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
21334     .addReg(tmpSPVReg).addReg(sizeVReg);
21335   BuildMI(BB, DL, TII->get(IsLP64 ? X86::CMP64mr:X86::CMP32mr))
21336     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
21337     .addReg(SPLimitVReg);
21338   BuildMI(BB, DL, TII->get(X86::JG_1)).addMBB(mallocMBB);
21339
21340   // bumpMBB simply decreases the stack pointer, since we know the current
21341   // stacklet has enough space.
21342   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
21343     .addReg(SPLimitVReg);
21344   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
21345     .addReg(SPLimitVReg);
21346   BuildMI(bumpMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
21347
21348   // Calls into a routine in libgcc to allocate more space from the heap.
21349   const uint32_t *RegMask =
21350       Subtarget->getRegisterInfo()->getCallPreservedMask(*MF, CallingConv::C);
21351   if (IsLP64) {
21352     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
21353       .addReg(sizeVReg);
21354     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
21355       .addExternalSymbol("__morestack_allocate_stack_space")
21356       .addRegMask(RegMask)
21357       .addReg(X86::RDI, RegState::Implicit)
21358       .addReg(X86::RAX, RegState::ImplicitDefine);
21359   } else if (Is64Bit) {
21360     BuildMI(mallocMBB, DL, TII->get(X86::MOV32rr), X86::EDI)
21361       .addReg(sizeVReg);
21362     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
21363       .addExternalSymbol("__morestack_allocate_stack_space")
21364       .addRegMask(RegMask)
21365       .addReg(X86::EDI, RegState::Implicit)
21366       .addReg(X86::EAX, RegState::ImplicitDefine);
21367   } else {
21368     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
21369       .addImm(12);
21370     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
21371     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
21372       .addExternalSymbol("__morestack_allocate_stack_space")
21373       .addRegMask(RegMask)
21374       .addReg(X86::EAX, RegState::ImplicitDefine);
21375   }
21376
21377   if (!Is64Bit)
21378     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
21379       .addImm(16);
21380
21381   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
21382     .addReg(IsLP64 ? X86::RAX : X86::EAX);
21383   BuildMI(mallocMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
21384
21385   // Set up the CFG correctly.
21386   BB->addSuccessor(bumpMBB);
21387   BB->addSuccessor(mallocMBB);
21388   mallocMBB->addSuccessor(continueMBB);
21389   bumpMBB->addSuccessor(continueMBB);
21390
21391   // Take care of the PHI nodes.
21392   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
21393           MI->getOperand(0).getReg())
21394     .addReg(mallocPtrVReg).addMBB(mallocMBB)
21395     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
21396
21397   // Delete the original pseudo instruction.
21398   MI->eraseFromParent();
21399
21400   // And we're done.
21401   return continueMBB;
21402 }
21403
21404 MachineBasicBlock *
21405 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
21406                                         MachineBasicBlock *BB) const {
21407   assert(!Subtarget->isTargetMachO());
21408   DebugLoc DL = MI->getDebugLoc();
21409   MachineInstr *ResumeMI = Subtarget->getFrameLowering()->emitStackProbe(
21410       *BB->getParent(), *BB, MI, DL, false);
21411   MachineBasicBlock *ResumeBB = ResumeMI->getParent();
21412   MI->eraseFromParent(); // The pseudo instruction is gone now.
21413   return ResumeBB;
21414 }
21415
21416 MachineBasicBlock *
21417 X86TargetLowering::EmitLoweredCatchRet(MachineInstr *MI,
21418                                        MachineBasicBlock *BB) const {
21419   MachineFunction *MF = BB->getParent();
21420   const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
21421   MachineBasicBlock *TargetMBB = MI->getOperand(0).getMBB();
21422   DebugLoc DL = MI->getDebugLoc();
21423
21424   assert(!isAsynchronousEHPersonality(
21425              classifyEHPersonality(MF->getFunction()->getPersonalityFn())) &&
21426          "SEH does not use catchret!");
21427
21428   // Only 32-bit EH needs to worry about manually restoring stack pointers.
21429   if (!Subtarget->is32Bit())
21430     return BB;
21431
21432   // C++ EH creates a new target block to hold the restore code, and wires up
21433   // the new block to the return destination with a normal JMP_4.
21434   MachineBasicBlock *RestoreMBB =
21435       MF->CreateMachineBasicBlock(BB->getBasicBlock());
21436   assert(BB->succ_size() == 1);
21437   MF->insert(std::next(BB->getIterator()), RestoreMBB);
21438   RestoreMBB->transferSuccessorsAndUpdatePHIs(BB);
21439   BB->addSuccessor(RestoreMBB);
21440   MI->getOperand(0).setMBB(RestoreMBB);
21441
21442   auto RestoreMBBI = RestoreMBB->begin();
21443   BuildMI(*RestoreMBB, RestoreMBBI, DL, TII.get(X86::EH_RESTORE));
21444   BuildMI(*RestoreMBB, RestoreMBBI, DL, TII.get(X86::JMP_4)).addMBB(TargetMBB);
21445   return BB;
21446 }
21447
21448 MachineBasicBlock *
21449 X86TargetLowering::EmitLoweredCatchPad(MachineInstr *MI,
21450                                        MachineBasicBlock *BB) const {
21451   MachineFunction *MF = BB->getParent();
21452   const Constant *PerFn = MF->getFunction()->getPersonalityFn();
21453   bool IsSEH = isAsynchronousEHPersonality(classifyEHPersonality(PerFn));
21454   // Only 32-bit SEH requires special handling for catchpad.
21455   if (IsSEH && Subtarget->is32Bit()) {
21456     const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
21457     DebugLoc DL = MI->getDebugLoc();
21458     BuildMI(*BB, MI, DL, TII.get(X86::EH_RESTORE));
21459   }
21460   MI->eraseFromParent();
21461   return BB;
21462 }
21463
21464 MachineBasicBlock *
21465 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
21466                                       MachineBasicBlock *BB) const {
21467   // This is pretty easy.  We're taking the value that we received from
21468   // our load from the relocation, sticking it in either RDI (x86-64)
21469   // or EAX and doing an indirect call.  The return value will then
21470   // be in the normal return register.
21471   MachineFunction *F = BB->getParent();
21472   const X86InstrInfo *TII = Subtarget->getInstrInfo();
21473   DebugLoc DL = MI->getDebugLoc();
21474
21475   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
21476   assert(MI->getOperand(3).isGlobal() && "This should be a global");
21477
21478   // Get a register mask for the lowered call.
21479   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
21480   // proper register mask.
21481   const uint32_t *RegMask =
21482       Subtarget->is64Bit() ?
21483       Subtarget->getRegisterInfo()->getDarwinTLSCallPreservedMask() :
21484       Subtarget->getRegisterInfo()->getCallPreservedMask(*F, CallingConv::C);
21485   if (Subtarget->is64Bit()) {
21486     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
21487                                       TII->get(X86::MOV64rm), X86::RDI)
21488     .addReg(X86::RIP)
21489     .addImm(0).addReg(0)
21490     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
21491                       MI->getOperand(3).getTargetFlags())
21492     .addReg(0);
21493     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
21494     addDirectMem(MIB, X86::RDI);
21495     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
21496   } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
21497     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
21498                                       TII->get(X86::MOV32rm), X86::EAX)
21499     .addReg(0)
21500     .addImm(0).addReg(0)
21501     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
21502                       MI->getOperand(3).getTargetFlags())
21503     .addReg(0);
21504     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
21505     addDirectMem(MIB, X86::EAX);
21506     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
21507   } else {
21508     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
21509                                       TII->get(X86::MOV32rm), X86::EAX)
21510     .addReg(TII->getGlobalBaseReg(F))
21511     .addImm(0).addReg(0)
21512     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
21513                       MI->getOperand(3).getTargetFlags())
21514     .addReg(0);
21515     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
21516     addDirectMem(MIB, X86::EAX);
21517     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
21518   }
21519
21520   MI->eraseFromParent(); // The pseudo instruction is gone now.
21521   return BB;
21522 }
21523
21524 MachineBasicBlock *
21525 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
21526                                     MachineBasicBlock *MBB) const {
21527   DebugLoc DL = MI->getDebugLoc();
21528   MachineFunction *MF = MBB->getParent();
21529   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21530   MachineRegisterInfo &MRI = MF->getRegInfo();
21531
21532   const BasicBlock *BB = MBB->getBasicBlock();
21533   MachineFunction::iterator I = ++MBB->getIterator();
21534
21535   // Memory Reference
21536   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
21537   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
21538
21539   unsigned DstReg;
21540   unsigned MemOpndSlot = 0;
21541
21542   unsigned CurOp = 0;
21543
21544   DstReg = MI->getOperand(CurOp++).getReg();
21545   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
21546   assert(RC->hasType(MVT::i32) && "Invalid destination!");
21547   unsigned mainDstReg = MRI.createVirtualRegister(RC);
21548   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
21549
21550   MemOpndSlot = CurOp;
21551
21552   MVT PVT = getPointerTy(MF->getDataLayout());
21553   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
21554          "Invalid Pointer Size!");
21555
21556   // For v = setjmp(buf), we generate
21557   //
21558   // thisMBB:
21559   //  buf[LabelOffset] = restoreMBB <-- takes address of restoreMBB
21560   //  SjLjSetup restoreMBB
21561   //
21562   // mainMBB:
21563   //  v_main = 0
21564   //
21565   // sinkMBB:
21566   //  v = phi(main, restore)
21567   //
21568   // restoreMBB:
21569   //  if base pointer being used, load it from frame
21570   //  v_restore = 1
21571
21572   MachineBasicBlock *thisMBB = MBB;
21573   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
21574   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
21575   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
21576   MF->insert(I, mainMBB);
21577   MF->insert(I, sinkMBB);
21578   MF->push_back(restoreMBB);
21579   restoreMBB->setHasAddressTaken();
21580
21581   MachineInstrBuilder MIB;
21582
21583   // Transfer the remainder of BB and its successor edges to sinkMBB.
21584   sinkMBB->splice(sinkMBB->begin(), MBB,
21585                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
21586   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
21587
21588   // thisMBB:
21589   unsigned PtrStoreOpc = 0;
21590   unsigned LabelReg = 0;
21591   const int64_t LabelOffset = 1 * PVT.getStoreSize();
21592   Reloc::Model RM = MF->getTarget().getRelocationModel();
21593   bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
21594                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
21595
21596   // Prepare IP either in reg or imm.
21597   if (!UseImmLabel) {
21598     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
21599     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
21600     LabelReg = MRI.createVirtualRegister(PtrRC);
21601     if (Subtarget->is64Bit()) {
21602       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
21603               .addReg(X86::RIP)
21604               .addImm(0)
21605               .addReg(0)
21606               .addMBB(restoreMBB)
21607               .addReg(0);
21608     } else {
21609       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
21610       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
21611               .addReg(XII->getGlobalBaseReg(MF))
21612               .addImm(0)
21613               .addReg(0)
21614               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
21615               .addReg(0);
21616     }
21617   } else
21618     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
21619   // Store IP
21620   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
21621   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
21622     if (i == X86::AddrDisp)
21623       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
21624     else
21625       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
21626   }
21627   if (!UseImmLabel)
21628     MIB.addReg(LabelReg);
21629   else
21630     MIB.addMBB(restoreMBB);
21631   MIB.setMemRefs(MMOBegin, MMOEnd);
21632   // Setup
21633   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
21634           .addMBB(restoreMBB);
21635
21636   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
21637   MIB.addRegMask(RegInfo->getNoPreservedMask());
21638   thisMBB->addSuccessor(mainMBB);
21639   thisMBB->addSuccessor(restoreMBB);
21640
21641   // mainMBB:
21642   //  EAX = 0
21643   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
21644   mainMBB->addSuccessor(sinkMBB);
21645
21646   // sinkMBB:
21647   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
21648           TII->get(X86::PHI), DstReg)
21649     .addReg(mainDstReg).addMBB(mainMBB)
21650     .addReg(restoreDstReg).addMBB(restoreMBB);
21651
21652   // restoreMBB:
21653   if (RegInfo->hasBasePointer(*MF)) {
21654     const bool Uses64BitFramePtr =
21655         Subtarget->isTarget64BitLP64() || Subtarget->isTargetNaCl64();
21656     X86MachineFunctionInfo *X86FI = MF->getInfo<X86MachineFunctionInfo>();
21657     X86FI->setRestoreBasePointer(MF);
21658     unsigned FramePtr = RegInfo->getFrameRegister(*MF);
21659     unsigned BasePtr = RegInfo->getBaseRegister();
21660     unsigned Opm = Uses64BitFramePtr ? X86::MOV64rm : X86::MOV32rm;
21661     addRegOffset(BuildMI(restoreMBB, DL, TII->get(Opm), BasePtr),
21662                  FramePtr, true, X86FI->getRestoreBasePointerOffset())
21663       .setMIFlag(MachineInstr::FrameSetup);
21664   }
21665   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
21666   BuildMI(restoreMBB, DL, TII->get(X86::JMP_1)).addMBB(sinkMBB);
21667   restoreMBB->addSuccessor(sinkMBB);
21668
21669   MI->eraseFromParent();
21670   return sinkMBB;
21671 }
21672
21673 MachineBasicBlock *
21674 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
21675                                      MachineBasicBlock *MBB) const {
21676   DebugLoc DL = MI->getDebugLoc();
21677   MachineFunction *MF = MBB->getParent();
21678   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21679   MachineRegisterInfo &MRI = MF->getRegInfo();
21680
21681   // Memory Reference
21682   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
21683   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
21684
21685   MVT PVT = getPointerTy(MF->getDataLayout());
21686   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
21687          "Invalid Pointer Size!");
21688
21689   const TargetRegisterClass *RC =
21690     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
21691   unsigned Tmp = MRI.createVirtualRegister(RC);
21692   // Since FP is only updated here but NOT referenced, it's treated as GPR.
21693   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
21694   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
21695   unsigned SP = RegInfo->getStackRegister();
21696
21697   MachineInstrBuilder MIB;
21698
21699   const int64_t LabelOffset = 1 * PVT.getStoreSize();
21700   const int64_t SPOffset = 2 * PVT.getStoreSize();
21701
21702   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
21703   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
21704
21705   // Reload FP
21706   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
21707   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
21708     MIB.addOperand(MI->getOperand(i));
21709   MIB.setMemRefs(MMOBegin, MMOEnd);
21710   // Reload IP
21711   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
21712   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
21713     if (i == X86::AddrDisp)
21714       MIB.addDisp(MI->getOperand(i), LabelOffset);
21715     else
21716       MIB.addOperand(MI->getOperand(i));
21717   }
21718   MIB.setMemRefs(MMOBegin, MMOEnd);
21719   // Reload SP
21720   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
21721   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
21722     if (i == X86::AddrDisp)
21723       MIB.addDisp(MI->getOperand(i), SPOffset);
21724     else
21725       MIB.addOperand(MI->getOperand(i));
21726   }
21727   MIB.setMemRefs(MMOBegin, MMOEnd);
21728   // Jump
21729   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
21730
21731   MI->eraseFromParent();
21732   return MBB;
21733 }
21734
21735 // Replace 213-type (isel default) FMA3 instructions with 231-type for
21736 // accumulator loops. Writing back to the accumulator allows the coalescer
21737 // to remove extra copies in the loop.
21738 // FIXME: Do this on AVX512.  We don't support 231 variants yet (PR23937).
21739 MachineBasicBlock *
21740 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
21741                                  MachineBasicBlock *MBB) const {
21742   MachineOperand &AddendOp = MI->getOperand(3);
21743
21744   // Bail out early if the addend isn't a register - we can't switch these.
21745   if (!AddendOp.isReg())
21746     return MBB;
21747
21748   MachineFunction &MF = *MBB->getParent();
21749   MachineRegisterInfo &MRI = MF.getRegInfo();
21750
21751   // Check whether the addend is defined by a PHI:
21752   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
21753   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
21754   if (!AddendDef.isPHI())
21755     return MBB;
21756
21757   // Look for the following pattern:
21758   // loop:
21759   //   %addend = phi [%entry, 0], [%loop, %result]
21760   //   ...
21761   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
21762
21763   // Replace with:
21764   //   loop:
21765   //   %addend = phi [%entry, 0], [%loop, %result]
21766   //   ...
21767   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
21768
21769   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
21770     assert(AddendDef.getOperand(i).isReg());
21771     MachineOperand PHISrcOp = AddendDef.getOperand(i);
21772     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
21773     if (&PHISrcInst == MI) {
21774       // Found a matching instruction.
21775       unsigned NewFMAOpc = 0;
21776       switch (MI->getOpcode()) {
21777         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
21778         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
21779         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
21780         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
21781         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
21782         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
21783         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
21784         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
21785         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
21786         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
21787         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
21788         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
21789         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
21790         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
21791         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
21792         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
21793         case X86::VFMADDSUBPDr213r: NewFMAOpc = X86::VFMADDSUBPDr231r; break;
21794         case X86::VFMADDSUBPSr213r: NewFMAOpc = X86::VFMADDSUBPSr231r; break;
21795         case X86::VFMSUBADDPDr213r: NewFMAOpc = X86::VFMSUBADDPDr231r; break;
21796         case X86::VFMSUBADDPSr213r: NewFMAOpc = X86::VFMSUBADDPSr231r; break;
21797
21798         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
21799         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
21800         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
21801         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
21802         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
21803         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
21804         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
21805         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
21806         case X86::VFMADDSUBPDr213rY: NewFMAOpc = X86::VFMADDSUBPDr231rY; break;
21807         case X86::VFMADDSUBPSr213rY: NewFMAOpc = X86::VFMADDSUBPSr231rY; break;
21808         case X86::VFMSUBADDPDr213rY: NewFMAOpc = X86::VFMSUBADDPDr231rY; break;
21809         case X86::VFMSUBADDPSr213rY: NewFMAOpc = X86::VFMSUBADDPSr231rY; break;
21810         default: llvm_unreachable("Unrecognized FMA variant.");
21811       }
21812
21813       const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
21814       MachineInstrBuilder MIB =
21815         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
21816         .addOperand(MI->getOperand(0))
21817         .addOperand(MI->getOperand(3))
21818         .addOperand(MI->getOperand(2))
21819         .addOperand(MI->getOperand(1));
21820       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
21821       MI->eraseFromParent();
21822     }
21823   }
21824
21825   return MBB;
21826 }
21827
21828 MachineBasicBlock *
21829 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
21830                                                MachineBasicBlock *BB) const {
21831   switch (MI->getOpcode()) {
21832   default: llvm_unreachable("Unexpected instr type to insert");
21833   case X86::TAILJMPd64:
21834   case X86::TAILJMPr64:
21835   case X86::TAILJMPm64:
21836   case X86::TAILJMPd64_REX:
21837   case X86::TAILJMPr64_REX:
21838   case X86::TAILJMPm64_REX:
21839     llvm_unreachable("TAILJMP64 would not be touched here.");
21840   case X86::TCRETURNdi64:
21841   case X86::TCRETURNri64:
21842   case X86::TCRETURNmi64:
21843     return BB;
21844   case X86::WIN_ALLOCA:
21845     return EmitLoweredWinAlloca(MI, BB);
21846   case X86::CATCHRET:
21847     return EmitLoweredCatchRet(MI, BB);
21848   case X86::CATCHPAD:
21849     return EmitLoweredCatchPad(MI, BB);
21850   case X86::SEG_ALLOCA_32:
21851   case X86::SEG_ALLOCA_64:
21852     return EmitLoweredSegAlloca(MI, BB);
21853   case X86::TLSCall_32:
21854   case X86::TLSCall_64:
21855     return EmitLoweredTLSCall(MI, BB);
21856   case X86::CMOV_FR32:
21857   case X86::CMOV_FR64:
21858   case X86::CMOV_GR8:
21859   case X86::CMOV_GR16:
21860   case X86::CMOV_GR32:
21861   case X86::CMOV_RFP32:
21862   case X86::CMOV_RFP64:
21863   case X86::CMOV_RFP80:
21864   case X86::CMOV_V2F64:
21865   case X86::CMOV_V2I64:
21866   case X86::CMOV_V4F32:
21867   case X86::CMOV_V4F64:
21868   case X86::CMOV_V4I64:
21869   case X86::CMOV_V16F32:
21870   case X86::CMOV_V8F32:
21871   case X86::CMOV_V8F64:
21872   case X86::CMOV_V8I64:
21873   case X86::CMOV_V8I1:
21874   case X86::CMOV_V16I1:
21875   case X86::CMOV_V32I1:
21876   case X86::CMOV_V64I1:
21877     return EmitLoweredSelect(MI, BB);
21878
21879   case X86::RELEASE_FADD32mr:
21880   case X86::RELEASE_FADD64mr:
21881     return EmitLoweredAtomicFP(MI, BB);
21882
21883   case X86::FP32_TO_INT16_IN_MEM:
21884   case X86::FP32_TO_INT32_IN_MEM:
21885   case X86::FP32_TO_INT64_IN_MEM:
21886   case X86::FP64_TO_INT16_IN_MEM:
21887   case X86::FP64_TO_INT32_IN_MEM:
21888   case X86::FP64_TO_INT64_IN_MEM:
21889   case X86::FP80_TO_INT16_IN_MEM:
21890   case X86::FP80_TO_INT32_IN_MEM:
21891   case X86::FP80_TO_INT64_IN_MEM: {
21892     MachineFunction *F = BB->getParent();
21893     const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21894     DebugLoc DL = MI->getDebugLoc();
21895
21896     // Change the floating point control register to use "round towards zero"
21897     // mode when truncating to an integer value.
21898     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
21899     addFrameReference(BuildMI(*BB, MI, DL,
21900                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
21901
21902     // Load the old value of the high byte of the control word...
21903     unsigned OldCW =
21904       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
21905     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
21906                       CWFrameIdx);
21907
21908     // Set the high part to be round to zero...
21909     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
21910       .addImm(0xC7F);
21911
21912     // Reload the modified control word now...
21913     addFrameReference(BuildMI(*BB, MI, DL,
21914                               TII->get(X86::FLDCW16m)), CWFrameIdx);
21915
21916     // Restore the memory image of control word to original value
21917     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
21918       .addReg(OldCW);
21919
21920     // Get the X86 opcode to use.
21921     unsigned Opc;
21922     switch (MI->getOpcode()) {
21923     default: llvm_unreachable("illegal opcode!");
21924     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
21925     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
21926     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
21927     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
21928     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
21929     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
21930     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
21931     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
21932     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
21933     }
21934
21935     X86AddressMode AM;
21936     MachineOperand &Op = MI->getOperand(0);
21937     if (Op.isReg()) {
21938       AM.BaseType = X86AddressMode::RegBase;
21939       AM.Base.Reg = Op.getReg();
21940     } else {
21941       AM.BaseType = X86AddressMode::FrameIndexBase;
21942       AM.Base.FrameIndex = Op.getIndex();
21943     }
21944     Op = MI->getOperand(1);
21945     if (Op.isImm())
21946       AM.Scale = Op.getImm();
21947     Op = MI->getOperand(2);
21948     if (Op.isImm())
21949       AM.IndexReg = Op.getImm();
21950     Op = MI->getOperand(3);
21951     if (Op.isGlobal()) {
21952       AM.GV = Op.getGlobal();
21953     } else {
21954       AM.Disp = Op.getImm();
21955     }
21956     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
21957                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
21958
21959     // Reload the original control word now.
21960     addFrameReference(BuildMI(*BB, MI, DL,
21961                               TII->get(X86::FLDCW16m)), CWFrameIdx);
21962
21963     MI->eraseFromParent();   // The pseudo instruction is gone now.
21964     return BB;
21965   }
21966     // String/text processing lowering.
21967   case X86::PCMPISTRM128REG:
21968   case X86::VPCMPISTRM128REG:
21969   case X86::PCMPISTRM128MEM:
21970   case X86::VPCMPISTRM128MEM:
21971   case X86::PCMPESTRM128REG:
21972   case X86::VPCMPESTRM128REG:
21973   case X86::PCMPESTRM128MEM:
21974   case X86::VPCMPESTRM128MEM:
21975     assert(Subtarget->hasSSE42() &&
21976            "Target must have SSE4.2 or AVX features enabled");
21977     return EmitPCMPSTRM(MI, BB, Subtarget->getInstrInfo());
21978
21979   // String/text processing lowering.
21980   case X86::PCMPISTRIREG:
21981   case X86::VPCMPISTRIREG:
21982   case X86::PCMPISTRIMEM:
21983   case X86::VPCMPISTRIMEM:
21984   case X86::PCMPESTRIREG:
21985   case X86::VPCMPESTRIREG:
21986   case X86::PCMPESTRIMEM:
21987   case X86::VPCMPESTRIMEM:
21988     assert(Subtarget->hasSSE42() &&
21989            "Target must have SSE4.2 or AVX features enabled");
21990     return EmitPCMPSTRI(MI, BB, Subtarget->getInstrInfo());
21991
21992   // Thread synchronization.
21993   case X86::MONITOR:
21994     return EmitMonitor(MI, BB, Subtarget);
21995
21996   // xbegin
21997   case X86::XBEGIN:
21998     return EmitXBegin(MI, BB, Subtarget->getInstrInfo());
21999
22000   case X86::VASTART_SAVE_XMM_REGS:
22001     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
22002
22003   case X86::VAARG_64:
22004     return EmitVAARG64WithCustomInserter(MI, BB);
22005
22006   case X86::EH_SjLj_SetJmp32:
22007   case X86::EH_SjLj_SetJmp64:
22008     return emitEHSjLjSetJmp(MI, BB);
22009
22010   case X86::EH_SjLj_LongJmp32:
22011   case X86::EH_SjLj_LongJmp64:
22012     return emitEHSjLjLongJmp(MI, BB);
22013
22014   case TargetOpcode::STATEPOINT:
22015     // As an implementation detail, STATEPOINT shares the STACKMAP format at
22016     // this point in the process.  We diverge later.
22017     return emitPatchPoint(MI, BB);
22018
22019   case TargetOpcode::STACKMAP:
22020   case TargetOpcode::PATCHPOINT:
22021     return emitPatchPoint(MI, BB);
22022
22023   case X86::VFMADDPDr213r:
22024   case X86::VFMADDPSr213r:
22025   case X86::VFMADDSDr213r:
22026   case X86::VFMADDSSr213r:
22027   case X86::VFMSUBPDr213r:
22028   case X86::VFMSUBPSr213r:
22029   case X86::VFMSUBSDr213r:
22030   case X86::VFMSUBSSr213r:
22031   case X86::VFNMADDPDr213r:
22032   case X86::VFNMADDPSr213r:
22033   case X86::VFNMADDSDr213r:
22034   case X86::VFNMADDSSr213r:
22035   case X86::VFNMSUBPDr213r:
22036   case X86::VFNMSUBPSr213r:
22037   case X86::VFNMSUBSDr213r:
22038   case X86::VFNMSUBSSr213r:
22039   case X86::VFMADDSUBPDr213r:
22040   case X86::VFMADDSUBPSr213r:
22041   case X86::VFMSUBADDPDr213r:
22042   case X86::VFMSUBADDPSr213r:
22043   case X86::VFMADDPDr213rY:
22044   case X86::VFMADDPSr213rY:
22045   case X86::VFMSUBPDr213rY:
22046   case X86::VFMSUBPSr213rY:
22047   case X86::VFNMADDPDr213rY:
22048   case X86::VFNMADDPSr213rY:
22049   case X86::VFNMSUBPDr213rY:
22050   case X86::VFNMSUBPSr213rY:
22051   case X86::VFMADDSUBPDr213rY:
22052   case X86::VFMADDSUBPSr213rY:
22053   case X86::VFMSUBADDPDr213rY:
22054   case X86::VFMSUBADDPSr213rY:
22055     return emitFMA3Instr(MI, BB);
22056   }
22057 }
22058
22059 //===----------------------------------------------------------------------===//
22060 //                           X86 Optimization Hooks
22061 //===----------------------------------------------------------------------===//
22062
22063 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
22064                                                       APInt &KnownZero,
22065                                                       APInt &KnownOne,
22066                                                       const SelectionDAG &DAG,
22067                                                       unsigned Depth) const {
22068   unsigned BitWidth = KnownZero.getBitWidth();
22069   unsigned Opc = Op.getOpcode();
22070   assert((Opc >= ISD::BUILTIN_OP_END ||
22071           Opc == ISD::INTRINSIC_WO_CHAIN ||
22072           Opc == ISD::INTRINSIC_W_CHAIN ||
22073           Opc == ISD::INTRINSIC_VOID) &&
22074          "Should use MaskedValueIsZero if you don't know whether Op"
22075          " is a target node!");
22076
22077   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
22078   switch (Opc) {
22079   default: break;
22080   case X86ISD::ADD:
22081   case X86ISD::SUB:
22082   case X86ISD::ADC:
22083   case X86ISD::SBB:
22084   case X86ISD::SMUL:
22085   case X86ISD::UMUL:
22086   case X86ISD::INC:
22087   case X86ISD::DEC:
22088   case X86ISD::OR:
22089   case X86ISD::XOR:
22090   case X86ISD::AND:
22091     // These nodes' second result is a boolean.
22092     if (Op.getResNo() == 0)
22093       break;
22094     // Fallthrough
22095   case X86ISD::SETCC:
22096     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
22097     break;
22098   case ISD::INTRINSIC_WO_CHAIN: {
22099     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
22100     unsigned NumLoBits = 0;
22101     switch (IntId) {
22102     default: break;
22103     case Intrinsic::x86_sse_movmsk_ps:
22104     case Intrinsic::x86_avx_movmsk_ps_256:
22105     case Intrinsic::x86_sse2_movmsk_pd:
22106     case Intrinsic::x86_avx_movmsk_pd_256:
22107     case Intrinsic::x86_mmx_pmovmskb:
22108     case Intrinsic::x86_sse2_pmovmskb_128:
22109     case Intrinsic::x86_avx2_pmovmskb: {
22110       // High bits of movmskp{s|d}, pmovmskb are known zero.
22111       switch (IntId) {
22112         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
22113         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
22114         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
22115         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
22116         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
22117         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
22118         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
22119         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
22120       }
22121       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
22122       break;
22123     }
22124     }
22125     break;
22126   }
22127   }
22128 }
22129
22130 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
22131   SDValue Op,
22132   const SelectionDAG &,
22133   unsigned Depth) const {
22134   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
22135   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
22136     return Op.getValueType().getScalarSizeInBits();
22137
22138   // Fallback case.
22139   return 1;
22140 }
22141
22142 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
22143 /// node is a GlobalAddress + offset.
22144 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
22145                                        const GlobalValue* &GA,
22146                                        int64_t &Offset) const {
22147   if (N->getOpcode() == X86ISD::Wrapper) {
22148     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
22149       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
22150       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
22151       return true;
22152     }
22153   }
22154   return TargetLowering::isGAPlusOffset(N, GA, Offset);
22155 }
22156
22157 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
22158 /// same as extracting the high 128-bit part of 256-bit vector and then
22159 /// inserting the result into the low part of a new 256-bit vector
22160 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
22161   EVT VT = SVOp->getValueType(0);
22162   unsigned NumElems = VT.getVectorNumElements();
22163
22164   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
22165   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
22166     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
22167         SVOp->getMaskElt(j) >= 0)
22168       return false;
22169
22170   return true;
22171 }
22172
22173 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
22174 /// same as extracting the low 128-bit part of 256-bit vector and then
22175 /// inserting the result into the high part of a new 256-bit vector
22176 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
22177   EVT VT = SVOp->getValueType(0);
22178   unsigned NumElems = VT.getVectorNumElements();
22179
22180   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
22181   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
22182     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
22183         SVOp->getMaskElt(j) >= 0)
22184       return false;
22185
22186   return true;
22187 }
22188
22189 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
22190 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
22191                                         TargetLowering::DAGCombinerInfo &DCI,
22192                                         const X86Subtarget* Subtarget) {
22193   SDLoc dl(N);
22194   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
22195   SDValue V1 = SVOp->getOperand(0);
22196   SDValue V2 = SVOp->getOperand(1);
22197   EVT VT = SVOp->getValueType(0);
22198   unsigned NumElems = VT.getVectorNumElements();
22199
22200   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
22201       V2.getOpcode() == ISD::CONCAT_VECTORS) {
22202     //
22203     //                   0,0,0,...
22204     //                      |
22205     //    V      UNDEF    BUILD_VECTOR    UNDEF
22206     //     \      /           \           /
22207     //  CONCAT_VECTOR         CONCAT_VECTOR
22208     //         \                  /
22209     //          \                /
22210     //          RESULT: V + zero extended
22211     //
22212     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
22213         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
22214         V1.getOperand(1).getOpcode() != ISD::UNDEF)
22215       return SDValue();
22216
22217     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
22218       return SDValue();
22219
22220     // To match the shuffle mask, the first half of the mask should
22221     // be exactly the first vector, and all the rest a splat with the
22222     // first element of the second one.
22223     for (unsigned i = 0; i != NumElems/2; ++i)
22224       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
22225           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
22226         return SDValue();
22227
22228     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
22229     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
22230       if (Ld->hasNUsesOfValue(1, 0)) {
22231         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
22232         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
22233         SDValue ResNode =
22234           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
22235                                   Ld->getMemoryVT(),
22236                                   Ld->getPointerInfo(),
22237                                   Ld->getAlignment(),
22238                                   false/*isVolatile*/, true/*ReadMem*/,
22239                                   false/*WriteMem*/);
22240
22241         // Make sure the newly-created LOAD is in the same position as Ld in
22242         // terms of dependency. We create a TokenFactor for Ld and ResNode,
22243         // and update uses of Ld's output chain to use the TokenFactor.
22244         if (Ld->hasAnyUseOfValue(1)) {
22245           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
22246                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
22247           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
22248           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
22249                                  SDValue(ResNode.getNode(), 1));
22250         }
22251
22252         return DAG.getBitcast(VT, ResNode);
22253       }
22254     }
22255
22256     // Emit a zeroed vector and insert the desired subvector on its
22257     // first half.
22258     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
22259     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
22260     return DCI.CombineTo(N, InsV);
22261   }
22262
22263   //===--------------------------------------------------------------------===//
22264   // Combine some shuffles into subvector extracts and inserts:
22265   //
22266
22267   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
22268   if (isShuffleHigh128VectorInsertLow(SVOp)) {
22269     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
22270     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
22271     return DCI.CombineTo(N, InsV);
22272   }
22273
22274   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
22275   if (isShuffleLow128VectorInsertHigh(SVOp)) {
22276     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
22277     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
22278     return DCI.CombineTo(N, InsV);
22279   }
22280
22281   return SDValue();
22282 }
22283
22284 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
22285 /// possible.
22286 ///
22287 /// This is the leaf of the recursive combinine below. When we have found some
22288 /// chain of single-use x86 shuffle instructions and accumulated the combined
22289 /// shuffle mask represented by them, this will try to pattern match that mask
22290 /// into either a single instruction if there is a special purpose instruction
22291 /// for this operation, or into a PSHUFB instruction which is a fully general
22292 /// instruction but should only be used to replace chains over a certain depth.
22293 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
22294                                    int Depth, bool HasPSHUFB, SelectionDAG &DAG,
22295                                    TargetLowering::DAGCombinerInfo &DCI,
22296                                    const X86Subtarget *Subtarget) {
22297   assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
22298
22299   // Find the operand that enters the chain. Note that multiple uses are OK
22300   // here, we're not going to remove the operand we find.
22301   SDValue Input = Op.getOperand(0);
22302   while (Input.getOpcode() == ISD::BITCAST)
22303     Input = Input.getOperand(0);
22304
22305   MVT VT = Input.getSimpleValueType();
22306   MVT RootVT = Root.getSimpleValueType();
22307   SDLoc DL(Root);
22308
22309   if (Mask.size() == 1) {
22310     int Index = Mask[0];
22311     assert((Index >= 0 || Index == SM_SentinelUndef ||
22312             Index == SM_SentinelZero) &&
22313            "Invalid shuffle index found!");
22314
22315     // We may end up with an accumulated mask of size 1 as a result of
22316     // widening of shuffle operands (see function canWidenShuffleElements).
22317     // If the only shuffle index is equal to SM_SentinelZero then propagate
22318     // a zero vector. Otherwise, the combine shuffle mask is a no-op shuffle
22319     // mask, and therefore the entire chain of shuffles can be folded away.
22320     if (Index == SM_SentinelZero)
22321       DCI.CombineTo(Root.getNode(), getZeroVector(RootVT, Subtarget, DAG, DL));
22322     else
22323       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Input),
22324                     /*AddTo*/ true);
22325     return true;
22326   }
22327
22328   // Use the float domain if the operand type is a floating point type.
22329   bool FloatDomain = VT.isFloatingPoint();
22330
22331   // For floating point shuffles, we don't have free copies in the shuffle
22332   // instructions or the ability to load as part of the instruction, so
22333   // canonicalize their shuffles to UNPCK or MOV variants.
22334   //
22335   // Note that even with AVX we prefer the PSHUFD form of shuffle for integer
22336   // vectors because it can have a load folded into it that UNPCK cannot. This
22337   // doesn't preclude something switching to the shorter encoding post-RA.
22338   //
22339   // FIXME: Should teach these routines about AVX vector widths.
22340   if (FloatDomain && VT.is128BitVector()) {
22341     if (Mask.equals({0, 0}) || Mask.equals({1, 1})) {
22342       bool Lo = Mask.equals({0, 0});
22343       unsigned Shuffle;
22344       MVT ShuffleVT;
22345       // Check if we have SSE3 which will let us use MOVDDUP. That instruction
22346       // is no slower than UNPCKLPD but has the option to fold the input operand
22347       // into even an unaligned memory load.
22348       if (Lo && Subtarget->hasSSE3()) {
22349         Shuffle = X86ISD::MOVDDUP;
22350         ShuffleVT = MVT::v2f64;
22351       } else {
22352         // We have MOVLHPS and MOVHLPS throughout SSE and they encode smaller
22353         // than the UNPCK variants.
22354         Shuffle = Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS;
22355         ShuffleVT = MVT::v4f32;
22356       }
22357       if (Depth == 1 && Root->getOpcode() == Shuffle)
22358         return false; // Nothing to do!
22359       Op = DAG.getBitcast(ShuffleVT, Input);
22360       DCI.AddToWorklist(Op.getNode());
22361       if (Shuffle == X86ISD::MOVDDUP)
22362         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
22363       else
22364         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
22365       DCI.AddToWorklist(Op.getNode());
22366       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
22367                     /*AddTo*/ true);
22368       return true;
22369     }
22370     if (Subtarget->hasSSE3() &&
22371         (Mask.equals({0, 0, 2, 2}) || Mask.equals({1, 1, 3, 3}))) {
22372       bool Lo = Mask.equals({0, 0, 2, 2});
22373       unsigned Shuffle = Lo ? X86ISD::MOVSLDUP : X86ISD::MOVSHDUP;
22374       MVT ShuffleVT = MVT::v4f32;
22375       if (Depth == 1 && Root->getOpcode() == Shuffle)
22376         return false; // Nothing to do!
22377       Op = DAG.getBitcast(ShuffleVT, Input);
22378       DCI.AddToWorklist(Op.getNode());
22379       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
22380       DCI.AddToWorklist(Op.getNode());
22381       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
22382                     /*AddTo*/ true);
22383       return true;
22384     }
22385     if (Mask.equals({0, 0, 1, 1}) || Mask.equals({2, 2, 3, 3})) {
22386       bool Lo = Mask.equals({0, 0, 1, 1});
22387       unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
22388       MVT ShuffleVT = MVT::v4f32;
22389       if (Depth == 1 && Root->getOpcode() == Shuffle)
22390         return false; // Nothing to do!
22391       Op = DAG.getBitcast(ShuffleVT, Input);
22392       DCI.AddToWorklist(Op.getNode());
22393       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
22394       DCI.AddToWorklist(Op.getNode());
22395       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
22396                     /*AddTo*/ true);
22397       return true;
22398     }
22399   }
22400
22401   // We always canonicalize the 8 x i16 and 16 x i8 shuffles into their UNPCK
22402   // variants as none of these have single-instruction variants that are
22403   // superior to the UNPCK formulation.
22404   if (!FloatDomain && VT.is128BitVector() &&
22405       (Mask.equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
22406        Mask.equals({4, 4, 5, 5, 6, 6, 7, 7}) ||
22407        Mask.equals({0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7}) ||
22408        Mask.equals(
22409            {8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15}))) {
22410     bool Lo = Mask[0] == 0;
22411     unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
22412     if (Depth == 1 && Root->getOpcode() == Shuffle)
22413       return false; // Nothing to do!
22414     MVT ShuffleVT;
22415     switch (Mask.size()) {
22416     case 8:
22417       ShuffleVT = MVT::v8i16;
22418       break;
22419     case 16:
22420       ShuffleVT = MVT::v16i8;
22421       break;
22422     default:
22423       llvm_unreachable("Impossible mask size!");
22424     };
22425     Op = DAG.getBitcast(ShuffleVT, Input);
22426     DCI.AddToWorklist(Op.getNode());
22427     Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
22428     DCI.AddToWorklist(Op.getNode());
22429     DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
22430                   /*AddTo*/ true);
22431     return true;
22432   }
22433
22434   // Don't try to re-form single instruction chains under any circumstances now
22435   // that we've done encoding canonicalization for them.
22436   if (Depth < 2)
22437     return false;
22438
22439   // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
22440   // can replace them with a single PSHUFB instruction profitably. Intel's
22441   // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
22442   // in practice PSHUFB tends to be *very* fast so we're more aggressive.
22443   if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
22444     SmallVector<SDValue, 16> PSHUFBMask;
22445     int NumBytes = VT.getSizeInBits() / 8;
22446     int Ratio = NumBytes / Mask.size();
22447     for (int i = 0; i < NumBytes; ++i) {
22448       if (Mask[i / Ratio] == SM_SentinelUndef) {
22449         PSHUFBMask.push_back(DAG.getUNDEF(MVT::i8));
22450         continue;
22451       }
22452       int M = Mask[i / Ratio] != SM_SentinelZero
22453                   ? Ratio * Mask[i / Ratio] + i % Ratio
22454                   : 255;
22455       PSHUFBMask.push_back(DAG.getConstant(M, DL, MVT::i8));
22456     }
22457     MVT ByteVT = MVT::getVectorVT(MVT::i8, NumBytes);
22458     Op = DAG.getBitcast(ByteVT, Input);
22459     DCI.AddToWorklist(Op.getNode());
22460     SDValue PSHUFBMaskOp =
22461         DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVT, PSHUFBMask);
22462     DCI.AddToWorklist(PSHUFBMaskOp.getNode());
22463     Op = DAG.getNode(X86ISD::PSHUFB, DL, ByteVT, Op, PSHUFBMaskOp);
22464     DCI.AddToWorklist(Op.getNode());
22465     DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
22466                   /*AddTo*/ true);
22467     return true;
22468   }
22469
22470   // Failed to find any combines.
22471   return false;
22472 }
22473
22474 /// \brief Fully generic combining of x86 shuffle instructions.
22475 ///
22476 /// This should be the last combine run over the x86 shuffle instructions. Once
22477 /// they have been fully optimized, this will recursively consider all chains
22478 /// of single-use shuffle instructions, build a generic model of the cumulative
22479 /// shuffle operation, and check for simpler instructions which implement this
22480 /// operation. We use this primarily for two purposes:
22481 ///
22482 /// 1) Collapse generic shuffles to specialized single instructions when
22483 ///    equivalent. In most cases, this is just an encoding size win, but
22484 ///    sometimes we will collapse multiple generic shuffles into a single
22485 ///    special-purpose shuffle.
22486 /// 2) Look for sequences of shuffle instructions with 3 or more total
22487 ///    instructions, and replace them with the slightly more expensive SSSE3
22488 ///    PSHUFB instruction if available. We do this as the last combining step
22489 ///    to ensure we avoid using PSHUFB if we can implement the shuffle with
22490 ///    a suitable short sequence of other instructions. The PHUFB will either
22491 ///    use a register or have to read from memory and so is slightly (but only
22492 ///    slightly) more expensive than the other shuffle instructions.
22493 ///
22494 /// Because this is inherently a quadratic operation (for each shuffle in
22495 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
22496 /// This should never be an issue in practice as the shuffle lowering doesn't
22497 /// produce sequences of more than 8 instructions.
22498 ///
22499 /// FIXME: We will currently miss some cases where the redundant shuffling
22500 /// would simplify under the threshold for PSHUFB formation because of
22501 /// combine-ordering. To fix this, we should do the redundant instruction
22502 /// combining in this recursive walk.
22503 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
22504                                           ArrayRef<int> RootMask,
22505                                           int Depth, bool HasPSHUFB,
22506                                           SelectionDAG &DAG,
22507                                           TargetLowering::DAGCombinerInfo &DCI,
22508                                           const X86Subtarget *Subtarget) {
22509   // Bound the depth of our recursive combine because this is ultimately
22510   // quadratic in nature.
22511   if (Depth > 8)
22512     return false;
22513
22514   // Directly rip through bitcasts to find the underlying operand.
22515   while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
22516     Op = Op.getOperand(0);
22517
22518   MVT VT = Op.getSimpleValueType();
22519   if (!VT.isVector())
22520     return false; // Bail if we hit a non-vector.
22521
22522   assert(Root.getSimpleValueType().isVector() &&
22523          "Shuffles operate on vector types!");
22524   assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
22525          "Can only combine shuffles of the same vector register size.");
22526
22527   if (!isTargetShuffle(Op.getOpcode()))
22528     return false;
22529   SmallVector<int, 16> OpMask;
22530   bool IsUnary;
22531   bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, OpMask, IsUnary);
22532   // We only can combine unary shuffles which we can decode the mask for.
22533   if (!HaveMask || !IsUnary)
22534     return false;
22535
22536   assert(VT.getVectorNumElements() == OpMask.size() &&
22537          "Different mask size from vector size!");
22538   assert(((RootMask.size() > OpMask.size() &&
22539            RootMask.size() % OpMask.size() == 0) ||
22540           (OpMask.size() > RootMask.size() &&
22541            OpMask.size() % RootMask.size() == 0) ||
22542           OpMask.size() == RootMask.size()) &&
22543          "The smaller number of elements must divide the larger.");
22544   int RootRatio = std::max<int>(1, OpMask.size() / RootMask.size());
22545   int OpRatio = std::max<int>(1, RootMask.size() / OpMask.size());
22546   assert(((RootRatio == 1 && OpRatio == 1) ||
22547           (RootRatio == 1) != (OpRatio == 1)) &&
22548          "Must not have a ratio for both incoming and op masks!");
22549
22550   SmallVector<int, 16> Mask;
22551   Mask.reserve(std::max(OpMask.size(), RootMask.size()));
22552
22553   // Merge this shuffle operation's mask into our accumulated mask. Note that
22554   // this shuffle's mask will be the first applied to the input, followed by the
22555   // root mask to get us all the way to the root value arrangement. The reason
22556   // for this order is that we are recursing up the operation chain.
22557   for (int i = 0, e = std::max(OpMask.size(), RootMask.size()); i < e; ++i) {
22558     int RootIdx = i / RootRatio;
22559     if (RootMask[RootIdx] < 0) {
22560       // This is a zero or undef lane, we're done.
22561       Mask.push_back(RootMask[RootIdx]);
22562       continue;
22563     }
22564
22565     int RootMaskedIdx = RootMask[RootIdx] * RootRatio + i % RootRatio;
22566     int OpIdx = RootMaskedIdx / OpRatio;
22567     if (OpMask[OpIdx] < 0) {
22568       // The incoming lanes are zero or undef, it doesn't matter which ones we
22569       // are using.
22570       Mask.push_back(OpMask[OpIdx]);
22571       continue;
22572     }
22573
22574     // Ok, we have non-zero lanes, map them through.
22575     Mask.push_back(OpMask[OpIdx] * OpRatio +
22576                    RootMaskedIdx % OpRatio);
22577   }
22578
22579   // See if we can recurse into the operand to combine more things.
22580   switch (Op.getOpcode()) {
22581   case X86ISD::PSHUFB:
22582     HasPSHUFB = true;
22583   case X86ISD::PSHUFD:
22584   case X86ISD::PSHUFHW:
22585   case X86ISD::PSHUFLW:
22586     if (Op.getOperand(0).hasOneUse() &&
22587         combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
22588                                       HasPSHUFB, DAG, DCI, Subtarget))
22589       return true;
22590     break;
22591
22592   case X86ISD::UNPCKL:
22593   case X86ISD::UNPCKH:
22594     assert(Op.getOperand(0) == Op.getOperand(1) &&
22595            "We only combine unary shuffles!");
22596     // We can't check for single use, we have to check that this shuffle is the
22597     // only user.
22598     if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
22599         combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
22600                                       HasPSHUFB, DAG, DCI, Subtarget))
22601       return true;
22602     break;
22603   }
22604
22605   // Minor canonicalization of the accumulated shuffle mask to make it easier
22606   // to match below. All this does is detect masks with squential pairs of
22607   // elements, and shrink them to the half-width mask. It does this in a loop
22608   // so it will reduce the size of the mask to the minimal width mask which
22609   // performs an equivalent shuffle.
22610   SmallVector<int, 16> WidenedMask;
22611   while (Mask.size() > 1 && canWidenShuffleElements(Mask, WidenedMask)) {
22612     Mask = std::move(WidenedMask);
22613     WidenedMask.clear();
22614   }
22615
22616   return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
22617                                 Subtarget);
22618 }
22619
22620 /// \brief Get the PSHUF-style mask from PSHUF node.
22621 ///
22622 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
22623 /// PSHUF-style masks that can be reused with such instructions.
22624 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
22625   MVT VT = N.getSimpleValueType();
22626   SmallVector<int, 4> Mask;
22627   bool IsUnary;
22628   bool HaveMask = getTargetShuffleMask(N.getNode(), VT, Mask, IsUnary);
22629   (void)HaveMask;
22630   assert(HaveMask);
22631
22632   // If we have more than 128-bits, only the low 128-bits of shuffle mask
22633   // matter. Check that the upper masks are repeats and remove them.
22634   if (VT.getSizeInBits() > 128) {
22635     int LaneElts = 128 / VT.getScalarSizeInBits();
22636 #ifndef NDEBUG
22637     for (int i = 1, NumLanes = VT.getSizeInBits() / 128; i < NumLanes; ++i)
22638       for (int j = 0; j < LaneElts; ++j)
22639         assert(Mask[j] == Mask[i * LaneElts + j] - (LaneElts * i) &&
22640                "Mask doesn't repeat in high 128-bit lanes!");
22641 #endif
22642     Mask.resize(LaneElts);
22643   }
22644
22645   switch (N.getOpcode()) {
22646   case X86ISD::PSHUFD:
22647     return Mask;
22648   case X86ISD::PSHUFLW:
22649     Mask.resize(4);
22650     return Mask;
22651   case X86ISD::PSHUFHW:
22652     Mask.erase(Mask.begin(), Mask.begin() + 4);
22653     for (int &M : Mask)
22654       M -= 4;
22655     return Mask;
22656   default:
22657     llvm_unreachable("No valid shuffle instruction found!");
22658   }
22659 }
22660
22661 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
22662 ///
22663 /// We walk up the chain and look for a combinable shuffle, skipping over
22664 /// shuffles that we could hoist this shuffle's transformation past without
22665 /// altering anything.
22666 static SDValue
22667 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
22668                              SelectionDAG &DAG,
22669                              TargetLowering::DAGCombinerInfo &DCI) {
22670   assert(N.getOpcode() == X86ISD::PSHUFD &&
22671          "Called with something other than an x86 128-bit half shuffle!");
22672   SDLoc DL(N);
22673
22674   // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
22675   // of the shuffles in the chain so that we can form a fresh chain to replace
22676   // this one.
22677   SmallVector<SDValue, 8> Chain;
22678   SDValue V = N.getOperand(0);
22679   for (; V.hasOneUse(); V = V.getOperand(0)) {
22680     switch (V.getOpcode()) {
22681     default:
22682       return SDValue(); // Nothing combined!
22683
22684     case ISD::BITCAST:
22685       // Skip bitcasts as we always know the type for the target specific
22686       // instructions.
22687       continue;
22688
22689     case X86ISD::PSHUFD:
22690       // Found another dword shuffle.
22691       break;
22692
22693     case X86ISD::PSHUFLW:
22694       // Check that the low words (being shuffled) are the identity in the
22695       // dword shuffle, and the high words are self-contained.
22696       if (Mask[0] != 0 || Mask[1] != 1 ||
22697           !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
22698         return SDValue();
22699
22700       Chain.push_back(V);
22701       continue;
22702
22703     case X86ISD::PSHUFHW:
22704       // Check that the high words (being shuffled) are the identity in the
22705       // dword shuffle, and the low words are self-contained.
22706       if (Mask[2] != 2 || Mask[3] != 3 ||
22707           !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
22708         return SDValue();
22709
22710       Chain.push_back(V);
22711       continue;
22712
22713     case X86ISD::UNPCKL:
22714     case X86ISD::UNPCKH:
22715       // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
22716       // shuffle into a preceding word shuffle.
22717       if (V.getSimpleValueType().getVectorElementType() != MVT::i8 &&
22718           V.getSimpleValueType().getVectorElementType() != MVT::i16)
22719         return SDValue();
22720
22721       // Search for a half-shuffle which we can combine with.
22722       unsigned CombineOp =
22723           V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
22724       if (V.getOperand(0) != V.getOperand(1) ||
22725           !V->isOnlyUserOf(V.getOperand(0).getNode()))
22726         return SDValue();
22727       Chain.push_back(V);
22728       V = V.getOperand(0);
22729       do {
22730         switch (V.getOpcode()) {
22731         default:
22732           return SDValue(); // Nothing to combine.
22733
22734         case X86ISD::PSHUFLW:
22735         case X86ISD::PSHUFHW:
22736           if (V.getOpcode() == CombineOp)
22737             break;
22738
22739           Chain.push_back(V);
22740
22741           // Fallthrough!
22742         case ISD::BITCAST:
22743           V = V.getOperand(0);
22744           continue;
22745         }
22746         break;
22747       } while (V.hasOneUse());
22748       break;
22749     }
22750     // Break out of the loop if we break out of the switch.
22751     break;
22752   }
22753
22754   if (!V.hasOneUse())
22755     // We fell out of the loop without finding a viable combining instruction.
22756     return SDValue();
22757
22758   // Merge this node's mask and our incoming mask.
22759   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
22760   for (int &M : Mask)
22761     M = VMask[M];
22762   V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
22763                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
22764
22765   // Rebuild the chain around this new shuffle.
22766   while (!Chain.empty()) {
22767     SDValue W = Chain.pop_back_val();
22768
22769     if (V.getValueType() != W.getOperand(0).getValueType())
22770       V = DAG.getBitcast(W.getOperand(0).getValueType(), V);
22771
22772     switch (W.getOpcode()) {
22773     default:
22774       llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
22775
22776     case X86ISD::UNPCKL:
22777     case X86ISD::UNPCKH:
22778       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
22779       break;
22780
22781     case X86ISD::PSHUFD:
22782     case X86ISD::PSHUFLW:
22783     case X86ISD::PSHUFHW:
22784       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
22785       break;
22786     }
22787   }
22788   if (V.getValueType() != N.getValueType())
22789     V = DAG.getBitcast(N.getValueType(), V);
22790
22791   // Return the new chain to replace N.
22792   return V;
22793 }
22794
22795 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or
22796 /// pshufhw.
22797 ///
22798 /// We walk up the chain, skipping shuffles of the other half and looking
22799 /// through shuffles which switch halves trying to find a shuffle of the same
22800 /// pair of dwords.
22801 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
22802                                         SelectionDAG &DAG,
22803                                         TargetLowering::DAGCombinerInfo &DCI) {
22804   assert(
22805       (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
22806       "Called with something other than an x86 128-bit half shuffle!");
22807   SDLoc DL(N);
22808   unsigned CombineOpcode = N.getOpcode();
22809
22810   // Walk up a single-use chain looking for a combinable shuffle.
22811   SDValue V = N.getOperand(0);
22812   for (; V.hasOneUse(); V = V.getOperand(0)) {
22813     switch (V.getOpcode()) {
22814     default:
22815       return false; // Nothing combined!
22816
22817     case ISD::BITCAST:
22818       // Skip bitcasts as we always know the type for the target specific
22819       // instructions.
22820       continue;
22821
22822     case X86ISD::PSHUFLW:
22823     case X86ISD::PSHUFHW:
22824       if (V.getOpcode() == CombineOpcode)
22825         break;
22826
22827       // Other-half shuffles are no-ops.
22828       continue;
22829     }
22830     // Break out of the loop if we break out of the switch.
22831     break;
22832   }
22833
22834   if (!V.hasOneUse())
22835     // We fell out of the loop without finding a viable combining instruction.
22836     return false;
22837
22838   // Combine away the bottom node as its shuffle will be accumulated into
22839   // a preceding shuffle.
22840   DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
22841
22842   // Record the old value.
22843   SDValue Old = V;
22844
22845   // Merge this node's mask and our incoming mask (adjusted to account for all
22846   // the pshufd instructions encountered).
22847   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
22848   for (int &M : Mask)
22849     M = VMask[M];
22850   V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
22851                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
22852
22853   // Check that the shuffles didn't cancel each other out. If not, we need to
22854   // combine to the new one.
22855   if (Old != V)
22856     // Replace the combinable shuffle with the combined one, updating all users
22857     // so that we re-evaluate the chain here.
22858     DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
22859
22860   return true;
22861 }
22862
22863 /// \brief Try to combine x86 target specific shuffles.
22864 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
22865                                            TargetLowering::DAGCombinerInfo &DCI,
22866                                            const X86Subtarget *Subtarget) {
22867   SDLoc DL(N);
22868   MVT VT = N.getSimpleValueType();
22869   SmallVector<int, 4> Mask;
22870
22871   switch (N.getOpcode()) {
22872   case X86ISD::PSHUFD:
22873   case X86ISD::PSHUFLW:
22874   case X86ISD::PSHUFHW:
22875     Mask = getPSHUFShuffleMask(N);
22876     assert(Mask.size() == 4);
22877     break;
22878   case X86ISD::UNPCKL: {
22879     // Combine X86ISD::UNPCKL and ISD::VECTOR_SHUFFLE into X86ISD::UNPCKH, in
22880     // which X86ISD::UNPCKL has a ISD::UNDEF operand, and ISD::VECTOR_SHUFFLE
22881     // moves upper half elements into the lower half part. For example:
22882     //
22883     // t2: v16i8 = vector_shuffle<8,9,10,11,12,13,14,15,u,u,u,u,u,u,u,u> t1,
22884     //     undef:v16i8
22885     // t3: v16i8 = X86ISD::UNPCKL undef:v16i8, t2
22886     //
22887     // will be combined to:
22888     //
22889     // t3: v16i8 = X86ISD::UNPCKH undef:v16i8, t1
22890
22891     // This is only for 128-bit vectors. From SSE4.1 onward this combine may not
22892     // happen due to advanced instructions.
22893     if (!VT.is128BitVector())
22894       return SDValue();
22895
22896     auto Op0 = N.getOperand(0);
22897     auto Op1 = N.getOperand(1);
22898     if (Op0.getOpcode() == ISD::UNDEF &&
22899         Op1.getNode()->getOpcode() == ISD::VECTOR_SHUFFLE) {
22900       ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op1.getNode())->getMask();
22901
22902       unsigned NumElts = VT.getVectorNumElements();
22903       SmallVector<int, 8> ExpectedMask(NumElts, -1);
22904       std::iota(ExpectedMask.begin(), ExpectedMask.begin() + NumElts / 2,
22905                 NumElts / 2);
22906
22907       auto ShufOp = Op1.getOperand(0);
22908       if (isShuffleEquivalent(Op1, ShufOp, Mask, ExpectedMask))
22909         return DAG.getNode(X86ISD::UNPCKH, DL, VT, N.getOperand(0), ShufOp);
22910     }
22911     return SDValue();
22912   }
22913   default:
22914     return SDValue();
22915   }
22916
22917   // Nuke no-op shuffles that show up after combining.
22918   if (isNoopShuffleMask(Mask))
22919     return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
22920
22921   // Look for simplifications involving one or two shuffle instructions.
22922   SDValue V = N.getOperand(0);
22923   switch (N.getOpcode()) {
22924   default:
22925     break;
22926   case X86ISD::PSHUFLW:
22927   case X86ISD::PSHUFHW:
22928     assert(VT.getVectorElementType() == MVT::i16 && "Bad word shuffle type!");
22929
22930     if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
22931       return SDValue(); // We combined away this shuffle, so we're done.
22932
22933     // See if this reduces to a PSHUFD which is no more expensive and can
22934     // combine with more operations. Note that it has to at least flip the
22935     // dwords as otherwise it would have been removed as a no-op.
22936     if (makeArrayRef(Mask).equals({2, 3, 0, 1})) {
22937       int DMask[] = {0, 1, 2, 3};
22938       int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
22939       DMask[DOffset + 0] = DOffset + 1;
22940       DMask[DOffset + 1] = DOffset + 0;
22941       MVT DVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
22942       V = DAG.getBitcast(DVT, V);
22943       DCI.AddToWorklist(V.getNode());
22944       V = DAG.getNode(X86ISD::PSHUFD, DL, DVT, V,
22945                       getV4X86ShuffleImm8ForMask(DMask, DL, DAG));
22946       DCI.AddToWorklist(V.getNode());
22947       return DAG.getBitcast(VT, V);
22948     }
22949
22950     // Look for shuffle patterns which can be implemented as a single unpack.
22951     // FIXME: This doesn't handle the location of the PSHUFD generically, and
22952     // only works when we have a PSHUFD followed by two half-shuffles.
22953     if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
22954         (V.getOpcode() == X86ISD::PSHUFLW ||
22955          V.getOpcode() == X86ISD::PSHUFHW) &&
22956         V.getOpcode() != N.getOpcode() &&
22957         V.hasOneUse()) {
22958       SDValue D = V.getOperand(0);
22959       while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
22960         D = D.getOperand(0);
22961       if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
22962         SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
22963         SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
22964         int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
22965         int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
22966         int WordMask[8];
22967         for (int i = 0; i < 4; ++i) {
22968           WordMask[i + NOffset] = Mask[i] + NOffset;
22969           WordMask[i + VOffset] = VMask[i] + VOffset;
22970         }
22971         // Map the word mask through the DWord mask.
22972         int MappedMask[8];
22973         for (int i = 0; i < 8; ++i)
22974           MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
22975         if (makeArrayRef(MappedMask).equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
22976             makeArrayRef(MappedMask).equals({4, 4, 5, 5, 6, 6, 7, 7})) {
22977           // We can replace all three shuffles with an unpack.
22978           V = DAG.getBitcast(VT, D.getOperand(0));
22979           DCI.AddToWorklist(V.getNode());
22980           return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
22981                                                 : X86ISD::UNPCKH,
22982                              DL, VT, V, V);
22983         }
22984       }
22985     }
22986
22987     break;
22988
22989   case X86ISD::PSHUFD:
22990     if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG, DCI))
22991       return NewN;
22992
22993     break;
22994   }
22995
22996   return SDValue();
22997 }
22998
22999 /// \brief Try to combine a shuffle into a target-specific add-sub node.
23000 ///
23001 /// We combine this directly on the abstract vector shuffle nodes so it is
23002 /// easier to generically match. We also insert dummy vector shuffle nodes for
23003 /// the operands which explicitly discard the lanes which are unused by this
23004 /// operation to try to flow through the rest of the combiner the fact that
23005 /// they're unused.
23006 static SDValue combineShuffleToAddSub(SDNode *N, SelectionDAG &DAG) {
23007   SDLoc DL(N);
23008   EVT VT = N->getValueType(0);
23009
23010   // We only handle target-independent shuffles.
23011   // FIXME: It would be easy and harmless to use the target shuffle mask
23012   // extraction tool to support more.
23013   if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
23014     return SDValue();
23015
23016   auto *SVN = cast<ShuffleVectorSDNode>(N);
23017   ArrayRef<int> Mask = SVN->getMask();
23018   SDValue V1 = N->getOperand(0);
23019   SDValue V2 = N->getOperand(1);
23020
23021   // We require the first shuffle operand to be the SUB node, and the second to
23022   // be the ADD node.
23023   // FIXME: We should support the commuted patterns.
23024   if (V1->getOpcode() != ISD::FSUB || V2->getOpcode() != ISD::FADD)
23025     return SDValue();
23026
23027   // If there are other uses of these operations we can't fold them.
23028   if (!V1->hasOneUse() || !V2->hasOneUse())
23029     return SDValue();
23030
23031   // Ensure that both operations have the same operands. Note that we can
23032   // commute the FADD operands.
23033   SDValue LHS = V1->getOperand(0), RHS = V1->getOperand(1);
23034   if ((V2->getOperand(0) != LHS || V2->getOperand(1) != RHS) &&
23035       (V2->getOperand(0) != RHS || V2->getOperand(1) != LHS))
23036     return SDValue();
23037
23038   // We're looking for blends between FADD and FSUB nodes. We insist on these
23039   // nodes being lined up in a specific expected pattern.
23040   if (!(isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
23041         isShuffleEquivalent(V1, V2, Mask, {0, 5, 2, 7}) ||
23042         isShuffleEquivalent(V1, V2, Mask, {0, 9, 2, 11, 4, 13, 6, 15})))
23043     return SDValue();
23044
23045   // Only specific types are legal at this point, assert so we notice if and
23046   // when these change.
23047   assert((VT == MVT::v4f32 || VT == MVT::v2f64 || VT == MVT::v8f32 ||
23048           VT == MVT::v4f64) &&
23049          "Unknown vector type encountered!");
23050
23051   return DAG.getNode(X86ISD::ADDSUB, DL, VT, LHS, RHS);
23052 }
23053
23054 /// PerformShuffleCombine - Performs several different shuffle combines.
23055 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
23056                                      TargetLowering::DAGCombinerInfo &DCI,
23057                                      const X86Subtarget *Subtarget) {
23058   SDLoc dl(N);
23059   SDValue N0 = N->getOperand(0);
23060   SDValue N1 = N->getOperand(1);
23061   EVT VT = N->getValueType(0);
23062
23063   // Don't create instructions with illegal types after legalize types has run.
23064   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23065   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
23066     return SDValue();
23067
23068   // If we have legalized the vector types, look for blends of FADD and FSUB
23069   // nodes that we can fuse into an ADDSUB node.
23070   if (TLI.isTypeLegal(VT) && Subtarget->hasSSE3())
23071     if (SDValue AddSub = combineShuffleToAddSub(N, DAG))
23072       return AddSub;
23073
23074   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
23075   if (Subtarget->hasFp256() && VT.is256BitVector() &&
23076       N->getOpcode() == ISD::VECTOR_SHUFFLE)
23077     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
23078
23079   // During Type Legalization, when promoting illegal vector types,
23080   // the backend might introduce new shuffle dag nodes and bitcasts.
23081   //
23082   // This code performs the following transformation:
23083   // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
23084   //       (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
23085   //
23086   // We do this only if both the bitcast and the BINOP dag nodes have
23087   // one use. Also, perform this transformation only if the new binary
23088   // operation is legal. This is to avoid introducing dag nodes that
23089   // potentially need to be further expanded (or custom lowered) into a
23090   // less optimal sequence of dag nodes.
23091   if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
23092       N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
23093       N0.getOpcode() == ISD::BITCAST) {
23094     SDValue BC0 = N0.getOperand(0);
23095     EVT SVT = BC0.getValueType();
23096     unsigned Opcode = BC0.getOpcode();
23097     unsigned NumElts = VT.getVectorNumElements();
23098
23099     if (BC0.hasOneUse() && SVT.isVector() &&
23100         SVT.getVectorNumElements() * 2 == NumElts &&
23101         TLI.isOperationLegal(Opcode, VT)) {
23102       bool CanFold = false;
23103       switch (Opcode) {
23104       default : break;
23105       case ISD::ADD :
23106       case ISD::FADD :
23107       case ISD::SUB :
23108       case ISD::FSUB :
23109       case ISD::MUL :
23110       case ISD::FMUL :
23111         CanFold = true;
23112       }
23113
23114       unsigned SVTNumElts = SVT.getVectorNumElements();
23115       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
23116       for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
23117         CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
23118       for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
23119         CanFold = SVOp->getMaskElt(i) < 0;
23120
23121       if (CanFold) {
23122         SDValue BC00 = DAG.getBitcast(VT, BC0.getOperand(0));
23123         SDValue BC01 = DAG.getBitcast(VT, BC0.getOperand(1));
23124         SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
23125         return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
23126       }
23127     }
23128   }
23129
23130   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
23131   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
23132   // consecutive, non-overlapping, and in the right order.
23133   SmallVector<SDValue, 16> Elts;
23134   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
23135     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
23136
23137   if (SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true))
23138     return LD;
23139
23140   if (isTargetShuffle(N->getOpcode())) {
23141     SDValue Shuffle =
23142         PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
23143     if (Shuffle.getNode())
23144       return Shuffle;
23145
23146     // Try recursively combining arbitrary sequences of x86 shuffle
23147     // instructions into higher-order shuffles. We do this after combining
23148     // specific PSHUF instruction sequences into their minimal form so that we
23149     // can evaluate how many specialized shuffle instructions are involved in
23150     // a particular chain.
23151     SmallVector<int, 1> NonceMask; // Just a placeholder.
23152     NonceMask.push_back(0);
23153     if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
23154                                       /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
23155                                       DCI, Subtarget))
23156       return SDValue(); // This routine will use CombineTo to replace N.
23157   }
23158
23159   return SDValue();
23160 }
23161
23162 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
23163 /// specific shuffle of a load can be folded into a single element load.
23164 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
23165 /// shuffles have been custom lowered so we need to handle those here.
23166 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
23167                                          TargetLowering::DAGCombinerInfo &DCI) {
23168   if (DCI.isBeforeLegalizeOps())
23169     return SDValue();
23170
23171   SDValue InVec = N->getOperand(0);
23172   SDValue EltNo = N->getOperand(1);
23173
23174   if (!isa<ConstantSDNode>(EltNo))
23175     return SDValue();
23176
23177   EVT OriginalVT = InVec.getValueType();
23178
23179   if (InVec.getOpcode() == ISD::BITCAST) {
23180     // Don't duplicate a load with other uses.
23181     if (!InVec.hasOneUse())
23182       return SDValue();
23183     EVT BCVT = InVec.getOperand(0).getValueType();
23184     if (!BCVT.isVector() ||
23185         BCVT.getVectorNumElements() != OriginalVT.getVectorNumElements())
23186       return SDValue();
23187     InVec = InVec.getOperand(0);
23188   }
23189
23190   EVT CurrentVT = InVec.getValueType();
23191
23192   if (!isTargetShuffle(InVec.getOpcode()))
23193     return SDValue();
23194
23195   // Don't duplicate a load with other uses.
23196   if (!InVec.hasOneUse())
23197     return SDValue();
23198
23199   SmallVector<int, 16> ShuffleMask;
23200   bool UnaryShuffle;
23201   if (!getTargetShuffleMask(InVec.getNode(), CurrentVT.getSimpleVT(),
23202                             ShuffleMask, UnaryShuffle))
23203     return SDValue();
23204
23205   // Select the input vector, guarding against out of range extract vector.
23206   unsigned NumElems = CurrentVT.getVectorNumElements();
23207   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
23208   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
23209   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
23210                                          : InVec.getOperand(1);
23211
23212   // If inputs to shuffle are the same for both ops, then allow 2 uses
23213   unsigned AllowedUses = InVec.getNumOperands() > 1 &&
23214                          InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
23215
23216   if (LdNode.getOpcode() == ISD::BITCAST) {
23217     // Don't duplicate a load with other uses.
23218     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
23219       return SDValue();
23220
23221     AllowedUses = 1; // only allow 1 load use if we have a bitcast
23222     LdNode = LdNode.getOperand(0);
23223   }
23224
23225   if (!ISD::isNormalLoad(LdNode.getNode()))
23226     return SDValue();
23227
23228   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
23229
23230   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
23231     return SDValue();
23232
23233   EVT EltVT = N->getValueType(0);
23234   // If there's a bitcast before the shuffle, check if the load type and
23235   // alignment is valid.
23236   unsigned Align = LN0->getAlignment();
23237   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23238   unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
23239       EltVT.getTypeForEVT(*DAG.getContext()));
23240
23241   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, EltVT))
23242     return SDValue();
23243
23244   // All checks match so transform back to vector_shuffle so that DAG combiner
23245   // can finish the job
23246   SDLoc dl(N);
23247
23248   // Create shuffle node taking into account the case that its a unary shuffle
23249   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(CurrentVT)
23250                                    : InVec.getOperand(1);
23251   Shuffle = DAG.getVectorShuffle(CurrentVT, dl,
23252                                  InVec.getOperand(0), Shuffle,
23253                                  &ShuffleMask[0]);
23254   Shuffle = DAG.getBitcast(OriginalVT, Shuffle);
23255   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
23256                      EltNo);
23257 }
23258
23259 static SDValue PerformBITCASTCombine(SDNode *N, SelectionDAG &DAG,
23260                                      const X86Subtarget *Subtarget) {
23261   SDValue N0 = N->getOperand(0);
23262   EVT VT = N->getValueType(0);
23263
23264   // Detect bitcasts between i32 to x86mmx low word. Since MMX types are
23265   // special and don't usually play with other vector types, it's better to
23266   // handle them early to be sure we emit efficient code by avoiding
23267   // store-load conversions.
23268   if (VT == MVT::x86mmx && N0.getOpcode() == ISD::BUILD_VECTOR &&
23269       N0.getValueType() == MVT::v2i32 &&
23270       isa<ConstantSDNode>(N0.getOperand(1))) {
23271     SDValue N00 = N0->getOperand(0);
23272     if (N0.getConstantOperandVal(1) == 0 && N00.getValueType() == MVT::i32)
23273       return DAG.getNode(X86ISD::MMX_MOVW2D, SDLoc(N00), VT, N00);
23274   }
23275
23276   // Convert a bitcasted integer logic operation that has one bitcasted
23277   // floating-point operand and one constant operand into a floating-point
23278   // logic operation. This may create a load of the constant, but that is
23279   // cheaper than materializing the constant in an integer register and
23280   // transferring it to an SSE register or transferring the SSE operand to
23281   // integer register and back.
23282   unsigned FPOpcode;
23283   switch (N0.getOpcode()) {
23284     case ISD::AND: FPOpcode = X86ISD::FAND; break;
23285     case ISD::OR:  FPOpcode = X86ISD::FOR;  break;
23286     case ISD::XOR: FPOpcode = X86ISD::FXOR; break;
23287     default: return SDValue();
23288   }
23289   if (((Subtarget->hasSSE1() && VT == MVT::f32) ||
23290        (Subtarget->hasSSE2() && VT == MVT::f64)) &&
23291       isa<ConstantSDNode>(N0.getOperand(1)) &&
23292       N0.getOperand(0).getOpcode() == ISD::BITCAST &&
23293       N0.getOperand(0).getOperand(0).getValueType() == VT) {
23294     SDValue N000 = N0.getOperand(0).getOperand(0);
23295     SDValue FPConst = DAG.getBitcast(VT, N0.getOperand(1));
23296     return DAG.getNode(FPOpcode, SDLoc(N0), VT, N000, FPConst);
23297   }
23298
23299   return SDValue();
23300 }
23301
23302 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
23303 /// generation and convert it from being a bunch of shuffles and extracts
23304 /// into a somewhat faster sequence. For i686, the best sequence is apparently
23305 /// storing the value and loading scalars back, while for x64 we should
23306 /// use 64-bit extracts and shifts.
23307 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
23308                                          TargetLowering::DAGCombinerInfo &DCI) {
23309   if (SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI))
23310     return NewOp;
23311
23312   SDValue InputVector = N->getOperand(0);
23313   SDLoc dl(InputVector);
23314   // Detect mmx to i32 conversion through a v2i32 elt extract.
23315   if (InputVector.getOpcode() == ISD::BITCAST && InputVector.hasOneUse() &&
23316       N->getValueType(0) == MVT::i32 &&
23317       InputVector.getValueType() == MVT::v2i32) {
23318
23319     // The bitcast source is a direct mmx result.
23320     SDValue MMXSrc = InputVector.getNode()->getOperand(0);
23321     if (MMXSrc.getValueType() == MVT::x86mmx)
23322       return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
23323                          N->getValueType(0),
23324                          InputVector.getNode()->getOperand(0));
23325
23326     // The mmx is indirect: (i64 extract_elt (v1i64 bitcast (x86mmx ...))).
23327     if (MMXSrc.getOpcode() == ISD::EXTRACT_VECTOR_ELT && MMXSrc.hasOneUse() &&
23328         MMXSrc.getValueType() == MVT::i64) {
23329       SDValue MMXSrcOp = MMXSrc.getOperand(0);
23330       if (MMXSrcOp.hasOneUse() && MMXSrcOp.getOpcode() == ISD::BITCAST &&
23331           MMXSrcOp.getValueType() == MVT::v1i64 &&
23332           MMXSrcOp.getOperand(0).getValueType() == MVT::x86mmx)
23333         return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
23334                            N->getValueType(0), MMXSrcOp.getOperand(0));
23335     }
23336   }
23337
23338   EVT VT = N->getValueType(0);
23339
23340   if (VT == MVT::i1 && isa<ConstantSDNode>(N->getOperand(1)) &&
23341       InputVector.getOpcode() == ISD::BITCAST &&
23342       isa<ConstantSDNode>(InputVector.getOperand(0))) {
23343     uint64_t ExtractedElt =
23344         cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
23345     uint64_t InputValue =
23346         cast<ConstantSDNode>(InputVector.getOperand(0))->getZExtValue();
23347     uint64_t Res = (InputValue >> ExtractedElt) & 1;
23348     return DAG.getConstant(Res, dl, MVT::i1);
23349   }
23350   // Only operate on vectors of 4 elements, where the alternative shuffling
23351   // gets to be more expensive.
23352   if (InputVector.getValueType() != MVT::v4i32)
23353     return SDValue();
23354
23355   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
23356   // single use which is a sign-extend or zero-extend, and all elements are
23357   // used.
23358   SmallVector<SDNode *, 4> Uses;
23359   unsigned ExtractedElements = 0;
23360   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
23361        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
23362     if (UI.getUse().getResNo() != InputVector.getResNo())
23363       return SDValue();
23364
23365     SDNode *Extract = *UI;
23366     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
23367       return SDValue();
23368
23369     if (Extract->getValueType(0) != MVT::i32)
23370       return SDValue();
23371     if (!Extract->hasOneUse())
23372       return SDValue();
23373     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
23374         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
23375       return SDValue();
23376     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
23377       return SDValue();
23378
23379     // Record which element was extracted.
23380     ExtractedElements |=
23381       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
23382
23383     Uses.push_back(Extract);
23384   }
23385
23386   // If not all the elements were used, this may not be worthwhile.
23387   if (ExtractedElements != 15)
23388     return SDValue();
23389
23390   // Ok, we've now decided to do the transformation.
23391   // If 64-bit shifts are legal, use the extract-shift sequence,
23392   // otherwise bounce the vector off the cache.
23393   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23394   SDValue Vals[4];
23395
23396   if (TLI.isOperationLegal(ISD::SRA, MVT::i64)) {
23397     SDValue Cst = DAG.getBitcast(MVT::v2i64, InputVector);
23398     auto &DL = DAG.getDataLayout();
23399     EVT VecIdxTy = DAG.getTargetLoweringInfo().getVectorIdxTy(DL);
23400     SDValue BottomHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
23401       DAG.getConstant(0, dl, VecIdxTy));
23402     SDValue TopHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
23403       DAG.getConstant(1, dl, VecIdxTy));
23404
23405     SDValue ShAmt = DAG.getConstant(
23406         32, dl, DAG.getTargetLoweringInfo().getShiftAmountTy(MVT::i64, DL));
23407     Vals[0] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BottomHalf);
23408     Vals[1] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
23409       DAG.getNode(ISD::SRA, dl, MVT::i64, BottomHalf, ShAmt));
23410     Vals[2] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, TopHalf);
23411     Vals[3] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
23412       DAG.getNode(ISD::SRA, dl, MVT::i64, TopHalf, ShAmt));
23413   } else {
23414     // Store the value to a temporary stack slot.
23415     SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
23416     SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
23417       MachinePointerInfo(), false, false, 0);
23418
23419     EVT ElementType = InputVector.getValueType().getVectorElementType();
23420     unsigned EltSize = ElementType.getSizeInBits() / 8;
23421
23422     // Replace each use (extract) with a load of the appropriate element.
23423     for (unsigned i = 0; i < 4; ++i) {
23424       uint64_t Offset = EltSize * i;
23425       auto PtrVT = TLI.getPointerTy(DAG.getDataLayout());
23426       SDValue OffsetVal = DAG.getConstant(Offset, dl, PtrVT);
23427
23428       SDValue ScalarAddr =
23429           DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, OffsetVal);
23430
23431       // Load the scalar.
23432       Vals[i] = DAG.getLoad(ElementType, dl, Ch,
23433                             ScalarAddr, MachinePointerInfo(),
23434                             false, false, false, 0);
23435
23436     }
23437   }
23438
23439   // Replace the extracts
23440   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
23441     UE = Uses.end(); UI != UE; ++UI) {
23442     SDNode *Extract = *UI;
23443
23444     SDValue Idx = Extract->getOperand(1);
23445     uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
23446     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), Vals[IdxVal]);
23447   }
23448
23449   // The replacement was made in place; don't return anything.
23450   return SDValue();
23451 }
23452
23453 static SDValue
23454 transformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
23455                                       const X86Subtarget *Subtarget) {
23456   SDLoc dl(N);
23457   SDValue Cond = N->getOperand(0);
23458   SDValue LHS = N->getOperand(1);
23459   SDValue RHS = N->getOperand(2);
23460
23461   if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
23462     SDValue CondSrc = Cond->getOperand(0);
23463     if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
23464       Cond = CondSrc->getOperand(0);
23465   }
23466
23467   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
23468     return SDValue();
23469
23470   // A vselect where all conditions and data are constants can be optimized into
23471   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
23472   if (ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
23473       ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
23474     return SDValue();
23475
23476   unsigned MaskValue = 0;
23477   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
23478     return SDValue();
23479
23480   MVT VT = N->getSimpleValueType(0);
23481   unsigned NumElems = VT.getVectorNumElements();
23482   SmallVector<int, 8> ShuffleMask(NumElems, -1);
23483   for (unsigned i = 0; i < NumElems; ++i) {
23484     // Be sure we emit undef where we can.
23485     if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
23486       ShuffleMask[i] = -1;
23487     else
23488       ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
23489   }
23490
23491   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23492   if (!TLI.isShuffleMaskLegal(ShuffleMask, VT))
23493     return SDValue();
23494   return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
23495 }
23496
23497 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
23498 /// nodes.
23499 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
23500                                     TargetLowering::DAGCombinerInfo &DCI,
23501                                     const X86Subtarget *Subtarget) {
23502   SDLoc DL(N);
23503   SDValue Cond = N->getOperand(0);
23504   // Get the LHS/RHS of the select.
23505   SDValue LHS = N->getOperand(1);
23506   SDValue RHS = N->getOperand(2);
23507   EVT VT = LHS.getValueType();
23508   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23509
23510   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
23511   // instructions match the semantics of the common C idiom x<y?x:y but not
23512   // x<=y?x:y, because of how they handle negative zero (which can be
23513   // ignored in unsafe-math mode).
23514   // We also try to create v2f32 min/max nodes, which we later widen to v4f32.
23515   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
23516       VT != MVT::f80 && (TLI.isTypeLegal(VT) || VT == MVT::v2f32) &&
23517       (Subtarget->hasSSE2() ||
23518        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
23519     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
23520
23521     unsigned Opcode = 0;
23522     // Check for x CC y ? x : y.
23523     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
23524         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
23525       switch (CC) {
23526       default: break;
23527       case ISD::SETULT:
23528         // Converting this to a min would handle NaNs incorrectly, and swapping
23529         // the operands would cause it to handle comparisons between positive
23530         // and negative zero incorrectly.
23531         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
23532           if (!DAG.getTarget().Options.UnsafeFPMath &&
23533               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
23534             break;
23535           std::swap(LHS, RHS);
23536         }
23537         Opcode = X86ISD::FMIN;
23538         break;
23539       case ISD::SETOLE:
23540         // Converting this to a min would handle comparisons between positive
23541         // and negative zero incorrectly.
23542         if (!DAG.getTarget().Options.UnsafeFPMath &&
23543             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
23544           break;
23545         Opcode = X86ISD::FMIN;
23546         break;
23547       case ISD::SETULE:
23548         // Converting this to a min would handle both negative zeros and NaNs
23549         // incorrectly, but we can swap the operands to fix both.
23550         std::swap(LHS, RHS);
23551       case ISD::SETOLT:
23552       case ISD::SETLT:
23553       case ISD::SETLE:
23554         Opcode = X86ISD::FMIN;
23555         break;
23556
23557       case ISD::SETOGE:
23558         // Converting this to a max would handle comparisons between positive
23559         // and negative zero incorrectly.
23560         if (!DAG.getTarget().Options.UnsafeFPMath &&
23561             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
23562           break;
23563         Opcode = X86ISD::FMAX;
23564         break;
23565       case ISD::SETUGT:
23566         // Converting this to a max would handle NaNs incorrectly, and swapping
23567         // the operands would cause it to handle comparisons between positive
23568         // and negative zero incorrectly.
23569         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
23570           if (!DAG.getTarget().Options.UnsafeFPMath &&
23571               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
23572             break;
23573           std::swap(LHS, RHS);
23574         }
23575         Opcode = X86ISD::FMAX;
23576         break;
23577       case ISD::SETUGE:
23578         // Converting this to a max would handle both negative zeros and NaNs
23579         // incorrectly, but we can swap the operands to fix both.
23580         std::swap(LHS, RHS);
23581       case ISD::SETOGT:
23582       case ISD::SETGT:
23583       case ISD::SETGE:
23584         Opcode = X86ISD::FMAX;
23585         break;
23586       }
23587     // Check for x CC y ? y : x -- a min/max with reversed arms.
23588     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
23589                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
23590       switch (CC) {
23591       default: break;
23592       case ISD::SETOGE:
23593         // Converting this to a min would handle comparisons between positive
23594         // and negative zero incorrectly, and swapping the operands would
23595         // cause it to handle NaNs incorrectly.
23596         if (!DAG.getTarget().Options.UnsafeFPMath &&
23597             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
23598           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
23599             break;
23600           std::swap(LHS, RHS);
23601         }
23602         Opcode = X86ISD::FMIN;
23603         break;
23604       case ISD::SETUGT:
23605         // Converting this to a min would handle NaNs incorrectly.
23606         if (!DAG.getTarget().Options.UnsafeFPMath &&
23607             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
23608           break;
23609         Opcode = X86ISD::FMIN;
23610         break;
23611       case ISD::SETUGE:
23612         // Converting this to a min would handle both negative zeros and NaNs
23613         // incorrectly, but we can swap the operands to fix both.
23614         std::swap(LHS, RHS);
23615       case ISD::SETOGT:
23616       case ISD::SETGT:
23617       case ISD::SETGE:
23618         Opcode = X86ISD::FMIN;
23619         break;
23620
23621       case ISD::SETULT:
23622         // Converting this to a max would handle NaNs incorrectly.
23623         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
23624           break;
23625         Opcode = X86ISD::FMAX;
23626         break;
23627       case ISD::SETOLE:
23628         // Converting this to a max would handle comparisons between positive
23629         // and negative zero incorrectly, and swapping the operands would
23630         // cause it to handle NaNs incorrectly.
23631         if (!DAG.getTarget().Options.UnsafeFPMath &&
23632             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
23633           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
23634             break;
23635           std::swap(LHS, RHS);
23636         }
23637         Opcode = X86ISD::FMAX;
23638         break;
23639       case ISD::SETULE:
23640         // Converting this to a max would handle both negative zeros and NaNs
23641         // incorrectly, but we can swap the operands to fix both.
23642         std::swap(LHS, RHS);
23643       case ISD::SETOLT:
23644       case ISD::SETLT:
23645       case ISD::SETLE:
23646         Opcode = X86ISD::FMAX;
23647         break;
23648       }
23649     }
23650
23651     if (Opcode)
23652       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
23653   }
23654
23655   EVT CondVT = Cond.getValueType();
23656   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
23657       CondVT.getVectorElementType() == MVT::i1) {
23658     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
23659     // lowering on KNL. In this case we convert it to
23660     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
23661     // The same situation for all 128 and 256-bit vectors of i8 and i16.
23662     // Since SKX these selects have a proper lowering.
23663     EVT OpVT = LHS.getValueType();
23664     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
23665         (OpVT.getVectorElementType() == MVT::i8 ||
23666          OpVT.getVectorElementType() == MVT::i16) &&
23667         !(Subtarget->hasBWI() && Subtarget->hasVLX())) {
23668       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
23669       DCI.AddToWorklist(Cond.getNode());
23670       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
23671     }
23672   }
23673   // If this is a select between two integer constants, try to do some
23674   // optimizations.
23675   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
23676     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
23677       // Don't do this for crazy integer types.
23678       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
23679         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
23680         // so that TrueC (the true value) is larger than FalseC.
23681         bool NeedsCondInvert = false;
23682
23683         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
23684             // Efficiently invertible.
23685             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
23686              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
23687               isa<ConstantSDNode>(Cond.getOperand(1))))) {
23688           NeedsCondInvert = true;
23689           std::swap(TrueC, FalseC);
23690         }
23691
23692         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
23693         if (FalseC->getAPIntValue() == 0 &&
23694             TrueC->getAPIntValue().isPowerOf2()) {
23695           if (NeedsCondInvert) // Invert the condition if needed.
23696             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
23697                                DAG.getConstant(1, DL, Cond.getValueType()));
23698
23699           // Zero extend the condition if needed.
23700           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
23701
23702           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
23703           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
23704                              DAG.getConstant(ShAmt, DL, MVT::i8));
23705         }
23706
23707         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
23708         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
23709           if (NeedsCondInvert) // Invert the condition if needed.
23710             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
23711                                DAG.getConstant(1, DL, Cond.getValueType()));
23712
23713           // Zero extend the condition if needed.
23714           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
23715                              FalseC->getValueType(0), Cond);
23716           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23717                              SDValue(FalseC, 0));
23718         }
23719
23720         // Optimize cases that will turn into an LEA instruction.  This requires
23721         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
23722         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
23723           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
23724           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
23725
23726           bool isFastMultiplier = false;
23727           if (Diff < 10) {
23728             switch ((unsigned char)Diff) {
23729               default: break;
23730               case 1:  // result = add base, cond
23731               case 2:  // result = lea base(    , cond*2)
23732               case 3:  // result = lea base(cond, cond*2)
23733               case 4:  // result = lea base(    , cond*4)
23734               case 5:  // result = lea base(cond, cond*4)
23735               case 8:  // result = lea base(    , cond*8)
23736               case 9:  // result = lea base(cond, cond*8)
23737                 isFastMultiplier = true;
23738                 break;
23739             }
23740           }
23741
23742           if (isFastMultiplier) {
23743             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
23744             if (NeedsCondInvert) // Invert the condition if needed.
23745               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
23746                                  DAG.getConstant(1, DL, Cond.getValueType()));
23747
23748             // Zero extend the condition if needed.
23749             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
23750                                Cond);
23751             // Scale the condition by the difference.
23752             if (Diff != 1)
23753               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
23754                                  DAG.getConstant(Diff, DL,
23755                                                  Cond.getValueType()));
23756
23757             // Add the base if non-zero.
23758             if (FalseC->getAPIntValue() != 0)
23759               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23760                                  SDValue(FalseC, 0));
23761             return Cond;
23762           }
23763         }
23764       }
23765   }
23766
23767   // Canonicalize max and min:
23768   // (x > y) ? x : y -> (x >= y) ? x : y
23769   // (x < y) ? x : y -> (x <= y) ? x : y
23770   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
23771   // the need for an extra compare
23772   // against zero. e.g.
23773   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
23774   // subl   %esi, %edi
23775   // testl  %edi, %edi
23776   // movl   $0, %eax
23777   // cmovgl %edi, %eax
23778   // =>
23779   // xorl   %eax, %eax
23780   // subl   %esi, $edi
23781   // cmovsl %eax, %edi
23782   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
23783       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
23784       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
23785     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
23786     switch (CC) {
23787     default: break;
23788     case ISD::SETLT:
23789     case ISD::SETGT: {
23790       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
23791       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
23792                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
23793       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
23794     }
23795     }
23796   }
23797
23798   // Early exit check
23799   if (!TLI.isTypeLegal(VT))
23800     return SDValue();
23801
23802   // Match VSELECTs into subs with unsigned saturation.
23803   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
23804       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
23805       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
23806        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
23807     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
23808
23809     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
23810     // left side invert the predicate to simplify logic below.
23811     SDValue Other;
23812     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
23813       Other = RHS;
23814       CC = ISD::getSetCCInverse(CC, true);
23815     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
23816       Other = LHS;
23817     }
23818
23819     if (Other.getNode() && Other->getNumOperands() == 2 &&
23820         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
23821       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
23822       SDValue CondRHS = Cond->getOperand(1);
23823
23824       // Look for a general sub with unsigned saturation first.
23825       // x >= y ? x-y : 0 --> subus x, y
23826       // x >  y ? x-y : 0 --> subus x, y
23827       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
23828           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
23829         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
23830
23831       if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
23832         if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
23833           if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
23834             if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
23835               // If the RHS is a constant we have to reverse the const
23836               // canonicalization.
23837               // x > C-1 ? x+-C : 0 --> subus x, C
23838               if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
23839                   CondRHSConst->getAPIntValue() ==
23840                       (-OpRHSConst->getAPIntValue() - 1))
23841                 return DAG.getNode(
23842                     X86ISD::SUBUS, DL, VT, OpLHS,
23843                     DAG.getConstant(-OpRHSConst->getAPIntValue(), DL, VT));
23844
23845           // Another special case: If C was a sign bit, the sub has been
23846           // canonicalized into a xor.
23847           // FIXME: Would it be better to use computeKnownBits to determine
23848           //        whether it's safe to decanonicalize the xor?
23849           // x s< 0 ? x^C : 0 --> subus x, C
23850           if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
23851               ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
23852               OpRHSConst->getAPIntValue().isSignBit())
23853             // Note that we have to rebuild the RHS constant here to ensure we
23854             // don't rely on particular values of undef lanes.
23855             return DAG.getNode(
23856                 X86ISD::SUBUS, DL, VT, OpLHS,
23857                 DAG.getConstant(OpRHSConst->getAPIntValue(), DL, VT));
23858         }
23859     }
23860   }
23861
23862   // Simplify vector selection if condition value type matches vselect
23863   // operand type
23864   if (N->getOpcode() == ISD::VSELECT && CondVT == VT) {
23865     assert(Cond.getValueType().isVector() &&
23866            "vector select expects a vector selector!");
23867
23868     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
23869     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
23870
23871     // Try invert the condition if true value is not all 1s and false value
23872     // is not all 0s.
23873     if (!TValIsAllOnes && !FValIsAllZeros &&
23874         // Check if the selector will be produced by CMPP*/PCMP*
23875         Cond.getOpcode() == ISD::SETCC &&
23876         // Check if SETCC has already been promoted
23877         TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT) ==
23878             CondVT) {
23879       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
23880       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
23881
23882       if (TValIsAllZeros || FValIsAllOnes) {
23883         SDValue CC = Cond.getOperand(2);
23884         ISD::CondCode NewCC =
23885           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
23886                                Cond.getOperand(0).getValueType().isInteger());
23887         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
23888         std::swap(LHS, RHS);
23889         TValIsAllOnes = FValIsAllOnes;
23890         FValIsAllZeros = TValIsAllZeros;
23891       }
23892     }
23893
23894     if (TValIsAllOnes || FValIsAllZeros) {
23895       SDValue Ret;
23896
23897       if (TValIsAllOnes && FValIsAllZeros)
23898         Ret = Cond;
23899       else if (TValIsAllOnes)
23900         Ret =
23901             DAG.getNode(ISD::OR, DL, CondVT, Cond, DAG.getBitcast(CondVT, RHS));
23902       else if (FValIsAllZeros)
23903         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
23904                           DAG.getBitcast(CondVT, LHS));
23905
23906       return DAG.getBitcast(VT, Ret);
23907     }
23908   }
23909
23910   // We should generate an X86ISD::BLENDI from a vselect if its argument
23911   // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
23912   // constants. This specific pattern gets generated when we split a
23913   // selector for a 512 bit vector in a machine without AVX512 (but with
23914   // 256-bit vectors), during legalization:
23915   //
23916   // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
23917   //
23918   // Iff we find this pattern and the build_vectors are built from
23919   // constants, we translate the vselect into a shuffle_vector that we
23920   // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
23921   if ((N->getOpcode() == ISD::VSELECT ||
23922        N->getOpcode() == X86ISD::SHRUNKBLEND) &&
23923       !DCI.isBeforeLegalize() && !VT.is512BitVector()) {
23924     SDValue Shuffle = transformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
23925     if (Shuffle.getNode())
23926       return Shuffle;
23927   }
23928
23929   // If this is a *dynamic* select (non-constant condition) and we can match
23930   // this node with one of the variable blend instructions, restructure the
23931   // condition so that the blends can use the high bit of each element and use
23932   // SimplifyDemandedBits to simplify the condition operand.
23933   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
23934       !DCI.isBeforeLegalize() &&
23935       !ISD::isBuildVectorOfConstantSDNodes(Cond.getNode())) {
23936     unsigned BitWidth = Cond.getValueType().getScalarSizeInBits();
23937
23938     // Don't optimize vector selects that map to mask-registers.
23939     if (BitWidth == 1)
23940       return SDValue();
23941
23942     // We can only handle the cases where VSELECT is directly legal on the
23943     // subtarget. We custom lower VSELECT nodes with constant conditions and
23944     // this makes it hard to see whether a dynamic VSELECT will correctly
23945     // lower, so we both check the operation's status and explicitly handle the
23946     // cases where a *dynamic* blend will fail even though a constant-condition
23947     // blend could be custom lowered.
23948     // FIXME: We should find a better way to handle this class of problems.
23949     // Potentially, we should combine constant-condition vselect nodes
23950     // pre-legalization into shuffles and not mark as many types as custom
23951     // lowered.
23952     if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
23953       return SDValue();
23954     // FIXME: We don't support i16-element blends currently. We could and
23955     // should support them by making *all* the bits in the condition be set
23956     // rather than just the high bit and using an i8-element blend.
23957     if (VT.getVectorElementType() == MVT::i16)
23958       return SDValue();
23959     // Dynamic blending was only available from SSE4.1 onward.
23960     if (VT.is128BitVector() && !Subtarget->hasSSE41())
23961       return SDValue();
23962     // Byte blends are only available in AVX2
23963     if (VT == MVT::v32i8 && !Subtarget->hasAVX2())
23964       return SDValue();
23965
23966     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
23967     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
23968
23969     APInt KnownZero, KnownOne;
23970     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
23971                                           DCI.isBeforeLegalizeOps());
23972     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
23973         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne,
23974                                  TLO)) {
23975       // If we changed the computation somewhere in the DAG, this change
23976       // will affect all users of Cond.
23977       // Make sure it is fine and update all the nodes so that we do not
23978       // use the generic VSELECT anymore. Otherwise, we may perform
23979       // wrong optimizations as we messed up with the actual expectation
23980       // for the vector boolean values.
23981       if (Cond != TLO.Old) {
23982         // Check all uses of that condition operand to check whether it will be
23983         // consumed by non-BLEND instructions, which may depend on all bits are
23984         // set properly.
23985         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
23986              I != E; ++I)
23987           if (I->getOpcode() != ISD::VSELECT)
23988             // TODO: Add other opcodes eventually lowered into BLEND.
23989             return SDValue();
23990
23991         // Update all the users of the condition, before committing the change,
23992         // so that the VSELECT optimizations that expect the correct vector
23993         // boolean value will not be triggered.
23994         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
23995              I != E; ++I)
23996           DAG.ReplaceAllUsesOfValueWith(
23997               SDValue(*I, 0),
23998               DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(*I), I->getValueType(0),
23999                           Cond, I->getOperand(1), I->getOperand(2)));
24000         DCI.CommitTargetLoweringOpt(TLO);
24001         return SDValue();
24002       }
24003       // At this point, only Cond is changed. Change the condition
24004       // just for N to keep the opportunity to optimize all other
24005       // users their own way.
24006       DAG.ReplaceAllUsesOfValueWith(
24007           SDValue(N, 0),
24008           DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(N), N->getValueType(0),
24009                       TLO.New, N->getOperand(1), N->getOperand(2)));
24010       return SDValue();
24011     }
24012   }
24013
24014   return SDValue();
24015 }
24016
24017 // Check whether a boolean test is testing a boolean value generated by
24018 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
24019 // code.
24020 //
24021 // Simplify the following patterns:
24022 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
24023 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
24024 // to (Op EFLAGS Cond)
24025 //
24026 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
24027 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
24028 // to (Op EFLAGS !Cond)
24029 //
24030 // where Op could be BRCOND or CMOV.
24031 //
24032 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
24033   // Quit if not CMP and SUB with its value result used.
24034   if (Cmp.getOpcode() != X86ISD::CMP &&
24035       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
24036       return SDValue();
24037
24038   // Quit if not used as a boolean value.
24039   if (CC != X86::COND_E && CC != X86::COND_NE)
24040     return SDValue();
24041
24042   // Check CMP operands. One of them should be 0 or 1 and the other should be
24043   // an SetCC or extended from it.
24044   SDValue Op1 = Cmp.getOperand(0);
24045   SDValue Op2 = Cmp.getOperand(1);
24046
24047   SDValue SetCC;
24048   const ConstantSDNode* C = nullptr;
24049   bool needOppositeCond = (CC == X86::COND_E);
24050   bool checkAgainstTrue = false; // Is it a comparison against 1?
24051
24052   if ((C = dyn_cast<ConstantSDNode>(Op1)))
24053     SetCC = Op2;
24054   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
24055     SetCC = Op1;
24056   else // Quit if all operands are not constants.
24057     return SDValue();
24058
24059   if (C->getZExtValue() == 1) {
24060     needOppositeCond = !needOppositeCond;
24061     checkAgainstTrue = true;
24062   } else if (C->getZExtValue() != 0)
24063     // Quit if the constant is neither 0 or 1.
24064     return SDValue();
24065
24066   bool truncatedToBoolWithAnd = false;
24067   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
24068   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
24069          SetCC.getOpcode() == ISD::TRUNCATE ||
24070          SetCC.getOpcode() == ISD::AND) {
24071     if (SetCC.getOpcode() == ISD::AND) {
24072       int OpIdx = -1;
24073       ConstantSDNode *CS;
24074       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
24075           CS->getZExtValue() == 1)
24076         OpIdx = 1;
24077       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
24078           CS->getZExtValue() == 1)
24079         OpIdx = 0;
24080       if (OpIdx == -1)
24081         break;
24082       SetCC = SetCC.getOperand(OpIdx);
24083       truncatedToBoolWithAnd = true;
24084     } else
24085       SetCC = SetCC.getOperand(0);
24086   }
24087
24088   switch (SetCC.getOpcode()) {
24089   case X86ISD::SETCC_CARRY:
24090     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
24091     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
24092     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
24093     // truncated to i1 using 'and'.
24094     if (checkAgainstTrue && !truncatedToBoolWithAnd)
24095       break;
24096     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
24097            "Invalid use of SETCC_CARRY!");
24098     // FALL THROUGH
24099   case X86ISD::SETCC:
24100     // Set the condition code or opposite one if necessary.
24101     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
24102     if (needOppositeCond)
24103       CC = X86::GetOppositeBranchCondition(CC);
24104     return SetCC.getOperand(1);
24105   case X86ISD::CMOV: {
24106     // Check whether false/true value has canonical one, i.e. 0 or 1.
24107     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
24108     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
24109     // Quit if true value is not a constant.
24110     if (!TVal)
24111       return SDValue();
24112     // Quit if false value is not a constant.
24113     if (!FVal) {
24114       SDValue Op = SetCC.getOperand(0);
24115       // Skip 'zext' or 'trunc' node.
24116       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
24117           Op.getOpcode() == ISD::TRUNCATE)
24118         Op = Op.getOperand(0);
24119       // A special case for rdrand/rdseed, where 0 is set if false cond is
24120       // found.
24121       if ((Op.getOpcode() != X86ISD::RDRAND &&
24122            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
24123         return SDValue();
24124     }
24125     // Quit if false value is not the constant 0 or 1.
24126     bool FValIsFalse = true;
24127     if (FVal && FVal->getZExtValue() != 0) {
24128       if (FVal->getZExtValue() != 1)
24129         return SDValue();
24130       // If FVal is 1, opposite cond is needed.
24131       needOppositeCond = !needOppositeCond;
24132       FValIsFalse = false;
24133     }
24134     // Quit if TVal is not the constant opposite of FVal.
24135     if (FValIsFalse && TVal->getZExtValue() != 1)
24136       return SDValue();
24137     if (!FValIsFalse && TVal->getZExtValue() != 0)
24138       return SDValue();
24139     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
24140     if (needOppositeCond)
24141       CC = X86::GetOppositeBranchCondition(CC);
24142     return SetCC.getOperand(3);
24143   }
24144   }
24145
24146   return SDValue();
24147 }
24148
24149 /// Check whether Cond is an AND/OR of SETCCs off of the same EFLAGS.
24150 /// Match:
24151 ///   (X86or (X86setcc) (X86setcc))
24152 ///   (X86cmp (and (X86setcc) (X86setcc)), 0)
24153 static bool checkBoolTestAndOrSetCCCombine(SDValue Cond, X86::CondCode &CC0,
24154                                            X86::CondCode &CC1, SDValue &Flags,
24155                                            bool &isAnd) {
24156   if (Cond->getOpcode() == X86ISD::CMP) {
24157     ConstantSDNode *CondOp1C = dyn_cast<ConstantSDNode>(Cond->getOperand(1));
24158     if (!CondOp1C || !CondOp1C->isNullValue())
24159       return false;
24160
24161     Cond = Cond->getOperand(0);
24162   }
24163
24164   isAnd = false;
24165
24166   SDValue SetCC0, SetCC1;
24167   switch (Cond->getOpcode()) {
24168   default: return false;
24169   case ISD::AND:
24170   case X86ISD::AND:
24171     isAnd = true;
24172     // fallthru
24173   case ISD::OR:
24174   case X86ISD::OR:
24175     SetCC0 = Cond->getOperand(0);
24176     SetCC1 = Cond->getOperand(1);
24177     break;
24178   };
24179
24180   // Make sure we have SETCC nodes, using the same flags value.
24181   if (SetCC0.getOpcode() != X86ISD::SETCC ||
24182       SetCC1.getOpcode() != X86ISD::SETCC ||
24183       SetCC0->getOperand(1) != SetCC1->getOperand(1))
24184     return false;
24185
24186   CC0 = (X86::CondCode)SetCC0->getConstantOperandVal(0);
24187   CC1 = (X86::CondCode)SetCC1->getConstantOperandVal(0);
24188   Flags = SetCC0->getOperand(1);
24189   return true;
24190 }
24191
24192 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
24193 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
24194                                   TargetLowering::DAGCombinerInfo &DCI,
24195                                   const X86Subtarget *Subtarget) {
24196   SDLoc DL(N);
24197
24198   // If the flag operand isn't dead, don't touch this CMOV.
24199   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
24200     return SDValue();
24201
24202   SDValue FalseOp = N->getOperand(0);
24203   SDValue TrueOp = N->getOperand(1);
24204   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
24205   SDValue Cond = N->getOperand(3);
24206
24207   if (CC == X86::COND_E || CC == X86::COND_NE) {
24208     switch (Cond.getOpcode()) {
24209     default: break;
24210     case X86ISD::BSR:
24211     case X86ISD::BSF:
24212       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
24213       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
24214         return (CC == X86::COND_E) ? FalseOp : TrueOp;
24215     }
24216   }
24217
24218   SDValue Flags;
24219
24220   Flags = checkBoolTestSetCCCombine(Cond, CC);
24221   if (Flags.getNode() &&
24222       // Extra check as FCMOV only supports a subset of X86 cond.
24223       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
24224     SDValue Ops[] = { FalseOp, TrueOp,
24225                       DAG.getConstant(CC, DL, MVT::i8), Flags };
24226     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
24227   }
24228
24229   // If this is a select between two integer constants, try to do some
24230   // optimizations.  Note that the operands are ordered the opposite of SELECT
24231   // operands.
24232   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
24233     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
24234       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
24235       // larger than FalseC (the false value).
24236       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
24237         CC = X86::GetOppositeBranchCondition(CC);
24238         std::swap(TrueC, FalseC);
24239         std::swap(TrueOp, FalseOp);
24240       }
24241
24242       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
24243       // This is efficient for any integer data type (including i8/i16) and
24244       // shift amount.
24245       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
24246         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
24247                            DAG.getConstant(CC, DL, MVT::i8), Cond);
24248
24249         // Zero extend the condition if needed.
24250         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
24251
24252         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
24253         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
24254                            DAG.getConstant(ShAmt, DL, MVT::i8));
24255         if (N->getNumValues() == 2)  // Dead flag value?
24256           return DCI.CombineTo(N, Cond, SDValue());
24257         return Cond;
24258       }
24259
24260       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
24261       // for any integer data type, including i8/i16.
24262       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
24263         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
24264                            DAG.getConstant(CC, DL, MVT::i8), Cond);
24265
24266         // Zero extend the condition if needed.
24267         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
24268                            FalseC->getValueType(0), Cond);
24269         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
24270                            SDValue(FalseC, 0));
24271
24272         if (N->getNumValues() == 2)  // Dead flag value?
24273           return DCI.CombineTo(N, Cond, SDValue());
24274         return Cond;
24275       }
24276
24277       // Optimize cases that will turn into an LEA instruction.  This requires
24278       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
24279       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
24280         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
24281         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
24282
24283         bool isFastMultiplier = false;
24284         if (Diff < 10) {
24285           switch ((unsigned char)Diff) {
24286           default: break;
24287           case 1:  // result = add base, cond
24288           case 2:  // result = lea base(    , cond*2)
24289           case 3:  // result = lea base(cond, cond*2)
24290           case 4:  // result = lea base(    , cond*4)
24291           case 5:  // result = lea base(cond, cond*4)
24292           case 8:  // result = lea base(    , cond*8)
24293           case 9:  // result = lea base(cond, cond*8)
24294             isFastMultiplier = true;
24295             break;
24296           }
24297         }
24298
24299         if (isFastMultiplier) {
24300           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
24301           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
24302                              DAG.getConstant(CC, DL, MVT::i8), Cond);
24303           // Zero extend the condition if needed.
24304           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
24305                              Cond);
24306           // Scale the condition by the difference.
24307           if (Diff != 1)
24308             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
24309                                DAG.getConstant(Diff, DL, Cond.getValueType()));
24310
24311           // Add the base if non-zero.
24312           if (FalseC->getAPIntValue() != 0)
24313             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
24314                                SDValue(FalseC, 0));
24315           if (N->getNumValues() == 2)  // Dead flag value?
24316             return DCI.CombineTo(N, Cond, SDValue());
24317           return Cond;
24318         }
24319       }
24320     }
24321   }
24322
24323   // Handle these cases:
24324   //   (select (x != c), e, c) -> select (x != c), e, x),
24325   //   (select (x == c), c, e) -> select (x == c), x, e)
24326   // where the c is an integer constant, and the "select" is the combination
24327   // of CMOV and CMP.
24328   //
24329   // The rationale for this change is that the conditional-move from a constant
24330   // needs two instructions, however, conditional-move from a register needs
24331   // only one instruction.
24332   //
24333   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
24334   //  some instruction-combining opportunities. This opt needs to be
24335   //  postponed as late as possible.
24336   //
24337   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
24338     // the DCI.xxxx conditions are provided to postpone the optimization as
24339     // late as possible.
24340
24341     ConstantSDNode *CmpAgainst = nullptr;
24342     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
24343         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
24344         !isa<ConstantSDNode>(Cond.getOperand(0))) {
24345
24346       if (CC == X86::COND_NE &&
24347           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
24348         CC = X86::GetOppositeBranchCondition(CC);
24349         std::swap(TrueOp, FalseOp);
24350       }
24351
24352       if (CC == X86::COND_E &&
24353           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
24354         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
24355                           DAG.getConstant(CC, DL, MVT::i8), Cond };
24356         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
24357       }
24358     }
24359   }
24360
24361   // Fold and/or of setcc's to double CMOV:
24362   //   (CMOV F, T, ((cc1 | cc2) != 0)) -> (CMOV (CMOV F, T, cc1), T, cc2)
24363   //   (CMOV F, T, ((cc1 & cc2) != 0)) -> (CMOV (CMOV T, F, !cc1), F, !cc2)
24364   //
24365   // This combine lets us generate:
24366   //   cmovcc1 (jcc1 if we don't have CMOV)
24367   //   cmovcc2 (same)
24368   // instead of:
24369   //   setcc1
24370   //   setcc2
24371   //   and/or
24372   //   cmovne (jne if we don't have CMOV)
24373   // When we can't use the CMOV instruction, it might increase branch
24374   // mispredicts.
24375   // When we can use CMOV, or when there is no mispredict, this improves
24376   // throughput and reduces register pressure.
24377   //
24378   if (CC == X86::COND_NE) {
24379     SDValue Flags;
24380     X86::CondCode CC0, CC1;
24381     bool isAndSetCC;
24382     if (checkBoolTestAndOrSetCCCombine(Cond, CC0, CC1, Flags, isAndSetCC)) {
24383       if (isAndSetCC) {
24384         std::swap(FalseOp, TrueOp);
24385         CC0 = X86::GetOppositeBranchCondition(CC0);
24386         CC1 = X86::GetOppositeBranchCondition(CC1);
24387       }
24388
24389       SDValue LOps[] = {FalseOp, TrueOp, DAG.getConstant(CC0, DL, MVT::i8),
24390         Flags};
24391       SDValue LCMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), LOps);
24392       SDValue Ops[] = {LCMOV, TrueOp, DAG.getConstant(CC1, DL, MVT::i8), Flags};
24393       SDValue CMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
24394       DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SDValue(CMOV.getNode(), 1));
24395       return CMOV;
24396     }
24397   }
24398
24399   return SDValue();
24400 }
24401
24402 /// PerformMulCombine - Optimize a single multiply with constant into two
24403 /// in order to implement it with two cheaper instructions, e.g.
24404 /// LEA + SHL, LEA + LEA.
24405 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
24406                                  TargetLowering::DAGCombinerInfo &DCI) {
24407   // An imul is usually smaller than the alternative sequence.
24408   if (DAG.getMachineFunction().getFunction()->optForMinSize())
24409     return SDValue();
24410
24411   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
24412     return SDValue();
24413
24414   EVT VT = N->getValueType(0);
24415   if (VT != MVT::i64 && VT != MVT::i32)
24416     return SDValue();
24417
24418   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
24419   if (!C)
24420     return SDValue();
24421   uint64_t MulAmt = C->getZExtValue();
24422   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
24423     return SDValue();
24424
24425   uint64_t MulAmt1 = 0;
24426   uint64_t MulAmt2 = 0;
24427   if ((MulAmt % 9) == 0) {
24428     MulAmt1 = 9;
24429     MulAmt2 = MulAmt / 9;
24430   } else if ((MulAmt % 5) == 0) {
24431     MulAmt1 = 5;
24432     MulAmt2 = MulAmt / 5;
24433   } else if ((MulAmt % 3) == 0) {
24434     MulAmt1 = 3;
24435     MulAmt2 = MulAmt / 3;
24436   }
24437   if (MulAmt2 &&
24438       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
24439     SDLoc DL(N);
24440
24441     if (isPowerOf2_64(MulAmt2) &&
24442         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
24443       // If second multiplifer is pow2, issue it first. We want the multiply by
24444       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
24445       // is an add.
24446       std::swap(MulAmt1, MulAmt2);
24447
24448     SDValue NewMul;
24449     if (isPowerOf2_64(MulAmt1))
24450       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
24451                            DAG.getConstant(Log2_64(MulAmt1), DL, MVT::i8));
24452     else
24453       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
24454                            DAG.getConstant(MulAmt1, DL, VT));
24455
24456     if (isPowerOf2_64(MulAmt2))
24457       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
24458                            DAG.getConstant(Log2_64(MulAmt2), DL, MVT::i8));
24459     else
24460       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
24461                            DAG.getConstant(MulAmt2, DL, VT));
24462
24463     // Do not add new nodes to DAG combiner worklist.
24464     DCI.CombineTo(N, NewMul, false);
24465   }
24466   return SDValue();
24467 }
24468
24469 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
24470   SDValue N0 = N->getOperand(0);
24471   SDValue N1 = N->getOperand(1);
24472   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
24473   EVT VT = N0.getValueType();
24474
24475   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
24476   // since the result of setcc_c is all zero's or all ones.
24477   if (VT.isInteger() && !VT.isVector() &&
24478       N1C && N0.getOpcode() == ISD::AND &&
24479       N0.getOperand(1).getOpcode() == ISD::Constant) {
24480     SDValue N00 = N0.getOperand(0);
24481     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
24482     APInt ShAmt = N1C->getAPIntValue();
24483     Mask = Mask.shl(ShAmt);
24484     bool MaskOK = false;
24485     // We can handle cases concerning bit-widening nodes containing setcc_c if
24486     // we carefully interrogate the mask to make sure we are semantics
24487     // preserving.
24488     // The transform is not safe if the result of C1 << C2 exceeds the bitwidth
24489     // of the underlying setcc_c operation if the setcc_c was zero extended.
24490     // Consider the following example:
24491     //   zext(setcc_c)                 -> i32 0x0000FFFF
24492     //   c1                            -> i32 0x0000FFFF
24493     //   c2                            -> i32 0x00000001
24494     //   (shl (and (setcc_c), c1), c2) -> i32 0x0001FFFE
24495     //   (and setcc_c, (c1 << c2))     -> i32 0x0000FFFE
24496     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
24497       MaskOK = true;
24498     } else if (N00.getOpcode() == ISD::SIGN_EXTEND &&
24499                N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
24500       MaskOK = true;
24501     } else if ((N00.getOpcode() == ISD::ZERO_EXTEND ||
24502                 N00.getOpcode() == ISD::ANY_EXTEND) &&
24503                N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
24504       MaskOK = Mask.isIntN(N00.getOperand(0).getValueSizeInBits());
24505     }
24506     if (MaskOK && Mask != 0) {
24507       SDLoc DL(N);
24508       return DAG.getNode(ISD::AND, DL, VT, N00, DAG.getConstant(Mask, DL, VT));
24509     }
24510   }
24511
24512   // Hardware support for vector shifts is sparse which makes us scalarize the
24513   // vector operations in many cases. Also, on sandybridge ADD is faster than
24514   // shl.
24515   // (shl V, 1) -> add V,V
24516   if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
24517     if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
24518       assert(N0.getValueType().isVector() && "Invalid vector shift type");
24519       // We shift all of the values by one. In many cases we do not have
24520       // hardware support for this operation. This is better expressed as an ADD
24521       // of two values.
24522       if (N1SplatC->getAPIntValue() == 1)
24523         return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
24524     }
24525
24526   return SDValue();
24527 }
24528
24529 /// \brief Returns a vector of 0s if the node in input is a vector logical
24530 /// shift by a constant amount which is known to be bigger than or equal
24531 /// to the vector element size in bits.
24532 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
24533                                       const X86Subtarget *Subtarget) {
24534   EVT VT = N->getValueType(0);
24535
24536   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
24537       (!Subtarget->hasInt256() ||
24538        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
24539     return SDValue();
24540
24541   SDValue Amt = N->getOperand(1);
24542   SDLoc DL(N);
24543   if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
24544     if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
24545       APInt ShiftAmt = AmtSplat->getAPIntValue();
24546       unsigned MaxAmount =
24547         VT.getSimpleVT().getVectorElementType().getSizeInBits();
24548
24549       // SSE2/AVX2 logical shifts always return a vector of 0s
24550       // if the shift amount is bigger than or equal to
24551       // the element size. The constant shift amount will be
24552       // encoded as a 8-bit immediate.
24553       if (ShiftAmt.trunc(8).uge(MaxAmount))
24554         return getZeroVector(VT, Subtarget, DAG, DL);
24555     }
24556
24557   return SDValue();
24558 }
24559
24560 /// PerformShiftCombine - Combine shifts.
24561 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
24562                                    TargetLowering::DAGCombinerInfo &DCI,
24563                                    const X86Subtarget *Subtarget) {
24564   if (N->getOpcode() == ISD::SHL)
24565     if (SDValue V = PerformSHLCombine(N, DAG))
24566       return V;
24567
24568   // Try to fold this logical shift into a zero vector.
24569   if (N->getOpcode() != ISD::SRA)
24570     if (SDValue V = performShiftToAllZeros(N, DAG, Subtarget))
24571       return V;
24572
24573   return SDValue();
24574 }
24575
24576 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
24577 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
24578 // and friends.  Likewise for OR -> CMPNEQSS.
24579 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
24580                             TargetLowering::DAGCombinerInfo &DCI,
24581                             const X86Subtarget *Subtarget) {
24582   unsigned opcode;
24583
24584   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
24585   // we're requiring SSE2 for both.
24586   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
24587     SDValue N0 = N->getOperand(0);
24588     SDValue N1 = N->getOperand(1);
24589     SDValue CMP0 = N0->getOperand(1);
24590     SDValue CMP1 = N1->getOperand(1);
24591     SDLoc DL(N);
24592
24593     // The SETCCs should both refer to the same CMP.
24594     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
24595       return SDValue();
24596
24597     SDValue CMP00 = CMP0->getOperand(0);
24598     SDValue CMP01 = CMP0->getOperand(1);
24599     EVT     VT    = CMP00.getValueType();
24600
24601     if (VT == MVT::f32 || VT == MVT::f64) {
24602       bool ExpectingFlags = false;
24603       // Check for any users that want flags:
24604       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
24605            !ExpectingFlags && UI != UE; ++UI)
24606         switch (UI->getOpcode()) {
24607         default:
24608         case ISD::BR_CC:
24609         case ISD::BRCOND:
24610         case ISD::SELECT:
24611           ExpectingFlags = true;
24612           break;
24613         case ISD::CopyToReg:
24614         case ISD::SIGN_EXTEND:
24615         case ISD::ZERO_EXTEND:
24616         case ISD::ANY_EXTEND:
24617           break;
24618         }
24619
24620       if (!ExpectingFlags) {
24621         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
24622         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
24623
24624         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
24625           X86::CondCode tmp = cc0;
24626           cc0 = cc1;
24627           cc1 = tmp;
24628         }
24629
24630         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
24631             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
24632           // FIXME: need symbolic constants for these magic numbers.
24633           // See X86ATTInstPrinter.cpp:printSSECC().
24634           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
24635           if (Subtarget->hasAVX512()) {
24636             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
24637                                          CMP01,
24638                                          DAG.getConstant(x86cc, DL, MVT::i8));
24639             if (N->getValueType(0) != MVT::i1)
24640               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
24641                                  FSetCC);
24642             return FSetCC;
24643           }
24644           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
24645                                               CMP00.getValueType(), CMP00, CMP01,
24646                                               DAG.getConstant(x86cc, DL,
24647                                                               MVT::i8));
24648
24649           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
24650           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
24651
24652           if (is64BitFP && !Subtarget->is64Bit()) {
24653             // On a 32-bit target, we cannot bitcast the 64-bit float to a
24654             // 64-bit integer, since that's not a legal type. Since
24655             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
24656             // bits, but can do this little dance to extract the lowest 32 bits
24657             // and work with those going forward.
24658             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
24659                                            OnesOrZeroesF);
24660             SDValue Vector32 = DAG.getBitcast(MVT::v4f32, Vector64);
24661             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
24662                                         Vector32, DAG.getIntPtrConstant(0, DL));
24663             IntVT = MVT::i32;
24664           }
24665
24666           SDValue OnesOrZeroesI = DAG.getBitcast(IntVT, OnesOrZeroesF);
24667           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
24668                                       DAG.getConstant(1, DL, IntVT));
24669           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8,
24670                                               ANDed);
24671           return OneBitOfTruth;
24672         }
24673       }
24674     }
24675   }
24676   return SDValue();
24677 }
24678
24679 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
24680 /// so it can be folded inside ANDNP.
24681 static bool CanFoldXORWithAllOnes(const SDNode *N) {
24682   EVT VT = N->getValueType(0);
24683
24684   // Match direct AllOnes for 128 and 256-bit vectors
24685   if (ISD::isBuildVectorAllOnes(N))
24686     return true;
24687
24688   // Look through a bit convert.
24689   if (N->getOpcode() == ISD::BITCAST)
24690     N = N->getOperand(0).getNode();
24691
24692   // Sometimes the operand may come from a insert_subvector building a 256-bit
24693   // allones vector
24694   if (VT.is256BitVector() &&
24695       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
24696     SDValue V1 = N->getOperand(0);
24697     SDValue V2 = N->getOperand(1);
24698
24699     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
24700         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
24701         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
24702         ISD::isBuildVectorAllOnes(V2.getNode()))
24703       return true;
24704   }
24705
24706   return false;
24707 }
24708
24709 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
24710 // register. In most cases we actually compare or select YMM-sized registers
24711 // and mixing the two types creates horrible code. This method optimizes
24712 // some of the transition sequences.
24713 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
24714                                  TargetLowering::DAGCombinerInfo &DCI,
24715                                  const X86Subtarget *Subtarget) {
24716   EVT VT = N->getValueType(0);
24717   if (!VT.is256BitVector())
24718     return SDValue();
24719
24720   assert((N->getOpcode() == ISD::ANY_EXTEND ||
24721           N->getOpcode() == ISD::ZERO_EXTEND ||
24722           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
24723
24724   SDValue Narrow = N->getOperand(0);
24725   EVT NarrowVT = Narrow->getValueType(0);
24726   if (!NarrowVT.is128BitVector())
24727     return SDValue();
24728
24729   if (Narrow->getOpcode() != ISD::XOR &&
24730       Narrow->getOpcode() != ISD::AND &&
24731       Narrow->getOpcode() != ISD::OR)
24732     return SDValue();
24733
24734   SDValue N0  = Narrow->getOperand(0);
24735   SDValue N1  = Narrow->getOperand(1);
24736   SDLoc DL(Narrow);
24737
24738   // The Left side has to be a trunc.
24739   if (N0.getOpcode() != ISD::TRUNCATE)
24740     return SDValue();
24741
24742   // The type of the truncated inputs.
24743   EVT WideVT = N0->getOperand(0)->getValueType(0);
24744   if (WideVT != VT)
24745     return SDValue();
24746
24747   // The right side has to be a 'trunc' or a constant vector.
24748   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
24749   ConstantSDNode *RHSConstSplat = nullptr;
24750   if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
24751     RHSConstSplat = RHSBV->getConstantSplatNode();
24752   if (!RHSTrunc && !RHSConstSplat)
24753     return SDValue();
24754
24755   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24756
24757   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
24758     return SDValue();
24759
24760   // Set N0 and N1 to hold the inputs to the new wide operation.
24761   N0 = N0->getOperand(0);
24762   if (RHSConstSplat) {
24763     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getVectorElementType(),
24764                      SDValue(RHSConstSplat, 0));
24765     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
24766     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
24767   } else if (RHSTrunc) {
24768     N1 = N1->getOperand(0);
24769   }
24770
24771   // Generate the wide operation.
24772   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
24773   unsigned Opcode = N->getOpcode();
24774   switch (Opcode) {
24775   case ISD::ANY_EXTEND:
24776     return Op;
24777   case ISD::ZERO_EXTEND: {
24778     unsigned InBits = NarrowVT.getScalarSizeInBits();
24779     APInt Mask = APInt::getAllOnesValue(InBits);
24780     Mask = Mask.zext(VT.getScalarSizeInBits());
24781     return DAG.getNode(ISD::AND, DL, VT,
24782                        Op, DAG.getConstant(Mask, DL, VT));
24783   }
24784   case ISD::SIGN_EXTEND:
24785     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
24786                        Op, DAG.getValueType(NarrowVT));
24787   default:
24788     llvm_unreachable("Unexpected opcode");
24789   }
24790 }
24791
24792 static SDValue VectorZextCombine(SDNode *N, SelectionDAG &DAG,
24793                                  TargetLowering::DAGCombinerInfo &DCI,
24794                                  const X86Subtarget *Subtarget) {
24795   SDValue N0 = N->getOperand(0);
24796   SDValue N1 = N->getOperand(1);
24797   SDLoc DL(N);
24798
24799   // A vector zext_in_reg may be represented as a shuffle,
24800   // feeding into a bitcast (this represents anyext) feeding into
24801   // an and with a mask.
24802   // We'd like to try to combine that into a shuffle with zero
24803   // plus a bitcast, removing the and.
24804   if (N0.getOpcode() != ISD::BITCAST ||
24805       N0.getOperand(0).getOpcode() != ISD::VECTOR_SHUFFLE)
24806     return SDValue();
24807
24808   // The other side of the AND should be a splat of 2^C, where C
24809   // is the number of bits in the source type.
24810   if (N1.getOpcode() == ISD::BITCAST)
24811     N1 = N1.getOperand(0);
24812   if (N1.getOpcode() != ISD::BUILD_VECTOR)
24813     return SDValue();
24814   BuildVectorSDNode *Vector = cast<BuildVectorSDNode>(N1);
24815
24816   ShuffleVectorSDNode *Shuffle = cast<ShuffleVectorSDNode>(N0.getOperand(0));
24817   EVT SrcType = Shuffle->getValueType(0);
24818
24819   // We expect a single-source shuffle
24820   if (Shuffle->getOperand(1)->getOpcode() != ISD::UNDEF)
24821     return SDValue();
24822
24823   unsigned SrcSize = SrcType.getScalarSizeInBits();
24824
24825   APInt SplatValue, SplatUndef;
24826   unsigned SplatBitSize;
24827   bool HasAnyUndefs;
24828   if (!Vector->isConstantSplat(SplatValue, SplatUndef,
24829                                 SplatBitSize, HasAnyUndefs))
24830     return SDValue();
24831
24832   unsigned ResSize = N1.getValueType().getScalarSizeInBits();
24833   // Make sure the splat matches the mask we expect
24834   if (SplatBitSize > ResSize ||
24835       (SplatValue + 1).exactLogBase2() != (int)SrcSize)
24836     return SDValue();
24837
24838   // Make sure the input and output size make sense
24839   if (SrcSize >= ResSize || ResSize % SrcSize)
24840     return SDValue();
24841
24842   // We expect a shuffle of the form <0, u, u, u, 1, u, u, u...>
24843   // The number of u's between each two values depends on the ratio between
24844   // the source and dest type.
24845   unsigned ZextRatio = ResSize / SrcSize;
24846   bool IsZext = true;
24847   for (unsigned i = 0; i < SrcType.getVectorNumElements(); ++i) {
24848     if (i % ZextRatio) {
24849       if (Shuffle->getMaskElt(i) > 0) {
24850         // Expected undef
24851         IsZext = false;
24852         break;
24853       }
24854     } else {
24855       if (Shuffle->getMaskElt(i) != (int)(i / ZextRatio)) {
24856         // Expected element number
24857         IsZext = false;
24858         break;
24859       }
24860     }
24861   }
24862
24863   if (!IsZext)
24864     return SDValue();
24865
24866   // Ok, perform the transformation - replace the shuffle with
24867   // a shuffle of the form <0, k, k, k, 1, k, k, k> with zero
24868   // (instead of undef) where the k elements come from the zero vector.
24869   SmallVector<int, 8> Mask;
24870   unsigned NumElems = SrcType.getVectorNumElements();
24871   for (unsigned i = 0; i < NumElems; ++i)
24872     if (i % ZextRatio)
24873       Mask.push_back(NumElems);
24874     else
24875       Mask.push_back(i / ZextRatio);
24876
24877   SDValue NewShuffle = DAG.getVectorShuffle(Shuffle->getValueType(0), DL,
24878     Shuffle->getOperand(0), DAG.getConstant(0, DL, SrcType), Mask);
24879   return DAG.getBitcast(N0.getValueType(), NewShuffle);
24880 }
24881
24882 /// If both input operands of a logic op are being cast from floating point
24883 /// types, try to convert this into a floating point logic node to avoid
24884 /// unnecessary moves from SSE to integer registers.
24885 static SDValue convertIntLogicToFPLogic(SDNode *N, SelectionDAG &DAG,
24886                                         const X86Subtarget *Subtarget) {
24887   unsigned FPOpcode = ISD::DELETED_NODE;
24888   if (N->getOpcode() == ISD::AND)
24889     FPOpcode = X86ISD::FAND;
24890   else if (N->getOpcode() == ISD::OR)
24891     FPOpcode = X86ISD::FOR;
24892   else if (N->getOpcode() == ISD::XOR)
24893     FPOpcode = X86ISD::FXOR;
24894
24895   assert(FPOpcode != ISD::DELETED_NODE &&
24896          "Unexpected input node for FP logic conversion");
24897
24898   EVT VT = N->getValueType(0);
24899   SDValue N0 = N->getOperand(0);
24900   SDValue N1 = N->getOperand(1);
24901   SDLoc DL(N);
24902   if (N0.getOpcode() == ISD::BITCAST && N1.getOpcode() == ISD::BITCAST &&
24903       ((Subtarget->hasSSE1() && VT == MVT::i32) ||
24904        (Subtarget->hasSSE2() && VT == MVT::i64))) {
24905     SDValue N00 = N0.getOperand(0);
24906     SDValue N10 = N1.getOperand(0);
24907     EVT N00Type = N00.getValueType();
24908     EVT N10Type = N10.getValueType();
24909     if (N00Type.isFloatingPoint() && N10Type.isFloatingPoint()) {
24910       SDValue FPLogic = DAG.getNode(FPOpcode, DL, N00Type, N00, N10);
24911       return DAG.getBitcast(VT, FPLogic);
24912     }
24913   }
24914   return SDValue();
24915 }
24916
24917 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
24918                                  TargetLowering::DAGCombinerInfo &DCI,
24919                                  const X86Subtarget *Subtarget) {
24920   if (DCI.isBeforeLegalizeOps())
24921     return SDValue();
24922
24923   if (SDValue Zext = VectorZextCombine(N, DAG, DCI, Subtarget))
24924     return Zext;
24925
24926   if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
24927     return R;
24928
24929   if (SDValue FPLogic = convertIntLogicToFPLogic(N, DAG, Subtarget))
24930     return FPLogic;
24931
24932   EVT VT = N->getValueType(0);
24933   SDValue N0 = N->getOperand(0);
24934   SDValue N1 = N->getOperand(1);
24935   SDLoc DL(N);
24936
24937   // Create BEXTR instructions
24938   // BEXTR is ((X >> imm) & (2**size-1))
24939   if (VT == MVT::i32 || VT == MVT::i64) {
24940     // Check for BEXTR.
24941     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
24942         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
24943       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
24944       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
24945       if (MaskNode && ShiftNode) {
24946         uint64_t Mask = MaskNode->getZExtValue();
24947         uint64_t Shift = ShiftNode->getZExtValue();
24948         if (isMask_64(Mask)) {
24949           uint64_t MaskSize = countPopulation(Mask);
24950           if (Shift + MaskSize <= VT.getSizeInBits())
24951             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
24952                                DAG.getConstant(Shift | (MaskSize << 8), DL,
24953                                                VT));
24954         }
24955       }
24956     } // BEXTR
24957
24958     return SDValue();
24959   }
24960
24961   // Want to form ANDNP nodes:
24962   // 1) In the hopes of then easily combining them with OR and AND nodes
24963   //    to form PBLEND/PSIGN.
24964   // 2) To match ANDN packed intrinsics
24965   if (VT != MVT::v2i64 && VT != MVT::v4i64)
24966     return SDValue();
24967
24968   // Check LHS for vnot
24969   if (N0.getOpcode() == ISD::XOR &&
24970       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
24971       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
24972     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
24973
24974   // Check RHS for vnot
24975   if (N1.getOpcode() == ISD::XOR &&
24976       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
24977       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
24978     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
24979
24980   return SDValue();
24981 }
24982
24983 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
24984                                 TargetLowering::DAGCombinerInfo &DCI,
24985                                 const X86Subtarget *Subtarget) {
24986   if (DCI.isBeforeLegalizeOps())
24987     return SDValue();
24988
24989   if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
24990     return R;
24991
24992   if (SDValue FPLogic = convertIntLogicToFPLogic(N, DAG, Subtarget))
24993     return FPLogic;
24994
24995   SDValue N0 = N->getOperand(0);
24996   SDValue N1 = N->getOperand(1);
24997   EVT VT = N->getValueType(0);
24998
24999   // look for psign/blend
25000   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
25001     if (!Subtarget->hasSSSE3() ||
25002         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
25003       return SDValue();
25004
25005     // Canonicalize pandn to RHS
25006     if (N0.getOpcode() == X86ISD::ANDNP)
25007       std::swap(N0, N1);
25008     // or (and (m, y), (pandn m, x))
25009     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
25010       SDValue Mask = N1.getOperand(0);
25011       SDValue X    = N1.getOperand(1);
25012       SDValue Y;
25013       if (N0.getOperand(0) == Mask)
25014         Y = N0.getOperand(1);
25015       if (N0.getOperand(1) == Mask)
25016         Y = N0.getOperand(0);
25017
25018       // Check to see if the mask appeared in both the AND and ANDNP and
25019       if (!Y.getNode())
25020         return SDValue();
25021
25022       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
25023       // Look through mask bitcast.
25024       if (Mask.getOpcode() == ISD::BITCAST)
25025         Mask = Mask.getOperand(0);
25026       if (X.getOpcode() == ISD::BITCAST)
25027         X = X.getOperand(0);
25028       if (Y.getOpcode() == ISD::BITCAST)
25029         Y = Y.getOperand(0);
25030
25031       EVT MaskVT = Mask.getValueType();
25032
25033       // Validate that the Mask operand is a vector sra node.
25034       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
25035       // there is no psrai.b
25036       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
25037       unsigned SraAmt = ~0;
25038       if (Mask.getOpcode() == ISD::SRA) {
25039         if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
25040           if (auto *AmtConst = AmtBV->getConstantSplatNode())
25041             SraAmt = AmtConst->getZExtValue();
25042       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
25043         SDValue SraC = Mask.getOperand(1);
25044         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
25045       }
25046       if ((SraAmt + 1) != EltBits)
25047         return SDValue();
25048
25049       SDLoc DL(N);
25050
25051       // Now we know we at least have a plendvb with the mask val.  See if
25052       // we can form a psignb/w/d.
25053       // psign = x.type == y.type == mask.type && y = sub(0, x);
25054       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
25055           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
25056           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
25057         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
25058                "Unsupported VT for PSIGN");
25059         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
25060         return DAG.getBitcast(VT, Mask);
25061       }
25062       // PBLENDVB only available on SSE 4.1
25063       if (!Subtarget->hasSSE41())
25064         return SDValue();
25065
25066       MVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
25067
25068       X = DAG.getBitcast(BlendVT, X);
25069       Y = DAG.getBitcast(BlendVT, Y);
25070       Mask = DAG.getBitcast(BlendVT, Mask);
25071       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
25072       return DAG.getBitcast(VT, Mask);
25073     }
25074   }
25075
25076   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
25077     return SDValue();
25078
25079   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
25080   bool OptForSize = DAG.getMachineFunction().getFunction()->optForSize();
25081
25082   // SHLD/SHRD instructions have lower register pressure, but on some
25083   // platforms they have higher latency than the equivalent
25084   // series of shifts/or that would otherwise be generated.
25085   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
25086   // have higher latencies and we are not optimizing for size.
25087   if (!OptForSize && Subtarget->isSHLDSlow())
25088     return SDValue();
25089
25090   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
25091     std::swap(N0, N1);
25092   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
25093     return SDValue();
25094   if (!N0.hasOneUse() || !N1.hasOneUse())
25095     return SDValue();
25096
25097   SDValue ShAmt0 = N0.getOperand(1);
25098   if (ShAmt0.getValueType() != MVT::i8)
25099     return SDValue();
25100   SDValue ShAmt1 = N1.getOperand(1);
25101   if (ShAmt1.getValueType() != MVT::i8)
25102     return SDValue();
25103   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
25104     ShAmt0 = ShAmt0.getOperand(0);
25105   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
25106     ShAmt1 = ShAmt1.getOperand(0);
25107
25108   SDLoc DL(N);
25109   unsigned Opc = X86ISD::SHLD;
25110   SDValue Op0 = N0.getOperand(0);
25111   SDValue Op1 = N1.getOperand(0);
25112   if (ShAmt0.getOpcode() == ISD::SUB) {
25113     Opc = X86ISD::SHRD;
25114     std::swap(Op0, Op1);
25115     std::swap(ShAmt0, ShAmt1);
25116   }
25117
25118   unsigned Bits = VT.getSizeInBits();
25119   if (ShAmt1.getOpcode() == ISD::SUB) {
25120     SDValue Sum = ShAmt1.getOperand(0);
25121     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
25122       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
25123       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
25124         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
25125       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
25126         return DAG.getNode(Opc, DL, VT,
25127                            Op0, Op1,
25128                            DAG.getNode(ISD::TRUNCATE, DL,
25129                                        MVT::i8, ShAmt0));
25130     }
25131   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
25132     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
25133     if (ShAmt0C &&
25134         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
25135       return DAG.getNode(Opc, DL, VT,
25136                          N0.getOperand(0), N1.getOperand(0),
25137                          DAG.getNode(ISD::TRUNCATE, DL,
25138                                        MVT::i8, ShAmt0));
25139   }
25140
25141   return SDValue();
25142 }
25143
25144 // Generate NEG and CMOV for integer abs.
25145 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
25146   EVT VT = N->getValueType(0);
25147
25148   // Since X86 does not have CMOV for 8-bit integer, we don't convert
25149   // 8-bit integer abs to NEG and CMOV.
25150   if (VT.isInteger() && VT.getSizeInBits() == 8)
25151     return SDValue();
25152
25153   SDValue N0 = N->getOperand(0);
25154   SDValue N1 = N->getOperand(1);
25155   SDLoc DL(N);
25156
25157   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
25158   // and change it to SUB and CMOV.
25159   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
25160       N0.getOpcode() == ISD::ADD &&
25161       N0.getOperand(1) == N1 &&
25162       N1.getOpcode() == ISD::SRA &&
25163       N1.getOperand(0) == N0.getOperand(0))
25164     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
25165       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
25166         // Generate SUB & CMOV.
25167         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
25168                                   DAG.getConstant(0, DL, VT), N0.getOperand(0));
25169
25170         SDValue Ops[] = { N0.getOperand(0), Neg,
25171                           DAG.getConstant(X86::COND_GE, DL, MVT::i8),
25172                           SDValue(Neg.getNode(), 1) };
25173         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
25174       }
25175   return SDValue();
25176 }
25177
25178 // Try to turn tests against the signbit in the form of:
25179 //   XOR(TRUNCATE(SRL(X, size(X)-1)), 1)
25180 // into:
25181 //   SETGT(X, -1)
25182 static SDValue foldXorTruncShiftIntoCmp(SDNode *N, SelectionDAG &DAG) {
25183   // This is only worth doing if the output type is i8.
25184   if (N->getValueType(0) != MVT::i8)
25185     return SDValue();
25186
25187   SDValue N0 = N->getOperand(0);
25188   SDValue N1 = N->getOperand(1);
25189
25190   // We should be performing an xor against a truncated shift.
25191   if (N0.getOpcode() != ISD::TRUNCATE || !N0.hasOneUse())
25192     return SDValue();
25193
25194   // Make sure we are performing an xor against one.
25195   if (!isa<ConstantSDNode>(N1) || !cast<ConstantSDNode>(N1)->isOne())
25196     return SDValue();
25197
25198   // SetCC on x86 zero extends so only act on this if it's a logical shift.
25199   SDValue Shift = N0.getOperand(0);
25200   if (Shift.getOpcode() != ISD::SRL || !Shift.hasOneUse())
25201     return SDValue();
25202
25203   // Make sure we are truncating from one of i16, i32 or i64.
25204   EVT ShiftTy = Shift.getValueType();
25205   if (ShiftTy != MVT::i16 && ShiftTy != MVT::i32 && ShiftTy != MVT::i64)
25206     return SDValue();
25207
25208   // Make sure the shift amount extracts the sign bit.
25209   if (!isa<ConstantSDNode>(Shift.getOperand(1)) ||
25210       Shift.getConstantOperandVal(1) != ShiftTy.getSizeInBits() - 1)
25211     return SDValue();
25212
25213   // Create a greater-than comparison against -1.
25214   // N.B. Using SETGE against 0 works but we want a canonical looking
25215   // comparison, using SETGT matches up with what TranslateX86CC.
25216   SDLoc DL(N);
25217   SDValue ShiftOp = Shift.getOperand(0);
25218   EVT ShiftOpTy = ShiftOp.getValueType();
25219   SDValue Cond = DAG.getSetCC(DL, MVT::i8, ShiftOp,
25220                               DAG.getConstant(-1, DL, ShiftOpTy), ISD::SETGT);
25221   return Cond;
25222 }
25223
25224 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
25225                                  TargetLowering::DAGCombinerInfo &DCI,
25226                                  const X86Subtarget *Subtarget) {
25227   if (DCI.isBeforeLegalizeOps())
25228     return SDValue();
25229
25230   if (SDValue RV = foldXorTruncShiftIntoCmp(N, DAG))
25231     return RV;
25232
25233   if (Subtarget->hasCMov())
25234     if (SDValue RV = performIntegerAbsCombine(N, DAG))
25235       return RV;
25236
25237   if (SDValue FPLogic = convertIntLogicToFPLogic(N, DAG, Subtarget))
25238     return FPLogic;
25239
25240   return SDValue();
25241 }
25242
25243 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
25244 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
25245                                   TargetLowering::DAGCombinerInfo &DCI,
25246                                   const X86Subtarget *Subtarget) {
25247   LoadSDNode *Ld = cast<LoadSDNode>(N);
25248   EVT RegVT = Ld->getValueType(0);
25249   EVT MemVT = Ld->getMemoryVT();
25250   SDLoc dl(Ld);
25251   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25252
25253   // For chips with slow 32-byte unaligned loads, break the 32-byte operation
25254   // into two 16-byte operations.
25255   ISD::LoadExtType Ext = Ld->getExtensionType();
25256   bool Fast;
25257   unsigned AddressSpace = Ld->getAddressSpace();
25258   unsigned Alignment = Ld->getAlignment();
25259   if (RegVT.is256BitVector() && !DCI.isBeforeLegalizeOps() &&
25260       Ext == ISD::NON_EXTLOAD &&
25261       TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), RegVT,
25262                              AddressSpace, Alignment, &Fast) && !Fast) {
25263     unsigned NumElems = RegVT.getVectorNumElements();
25264     if (NumElems < 2)
25265       return SDValue();
25266
25267     SDValue Ptr = Ld->getBasePtr();
25268     SDValue Increment =
25269         DAG.getConstant(16, dl, TLI.getPointerTy(DAG.getDataLayout()));
25270
25271     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
25272                                   NumElems/2);
25273     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
25274                                 Ld->getPointerInfo(), Ld->isVolatile(),
25275                                 Ld->isNonTemporal(), Ld->isInvariant(),
25276                                 Alignment);
25277     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
25278     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
25279                                 Ld->getPointerInfo(), Ld->isVolatile(),
25280                                 Ld->isNonTemporal(), Ld->isInvariant(),
25281                                 std::min(16U, Alignment));
25282     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
25283                              Load1.getValue(1),
25284                              Load2.getValue(1));
25285
25286     SDValue NewVec = DAG.getUNDEF(RegVT);
25287     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
25288     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
25289     return DCI.CombineTo(N, NewVec, TF, true);
25290   }
25291
25292   return SDValue();
25293 }
25294
25295 /// PerformMLOADCombine - Resolve extending loads
25296 static SDValue PerformMLOADCombine(SDNode *N, SelectionDAG &DAG,
25297                                    TargetLowering::DAGCombinerInfo &DCI,
25298                                    const X86Subtarget *Subtarget) {
25299   MaskedLoadSDNode *Mld = cast<MaskedLoadSDNode>(N);
25300   if (Mld->getExtensionType() != ISD::SEXTLOAD)
25301     return SDValue();
25302
25303   EVT VT = Mld->getValueType(0);
25304   unsigned NumElems = VT.getVectorNumElements();
25305   EVT LdVT = Mld->getMemoryVT();
25306   SDLoc dl(Mld);
25307
25308   assert(LdVT != VT && "Cannot extend to the same type");
25309   unsigned ToSz = VT.getVectorElementType().getSizeInBits();
25310   unsigned FromSz = LdVT.getVectorElementType().getSizeInBits();
25311   // From, To sizes and ElemCount must be pow of two
25312   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
25313     "Unexpected size for extending masked load");
25314
25315   unsigned SizeRatio  = ToSz / FromSz;
25316   assert(SizeRatio * NumElems * FromSz == VT.getSizeInBits());
25317
25318   // Create a type on which we perform the shuffle
25319   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
25320           LdVT.getScalarType(), NumElems*SizeRatio);
25321   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
25322
25323   // Convert Src0 value
25324   SDValue WideSrc0 = DAG.getBitcast(WideVecVT, Mld->getSrc0());
25325   if (Mld->getSrc0().getOpcode() != ISD::UNDEF) {
25326     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
25327     for (unsigned i = 0; i != NumElems; ++i)
25328       ShuffleVec[i] = i * SizeRatio;
25329
25330     // Can't shuffle using an illegal type.
25331     assert(DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT) &&
25332            "WideVecVT should be legal");
25333     WideSrc0 = DAG.getVectorShuffle(WideVecVT, dl, WideSrc0,
25334                                     DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
25335   }
25336   // Prepare the new mask
25337   SDValue NewMask;
25338   SDValue Mask = Mld->getMask();
25339   if (Mask.getValueType() == VT) {
25340     // Mask and original value have the same type
25341     NewMask = DAG.getBitcast(WideVecVT, Mask);
25342     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
25343     for (unsigned i = 0; i != NumElems; ++i)
25344       ShuffleVec[i] = i * SizeRatio;
25345     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
25346       ShuffleVec[i] = NumElems*SizeRatio;
25347     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
25348                                    DAG.getConstant(0, dl, WideVecVT),
25349                                    &ShuffleVec[0]);
25350   }
25351   else {
25352     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
25353     unsigned WidenNumElts = NumElems*SizeRatio;
25354     unsigned MaskNumElts = VT.getVectorNumElements();
25355     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
25356                                      WidenNumElts);
25357
25358     unsigned NumConcat = WidenNumElts / MaskNumElts;
25359     SmallVector<SDValue, 16> Ops(NumConcat);
25360     SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
25361     Ops[0] = Mask;
25362     for (unsigned i = 1; i != NumConcat; ++i)
25363       Ops[i] = ZeroVal;
25364
25365     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
25366   }
25367
25368   SDValue WideLd = DAG.getMaskedLoad(WideVecVT, dl, Mld->getChain(),
25369                                      Mld->getBasePtr(), NewMask, WideSrc0,
25370                                      Mld->getMemoryVT(), Mld->getMemOperand(),
25371                                      ISD::NON_EXTLOAD);
25372   SDValue NewVec = DAG.getNode(X86ISD::VSEXT, dl, VT, WideLd);
25373   return DCI.CombineTo(N, NewVec, WideLd.getValue(1), true);
25374 }
25375 /// PerformMSTORECombine - Resolve truncating stores
25376 static SDValue PerformMSTORECombine(SDNode *N, SelectionDAG &DAG,
25377                                     const X86Subtarget *Subtarget) {
25378   MaskedStoreSDNode *Mst = cast<MaskedStoreSDNode>(N);
25379   if (!Mst->isTruncatingStore())
25380     return SDValue();
25381
25382   EVT VT = Mst->getValue().getValueType();
25383   unsigned NumElems = VT.getVectorNumElements();
25384   EVT StVT = Mst->getMemoryVT();
25385   SDLoc dl(Mst);
25386
25387   assert(StVT != VT && "Cannot truncate to the same type");
25388   unsigned FromSz = VT.getVectorElementType().getSizeInBits();
25389   unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
25390
25391   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25392
25393   // The truncating store is legal in some cases. For example
25394   // vpmovqb, vpmovqw, vpmovqd, vpmovdb, vpmovdw
25395   // are designated for truncate store.
25396   // In this case we don't need any further transformations.
25397   if (TLI.isTruncStoreLegal(VT, StVT))
25398     return SDValue();
25399
25400   // From, To sizes and ElemCount must be pow of two
25401   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
25402     "Unexpected size for truncating masked store");
25403   // We are going to use the original vector elt for storing.
25404   // Accumulated smaller vector elements must be a multiple of the store size.
25405   assert (((NumElems * FromSz) % ToSz) == 0 &&
25406           "Unexpected ratio for truncating masked store");
25407
25408   unsigned SizeRatio  = FromSz / ToSz;
25409   assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
25410
25411   // Create a type on which we perform the shuffle
25412   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
25413           StVT.getScalarType(), NumElems*SizeRatio);
25414
25415   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
25416
25417   SDValue WideVec = DAG.getBitcast(WideVecVT, Mst->getValue());
25418   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
25419   for (unsigned i = 0; i != NumElems; ++i)
25420     ShuffleVec[i] = i * SizeRatio;
25421
25422   // Can't shuffle using an illegal type.
25423   assert(DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT) &&
25424          "WideVecVT should be legal");
25425
25426   SDValue TruncatedVal = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
25427                                         DAG.getUNDEF(WideVecVT),
25428                                         &ShuffleVec[0]);
25429
25430   SDValue NewMask;
25431   SDValue Mask = Mst->getMask();
25432   if (Mask.getValueType() == VT) {
25433     // Mask and original value have the same type
25434     NewMask = DAG.getBitcast(WideVecVT, Mask);
25435     for (unsigned i = 0; i != NumElems; ++i)
25436       ShuffleVec[i] = i * SizeRatio;
25437     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
25438       ShuffleVec[i] = NumElems*SizeRatio;
25439     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
25440                                    DAG.getConstant(0, dl, WideVecVT),
25441                                    &ShuffleVec[0]);
25442   }
25443   else {
25444     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
25445     unsigned WidenNumElts = NumElems*SizeRatio;
25446     unsigned MaskNumElts = VT.getVectorNumElements();
25447     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
25448                                      WidenNumElts);
25449
25450     unsigned NumConcat = WidenNumElts / MaskNumElts;
25451     SmallVector<SDValue, 16> Ops(NumConcat);
25452     SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
25453     Ops[0] = Mask;
25454     for (unsigned i = 1; i != NumConcat; ++i)
25455       Ops[i] = ZeroVal;
25456
25457     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
25458   }
25459
25460   return DAG.getMaskedStore(Mst->getChain(), dl, TruncatedVal, Mst->getBasePtr(),
25461                             NewMask, StVT, Mst->getMemOperand(), false);
25462 }
25463 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
25464 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
25465                                    const X86Subtarget *Subtarget) {
25466   StoreSDNode *St = cast<StoreSDNode>(N);
25467   EVT VT = St->getValue().getValueType();
25468   EVT StVT = St->getMemoryVT();
25469   SDLoc dl(St);
25470   SDValue StoredVal = St->getOperand(1);
25471   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25472
25473   // If we are saving a concatenation of two XMM registers and 32-byte stores
25474   // are slow, such as on Sandy Bridge, perform two 16-byte stores.
25475   bool Fast;
25476   unsigned AddressSpace = St->getAddressSpace();
25477   unsigned Alignment = St->getAlignment();
25478   if (VT.is256BitVector() && StVT == VT &&
25479       TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
25480                              AddressSpace, Alignment, &Fast) && !Fast) {
25481     unsigned NumElems = VT.getVectorNumElements();
25482     if (NumElems < 2)
25483       return SDValue();
25484
25485     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
25486     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
25487
25488     SDValue Stride =
25489         DAG.getConstant(16, dl, TLI.getPointerTy(DAG.getDataLayout()));
25490     SDValue Ptr0 = St->getBasePtr();
25491     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
25492
25493     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
25494                                 St->getPointerInfo(), St->isVolatile(),
25495                                 St->isNonTemporal(), Alignment);
25496     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
25497                                 St->getPointerInfo(), St->isVolatile(),
25498                                 St->isNonTemporal(),
25499                                 std::min(16U, Alignment));
25500     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
25501   }
25502
25503   // Optimize trunc store (of multiple scalars) to shuffle and store.
25504   // First, pack all of the elements in one place. Next, store to memory
25505   // in fewer chunks.
25506   if (St->isTruncatingStore() && VT.isVector()) {
25507     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25508     unsigned NumElems = VT.getVectorNumElements();
25509     assert(StVT != VT && "Cannot truncate to the same type");
25510     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
25511     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
25512
25513     // The truncating store is legal in some cases. For example
25514     // vpmovqb, vpmovqw, vpmovqd, vpmovdb, vpmovdw
25515     // are designated for truncate store.
25516     // In this case we don't need any further transformations.
25517     if (TLI.isTruncStoreLegal(VT, StVT))
25518       return SDValue();
25519
25520     // From, To sizes and ElemCount must be pow of two
25521     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
25522     // We are going to use the original vector elt for storing.
25523     // Accumulated smaller vector elements must be a multiple of the store size.
25524     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
25525
25526     unsigned SizeRatio  = FromSz / ToSz;
25527
25528     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
25529
25530     // Create a type on which we perform the shuffle
25531     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
25532             StVT.getScalarType(), NumElems*SizeRatio);
25533
25534     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
25535
25536     SDValue WideVec = DAG.getBitcast(WideVecVT, St->getValue());
25537     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
25538     for (unsigned i = 0; i != NumElems; ++i)
25539       ShuffleVec[i] = i * SizeRatio;
25540
25541     // Can't shuffle using an illegal type.
25542     if (!TLI.isTypeLegal(WideVecVT))
25543       return SDValue();
25544
25545     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
25546                                          DAG.getUNDEF(WideVecVT),
25547                                          &ShuffleVec[0]);
25548     // At this point all of the data is stored at the bottom of the
25549     // register. We now need to save it to mem.
25550
25551     // Find the largest store unit
25552     MVT StoreType = MVT::i8;
25553     for (MVT Tp : MVT::integer_valuetypes()) {
25554       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
25555         StoreType = Tp;
25556     }
25557
25558     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
25559     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
25560         (64 <= NumElems * ToSz))
25561       StoreType = MVT::f64;
25562
25563     // Bitcast the original vector into a vector of store-size units
25564     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
25565             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
25566     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
25567     SDValue ShuffWide = DAG.getBitcast(StoreVecVT, Shuff);
25568     SmallVector<SDValue, 8> Chains;
25569     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, dl,
25570                                         TLI.getPointerTy(DAG.getDataLayout()));
25571     SDValue Ptr = St->getBasePtr();
25572
25573     // Perform one or more big stores into memory.
25574     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
25575       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
25576                                    StoreType, ShuffWide,
25577                                    DAG.getIntPtrConstant(i, dl));
25578       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
25579                                 St->getPointerInfo(), St->isVolatile(),
25580                                 St->isNonTemporal(), St->getAlignment());
25581       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
25582       Chains.push_back(Ch);
25583     }
25584
25585     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
25586   }
25587
25588   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
25589   // the FP state in cases where an emms may be missing.
25590   // A preferable solution to the general problem is to figure out the right
25591   // places to insert EMMS.  This qualifies as a quick hack.
25592
25593   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
25594   if (VT.getSizeInBits() != 64)
25595     return SDValue();
25596
25597   const Function *F = DAG.getMachineFunction().getFunction();
25598   bool NoImplicitFloatOps = F->hasFnAttribute(Attribute::NoImplicitFloat);
25599   bool F64IsLegal =
25600       !Subtarget->useSoftFloat() && !NoImplicitFloatOps && Subtarget->hasSSE2();
25601   if ((VT.isVector() ||
25602        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
25603       isa<LoadSDNode>(St->getValue()) &&
25604       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
25605       St->getChain().hasOneUse() && !St->isVolatile()) {
25606     SDNode* LdVal = St->getValue().getNode();
25607     LoadSDNode *Ld = nullptr;
25608     int TokenFactorIndex = -1;
25609     SmallVector<SDValue, 8> Ops;
25610     SDNode* ChainVal = St->getChain().getNode();
25611     // Must be a store of a load.  We currently handle two cases:  the load
25612     // is a direct child, and it's under an intervening TokenFactor.  It is
25613     // possible to dig deeper under nested TokenFactors.
25614     if (ChainVal == LdVal)
25615       Ld = cast<LoadSDNode>(St->getChain());
25616     else if (St->getValue().hasOneUse() &&
25617              ChainVal->getOpcode() == ISD::TokenFactor) {
25618       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
25619         if (ChainVal->getOperand(i).getNode() == LdVal) {
25620           TokenFactorIndex = i;
25621           Ld = cast<LoadSDNode>(St->getValue());
25622         } else
25623           Ops.push_back(ChainVal->getOperand(i));
25624       }
25625     }
25626
25627     if (!Ld || !ISD::isNormalLoad(Ld))
25628       return SDValue();
25629
25630     // If this is not the MMX case, i.e. we are just turning i64 load/store
25631     // into f64 load/store, avoid the transformation if there are multiple
25632     // uses of the loaded value.
25633     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
25634       return SDValue();
25635
25636     SDLoc LdDL(Ld);
25637     SDLoc StDL(N);
25638     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
25639     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
25640     // pair instead.
25641     if (Subtarget->is64Bit() || F64IsLegal) {
25642       MVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
25643       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
25644                                   Ld->getPointerInfo(), Ld->isVolatile(),
25645                                   Ld->isNonTemporal(), Ld->isInvariant(),
25646                                   Ld->getAlignment());
25647       SDValue NewChain = NewLd.getValue(1);
25648       if (TokenFactorIndex != -1) {
25649         Ops.push_back(NewChain);
25650         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
25651       }
25652       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
25653                           St->getPointerInfo(),
25654                           St->isVolatile(), St->isNonTemporal(),
25655                           St->getAlignment());
25656     }
25657
25658     // Otherwise, lower to two pairs of 32-bit loads / stores.
25659     SDValue LoAddr = Ld->getBasePtr();
25660     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
25661                                  DAG.getConstant(4, LdDL, MVT::i32));
25662
25663     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
25664                                Ld->getPointerInfo(),
25665                                Ld->isVolatile(), Ld->isNonTemporal(),
25666                                Ld->isInvariant(), Ld->getAlignment());
25667     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
25668                                Ld->getPointerInfo().getWithOffset(4),
25669                                Ld->isVolatile(), Ld->isNonTemporal(),
25670                                Ld->isInvariant(),
25671                                MinAlign(Ld->getAlignment(), 4));
25672
25673     SDValue NewChain = LoLd.getValue(1);
25674     if (TokenFactorIndex != -1) {
25675       Ops.push_back(LoLd);
25676       Ops.push_back(HiLd);
25677       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
25678     }
25679
25680     LoAddr = St->getBasePtr();
25681     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
25682                          DAG.getConstant(4, StDL, MVT::i32));
25683
25684     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
25685                                 St->getPointerInfo(),
25686                                 St->isVolatile(), St->isNonTemporal(),
25687                                 St->getAlignment());
25688     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
25689                                 St->getPointerInfo().getWithOffset(4),
25690                                 St->isVolatile(),
25691                                 St->isNonTemporal(),
25692                                 MinAlign(St->getAlignment(), 4));
25693     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
25694   }
25695
25696   // This is similar to the above case, but here we handle a scalar 64-bit
25697   // integer store that is extracted from a vector on a 32-bit target.
25698   // If we have SSE2, then we can treat it like a floating-point double
25699   // to get past legalization. The execution dependencies fixup pass will
25700   // choose the optimal machine instruction for the store if this really is
25701   // an integer or v2f32 rather than an f64.
25702   if (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit() &&
25703       St->getOperand(1).getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
25704     SDValue OldExtract = St->getOperand(1);
25705     SDValue ExtOp0 = OldExtract.getOperand(0);
25706     unsigned VecSize = ExtOp0.getValueSizeInBits();
25707     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, VecSize / 64);
25708     SDValue BitCast = DAG.getBitcast(VecVT, ExtOp0);
25709     SDValue NewExtract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
25710                                      BitCast, OldExtract.getOperand(1));
25711     return DAG.getStore(St->getChain(), dl, NewExtract, St->getBasePtr(),
25712                         St->getPointerInfo(), St->isVolatile(),
25713                         St->isNonTemporal(), St->getAlignment());
25714   }
25715
25716   return SDValue();
25717 }
25718
25719 /// Return 'true' if this vector operation is "horizontal"
25720 /// and return the operands for the horizontal operation in LHS and RHS.  A
25721 /// horizontal operation performs the binary operation on successive elements
25722 /// of its first operand, then on successive elements of its second operand,
25723 /// returning the resulting values in a vector.  For example, if
25724 ///   A = < float a0, float a1, float a2, float a3 >
25725 /// and
25726 ///   B = < float b0, float b1, float b2, float b3 >
25727 /// then the result of doing a horizontal operation on A and B is
25728 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
25729 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
25730 /// A horizontal-op B, for some already available A and B, and if so then LHS is
25731 /// set to A, RHS to B, and the routine returns 'true'.
25732 /// Note that the binary operation should have the property that if one of the
25733 /// operands is UNDEF then the result is UNDEF.
25734 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
25735   // Look for the following pattern: if
25736   //   A = < float a0, float a1, float a2, float a3 >
25737   //   B = < float b0, float b1, float b2, float b3 >
25738   // and
25739   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
25740   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
25741   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
25742   // which is A horizontal-op B.
25743
25744   // At least one of the operands should be a vector shuffle.
25745   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
25746       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
25747     return false;
25748
25749   MVT VT = LHS.getSimpleValueType();
25750
25751   assert((VT.is128BitVector() || VT.is256BitVector()) &&
25752          "Unsupported vector type for horizontal add/sub");
25753
25754   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
25755   // operate independently on 128-bit lanes.
25756   unsigned NumElts = VT.getVectorNumElements();
25757   unsigned NumLanes = VT.getSizeInBits()/128;
25758   unsigned NumLaneElts = NumElts / NumLanes;
25759   assert((NumLaneElts % 2 == 0) &&
25760          "Vector type should have an even number of elements in each lane");
25761   unsigned HalfLaneElts = NumLaneElts/2;
25762
25763   // View LHS in the form
25764   //   LHS = VECTOR_SHUFFLE A, B, LMask
25765   // If LHS is not a shuffle then pretend it is the shuffle
25766   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
25767   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
25768   // type VT.
25769   SDValue A, B;
25770   SmallVector<int, 16> LMask(NumElts);
25771   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
25772     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
25773       A = LHS.getOperand(0);
25774     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
25775       B = LHS.getOperand(1);
25776     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
25777     std::copy(Mask.begin(), Mask.end(), LMask.begin());
25778   } else {
25779     if (LHS.getOpcode() != ISD::UNDEF)
25780       A = LHS;
25781     for (unsigned i = 0; i != NumElts; ++i)
25782       LMask[i] = i;
25783   }
25784
25785   // Likewise, view RHS in the form
25786   //   RHS = VECTOR_SHUFFLE C, D, RMask
25787   SDValue C, D;
25788   SmallVector<int, 16> RMask(NumElts);
25789   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
25790     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
25791       C = RHS.getOperand(0);
25792     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
25793       D = RHS.getOperand(1);
25794     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
25795     std::copy(Mask.begin(), Mask.end(), RMask.begin());
25796   } else {
25797     if (RHS.getOpcode() != ISD::UNDEF)
25798       C = RHS;
25799     for (unsigned i = 0; i != NumElts; ++i)
25800       RMask[i] = i;
25801   }
25802
25803   // Check that the shuffles are both shuffling the same vectors.
25804   if (!(A == C && B == D) && !(A == D && B == C))
25805     return false;
25806
25807   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
25808   if (!A.getNode() && !B.getNode())
25809     return false;
25810
25811   // If A and B occur in reverse order in RHS, then "swap" them (which means
25812   // rewriting the mask).
25813   if (A != C)
25814     ShuffleVectorSDNode::commuteMask(RMask);
25815
25816   // At this point LHS and RHS are equivalent to
25817   //   LHS = VECTOR_SHUFFLE A, B, LMask
25818   //   RHS = VECTOR_SHUFFLE A, B, RMask
25819   // Check that the masks correspond to performing a horizontal operation.
25820   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
25821     for (unsigned i = 0; i != NumLaneElts; ++i) {
25822       int LIdx = LMask[i+l], RIdx = RMask[i+l];
25823
25824       // Ignore any UNDEF components.
25825       if (LIdx < 0 || RIdx < 0 ||
25826           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
25827           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
25828         continue;
25829
25830       // Check that successive elements are being operated on.  If not, this is
25831       // not a horizontal operation.
25832       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
25833       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
25834       if (!(LIdx == Index && RIdx == Index + 1) &&
25835           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
25836         return false;
25837     }
25838   }
25839
25840   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
25841   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
25842   return true;
25843 }
25844
25845 /// Do target-specific dag combines on floating point adds.
25846 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
25847                                   const X86Subtarget *Subtarget) {
25848   EVT VT = N->getValueType(0);
25849   SDValue LHS = N->getOperand(0);
25850   SDValue RHS = N->getOperand(1);
25851
25852   // Try to synthesize horizontal adds from adds of shuffles.
25853   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
25854        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
25855       isHorizontalBinOp(LHS, RHS, true))
25856     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
25857   return SDValue();
25858 }
25859
25860 /// Do target-specific dag combines on floating point subs.
25861 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
25862                                   const X86Subtarget *Subtarget) {
25863   EVT VT = N->getValueType(0);
25864   SDValue LHS = N->getOperand(0);
25865   SDValue RHS = N->getOperand(1);
25866
25867   // Try to synthesize horizontal subs from subs of shuffles.
25868   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
25869        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
25870       isHorizontalBinOp(LHS, RHS, false))
25871     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
25872   return SDValue();
25873 }
25874
25875 /// Do target-specific dag combines on X86ISD::FOR and X86ISD::FXOR nodes.
25876 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG,
25877                                  const X86Subtarget *Subtarget) {
25878   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
25879
25880   // F[X]OR(0.0, x) -> x
25881   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
25882     if (C->getValueAPF().isPosZero())
25883       return N->getOperand(1);
25884
25885   // F[X]OR(x, 0.0) -> x
25886   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
25887     if (C->getValueAPF().isPosZero())
25888       return N->getOperand(0);
25889
25890   EVT VT = N->getValueType(0);
25891   if (VT.is512BitVector() && !Subtarget->hasDQI()) {
25892     SDLoc dl(N);
25893     MVT IntScalar = MVT::getIntegerVT(VT.getScalarSizeInBits());
25894     MVT IntVT = MVT::getVectorVT(IntScalar, VT.getVectorNumElements());
25895
25896     SDValue Op0 = DAG.getNode(ISD::BITCAST, dl, IntVT, N->getOperand(0));
25897     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, IntVT, N->getOperand(1));
25898     unsigned IntOpcode = (N->getOpcode() == X86ISD::FOR) ? ISD::OR : ISD::XOR;
25899     SDValue IntOp = DAG.getNode(IntOpcode, dl, IntVT, Op0, Op1);
25900     return  DAG.getNode(ISD::BITCAST, dl, VT, IntOp);
25901   }
25902   return SDValue();
25903 }
25904
25905 /// Do target-specific dag combines on X86ISD::FMIN and X86ISD::FMAX nodes.
25906 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
25907   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
25908
25909   // Only perform optimizations if UnsafeMath is used.
25910   if (!DAG.getTarget().Options.UnsafeFPMath)
25911     return SDValue();
25912
25913   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
25914   // into FMINC and FMAXC, which are Commutative operations.
25915   unsigned NewOp = 0;
25916   switch (N->getOpcode()) {
25917     default: llvm_unreachable("unknown opcode");
25918     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
25919     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
25920   }
25921
25922   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
25923                      N->getOperand(0), N->getOperand(1));
25924 }
25925
25926 /// Do target-specific dag combines on X86ISD::FAND nodes.
25927 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
25928   // FAND(0.0, x) -> 0.0
25929   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
25930     if (C->getValueAPF().isPosZero())
25931       return N->getOperand(0);
25932
25933   // FAND(x, 0.0) -> 0.0
25934   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
25935     if (C->getValueAPF().isPosZero())
25936       return N->getOperand(1);
25937
25938   return SDValue();
25939 }
25940
25941 /// Do target-specific dag combines on X86ISD::FANDN nodes
25942 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
25943   // FANDN(0.0, x) -> x
25944   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
25945     if (C->getValueAPF().isPosZero())
25946       return N->getOperand(1);
25947
25948   // FANDN(x, 0.0) -> 0.0
25949   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
25950     if (C->getValueAPF().isPosZero())
25951       return N->getOperand(1);
25952
25953   return SDValue();
25954 }
25955
25956 static SDValue PerformBTCombine(SDNode *N,
25957                                 SelectionDAG &DAG,
25958                                 TargetLowering::DAGCombinerInfo &DCI) {
25959   // BT ignores high bits in the bit index operand.
25960   SDValue Op1 = N->getOperand(1);
25961   if (Op1.hasOneUse()) {
25962     unsigned BitWidth = Op1.getValueSizeInBits();
25963     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
25964     APInt KnownZero, KnownOne;
25965     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
25966                                           !DCI.isBeforeLegalizeOps());
25967     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25968     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
25969         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
25970       DCI.CommitTargetLoweringOpt(TLO);
25971   }
25972   return SDValue();
25973 }
25974
25975 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
25976   SDValue Op = N->getOperand(0);
25977   if (Op.getOpcode() == ISD::BITCAST)
25978     Op = Op.getOperand(0);
25979   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
25980   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
25981       VT.getVectorElementType().getSizeInBits() ==
25982       OpVT.getVectorElementType().getSizeInBits()) {
25983     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
25984   }
25985   return SDValue();
25986 }
25987
25988 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
25989                                                const X86Subtarget *Subtarget) {
25990   EVT VT = N->getValueType(0);
25991   if (!VT.isVector())
25992     return SDValue();
25993
25994   SDValue N0 = N->getOperand(0);
25995   SDValue N1 = N->getOperand(1);
25996   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
25997   SDLoc dl(N);
25998
25999   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
26000   // both SSE and AVX2 since there is no sign-extended shift right
26001   // operation on a vector with 64-bit elements.
26002   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
26003   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
26004   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
26005       N0.getOpcode() == ISD::SIGN_EXTEND)) {
26006     SDValue N00 = N0.getOperand(0);
26007
26008     // EXTLOAD has a better solution on AVX2,
26009     // it may be replaced with X86ISD::VSEXT node.
26010     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
26011       if (!ISD::isNormalLoad(N00.getNode()))
26012         return SDValue();
26013
26014     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
26015         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
26016                                   N00, N1);
26017       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
26018     }
26019   }
26020   return SDValue();
26021 }
26022
26023 /// sext(add_nsw(x, C)) --> add(sext(x), C_sext)
26024 /// Promoting a sign extension ahead of an 'add nsw' exposes opportunities
26025 /// to combine math ops, use an LEA, or use a complex addressing mode. This can
26026 /// eliminate extend, add, and shift instructions.
26027 static SDValue promoteSextBeforeAddNSW(SDNode *Sext, SelectionDAG &DAG,
26028                                        const X86Subtarget *Subtarget) {
26029   // TODO: This should be valid for other integer types.
26030   EVT VT = Sext->getValueType(0);
26031   if (VT != MVT::i64)
26032     return SDValue();
26033
26034   // We need an 'add nsw' feeding into the 'sext'.
26035   SDValue Add = Sext->getOperand(0);
26036   if (Add.getOpcode() != ISD::ADD || !Add->getFlags()->hasNoSignedWrap())
26037     return SDValue();
26038
26039   // Having a constant operand to the 'add' ensures that we are not increasing
26040   // the instruction count because the constant is extended for free below.
26041   // A constant operand can also become the displacement field of an LEA.
26042   auto *AddOp1 = dyn_cast<ConstantSDNode>(Add.getOperand(1));
26043   if (!AddOp1)
26044     return SDValue();
26045
26046   // Don't make the 'add' bigger if there's no hope of combining it with some
26047   // other 'add' or 'shl' instruction.
26048   // TODO: It may be profitable to generate simpler LEA instructions in place
26049   // of single 'add' instructions, but the cost model for selecting an LEA
26050   // currently has a high threshold.
26051   bool HasLEAPotential = false;
26052   for (auto *User : Sext->uses()) {
26053     if (User->getOpcode() == ISD::ADD || User->getOpcode() == ISD::SHL) {
26054       HasLEAPotential = true;
26055       break;
26056     }
26057   }
26058   if (!HasLEAPotential)
26059     return SDValue();
26060
26061   // Everything looks good, so pull the 'sext' ahead of the 'add'.
26062   int64_t AddConstant = AddOp1->getSExtValue();
26063   SDValue AddOp0 = Add.getOperand(0);
26064   SDValue NewSext = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(Sext), VT, AddOp0);
26065   SDValue NewConstant = DAG.getConstant(AddConstant, SDLoc(Add), VT);
26066
26067   // The wider add is guaranteed to not wrap because both operands are
26068   // sign-extended.
26069   SDNodeFlags Flags;
26070   Flags.setNoSignedWrap(true);
26071   return DAG.getNode(ISD::ADD, SDLoc(Add), VT, NewSext, NewConstant, &Flags);
26072 }
26073
26074 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
26075                                   TargetLowering::DAGCombinerInfo &DCI,
26076                                   const X86Subtarget *Subtarget) {
26077   SDValue N0 = N->getOperand(0);
26078   EVT VT = N->getValueType(0);
26079   EVT SVT = VT.getScalarType();
26080   EVT InVT = N0.getValueType();
26081   EVT InSVT = InVT.getScalarType();
26082   SDLoc DL(N);
26083
26084   // (i8,i32 sext (sdivrem (i8 x, i8 y)) ->
26085   // (i8,i32 (sdivrem_sext_hreg (i8 x, i8 y)
26086   // This exposes the sext to the sdivrem lowering, so that it directly extends
26087   // from AH (which we otherwise need to do contortions to access).
26088   if (N0.getOpcode() == ISD::SDIVREM && N0.getResNo() == 1 &&
26089       InVT == MVT::i8 && VT == MVT::i32) {
26090     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
26091     SDValue R = DAG.getNode(X86ISD::SDIVREM8_SEXT_HREG, DL, NodeTys,
26092                             N0.getOperand(0), N0.getOperand(1));
26093     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
26094     return R.getValue(1);
26095   }
26096
26097   if (!DCI.isBeforeLegalizeOps()) {
26098     if (InVT == MVT::i1) {
26099       SDValue Zero = DAG.getConstant(0, DL, VT);
26100       SDValue AllOnes =
26101         DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL, VT);
26102       return DAG.getNode(ISD::SELECT, DL, VT, N0, AllOnes, Zero);
26103     }
26104     return SDValue();
26105   }
26106
26107   if (VT.isVector() && Subtarget->hasSSE2()) {
26108     auto ExtendVecSize = [&DAG](SDLoc DL, SDValue N, unsigned Size) {
26109       EVT InVT = N.getValueType();
26110       EVT OutVT = EVT::getVectorVT(*DAG.getContext(), InVT.getScalarType(),
26111                                    Size / InVT.getScalarSizeInBits());
26112       SmallVector<SDValue, 8> Opnds(Size / InVT.getSizeInBits(),
26113                                     DAG.getUNDEF(InVT));
26114       Opnds[0] = N;
26115       return DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Opnds);
26116     };
26117
26118     // If target-size is less than 128-bits, extend to a type that would extend
26119     // to 128 bits, extend that and extract the original target vector.
26120     if (VT.getSizeInBits() < 128 && !(128 % VT.getSizeInBits()) &&
26121         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
26122         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
26123       unsigned Scale = 128 / VT.getSizeInBits();
26124       EVT ExVT =
26125           EVT::getVectorVT(*DAG.getContext(), SVT, 128 / SVT.getSizeInBits());
26126       SDValue Ex = ExtendVecSize(DL, N0, Scale * InVT.getSizeInBits());
26127       SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, ExVT, Ex);
26128       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, SExt,
26129                          DAG.getIntPtrConstant(0, DL));
26130     }
26131
26132     // If target-size is 128-bits, then convert to ISD::SIGN_EXTEND_VECTOR_INREG
26133     // which ensures lowering to X86ISD::VSEXT (pmovsx*).
26134     if (VT.getSizeInBits() == 128 &&
26135         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
26136         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
26137       SDValue ExOp = ExtendVecSize(DL, N0, 128);
26138       return DAG.getSignExtendVectorInReg(ExOp, DL, VT);
26139     }
26140
26141     // On pre-AVX2 targets, split into 128-bit nodes of
26142     // ISD::SIGN_EXTEND_VECTOR_INREG.
26143     if (!Subtarget->hasInt256() && !(VT.getSizeInBits() % 128) &&
26144         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
26145         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
26146       unsigned NumVecs = VT.getSizeInBits() / 128;
26147       unsigned NumSubElts = 128 / SVT.getSizeInBits();
26148       EVT SubVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumSubElts);
26149       EVT InSubVT = EVT::getVectorVT(*DAG.getContext(), InSVT, NumSubElts);
26150
26151       SmallVector<SDValue, 8> Opnds;
26152       for (unsigned i = 0, Offset = 0; i != NumVecs;
26153            ++i, Offset += NumSubElts) {
26154         SDValue SrcVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InSubVT, N0,
26155                                      DAG.getIntPtrConstant(Offset, DL));
26156         SrcVec = ExtendVecSize(DL, SrcVec, 128);
26157         SrcVec = DAG.getSignExtendVectorInReg(SrcVec, DL, SubVT);
26158         Opnds.push_back(SrcVec);
26159       }
26160       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Opnds);
26161     }
26162   }
26163
26164   if (Subtarget->hasAVX() && VT.is256BitVector())
26165     if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
26166       return R;
26167
26168   if (SDValue NewAdd = promoteSextBeforeAddNSW(N, DAG, Subtarget))
26169     return NewAdd;
26170
26171   return SDValue();
26172 }
26173
26174 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
26175                                  const X86Subtarget* Subtarget) {
26176   SDLoc dl(N);
26177   EVT VT = N->getValueType(0);
26178
26179   // Let legalize expand this if it isn't a legal type yet.
26180   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
26181     return SDValue();
26182
26183   EVT ScalarVT = VT.getScalarType();
26184   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
26185       (!Subtarget->hasFMA() && !Subtarget->hasFMA4() &&
26186        !Subtarget->hasAVX512()))
26187     return SDValue();
26188
26189   SDValue A = N->getOperand(0);
26190   SDValue B = N->getOperand(1);
26191   SDValue C = N->getOperand(2);
26192
26193   bool NegA = (A.getOpcode() == ISD::FNEG);
26194   bool NegB = (B.getOpcode() == ISD::FNEG);
26195   bool NegC = (C.getOpcode() == ISD::FNEG);
26196
26197   // Negative multiplication when NegA xor NegB
26198   bool NegMul = (NegA != NegB);
26199   if (NegA)
26200     A = A.getOperand(0);
26201   if (NegB)
26202     B = B.getOperand(0);
26203   if (NegC)
26204     C = C.getOperand(0);
26205
26206   unsigned Opcode;
26207   if (!NegMul)
26208     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
26209   else
26210     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
26211
26212   return DAG.getNode(Opcode, dl, VT, A, B, C);
26213 }
26214
26215 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
26216                                   TargetLowering::DAGCombinerInfo &DCI,
26217                                   const X86Subtarget *Subtarget) {
26218   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
26219   //           (and (i32 x86isd::setcc_carry), 1)
26220   // This eliminates the zext. This transformation is necessary because
26221   // ISD::SETCC is always legalized to i8.
26222   SDLoc dl(N);
26223   SDValue N0 = N->getOperand(0);
26224   EVT VT = N->getValueType(0);
26225
26226   if (N0.getOpcode() == ISD::AND &&
26227       N0.hasOneUse() &&
26228       N0.getOperand(0).hasOneUse()) {
26229     SDValue N00 = N0.getOperand(0);
26230     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
26231       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
26232       if (!C || C->getZExtValue() != 1)
26233         return SDValue();
26234       return DAG.getNode(ISD::AND, dl, VT,
26235                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
26236                                      N00.getOperand(0), N00.getOperand(1)),
26237                          DAG.getConstant(1, dl, VT));
26238     }
26239   }
26240
26241   if (N0.getOpcode() == ISD::TRUNCATE &&
26242       N0.hasOneUse() &&
26243       N0.getOperand(0).hasOneUse()) {
26244     SDValue N00 = N0.getOperand(0);
26245     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
26246       return DAG.getNode(ISD::AND, dl, VT,
26247                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
26248                                      N00.getOperand(0), N00.getOperand(1)),
26249                          DAG.getConstant(1, dl, VT));
26250     }
26251   }
26252
26253   if (VT.is256BitVector())
26254     if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
26255       return R;
26256
26257   // (i8,i32 zext (udivrem (i8 x, i8 y)) ->
26258   // (i8,i32 (udivrem_zext_hreg (i8 x, i8 y)
26259   // This exposes the zext to the udivrem lowering, so that it directly extends
26260   // from AH (which we otherwise need to do contortions to access).
26261   if (N0.getOpcode() == ISD::UDIVREM &&
26262       N0.getResNo() == 1 && N0.getValueType() == MVT::i8 &&
26263       (VT == MVT::i32 || VT == MVT::i64)) {
26264     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
26265     SDValue R = DAG.getNode(X86ISD::UDIVREM8_ZEXT_HREG, dl, NodeTys,
26266                             N0.getOperand(0), N0.getOperand(1));
26267     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
26268     return R.getValue(1);
26269   }
26270
26271   return SDValue();
26272 }
26273
26274 // Optimize x == -y --> x+y == 0
26275 //          x != -y --> x+y != 0
26276 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
26277                                       const X86Subtarget* Subtarget) {
26278   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
26279   SDValue LHS = N->getOperand(0);
26280   SDValue RHS = N->getOperand(1);
26281   EVT VT = N->getValueType(0);
26282   SDLoc DL(N);
26283
26284   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
26285     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
26286       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
26287         SDValue addV = DAG.getNode(ISD::ADD, DL, LHS.getValueType(), RHS,
26288                                    LHS.getOperand(1));
26289         return DAG.getSetCC(DL, N->getValueType(0), addV,
26290                             DAG.getConstant(0, DL, addV.getValueType()), CC);
26291       }
26292   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
26293     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
26294       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
26295         SDValue addV = DAG.getNode(ISD::ADD, DL, RHS.getValueType(), LHS,
26296                                    RHS.getOperand(1));
26297         return DAG.getSetCC(DL, N->getValueType(0), addV,
26298                             DAG.getConstant(0, DL, addV.getValueType()), CC);
26299       }
26300
26301   if (VT.getScalarType() == MVT::i1 &&
26302       (CC == ISD::SETNE || CC == ISD::SETEQ || ISD::isSignedIntSetCC(CC))) {
26303     bool IsSEXT0 =
26304         (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
26305         (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
26306     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
26307
26308     if (!IsSEXT0 || !IsVZero1) {
26309       // Swap the operands and update the condition code.
26310       std::swap(LHS, RHS);
26311       CC = ISD::getSetCCSwappedOperands(CC);
26312
26313       IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
26314                 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
26315       IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
26316     }
26317
26318     if (IsSEXT0 && IsVZero1) {
26319       assert(VT == LHS.getOperand(0).getValueType() &&
26320              "Uexpected operand type");
26321       if (CC == ISD::SETGT)
26322         return DAG.getConstant(0, DL, VT);
26323       if (CC == ISD::SETLE)
26324         return DAG.getConstant(1, DL, VT);
26325       if (CC == ISD::SETEQ || CC == ISD::SETGE)
26326         return DAG.getNOT(DL, LHS.getOperand(0), VT);
26327
26328       assert((CC == ISD::SETNE || CC == ISD::SETLT) &&
26329              "Unexpected condition code!");
26330       return LHS.getOperand(0);
26331     }
26332   }
26333
26334   return SDValue();
26335 }
26336
26337 static SDValue PerformBLENDICombine(SDNode *N, SelectionDAG &DAG) {
26338   SDValue V0 = N->getOperand(0);
26339   SDValue V1 = N->getOperand(1);
26340   SDLoc DL(N);
26341   EVT VT = N->getValueType(0);
26342
26343   // Canonicalize a v2f64 blend with a mask of 2 by swapping the vector
26344   // operands and changing the mask to 1. This saves us a bunch of
26345   // pattern-matching possibilities related to scalar math ops in SSE/AVX.
26346   // x86InstrInfo knows how to commute this back after instruction selection
26347   // if it would help register allocation.
26348
26349   // TODO: If optimizing for size or a processor that doesn't suffer from
26350   // partial register update stalls, this should be transformed into a MOVSD
26351   // instruction because a MOVSD is 1-2 bytes smaller than a BLENDPD.
26352
26353   if (VT == MVT::v2f64)
26354     if (auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(2)))
26355       if (Mask->getZExtValue() == 2 && !isShuffleFoldableLoad(V0)) {
26356         SDValue NewMask = DAG.getConstant(1, DL, MVT::i8);
26357         return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V0, NewMask);
26358       }
26359
26360   return SDValue();
26361 }
26362
26363 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
26364 // as "sbb reg,reg", since it can be extended without zext and produces
26365 // an all-ones bit which is more useful than 0/1 in some cases.
26366 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
26367                                MVT VT) {
26368   if (VT == MVT::i8)
26369     return DAG.getNode(ISD::AND, DL, VT,
26370                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
26371                                    DAG.getConstant(X86::COND_B, DL, MVT::i8),
26372                                    EFLAGS),
26373                        DAG.getConstant(1, DL, VT));
26374   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
26375   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
26376                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
26377                                  DAG.getConstant(X86::COND_B, DL, MVT::i8),
26378                                  EFLAGS));
26379 }
26380
26381 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
26382 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
26383                                    TargetLowering::DAGCombinerInfo &DCI,
26384                                    const X86Subtarget *Subtarget) {
26385   SDLoc DL(N);
26386   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
26387   SDValue EFLAGS = N->getOperand(1);
26388
26389   if (CC == X86::COND_A) {
26390     // Try to convert COND_A into COND_B in an attempt to facilitate
26391     // materializing "setb reg".
26392     //
26393     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
26394     // cannot take an immediate as its first operand.
26395     //
26396     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
26397         EFLAGS.getValueType().isInteger() &&
26398         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
26399       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
26400                                    EFLAGS.getNode()->getVTList(),
26401                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
26402       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
26403       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
26404     }
26405   }
26406
26407   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
26408   // a zext and produces an all-ones bit which is more useful than 0/1 in some
26409   // cases.
26410   if (CC == X86::COND_B)
26411     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
26412
26413   if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
26414     SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
26415     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
26416   }
26417
26418   return SDValue();
26419 }
26420
26421 // Optimize branch condition evaluation.
26422 //
26423 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
26424                                     TargetLowering::DAGCombinerInfo &DCI,
26425                                     const X86Subtarget *Subtarget) {
26426   SDLoc DL(N);
26427   SDValue Chain = N->getOperand(0);
26428   SDValue Dest = N->getOperand(1);
26429   SDValue EFLAGS = N->getOperand(3);
26430   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
26431
26432   if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
26433     SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
26434     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
26435                        Flags);
26436   }
26437
26438   return SDValue();
26439 }
26440
26441 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
26442                                                          SelectionDAG &DAG) {
26443   // Take advantage of vector comparisons producing 0 or -1 in each lane to
26444   // optimize away operation when it's from a constant.
26445   //
26446   // The general transformation is:
26447   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
26448   //       AND(VECTOR_CMP(x,y), constant2)
26449   //    constant2 = UNARYOP(constant)
26450
26451   // Early exit if this isn't a vector operation, the operand of the
26452   // unary operation isn't a bitwise AND, or if the sizes of the operations
26453   // aren't the same.
26454   EVT VT = N->getValueType(0);
26455   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
26456       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
26457       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
26458     return SDValue();
26459
26460   // Now check that the other operand of the AND is a constant. We could
26461   // make the transformation for non-constant splats as well, but it's unclear
26462   // that would be a benefit as it would not eliminate any operations, just
26463   // perform one more step in scalar code before moving to the vector unit.
26464   if (BuildVectorSDNode *BV =
26465           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
26466     // Bail out if the vector isn't a constant.
26467     if (!BV->isConstant())
26468       return SDValue();
26469
26470     // Everything checks out. Build up the new and improved node.
26471     SDLoc DL(N);
26472     EVT IntVT = BV->getValueType(0);
26473     // Create a new constant of the appropriate type for the transformed
26474     // DAG.
26475     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
26476     // The AND node needs bitcasts to/from an integer vector type around it.
26477     SDValue MaskConst = DAG.getBitcast(IntVT, SourceConst);
26478     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
26479                                  N->getOperand(0)->getOperand(0), MaskConst);
26480     SDValue Res = DAG.getBitcast(VT, NewAnd);
26481     return Res;
26482   }
26483
26484   return SDValue();
26485 }
26486
26487 static SDValue PerformUINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
26488                                         const X86Subtarget *Subtarget) {
26489   SDValue Op0 = N->getOperand(0);
26490   EVT VT = N->getValueType(0);
26491   EVT InVT = Op0.getValueType();
26492   EVT InSVT = InVT.getScalarType();
26493   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
26494
26495   // UINT_TO_FP(vXi8) -> SINT_TO_FP(ZEXT(vXi8 to vXi32))
26496   // UINT_TO_FP(vXi16) -> SINT_TO_FP(ZEXT(vXi16 to vXi32))
26497   if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
26498     SDLoc dl(N);
26499     EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
26500                                  InVT.getVectorNumElements());
26501     SDValue P = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Op0);
26502
26503     if (TLI.isOperationLegal(ISD::UINT_TO_FP, DstVT))
26504       return DAG.getNode(ISD::UINT_TO_FP, dl, VT, P);
26505
26506     return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
26507   }
26508
26509   return SDValue();
26510 }
26511
26512 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
26513                                         const X86Subtarget *Subtarget) {
26514   // First try to optimize away the conversion entirely when it's
26515   // conditionally from a constant. Vectors only.
26516   if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
26517     return Res;
26518
26519   // Now move on to more general possibilities.
26520   SDValue Op0 = N->getOperand(0);
26521   EVT VT = N->getValueType(0);
26522   EVT InVT = Op0.getValueType();
26523   EVT InSVT = InVT.getScalarType();
26524
26525   // SINT_TO_FP(vXi8) -> SINT_TO_FP(SEXT(vXi8 to vXi32))
26526   // SINT_TO_FP(vXi16) -> SINT_TO_FP(SEXT(vXi16 to vXi32))
26527   if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
26528     SDLoc dl(N);
26529     EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
26530                                  InVT.getVectorNumElements());
26531     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
26532     return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
26533   }
26534
26535   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
26536   // a 32-bit target where SSE doesn't support i64->FP operations.
26537   if (!Subtarget->useSoftFloat() && Op0.getOpcode() == ISD::LOAD) {
26538     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
26539     EVT LdVT = Ld->getValueType(0);
26540
26541     // This transformation is not supported if the result type is f16
26542     if (VT == MVT::f16)
26543       return SDValue();
26544
26545     if (!Ld->isVolatile() && !VT.isVector() &&
26546         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
26547         !Subtarget->is64Bit() && LdVT == MVT::i64) {
26548       SDValue FILDChain = Subtarget->getTargetLowering()->BuildFILD(
26549           SDValue(N, 0), LdVT, Ld->getChain(), Op0, DAG);
26550       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
26551       return FILDChain;
26552     }
26553   }
26554   return SDValue();
26555 }
26556
26557 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
26558 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
26559                                  X86TargetLowering::DAGCombinerInfo &DCI) {
26560   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
26561   // the result is either zero or one (depending on the input carry bit).
26562   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
26563   if (X86::isZeroNode(N->getOperand(0)) &&
26564       X86::isZeroNode(N->getOperand(1)) &&
26565       // We don't have a good way to replace an EFLAGS use, so only do this when
26566       // dead right now.
26567       SDValue(N, 1).use_empty()) {
26568     SDLoc DL(N);
26569     EVT VT = N->getValueType(0);
26570     SDValue CarryOut = DAG.getConstant(0, DL, N->getValueType(1));
26571     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
26572                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
26573                                            DAG.getConstant(X86::COND_B, DL,
26574                                                            MVT::i8),
26575                                            N->getOperand(2)),
26576                                DAG.getConstant(1, DL, VT));
26577     return DCI.CombineTo(N, Res1, CarryOut);
26578   }
26579
26580   return SDValue();
26581 }
26582
26583 // fold (add Y, (sete  X, 0)) -> adc  0, Y
26584 //      (add Y, (setne X, 0)) -> sbb -1, Y
26585 //      (sub (sete  X, 0), Y) -> sbb  0, Y
26586 //      (sub (setne X, 0), Y) -> adc -1, Y
26587 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
26588   SDLoc DL(N);
26589
26590   // Look through ZExts.
26591   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
26592   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
26593     return SDValue();
26594
26595   SDValue SetCC = Ext.getOperand(0);
26596   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
26597     return SDValue();
26598
26599   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
26600   if (CC != X86::COND_E && CC != X86::COND_NE)
26601     return SDValue();
26602
26603   SDValue Cmp = SetCC.getOperand(1);
26604   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
26605       !X86::isZeroNode(Cmp.getOperand(1)) ||
26606       !Cmp.getOperand(0).getValueType().isInteger())
26607     return SDValue();
26608
26609   SDValue CmpOp0 = Cmp.getOperand(0);
26610   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
26611                                DAG.getConstant(1, DL, CmpOp0.getValueType()));
26612
26613   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
26614   if (CC == X86::COND_NE)
26615     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
26616                        DL, OtherVal.getValueType(), OtherVal,
26617                        DAG.getConstant(-1ULL, DL, OtherVal.getValueType()),
26618                        NewCmp);
26619   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
26620                      DL, OtherVal.getValueType(), OtherVal,
26621                      DAG.getConstant(0, DL, OtherVal.getValueType()), NewCmp);
26622 }
26623
26624 /// PerformADDCombine - Do target-specific dag combines on integer adds.
26625 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
26626                                  const X86Subtarget *Subtarget) {
26627   EVT VT = N->getValueType(0);
26628   SDValue Op0 = N->getOperand(0);
26629   SDValue Op1 = N->getOperand(1);
26630
26631   // Try to synthesize horizontal adds from adds of shuffles.
26632   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
26633        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
26634       isHorizontalBinOp(Op0, Op1, true))
26635     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
26636
26637   return OptimizeConditionalInDecrement(N, DAG);
26638 }
26639
26640 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
26641                                  const X86Subtarget *Subtarget) {
26642   SDValue Op0 = N->getOperand(0);
26643   SDValue Op1 = N->getOperand(1);
26644
26645   // X86 can't encode an immediate LHS of a sub. See if we can push the
26646   // negation into a preceding instruction.
26647   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
26648     // If the RHS of the sub is a XOR with one use and a constant, invert the
26649     // immediate. Then add one to the LHS of the sub so we can turn
26650     // X-Y -> X+~Y+1, saving one register.
26651     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
26652         isa<ConstantSDNode>(Op1.getOperand(1))) {
26653       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
26654       EVT VT = Op0.getValueType();
26655       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
26656                                    Op1.getOperand(0),
26657                                    DAG.getConstant(~XorC, SDLoc(Op1), VT));
26658       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
26659                          DAG.getConstant(C->getAPIntValue() + 1, SDLoc(N), VT));
26660     }
26661   }
26662
26663   // Try to synthesize horizontal adds from adds of shuffles.
26664   EVT VT = N->getValueType(0);
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::HSUB, SDLoc(N), VT, Op0, Op1);
26669
26670   return OptimizeConditionalInDecrement(N, DAG);
26671 }
26672
26673 /// performVZEXTCombine - Performs build vector combines
26674 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
26675                                    TargetLowering::DAGCombinerInfo &DCI,
26676                                    const X86Subtarget *Subtarget) {
26677   SDLoc DL(N);
26678   MVT VT = N->getSimpleValueType(0);
26679   SDValue Op = N->getOperand(0);
26680   MVT OpVT = Op.getSimpleValueType();
26681   MVT OpEltVT = OpVT.getVectorElementType();
26682   unsigned InputBits = OpEltVT.getSizeInBits() * VT.getVectorNumElements();
26683
26684   // (vzext (bitcast (vzext (x)) -> (vzext x)
26685   SDValue V = Op;
26686   while (V.getOpcode() == ISD::BITCAST)
26687     V = V.getOperand(0);
26688
26689   if (V != Op && V.getOpcode() == X86ISD::VZEXT) {
26690     MVT InnerVT = V.getSimpleValueType();
26691     MVT InnerEltVT = InnerVT.getVectorElementType();
26692
26693     // If the element sizes match exactly, we can just do one larger vzext. This
26694     // is always an exact type match as vzext operates on integer types.
26695     if (OpEltVT == InnerEltVT) {
26696       assert(OpVT == InnerVT && "Types must match for vzext!");
26697       return DAG.getNode(X86ISD::VZEXT, DL, VT, V.getOperand(0));
26698     }
26699
26700     // The only other way we can combine them is if only a single element of the
26701     // inner vzext is used in the input to the outer vzext.
26702     if (InnerEltVT.getSizeInBits() < InputBits)
26703       return SDValue();
26704
26705     // In this case, the inner vzext is completely dead because we're going to
26706     // only look at bits inside of the low element. Just do the outer vzext on
26707     // a bitcast of the input to the inner.
26708     return DAG.getNode(X86ISD::VZEXT, DL, VT, DAG.getBitcast(OpVT, V));
26709   }
26710
26711   // Check if we can bypass extracting and re-inserting an element of an input
26712   // vector. Essentially:
26713   // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
26714   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR &&
26715       V.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
26716       V.getOperand(0).getSimpleValueType().getSizeInBits() == InputBits) {
26717     SDValue ExtractedV = V.getOperand(0);
26718     SDValue OrigV = ExtractedV.getOperand(0);
26719     if (auto *ExtractIdx = dyn_cast<ConstantSDNode>(ExtractedV.getOperand(1)))
26720       if (ExtractIdx->getZExtValue() == 0) {
26721         MVT OrigVT = OrigV.getSimpleValueType();
26722         // Extract a subvector if necessary...
26723         if (OrigVT.getSizeInBits() > OpVT.getSizeInBits()) {
26724           int Ratio = OrigVT.getSizeInBits() / OpVT.getSizeInBits();
26725           OrigVT = MVT::getVectorVT(OrigVT.getVectorElementType(),
26726                                     OrigVT.getVectorNumElements() / Ratio);
26727           OrigV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigVT, OrigV,
26728                               DAG.getIntPtrConstant(0, DL));
26729         }
26730         Op = DAG.getBitcast(OpVT, OrigV);
26731         return DAG.getNode(X86ISD::VZEXT, DL, VT, Op);
26732       }
26733   }
26734
26735   return SDValue();
26736 }
26737
26738 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
26739                                              DAGCombinerInfo &DCI) const {
26740   SelectionDAG &DAG = DCI.DAG;
26741   switch (N->getOpcode()) {
26742   default: break;
26743   case ISD::EXTRACT_VECTOR_ELT:
26744     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
26745   case ISD::VSELECT:
26746   case ISD::SELECT:
26747   case X86ISD::SHRUNKBLEND:
26748     return PerformSELECTCombine(N, DAG, DCI, Subtarget);
26749   case ISD::BITCAST:        return PerformBITCASTCombine(N, DAG, Subtarget);
26750   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
26751   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
26752   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
26753   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
26754   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
26755   case ISD::SHL:
26756   case ISD::SRA:
26757   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
26758   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
26759   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
26760   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
26761   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
26762   case ISD::MLOAD:          return PerformMLOADCombine(N, DAG, DCI, Subtarget);
26763   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
26764   case ISD::MSTORE:         return PerformMSTORECombine(N, DAG, Subtarget);
26765   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, Subtarget);
26766   case ISD::UINT_TO_FP:     return PerformUINT_TO_FPCombine(N, DAG, Subtarget);
26767   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
26768   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
26769   case X86ISD::FXOR:
26770   case X86ISD::FOR:         return PerformFORCombine(N, DAG, Subtarget);
26771   case X86ISD::FMIN:
26772   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
26773   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
26774   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
26775   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
26776   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
26777   case ISD::ANY_EXTEND:
26778   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
26779   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
26780   case ISD::SIGN_EXTEND_INREG:
26781     return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
26782   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
26783   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
26784   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
26785   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
26786   case X86ISD::SHUFP:       // Handle all target specific shuffles
26787   case X86ISD::PALIGNR:
26788   case X86ISD::UNPCKH:
26789   case X86ISD::UNPCKL:
26790   case X86ISD::MOVHLPS:
26791   case X86ISD::MOVLHPS:
26792   case X86ISD::PSHUFB:
26793   case X86ISD::PSHUFD:
26794   case X86ISD::PSHUFHW:
26795   case X86ISD::PSHUFLW:
26796   case X86ISD::MOVSS:
26797   case X86ISD::MOVSD:
26798   case X86ISD::VPERMILPI:
26799   case X86ISD::VPERM2X128:
26800   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
26801   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
26802   case X86ISD::BLENDI:    return PerformBLENDICombine(N, DAG);
26803   }
26804
26805   return SDValue();
26806 }
26807
26808 /// isTypeDesirableForOp - Return true if the target has native support for
26809 /// the specified value type and it is 'desirable' to use the type for the
26810 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
26811 /// instruction encodings are longer and some i16 instructions are slow.
26812 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
26813   if (!isTypeLegal(VT))
26814     return false;
26815   if (VT != MVT::i16)
26816     return true;
26817
26818   switch (Opc) {
26819   default:
26820     return true;
26821   case ISD::LOAD:
26822   case ISD::SIGN_EXTEND:
26823   case ISD::ZERO_EXTEND:
26824   case ISD::ANY_EXTEND:
26825   case ISD::SHL:
26826   case ISD::SRL:
26827   case ISD::SUB:
26828   case ISD::ADD:
26829   case ISD::MUL:
26830   case ISD::AND:
26831   case ISD::OR:
26832   case ISD::XOR:
26833     return false;
26834   }
26835 }
26836
26837 /// IsDesirableToPromoteOp - This method query the target whether it is
26838 /// beneficial for dag combiner to promote the specified node. If true, it
26839 /// should return the desired promotion type by reference.
26840 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
26841   EVT VT = Op.getValueType();
26842   if (VT != MVT::i16)
26843     return false;
26844
26845   bool Promote = false;
26846   bool Commute = false;
26847   switch (Op.getOpcode()) {
26848   default: break;
26849   case ISD::LOAD: {
26850     LoadSDNode *LD = cast<LoadSDNode>(Op);
26851     // If the non-extending load has a single use and it's not live out, then it
26852     // might be folded.
26853     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
26854                                                      Op.hasOneUse()*/) {
26855       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
26856              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
26857         // The only case where we'd want to promote LOAD (rather then it being
26858         // promoted as an operand is when it's only use is liveout.
26859         if (UI->getOpcode() != ISD::CopyToReg)
26860           return false;
26861       }
26862     }
26863     Promote = true;
26864     break;
26865   }
26866   case ISD::SIGN_EXTEND:
26867   case ISD::ZERO_EXTEND:
26868   case ISD::ANY_EXTEND:
26869     Promote = true;
26870     break;
26871   case ISD::SHL:
26872   case ISD::SRL: {
26873     SDValue N0 = Op.getOperand(0);
26874     // Look out for (store (shl (load), x)).
26875     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
26876       return false;
26877     Promote = true;
26878     break;
26879   }
26880   case ISD::ADD:
26881   case ISD::MUL:
26882   case ISD::AND:
26883   case ISD::OR:
26884   case ISD::XOR:
26885     Commute = true;
26886     // fallthrough
26887   case ISD::SUB: {
26888     SDValue N0 = Op.getOperand(0);
26889     SDValue N1 = Op.getOperand(1);
26890     if (!Commute && MayFoldLoad(N1))
26891       return false;
26892     // Avoid disabling potential load folding opportunities.
26893     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
26894       return false;
26895     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
26896       return false;
26897     Promote = true;
26898   }
26899   }
26900
26901   PVT = MVT::i32;
26902   return Promote;
26903 }
26904
26905 //===----------------------------------------------------------------------===//
26906 //                           X86 Inline Assembly Support
26907 //===----------------------------------------------------------------------===//
26908
26909 // Helper to match a string separated by whitespace.
26910 static bool matchAsm(StringRef S, ArrayRef<const char *> Pieces) {
26911   S = S.substr(S.find_first_not_of(" \t")); // Skip leading whitespace.
26912
26913   for (StringRef Piece : Pieces) {
26914     if (!S.startswith(Piece)) // Check if the piece matches.
26915       return false;
26916
26917     S = S.substr(Piece.size());
26918     StringRef::size_type Pos = S.find_first_not_of(" \t");
26919     if (Pos == 0) // We matched a prefix.
26920       return false;
26921
26922     S = S.substr(Pos);
26923   }
26924
26925   return S.empty();
26926 }
26927
26928 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
26929
26930   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
26931     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
26932         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
26933         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
26934
26935       if (AsmPieces.size() == 3)
26936         return true;
26937       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
26938         return true;
26939     }
26940   }
26941   return false;
26942 }
26943
26944 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
26945   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
26946
26947   std::string AsmStr = IA->getAsmString();
26948
26949   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
26950   if (!Ty || Ty->getBitWidth() % 16 != 0)
26951     return false;
26952
26953   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
26954   SmallVector<StringRef, 4> AsmPieces;
26955   SplitString(AsmStr, AsmPieces, ";\n");
26956
26957   switch (AsmPieces.size()) {
26958   default: return false;
26959   case 1:
26960     // FIXME: this should verify that we are targeting a 486 or better.  If not,
26961     // we will turn this bswap into something that will be lowered to logical
26962     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
26963     // lower so don't worry about this.
26964     // bswap $0
26965     if (matchAsm(AsmPieces[0], {"bswap", "$0"}) ||
26966         matchAsm(AsmPieces[0], {"bswapl", "$0"}) ||
26967         matchAsm(AsmPieces[0], {"bswapq", "$0"}) ||
26968         matchAsm(AsmPieces[0], {"bswap", "${0:q}"}) ||
26969         matchAsm(AsmPieces[0], {"bswapl", "${0:q}"}) ||
26970         matchAsm(AsmPieces[0], {"bswapq", "${0:q}"})) {
26971       // No need to check constraints, nothing other than the equivalent of
26972       // "=r,0" would be valid here.
26973       return IntrinsicLowering::LowerToByteSwap(CI);
26974     }
26975
26976     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
26977     if (CI->getType()->isIntegerTy(16) &&
26978         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
26979         (matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) ||
26980          matchAsm(AsmPieces[0], {"rolw", "$$8,", "${0:w}"}))) {
26981       AsmPieces.clear();
26982       StringRef ConstraintsStr = IA->getConstraintString();
26983       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
26984       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
26985       if (clobbersFlagRegisters(AsmPieces))
26986         return IntrinsicLowering::LowerToByteSwap(CI);
26987     }
26988     break;
26989   case 3:
26990     if (CI->getType()->isIntegerTy(32) &&
26991         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
26992         matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) &&
26993         matchAsm(AsmPieces[1], {"rorl", "$$16,", "$0"}) &&
26994         matchAsm(AsmPieces[2], {"rorw", "$$8,", "${0:w}"})) {
26995       AsmPieces.clear();
26996       StringRef ConstraintsStr = IA->getConstraintString();
26997       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
26998       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
26999       if (clobbersFlagRegisters(AsmPieces))
27000         return IntrinsicLowering::LowerToByteSwap(CI);
27001     }
27002
27003     if (CI->getType()->isIntegerTy(64)) {
27004       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
27005       if (Constraints.size() >= 2 &&
27006           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
27007           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
27008         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
27009         if (matchAsm(AsmPieces[0], {"bswap", "%eax"}) &&
27010             matchAsm(AsmPieces[1], {"bswap", "%edx"}) &&
27011             matchAsm(AsmPieces[2], {"xchgl", "%eax,", "%edx"}))
27012           return IntrinsicLowering::LowerToByteSwap(CI);
27013       }
27014     }
27015     break;
27016   }
27017   return false;
27018 }
27019
27020 /// getConstraintType - Given a constraint letter, return the type of
27021 /// constraint it is for this target.
27022 X86TargetLowering::ConstraintType
27023 X86TargetLowering::getConstraintType(StringRef Constraint) const {
27024   if (Constraint.size() == 1) {
27025     switch (Constraint[0]) {
27026     case 'R':
27027     case 'q':
27028     case 'Q':
27029     case 'f':
27030     case 't':
27031     case 'u':
27032     case 'y':
27033     case 'x':
27034     case 'Y':
27035     case 'l':
27036       return C_RegisterClass;
27037     case 'a':
27038     case 'b':
27039     case 'c':
27040     case 'd':
27041     case 'S':
27042     case 'D':
27043     case 'A':
27044       return C_Register;
27045     case 'I':
27046     case 'J':
27047     case 'K':
27048     case 'L':
27049     case 'M':
27050     case 'N':
27051     case 'G':
27052     case 'C':
27053     case 'e':
27054     case 'Z':
27055       return C_Other;
27056     default:
27057       break;
27058     }
27059   }
27060   return TargetLowering::getConstraintType(Constraint);
27061 }
27062
27063 /// Examine constraint type and operand type and determine a weight value.
27064 /// This object must already have been set up with the operand type
27065 /// and the current alternative constraint selected.
27066 TargetLowering::ConstraintWeight
27067   X86TargetLowering::getSingleConstraintMatchWeight(
27068     AsmOperandInfo &info, const char *constraint) const {
27069   ConstraintWeight weight = CW_Invalid;
27070   Value *CallOperandVal = info.CallOperandVal;
27071     // If we don't have a value, we can't do a match,
27072     // but allow it at the lowest weight.
27073   if (!CallOperandVal)
27074     return CW_Default;
27075   Type *type = CallOperandVal->getType();
27076   // Look at the constraint type.
27077   switch (*constraint) {
27078   default:
27079     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
27080   case 'R':
27081   case 'q':
27082   case 'Q':
27083   case 'a':
27084   case 'b':
27085   case 'c':
27086   case 'd':
27087   case 'S':
27088   case 'D':
27089   case 'A':
27090     if (CallOperandVal->getType()->isIntegerTy())
27091       weight = CW_SpecificReg;
27092     break;
27093   case 'f':
27094   case 't':
27095   case 'u':
27096     if (type->isFloatingPointTy())
27097       weight = CW_SpecificReg;
27098     break;
27099   case 'y':
27100     if (type->isX86_MMXTy() && Subtarget->hasMMX())
27101       weight = CW_SpecificReg;
27102     break;
27103   case 'x':
27104   case 'Y':
27105     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
27106         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
27107       weight = CW_Register;
27108     break;
27109   case 'I':
27110     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
27111       if (C->getZExtValue() <= 31)
27112         weight = CW_Constant;
27113     }
27114     break;
27115   case 'J':
27116     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
27117       if (C->getZExtValue() <= 63)
27118         weight = CW_Constant;
27119     }
27120     break;
27121   case 'K':
27122     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
27123       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
27124         weight = CW_Constant;
27125     }
27126     break;
27127   case 'L':
27128     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
27129       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
27130         weight = CW_Constant;
27131     }
27132     break;
27133   case 'M':
27134     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
27135       if (C->getZExtValue() <= 3)
27136         weight = CW_Constant;
27137     }
27138     break;
27139   case 'N':
27140     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
27141       if (C->getZExtValue() <= 0xff)
27142         weight = CW_Constant;
27143     }
27144     break;
27145   case 'G':
27146   case 'C':
27147     if (isa<ConstantFP>(CallOperandVal)) {
27148       weight = CW_Constant;
27149     }
27150     break;
27151   case 'e':
27152     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
27153       if ((C->getSExtValue() >= -0x80000000LL) &&
27154           (C->getSExtValue() <= 0x7fffffffLL))
27155         weight = CW_Constant;
27156     }
27157     break;
27158   case 'Z':
27159     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
27160       if (C->getZExtValue() <= 0xffffffff)
27161         weight = CW_Constant;
27162     }
27163     break;
27164   }
27165   return weight;
27166 }
27167
27168 /// LowerXConstraint - try to replace an X constraint, which matches anything,
27169 /// with another that has more specific requirements based on the type of the
27170 /// corresponding operand.
27171 const char *X86TargetLowering::
27172 LowerXConstraint(EVT ConstraintVT) const {
27173   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
27174   // 'f' like normal targets.
27175   if (ConstraintVT.isFloatingPoint()) {
27176     if (Subtarget->hasSSE2())
27177       return "Y";
27178     if (Subtarget->hasSSE1())
27179       return "x";
27180   }
27181
27182   return TargetLowering::LowerXConstraint(ConstraintVT);
27183 }
27184
27185 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
27186 /// vector.  If it is invalid, don't add anything to Ops.
27187 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
27188                                                      std::string &Constraint,
27189                                                      std::vector<SDValue>&Ops,
27190                                                      SelectionDAG &DAG) const {
27191   SDValue Result;
27192
27193   // Only support length 1 constraints for now.
27194   if (Constraint.length() > 1) return;
27195
27196   char ConstraintLetter = Constraint[0];
27197   switch (ConstraintLetter) {
27198   default: break;
27199   case 'I':
27200     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
27201       if (C->getZExtValue() <= 31) {
27202         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
27203                                        Op.getValueType());
27204         break;
27205       }
27206     }
27207     return;
27208   case 'J':
27209     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
27210       if (C->getZExtValue() <= 63) {
27211         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
27212                                        Op.getValueType());
27213         break;
27214       }
27215     }
27216     return;
27217   case 'K':
27218     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
27219       if (isInt<8>(C->getSExtValue())) {
27220         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
27221                                        Op.getValueType());
27222         break;
27223       }
27224     }
27225     return;
27226   case 'L':
27227     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
27228       if (C->getZExtValue() == 0xff || C->getZExtValue() == 0xffff ||
27229           (Subtarget->is64Bit() && C->getZExtValue() == 0xffffffff)) {
27230         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op),
27231                                        Op.getValueType());
27232         break;
27233       }
27234     }
27235     return;
27236   case 'M':
27237     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
27238       if (C->getZExtValue() <= 3) {
27239         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
27240                                        Op.getValueType());
27241         break;
27242       }
27243     }
27244     return;
27245   case 'N':
27246     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
27247       if (C->getZExtValue() <= 255) {
27248         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
27249                                        Op.getValueType());
27250         break;
27251       }
27252     }
27253     return;
27254   case 'O':
27255     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
27256       if (C->getZExtValue() <= 127) {
27257         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
27258                                        Op.getValueType());
27259         break;
27260       }
27261     }
27262     return;
27263   case 'e': {
27264     // 32-bit signed value
27265     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
27266       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
27267                                            C->getSExtValue())) {
27268         // Widen to 64 bits here to get it sign extended.
27269         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op), MVT::i64);
27270         break;
27271       }
27272     // FIXME gcc accepts some relocatable values here too, but only in certain
27273     // memory models; it's complicated.
27274     }
27275     return;
27276   }
27277   case 'Z': {
27278     // 32-bit unsigned value
27279     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
27280       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
27281                                            C->getZExtValue())) {
27282         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
27283                                        Op.getValueType());
27284         break;
27285       }
27286     }
27287     // FIXME gcc accepts some relocatable values here too, but only in certain
27288     // memory models; it's complicated.
27289     return;
27290   }
27291   case 'i': {
27292     // Literal immediates are always ok.
27293     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
27294       // Widen to 64 bits here to get it sign extended.
27295       Result = DAG.getTargetConstant(CST->getSExtValue(), SDLoc(Op), MVT::i64);
27296       break;
27297     }
27298
27299     // In any sort of PIC mode addresses need to be computed at runtime by
27300     // adding in a register or some sort of table lookup.  These can't
27301     // be used as immediates.
27302     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
27303       return;
27304
27305     // If we are in non-pic codegen mode, we allow the address of a global (with
27306     // an optional displacement) to be used with 'i'.
27307     GlobalAddressSDNode *GA = nullptr;
27308     int64_t Offset = 0;
27309
27310     // Match either (GA), (GA+C), (GA+C1+C2), etc.
27311     while (1) {
27312       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
27313         Offset += GA->getOffset();
27314         break;
27315       } else if (Op.getOpcode() == ISD::ADD) {
27316         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
27317           Offset += C->getZExtValue();
27318           Op = Op.getOperand(0);
27319           continue;
27320         }
27321       } else if (Op.getOpcode() == ISD::SUB) {
27322         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
27323           Offset += -C->getZExtValue();
27324           Op = Op.getOperand(0);
27325           continue;
27326         }
27327       }
27328
27329       // Otherwise, this isn't something we can handle, reject it.
27330       return;
27331     }
27332
27333     const GlobalValue *GV = GA->getGlobal();
27334     // If we require an extra load to get this address, as in PIC mode, we
27335     // can't accept it.
27336     if (isGlobalStubReference(
27337             Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
27338       return;
27339
27340     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
27341                                         GA->getValueType(0), Offset);
27342     break;
27343   }
27344   }
27345
27346   if (Result.getNode()) {
27347     Ops.push_back(Result);
27348     return;
27349   }
27350   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
27351 }
27352
27353 std::pair<unsigned, const TargetRegisterClass *>
27354 X86TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
27355                                                 StringRef Constraint,
27356                                                 MVT VT) const {
27357   // First, see if this is a constraint that directly corresponds to an LLVM
27358   // register class.
27359   if (Constraint.size() == 1) {
27360     // GCC Constraint Letters
27361     switch (Constraint[0]) {
27362     default: break;
27363       // TODO: Slight differences here in allocation order and leaving
27364       // RIP in the class. Do they matter any more here than they do
27365       // in the normal allocation?
27366     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
27367       if (Subtarget->is64Bit()) {
27368         if (VT == MVT::i32 || VT == MVT::f32)
27369           return std::make_pair(0U, &X86::GR32RegClass);
27370         if (VT == MVT::i16)
27371           return std::make_pair(0U, &X86::GR16RegClass);
27372         if (VT == MVT::i8 || VT == MVT::i1)
27373           return std::make_pair(0U, &X86::GR8RegClass);
27374         if (VT == MVT::i64 || VT == MVT::f64)
27375           return std::make_pair(0U, &X86::GR64RegClass);
27376         break;
27377       }
27378       // 32-bit fallthrough
27379     case 'Q':   // Q_REGS
27380       if (VT == MVT::i32 || VT == MVT::f32)
27381         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
27382       if (VT == MVT::i16)
27383         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
27384       if (VT == MVT::i8 || VT == MVT::i1)
27385         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
27386       if (VT == MVT::i64)
27387         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
27388       break;
27389     case 'r':   // GENERAL_REGS
27390     case 'l':   // INDEX_REGS
27391       if (VT == MVT::i8 || VT == MVT::i1)
27392         return std::make_pair(0U, &X86::GR8RegClass);
27393       if (VT == MVT::i16)
27394         return std::make_pair(0U, &X86::GR16RegClass);
27395       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
27396         return std::make_pair(0U, &X86::GR32RegClass);
27397       return std::make_pair(0U, &X86::GR64RegClass);
27398     case 'R':   // LEGACY_REGS
27399       if (VT == MVT::i8 || VT == MVT::i1)
27400         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
27401       if (VT == MVT::i16)
27402         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
27403       if (VT == MVT::i32 || !Subtarget->is64Bit())
27404         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
27405       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
27406     case 'f':  // FP Stack registers.
27407       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
27408       // value to the correct fpstack register class.
27409       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
27410         return std::make_pair(0U, &X86::RFP32RegClass);
27411       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
27412         return std::make_pair(0U, &X86::RFP64RegClass);
27413       return std::make_pair(0U, &X86::RFP80RegClass);
27414     case 'y':   // MMX_REGS if MMX allowed.
27415       if (!Subtarget->hasMMX()) break;
27416       return std::make_pair(0U, &X86::VR64RegClass);
27417     case 'Y':   // SSE_REGS if SSE2 allowed
27418       if (!Subtarget->hasSSE2()) break;
27419       // FALL THROUGH.
27420     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
27421       if (!Subtarget->hasSSE1()) break;
27422
27423       switch (VT.SimpleTy) {
27424       default: break;
27425       // Scalar SSE types.
27426       case MVT::f32:
27427       case MVT::i32:
27428         return std::make_pair(0U, &X86::FR32RegClass);
27429       case MVT::f64:
27430       case MVT::i64:
27431         return std::make_pair(0U, &X86::FR64RegClass);
27432       // Vector types.
27433       case MVT::v16i8:
27434       case MVT::v8i16:
27435       case MVT::v4i32:
27436       case MVT::v2i64:
27437       case MVT::v4f32:
27438       case MVT::v2f64:
27439         return std::make_pair(0U, &X86::VR128RegClass);
27440       // AVX types.
27441       case MVT::v32i8:
27442       case MVT::v16i16:
27443       case MVT::v8i32:
27444       case MVT::v4i64:
27445       case MVT::v8f32:
27446       case MVT::v4f64:
27447         return std::make_pair(0U, &X86::VR256RegClass);
27448       case MVT::v8f64:
27449       case MVT::v16f32:
27450       case MVT::v16i32:
27451       case MVT::v8i64:
27452         return std::make_pair(0U, &X86::VR512RegClass);
27453       }
27454       break;
27455     }
27456   }
27457
27458   // Use the default implementation in TargetLowering to convert the register
27459   // constraint into a member of a register class.
27460   std::pair<unsigned, const TargetRegisterClass*> Res;
27461   Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
27462
27463   // Not found as a standard register?
27464   if (!Res.second) {
27465     // Map st(0) -> st(7) -> ST0
27466     if (Constraint.size() == 7 && Constraint[0] == '{' &&
27467         tolower(Constraint[1]) == 's' &&
27468         tolower(Constraint[2]) == 't' &&
27469         Constraint[3] == '(' &&
27470         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
27471         Constraint[5] == ')' &&
27472         Constraint[6] == '}') {
27473
27474       Res.first = X86::FP0+Constraint[4]-'0';
27475       Res.second = &X86::RFP80RegClass;
27476       return Res;
27477     }
27478
27479     // GCC allows "st(0)" to be called just plain "st".
27480     if (StringRef("{st}").equals_lower(Constraint)) {
27481       Res.first = X86::FP0;
27482       Res.second = &X86::RFP80RegClass;
27483       return Res;
27484     }
27485
27486     // flags -> EFLAGS
27487     if (StringRef("{flags}").equals_lower(Constraint)) {
27488       Res.first = X86::EFLAGS;
27489       Res.second = &X86::CCRRegClass;
27490       return Res;
27491     }
27492
27493     // 'A' means EAX + EDX.
27494     if (Constraint == "A") {
27495       Res.first = X86::EAX;
27496       Res.second = &X86::GR32_ADRegClass;
27497       return Res;
27498     }
27499     return Res;
27500   }
27501
27502   // Otherwise, check to see if this is a register class of the wrong value
27503   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
27504   // turn into {ax},{dx}.
27505   // MVT::Other is used to specify clobber names.
27506   if (Res.second->hasType(VT) || VT == MVT::Other)
27507     return Res;   // Correct type already, nothing to do.
27508
27509   // Get a matching integer of the correct size. i.e. "ax" with MVT::32 should
27510   // return "eax". This should even work for things like getting 64bit integer
27511   // registers when given an f64 type.
27512   const TargetRegisterClass *Class = Res.second;
27513   if (Class == &X86::GR8RegClass || Class == &X86::GR16RegClass ||
27514       Class == &X86::GR32RegClass || Class == &X86::GR64RegClass) {
27515     unsigned Size = VT.getSizeInBits();
27516     MVT::SimpleValueType SimpleTy = Size == 1 || Size == 8 ? MVT::i8
27517                                   : Size == 16 ? MVT::i16
27518                                   : Size == 32 ? MVT::i32
27519                                   : Size == 64 ? MVT::i64
27520                                   : MVT::Other;
27521     unsigned DestReg = getX86SubSuperRegisterOrZero(Res.first, SimpleTy);
27522     if (DestReg > 0) {
27523       Res.first = DestReg;
27524       Res.second = SimpleTy == MVT::i8 ? &X86::GR8RegClass
27525                  : SimpleTy == MVT::i16 ? &X86::GR16RegClass
27526                  : SimpleTy == MVT::i32 ? &X86::GR32RegClass
27527                  : &X86::GR64RegClass;
27528       assert(Res.second->contains(Res.first) && "Register in register class");
27529     } else {
27530       // No register found/type mismatch.
27531       Res.first = 0;
27532       Res.second = nullptr;
27533     }
27534   } else if (Class == &X86::FR32RegClass || Class == &X86::FR64RegClass ||
27535              Class == &X86::VR128RegClass || Class == &X86::VR256RegClass ||
27536              Class == &X86::FR32XRegClass || Class == &X86::FR64XRegClass ||
27537              Class == &X86::VR128XRegClass || Class == &X86::VR256XRegClass ||
27538              Class == &X86::VR512RegClass) {
27539     // Handle references to XMM physical registers that got mapped into the
27540     // wrong class.  This can happen with constraints like {xmm0} where the
27541     // target independent register mapper will just pick the first match it can
27542     // find, ignoring the required type.
27543
27544     if (VT == MVT::f32 || VT == MVT::i32)
27545       Res.second = &X86::FR32RegClass;
27546     else if (VT == MVT::f64 || VT == MVT::i64)
27547       Res.second = &X86::FR64RegClass;
27548     else if (X86::VR128RegClass.hasType(VT))
27549       Res.second = &X86::VR128RegClass;
27550     else if (X86::VR256RegClass.hasType(VT))
27551       Res.second = &X86::VR256RegClass;
27552     else if (X86::VR512RegClass.hasType(VT))
27553       Res.second = &X86::VR512RegClass;
27554     else {
27555       // Type mismatch and not a clobber: Return an error;
27556       Res.first = 0;
27557       Res.second = nullptr;
27558     }
27559   }
27560
27561   return Res;
27562 }
27563
27564 int X86TargetLowering::getScalingFactorCost(const DataLayout &DL,
27565                                             const AddrMode &AM, Type *Ty,
27566                                             unsigned AS) const {
27567   // Scaling factors are not free at all.
27568   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
27569   // will take 2 allocations in the out of order engine instead of 1
27570   // for plain addressing mode, i.e. inst (reg1).
27571   // E.g.,
27572   // vaddps (%rsi,%drx), %ymm0, %ymm1
27573   // Requires two allocations (one for the load, one for the computation)
27574   // whereas:
27575   // vaddps (%rsi), %ymm0, %ymm1
27576   // Requires just 1 allocation, i.e., freeing allocations for other operations
27577   // and having less micro operations to execute.
27578   //
27579   // For some X86 architectures, this is even worse because for instance for
27580   // stores, the complex addressing mode forces the instruction to use the
27581   // "load" ports instead of the dedicated "store" port.
27582   // E.g., on Haswell:
27583   // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
27584   // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
27585   if (isLegalAddressingMode(DL, AM, Ty, AS))
27586     // Scale represents reg2 * scale, thus account for 1
27587     // as soon as we use a second register.
27588     return AM.Scale != 0;
27589   return -1;
27590 }
27591
27592 bool X86TargetLowering::isIntDivCheap(EVT VT, AttributeSet Attr) const {
27593   // Integer division on x86 is expensive. However, when aggressively optimizing
27594   // for code size, we prefer to use a div instruction, as it is usually smaller
27595   // than the alternative sequence.
27596   // The exception to this is vector division. Since x86 doesn't have vector
27597   // integer division, leaving the division as-is is a loss even in terms of
27598   // size, because it will have to be scalarized, while the alternative code
27599   // sequence can be performed in vector form.
27600   bool OptSize = Attr.hasAttribute(AttributeSet::FunctionIndex,
27601                                    Attribute::MinSize);
27602   return OptSize && !VT.isVector();
27603 }
27604
27605 void X86TargetLowering::markInRegArguments(SelectionDAG &DAG,
27606        TargetLowering::ArgListTy& Args) const {
27607   // The MCU psABI requires some arguments to be passed in-register.
27608   // For regular calls, the inreg arguments are marked by the front-end.
27609   // However, for compiler generated library calls, we have to patch this
27610   // up here.
27611   if (!Subtarget->isTargetMCU() || !Args.size())
27612     return;
27613
27614   unsigned FreeRegs = 3;
27615   for (auto &Arg : Args) {
27616     // For library functions, we do not expect any fancy types.
27617     unsigned Size = DAG.getDataLayout().getTypeSizeInBits(Arg.Ty);
27618     unsigned SizeInRegs = (Size + 31) / 32;
27619     if (SizeInRegs > 2 || SizeInRegs > FreeRegs)
27620       continue;
27621
27622     Arg.isInReg = true;
27623     FreeRegs -= SizeInRegs;
27624     if (!FreeRegs)
27625       break;
27626   }
27627 }