5a7214f912bcd13b88bd996e9fef7ff5037f48f4
[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   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
203   // are Legal, f80 is custom lowered.
204   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
205   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
206
207   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
208   // this operation.
209   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
210   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
211
212   if (X86ScalarSSEf32) {
213     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
214     // f32 and f64 cases are Legal, f80 case is not
215     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
216   } else {
217     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
218     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
219   }
220
221   // Handle FP_TO_UINT by promoting the destination to a larger signed
222   // conversion.
223   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
224   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
225   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
226
227   if (Subtarget->is64Bit()) {
228     if (!Subtarget->useSoftFloat() && Subtarget->hasAVX512()) {
229       // FP_TO_UINT-i32/i64 is legal for f32/f64, but custom for f80.
230       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
231       setOperationAction(ISD::FP_TO_UINT   , MVT::i64  , Custom);
232     } else {
233       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Promote);
234       setOperationAction(ISD::FP_TO_UINT   , MVT::i64  , Expand);
235     }
236   } else if (!Subtarget->useSoftFloat()) {
237     // Since AVX is a superset of SSE3, only check for SSE here.
238     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
239       // Expand FP_TO_UINT into a select.
240       // FIXME: We would like to use a Custom expander here eventually to do
241       // the optimal thing for SSE vs. the default expansion in the legalizer.
242       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
243     else
244       // With AVX512 we can use vcvts[ds]2usi for f32/f64->i32, f80 is custom.
245       // With SSE3 we can use fisttpll to convert to a signed i64; without
246       // SSE, we're stuck with a fistpll.
247       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
248
249     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
250   }
251
252   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
253   if (!X86ScalarSSEf64) {
254     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
255     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
256     if (Subtarget->is64Bit()) {
257       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
258       // Without SSE, i64->f64 goes through memory.
259       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
260     }
261   }
262
263   // Scalar integer divide and remainder are lowered to use operations that
264   // produce two results, to match the available instructions. This exposes
265   // the two-result form to trivial CSE, which is able to combine x/y and x%y
266   // into a single instruction.
267   //
268   // Scalar integer multiply-high is also lowered to use two-result
269   // operations, to match the available instructions. However, plain multiply
270   // (low) operations are left as Legal, as there are single-result
271   // instructions for this in x86. Using the two-result multiply instructions
272   // when both high and low results are needed must be arranged by dagcombine.
273   for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
274     setOperationAction(ISD::MULHS, VT, Expand);
275     setOperationAction(ISD::MULHU, VT, Expand);
276     setOperationAction(ISD::SDIV, VT, Expand);
277     setOperationAction(ISD::UDIV, VT, Expand);
278     setOperationAction(ISD::SREM, VT, Expand);
279     setOperationAction(ISD::UREM, VT, Expand);
280
281     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
282     setOperationAction(ISD::ADDC, VT, Custom);
283     setOperationAction(ISD::ADDE, VT, Custom);
284     setOperationAction(ISD::SUBC, VT, Custom);
285     setOperationAction(ISD::SUBE, VT, Custom);
286   }
287
288   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
289   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
290   setOperationAction(ISD::BR_CC            , MVT::f32,   Expand);
291   setOperationAction(ISD::BR_CC            , MVT::f64,   Expand);
292   setOperationAction(ISD::BR_CC            , MVT::f80,   Expand);
293   setOperationAction(ISD::BR_CC            , MVT::i8,    Expand);
294   setOperationAction(ISD::BR_CC            , MVT::i16,   Expand);
295   setOperationAction(ISD::BR_CC            , MVT::i32,   Expand);
296   setOperationAction(ISD::BR_CC            , MVT::i64,   Expand);
297   setOperationAction(ISD::SELECT_CC        , MVT::f32,   Expand);
298   setOperationAction(ISD::SELECT_CC        , MVT::f64,   Expand);
299   setOperationAction(ISD::SELECT_CC        , MVT::f80,   Expand);
300   setOperationAction(ISD::SELECT_CC        , MVT::i8,    Expand);
301   setOperationAction(ISD::SELECT_CC        , MVT::i16,   Expand);
302   setOperationAction(ISD::SELECT_CC        , MVT::i32,   Expand);
303   setOperationAction(ISD::SELECT_CC        , MVT::i64,   Expand);
304   if (Subtarget->is64Bit())
305     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
306   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
307   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
308   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
309   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
310
311   if (Subtarget->is32Bit() && Subtarget->isTargetKnownWindowsMSVC()) {
312     // On 32 bit MSVC, `fmodf(f32)` is not defined - only `fmod(f64)`
313     // is. We should promote the value to 64-bits to solve this.
314     // This is what the CRT headers do - `fmodf` is an inline header
315     // function casting to f64 and calling `fmod`.
316     setOperationAction(ISD::FREM           , MVT::f32  , Promote);
317   } else {
318     setOperationAction(ISD::FREM           , MVT::f32  , Expand);
319   }
320
321   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
322   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
323   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
324
325   // Promote the i8 variants and force them on up to i32 which has a shorter
326   // encoding.
327   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
328   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
329   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
330   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
331   if (Subtarget->hasBMI()) {
332     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
333     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
334     if (Subtarget->is64Bit())
335       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
336   } else {
337     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
338     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
339     if (Subtarget->is64Bit())
340       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
341   }
342
343   if (Subtarget->hasLZCNT()) {
344     // When promoting the i8 variants, force them to i32 for a shorter
345     // encoding.
346     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
347     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
348     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
349     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
350     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
351     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
352     if (Subtarget->is64Bit())
353       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
354   } else {
355     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
356     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
357     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
358     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
359     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
360     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
361     if (Subtarget->is64Bit()) {
362       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
363       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
364     }
365   }
366
367   // Special handling for half-precision floating point conversions.
368   // If we don't have F16C support, then lower half float conversions
369   // into library calls.
370   if (Subtarget->useSoftFloat() || !Subtarget->hasF16C()) {
371     setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
372     setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
373   }
374
375   // There's never any support for operations beyond MVT::f32.
376   setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
377   setOperationAction(ISD::FP16_TO_FP, MVT::f80, Expand);
378   setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
379   setOperationAction(ISD::FP_TO_FP16, MVT::f80, Expand);
380
381   setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
382   setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
383   setLoadExtAction(ISD::EXTLOAD, MVT::f80, MVT::f16, Expand);
384   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
385   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
386   setTruncStoreAction(MVT::f80, MVT::f16, Expand);
387
388   if (Subtarget->hasPOPCNT()) {
389     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
390   } else {
391     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
392     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
393     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
394     if (Subtarget->is64Bit())
395       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
396   }
397
398   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
399
400   if (!Subtarget->hasMOVBE())
401     setOperationAction(ISD::BSWAP          , MVT::i16  , Expand);
402
403   // These should be promoted to a larger select which is supported.
404   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
405   // X86 wants to expand cmov itself.
406   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
407   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
408   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
409   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
410   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
411   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
412   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
413   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
414   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
415   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
416   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
417   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
418   if (Subtarget->is64Bit()) {
419     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
420     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
421   }
422   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
423   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
424   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
425   // support continuation, user-level threading, and etc.. As a result, no
426   // other SjLj exception interfaces are implemented and please don't build
427   // your own exception handling based on them.
428   // LLVM/Clang supports zero-cost DWARF exception handling.
429   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
430   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
431
432   // Darwin ABI issue.
433   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
434   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
435   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
436   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
437   if (Subtarget->is64Bit())
438     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
439   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
440   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
441   if (Subtarget->is64Bit()) {
442     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
443     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
444     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
445     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
446     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
447   }
448   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
449   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
450   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
451   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
452   if (Subtarget->is64Bit()) {
453     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
454     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
455     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
456   }
457
458   if (Subtarget->hasSSE1())
459     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
460
461   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
462
463   // Expand certain atomics
464   for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
465     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
466     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
467     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
468   }
469
470   if (Subtarget->hasCmpxchg16b()) {
471     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
472   }
473
474   // FIXME - use subtarget debug flags
475   if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetELF() &&
476       !Subtarget->isTargetCygMing() && !Subtarget->isTargetWin64()) {
477     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
478   }
479
480   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
481   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
482
483   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
484   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
485
486   setOperationAction(ISD::TRAP, MVT::Other, Legal);
487   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
488
489   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
490   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
491   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
492   if (Subtarget->is64Bit()) {
493     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
494     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
495   } else {
496     // TargetInfo::CharPtrBuiltinVaList
497     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
498     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
499   }
500
501   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
502   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
503
504   setOperationAction(ISD::DYNAMIC_STACKALLOC, PtrVT, Custom);
505
506   // GC_TRANSITION_START and GC_TRANSITION_END need custom lowering.
507   setOperationAction(ISD::GC_TRANSITION_START, MVT::Other, Custom);
508   setOperationAction(ISD::GC_TRANSITION_END, MVT::Other, Custom);
509
510   if (!Subtarget->useSoftFloat() && X86ScalarSSEf64) {
511     // f32 and f64 use SSE.
512     // Set up the FP register classes.
513     addRegisterClass(MVT::f32, &X86::FR32RegClass);
514     addRegisterClass(MVT::f64, &X86::FR64RegClass);
515
516     // Use ANDPD to simulate FABS.
517     setOperationAction(ISD::FABS , MVT::f64, Custom);
518     setOperationAction(ISD::FABS , MVT::f32, Custom);
519
520     // Use XORP to simulate FNEG.
521     setOperationAction(ISD::FNEG , MVT::f64, Custom);
522     setOperationAction(ISD::FNEG , MVT::f32, Custom);
523
524     // Use ANDPD and ORPD to simulate FCOPYSIGN.
525     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
526     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
527
528     // Lower this to FGETSIGNx86 plus an AND.
529     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
530     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
531
532     // We don't support sin/cos/fmod
533     setOperationAction(ISD::FSIN   , MVT::f64, Expand);
534     setOperationAction(ISD::FCOS   , MVT::f64, Expand);
535     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
536     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
537     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
538     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
539
540     // Expand FP immediates into loads from the stack, except for the special
541     // cases we handle.
542     addLegalFPImmediate(APFloat(+0.0)); // xorpd
543     addLegalFPImmediate(APFloat(+0.0f)); // xorps
544   } else if (!Subtarget->useSoftFloat() && X86ScalarSSEf32) {
545     // Use SSE for f32, x87 for f64.
546     // Set up the FP register classes.
547     addRegisterClass(MVT::f32, &X86::FR32RegClass);
548     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
549
550     // Use ANDPS to simulate FABS.
551     setOperationAction(ISD::FABS , MVT::f32, Custom);
552
553     // Use XORP to simulate FNEG.
554     setOperationAction(ISD::FNEG , MVT::f32, Custom);
555
556     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
557
558     // Use ANDPS and ORPS to simulate FCOPYSIGN.
559     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
560     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
561
562     // We don't support sin/cos/fmod
563     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
564     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
565     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
566
567     // Special cases we handle for FP constants.
568     addLegalFPImmediate(APFloat(+0.0f)); // xorps
569     addLegalFPImmediate(APFloat(+0.0)); // FLD0
570     addLegalFPImmediate(APFloat(+1.0)); // FLD1
571     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
572     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
573
574     if (!TM.Options.UnsafeFPMath) {
575       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
576       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
577       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
578     }
579   } else if (!Subtarget->useSoftFloat()) {
580     // f32 and f64 in x87.
581     // Set up the FP register classes.
582     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
583     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
584
585     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
586     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
587     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
588     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
589
590     if (!TM.Options.UnsafeFPMath) {
591       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
592       setOperationAction(ISD::FSIN   , MVT::f32, Expand);
593       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
594       setOperationAction(ISD::FCOS   , MVT::f32, Expand);
595       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
596       setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
597     }
598     addLegalFPImmediate(APFloat(+0.0)); // FLD0
599     addLegalFPImmediate(APFloat(+1.0)); // FLD1
600     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
601     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
602     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
603     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
604     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
605     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
606   }
607
608   // We don't support FMA.
609   setOperationAction(ISD::FMA, MVT::f64, Expand);
610   setOperationAction(ISD::FMA, MVT::f32, Expand);
611
612   // Long double always uses X87.
613   if (!Subtarget->useSoftFloat()) {
614     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
615     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
616     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
617     {
618       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
619       addLegalFPImmediate(TmpFlt);  // FLD0
620       TmpFlt.changeSign();
621       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
622
623       bool ignored;
624       APFloat TmpFlt2(+1.0);
625       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
626                       &ignored);
627       addLegalFPImmediate(TmpFlt2);  // FLD1
628       TmpFlt2.changeSign();
629       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
630     }
631
632     if (!TM.Options.UnsafeFPMath) {
633       setOperationAction(ISD::FSIN   , MVT::f80, Expand);
634       setOperationAction(ISD::FCOS   , MVT::f80, Expand);
635       setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
636     }
637
638     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
639     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
640     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
641     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
642     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
643     setOperationAction(ISD::FMA, MVT::f80, Expand);
644   }
645
646   // Always use a library call for pow.
647   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
648   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
649   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
650
651   setOperationAction(ISD::FLOG, MVT::f80, Expand);
652   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
653   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
654   setOperationAction(ISD::FEXP, MVT::f80, Expand);
655   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
656   setOperationAction(ISD::FMINNUM, MVT::f80, Expand);
657   setOperationAction(ISD::FMAXNUM, MVT::f80, Expand);
658
659   // First set operation action for all vector types to either promote
660   // (for widening) or expand (for scalarization). Then we will selectively
661   // turn on ones that can be effectively codegen'd.
662   for (MVT VT : MVT::vector_valuetypes()) {
663     setOperationAction(ISD::ADD , VT, Expand);
664     setOperationAction(ISD::SUB , VT, Expand);
665     setOperationAction(ISD::FADD, VT, Expand);
666     setOperationAction(ISD::FNEG, VT, Expand);
667     setOperationAction(ISD::FSUB, VT, Expand);
668     setOperationAction(ISD::MUL , VT, Expand);
669     setOperationAction(ISD::FMUL, VT, Expand);
670     setOperationAction(ISD::SDIV, VT, Expand);
671     setOperationAction(ISD::UDIV, VT, Expand);
672     setOperationAction(ISD::FDIV, VT, Expand);
673     setOperationAction(ISD::SREM, VT, Expand);
674     setOperationAction(ISD::UREM, VT, Expand);
675     setOperationAction(ISD::LOAD, VT, Expand);
676     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
677     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
678     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
679     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
680     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
681     setOperationAction(ISD::FABS, VT, Expand);
682     setOperationAction(ISD::FSIN, VT, Expand);
683     setOperationAction(ISD::FSINCOS, VT, Expand);
684     setOperationAction(ISD::FCOS, VT, Expand);
685     setOperationAction(ISD::FSINCOS, VT, Expand);
686     setOperationAction(ISD::FREM, VT, Expand);
687     setOperationAction(ISD::FMA,  VT, Expand);
688     setOperationAction(ISD::FPOWI, VT, Expand);
689     setOperationAction(ISD::FSQRT, VT, Expand);
690     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
691     setOperationAction(ISD::FFLOOR, VT, Expand);
692     setOperationAction(ISD::FCEIL, VT, Expand);
693     setOperationAction(ISD::FTRUNC, VT, Expand);
694     setOperationAction(ISD::FRINT, VT, Expand);
695     setOperationAction(ISD::FNEARBYINT, VT, Expand);
696     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
697     setOperationAction(ISD::MULHS, VT, Expand);
698     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
699     setOperationAction(ISD::MULHU, VT, Expand);
700     setOperationAction(ISD::SDIVREM, VT, Expand);
701     setOperationAction(ISD::UDIVREM, VT, Expand);
702     setOperationAction(ISD::FPOW, VT, Expand);
703     setOperationAction(ISD::CTPOP, VT, Expand);
704     setOperationAction(ISD::CTTZ, VT, Expand);
705     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
706     setOperationAction(ISD::CTLZ, VT, Expand);
707     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
708     setOperationAction(ISD::SHL, VT, Expand);
709     setOperationAction(ISD::SRA, VT, Expand);
710     setOperationAction(ISD::SRL, VT, Expand);
711     setOperationAction(ISD::ROTL, VT, Expand);
712     setOperationAction(ISD::ROTR, VT, Expand);
713     setOperationAction(ISD::BSWAP, VT, Expand);
714     setOperationAction(ISD::SETCC, VT, Expand);
715     setOperationAction(ISD::FLOG, VT, Expand);
716     setOperationAction(ISD::FLOG2, VT, Expand);
717     setOperationAction(ISD::FLOG10, VT, Expand);
718     setOperationAction(ISD::FEXP, VT, Expand);
719     setOperationAction(ISD::FEXP2, VT, Expand);
720     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
721     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
722     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
723     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
724     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
725     setOperationAction(ISD::TRUNCATE, VT, Expand);
726     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
727     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
728     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
729     setOperationAction(ISD::VSELECT, VT, Expand);
730     setOperationAction(ISD::SELECT_CC, VT, Expand);
731     for (MVT InnerVT : MVT::vector_valuetypes()) {
732       setTruncStoreAction(InnerVT, VT, Expand);
733
734       setLoadExtAction(ISD::SEXTLOAD, InnerVT, VT, Expand);
735       setLoadExtAction(ISD::ZEXTLOAD, InnerVT, VT, Expand);
736
737       // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like
738       // types, we have to deal with them whether we ask for Expansion or not.
739       // Setting Expand causes its own optimisation problems though, so leave
740       // them legal.
741       if (VT.getVectorElementType() == MVT::i1)
742         setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
743
744       // EXTLOAD for MVT::f16 vectors is not legal because f16 vectors are
745       // split/scalarized right now.
746       if (VT.getVectorElementType() == MVT::f16)
747         setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
748     }
749   }
750
751   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
752   // with -msoft-float, disable use of MMX as well.
753   if (!Subtarget->useSoftFloat() && Subtarget->hasMMX()) {
754     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
755     // No operations on x86mmx supported, everything uses intrinsics.
756   }
757
758   // MMX-sized vectors (other than x86mmx) are expected to be expanded
759   // into smaller operations.
760   for (MVT MMXTy : {MVT::v8i8, MVT::v4i16, MVT::v2i32, MVT::v1i64}) {
761     setOperationAction(ISD::MULHS,              MMXTy,      Expand);
762     setOperationAction(ISD::AND,                MMXTy,      Expand);
763     setOperationAction(ISD::OR,                 MMXTy,      Expand);
764     setOperationAction(ISD::XOR,                MMXTy,      Expand);
765     setOperationAction(ISD::SCALAR_TO_VECTOR,   MMXTy,      Expand);
766     setOperationAction(ISD::SELECT,             MMXTy,      Expand);
767     setOperationAction(ISD::BITCAST,            MMXTy,      Expand);
768   }
769   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
770
771   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE1()) {
772     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
773
774     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
775     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
776     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
777     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
778     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
779     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
780     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
781     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
782     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
783     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
784     setOperationAction(ISD::VSELECT,            MVT::v4f32, Custom);
785     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
786     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
787     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Custom);
788   }
789
790   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE2()) {
791     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
792
793     // FIXME: Unfortunately, -soft-float and -no-implicit-float mean XMM
794     // registers cannot be used even for integer operations.
795     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
796     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
797     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
798     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
799
800     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
801     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
802     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
803     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
804     setOperationAction(ISD::MUL,                MVT::v16i8, Custom);
805     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
806     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
807     setOperationAction(ISD::UMUL_LOHI,          MVT::v4i32, Custom);
808     setOperationAction(ISD::SMUL_LOHI,          MVT::v4i32, Custom);
809     setOperationAction(ISD::MULHU,              MVT::v8i16, Legal);
810     setOperationAction(ISD::MULHS,              MVT::v8i16, Legal);
811     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
812     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
813     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
814     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
815     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
816     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
817     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
818     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
819     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
820     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
821     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
822     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
823
824     setOperationAction(ISD::SMAX,               MVT::v8i16, Legal);
825     setOperationAction(ISD::UMAX,               MVT::v16i8, Legal);
826     setOperationAction(ISD::SMIN,               MVT::v8i16, Legal);
827     setOperationAction(ISD::UMIN,               MVT::v16i8, Legal);
828
829     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
830     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
831     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
832     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
833
834     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
835     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
836     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
837     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
838     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
839
840     setOperationAction(ISD::CTPOP,              MVT::v16i8, Custom);
841     setOperationAction(ISD::CTPOP,              MVT::v8i16, Custom);
842     setOperationAction(ISD::CTPOP,              MVT::v4i32, Custom);
843     setOperationAction(ISD::CTPOP,              MVT::v2i64, Custom);
844
845     setOperationAction(ISD::CTTZ,               MVT::v16i8, Custom);
846     setOperationAction(ISD::CTTZ,               MVT::v8i16, Custom);
847     setOperationAction(ISD::CTTZ,               MVT::v4i32, Custom);
848     // ISD::CTTZ v2i64 - scalarization is faster.
849     setOperationAction(ISD::CTTZ_ZERO_UNDEF,    MVT::v16i8, Custom);
850     setOperationAction(ISD::CTTZ_ZERO_UNDEF,    MVT::v8i16, Custom);
851     setOperationAction(ISD::CTTZ_ZERO_UNDEF,    MVT::v4i32, Custom);
852     // ISD::CTTZ_ZERO_UNDEF v2i64 - scalarization is faster.
853
854     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
855     for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) {
856       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
857       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
858       setOperationAction(ISD::VSELECT,            VT, Custom);
859       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
860     }
861
862     // We support custom legalizing of sext and anyext loads for specific
863     // memory vector types which we can load as a scalar (or sequence of
864     // scalars) and extend in-register to a legal 128-bit vector type. For sext
865     // loads these must work with a single scalar load.
866     for (MVT VT : MVT::integer_vector_valuetypes()) {
867       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i8, Custom);
868       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i16, Custom);
869       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v8i8, Custom);
870       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i8, Custom);
871       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i16, Custom);
872       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i32, Custom);
873       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i8, Custom);
874       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i16, Custom);
875       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8i8, Custom);
876     }
877
878     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
879     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
880     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
881     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
882     setOperationAction(ISD::VSELECT,            MVT::v2f64, Custom);
883     setOperationAction(ISD::VSELECT,            MVT::v2i64, Custom);
884     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
885     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
886
887     if (Subtarget->is64Bit()) {
888       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
889       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
890     }
891
892     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
893     for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) {
894       setOperationAction(ISD::AND,    VT, Promote);
895       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
896       setOperationAction(ISD::OR,     VT, Promote);
897       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
898       setOperationAction(ISD::XOR,    VT, Promote);
899       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
900       setOperationAction(ISD::LOAD,   VT, Promote);
901       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
902       setOperationAction(ISD::SELECT, VT, Promote);
903       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
904     }
905
906     // Custom lower v2i64 and v2f64 selects.
907     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
908     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
909     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
910     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
911
912     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
913     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
914
915     setOperationAction(ISD::SINT_TO_FP,         MVT::v2i32, Custom);
916
917     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
918     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
919     // As there is no 64-bit GPR available, we need build a special custom
920     // sequence to convert from v2i32 to v2f32.
921     if (!Subtarget->is64Bit())
922       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
923
924     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
925     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
926
927     for (MVT VT : MVT::fp_vector_valuetypes())
928       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2f32, Legal);
929
930     setOperationAction(ISD::BITCAST,            MVT::v2i32, Custom);
931     setOperationAction(ISD::BITCAST,            MVT::v4i16, Custom);
932     setOperationAction(ISD::BITCAST,            MVT::v8i8,  Custom);
933   }
934
935   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE41()) {
936     for (MVT RoundedTy : {MVT::f32, MVT::f64, MVT::v4f32, MVT::v2f64}) {
937       setOperationAction(ISD::FFLOOR,           RoundedTy,  Legal);
938       setOperationAction(ISD::FCEIL,            RoundedTy,  Legal);
939       setOperationAction(ISD::FTRUNC,           RoundedTy,  Legal);
940       setOperationAction(ISD::FRINT,            RoundedTy,  Legal);
941       setOperationAction(ISD::FNEARBYINT,       RoundedTy,  Legal);
942     }
943
944     setOperationAction(ISD::SMAX,               MVT::v16i8, Legal);
945     setOperationAction(ISD::SMAX,               MVT::v4i32, Legal);
946     setOperationAction(ISD::UMAX,               MVT::v8i16, Legal);
947     setOperationAction(ISD::UMAX,               MVT::v4i32, Legal);
948     setOperationAction(ISD::SMIN,               MVT::v16i8, Legal);
949     setOperationAction(ISD::SMIN,               MVT::v4i32, Legal);
950     setOperationAction(ISD::UMIN,               MVT::v8i16, Legal);
951     setOperationAction(ISD::UMIN,               MVT::v4i32, Legal);
952
953     // FIXME: Do we need to handle scalar-to-vector here?
954     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
955
956     // We directly match byte blends in the backend as they match the VSELECT
957     // condition form.
958     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
959
960     // SSE41 brings specific instructions for doing vector sign extend even in
961     // cases where we don't have SRA.
962     for (MVT VT : MVT::integer_vector_valuetypes()) {
963       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i8, Custom);
964       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i16, Custom);
965       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i32, Custom);
966     }
967
968     // SSE41 also has vector sign/zero extending loads, PMOV[SZ]X
969     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i16, MVT::v8i8,  Legal);
970     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i8,  Legal);
971     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i8,  Legal);
972     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
973     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
974     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
975
976     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i16, MVT::v8i8,  Legal);
977     setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i8,  Legal);
978     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i8,  Legal);
979     setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
980     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
981     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
982
983     // i8 and i16 vectors are custom because the source register and source
984     // source memory operand types are not the same width.  f32 vectors are
985     // custom since the immediate controlling the insert encodes additional
986     // information.
987     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
988     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
989     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
990     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
991
992     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
993     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
994     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
995     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
996
997     // FIXME: these should be Legal, but that's only for the case where
998     // the index is constant.  For now custom expand to deal with that.
999     if (Subtarget->is64Bit()) {
1000       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1001       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1002     }
1003   }
1004
1005   if (Subtarget->hasSSE2()) {
1006     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v2i64, Custom);
1007     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v4i32, Custom);
1008     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v8i16, Custom);
1009
1010     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1011     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1012
1013     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1014     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1015
1016     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1017     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1018
1019     // In the customized shift lowering, the legal cases in AVX2 will be
1020     // recognized.
1021     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1022     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1023
1024     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1025     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1026
1027     setOperationAction(ISD::SRA,               MVT::v2i64, Custom);
1028     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1029   }
1030
1031   if (Subtarget->hasXOP()) {
1032     setOperationAction(ISD::ROTL,              MVT::v16i8, Custom);
1033     setOperationAction(ISD::ROTL,              MVT::v8i16, Custom);
1034     setOperationAction(ISD::ROTL,              MVT::v4i32, Custom);
1035     setOperationAction(ISD::ROTL,              MVT::v2i64, Custom);
1036     setOperationAction(ISD::ROTL,              MVT::v32i8, Custom);
1037     setOperationAction(ISD::ROTL,              MVT::v16i16, Custom);
1038     setOperationAction(ISD::ROTL,              MVT::v8i32, Custom);
1039     setOperationAction(ISD::ROTL,              MVT::v4i64, Custom);
1040   }
1041
1042   if (!Subtarget->useSoftFloat() && Subtarget->hasFp256()) {
1043     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1044     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1045     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1046     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1047     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1048     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1049
1050     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1051     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1052     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1053
1054     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1055     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1056     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1057     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1058     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1059     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1060     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1061     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1062     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1063     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1064     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1065     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1066
1067     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1068     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1069     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1070     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1071     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1072     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1073     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1074     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1075     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1076     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1077     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1078     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1079
1080     // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1081     // even though v8i16 is a legal type.
1082     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Promote);
1083     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i16, Promote);
1084     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1085
1086     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1087     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1088     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1089
1090     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1091     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1092
1093     for (MVT VT : MVT::fp_vector_valuetypes())
1094       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4f32, Legal);
1095
1096     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1097     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1098
1099     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1100     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1101
1102     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1103     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1104
1105     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1106     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1107     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1108     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1109
1110     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1111     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1112     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1113
1114     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1115     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1116     setOperationAction(ISD::SIGN_EXTEND,       MVT::v16i16, Custom);
1117     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1118     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1119     setOperationAction(ISD::ZERO_EXTEND,       MVT::v16i16, Custom);
1120     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1121     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1122     setOperationAction(ISD::ANY_EXTEND,        MVT::v16i16, Custom);
1123     setOperationAction(ISD::TRUNCATE,          MVT::v16i8, Custom);
1124     setOperationAction(ISD::TRUNCATE,          MVT::v8i16, Custom);
1125     setOperationAction(ISD::TRUNCATE,          MVT::v4i32, Custom);
1126
1127     setOperationAction(ISD::CTPOP,             MVT::v32i8, Custom);
1128     setOperationAction(ISD::CTPOP,             MVT::v16i16, Custom);
1129     setOperationAction(ISD::CTPOP,             MVT::v8i32, Custom);
1130     setOperationAction(ISD::CTPOP,             MVT::v4i64, Custom);
1131
1132     setOperationAction(ISD::CTTZ,              MVT::v32i8, Custom);
1133     setOperationAction(ISD::CTTZ,              MVT::v16i16, Custom);
1134     setOperationAction(ISD::CTTZ,              MVT::v8i32, Custom);
1135     setOperationAction(ISD::CTTZ,              MVT::v4i64, Custom);
1136     setOperationAction(ISD::CTTZ_ZERO_UNDEF,   MVT::v32i8, Custom);
1137     setOperationAction(ISD::CTTZ_ZERO_UNDEF,   MVT::v16i16, Custom);
1138     setOperationAction(ISD::CTTZ_ZERO_UNDEF,   MVT::v8i32, Custom);
1139     setOperationAction(ISD::CTTZ_ZERO_UNDEF,   MVT::v4i64, Custom);
1140
1141     if (Subtarget->hasFMA() || Subtarget->hasFMA4() || Subtarget->hasAVX512()) {
1142       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1143       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1144       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1145       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1146       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1147       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1148     }
1149
1150     if (Subtarget->hasInt256()) {
1151       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1152       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1153       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1154       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1155
1156       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1157       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1158       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1159       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1160
1161       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1162       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1163       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1164       setOperationAction(ISD::MUL,             MVT::v32i8, Custom);
1165
1166       setOperationAction(ISD::UMUL_LOHI,       MVT::v8i32, Custom);
1167       setOperationAction(ISD::SMUL_LOHI,       MVT::v8i32, Custom);
1168       setOperationAction(ISD::MULHU,           MVT::v16i16, Legal);
1169       setOperationAction(ISD::MULHS,           MVT::v16i16, Legal);
1170
1171       setOperationAction(ISD::SMAX,            MVT::v32i8,  Legal);
1172       setOperationAction(ISD::SMAX,            MVT::v16i16, Legal);
1173       setOperationAction(ISD::SMAX,            MVT::v8i32,  Legal);
1174       setOperationAction(ISD::UMAX,            MVT::v32i8,  Legal);
1175       setOperationAction(ISD::UMAX,            MVT::v16i16, Legal);
1176       setOperationAction(ISD::UMAX,            MVT::v8i32,  Legal);
1177       setOperationAction(ISD::SMIN,            MVT::v32i8,  Legal);
1178       setOperationAction(ISD::SMIN,            MVT::v16i16, Legal);
1179       setOperationAction(ISD::SMIN,            MVT::v8i32,  Legal);
1180       setOperationAction(ISD::UMIN,            MVT::v32i8,  Legal);
1181       setOperationAction(ISD::UMIN,            MVT::v16i16, Legal);
1182       setOperationAction(ISD::UMIN,            MVT::v8i32,  Legal);
1183
1184       // The custom lowering for UINT_TO_FP for v8i32 becomes interesting
1185       // when we have a 256bit-wide blend with immediate.
1186       setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Custom);
1187
1188       // AVX2 also has wider vector sign/zero extending loads, VPMOV[SZ]X
1189       setLoadExtAction(ISD::SEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1190       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32,  MVT::v8i8,  Legal);
1191       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i8,  Legal);
1192       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32,  MVT::v8i16, Legal);
1193       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i16, Legal);
1194       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i32, Legal);
1195
1196       setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1197       setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32,  MVT::v8i8,  Legal);
1198       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i8,  Legal);
1199       setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32,  MVT::v8i16, Legal);
1200       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i16, Legal);
1201       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i32, Legal);
1202     } else {
1203       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1204       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1205       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1206       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1207
1208       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1209       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1210       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1211       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1212
1213       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1214       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1215       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1216       setOperationAction(ISD::MUL,             MVT::v32i8, Custom);
1217
1218       setOperationAction(ISD::SMAX,            MVT::v32i8,  Custom);
1219       setOperationAction(ISD::SMAX,            MVT::v16i16, Custom);
1220       setOperationAction(ISD::SMAX,            MVT::v8i32,  Custom);
1221       setOperationAction(ISD::UMAX,            MVT::v32i8,  Custom);
1222       setOperationAction(ISD::UMAX,            MVT::v16i16, Custom);
1223       setOperationAction(ISD::UMAX,            MVT::v8i32,  Custom);
1224       setOperationAction(ISD::SMIN,            MVT::v32i8,  Custom);
1225       setOperationAction(ISD::SMIN,            MVT::v16i16, Custom);
1226       setOperationAction(ISD::SMIN,            MVT::v8i32,  Custom);
1227       setOperationAction(ISD::UMIN,            MVT::v32i8,  Custom);
1228       setOperationAction(ISD::UMIN,            MVT::v16i16, Custom);
1229       setOperationAction(ISD::UMIN,            MVT::v8i32,  Custom);
1230     }
1231
1232     // In the customized shift lowering, the legal cases in AVX2 will be
1233     // recognized.
1234     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1235     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1236
1237     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1238     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1239
1240     setOperationAction(ISD::SRA,               MVT::v4i64, Custom);
1241     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1242
1243     // Custom lower several nodes for 256-bit types.
1244     for (MVT VT : MVT::vector_valuetypes()) {
1245       if (VT.getScalarSizeInBits() >= 32) {
1246         setOperationAction(ISD::MLOAD,  VT, Legal);
1247         setOperationAction(ISD::MSTORE, VT, Legal);
1248       }
1249       // Extract subvector is special because the value type
1250       // (result) is 128-bit but the source is 256-bit wide.
1251       if (VT.is128BitVector()) {
1252         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1253       }
1254       // Do not attempt to custom lower other non-256-bit vectors
1255       if (!VT.is256BitVector())
1256         continue;
1257
1258       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1259       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1260       setOperationAction(ISD::VSELECT,            VT, Custom);
1261       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1262       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1263       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1264       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1265       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1266     }
1267
1268     if (Subtarget->hasInt256())
1269       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1270
1271     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1272     for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32 }) {
1273       setOperationAction(ISD::AND,    VT, Promote);
1274       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1275       setOperationAction(ISD::OR,     VT, Promote);
1276       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1277       setOperationAction(ISD::XOR,    VT, Promote);
1278       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1279       setOperationAction(ISD::LOAD,   VT, Promote);
1280       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1281       setOperationAction(ISD::SELECT, VT, Promote);
1282       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1283     }
1284   }
1285
1286   if (!Subtarget->useSoftFloat() && Subtarget->hasAVX512()) {
1287     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1288     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1289     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1290     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1291
1292     addRegisterClass(MVT::i1,     &X86::VK1RegClass);
1293     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1294     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1295
1296     for (MVT VT : MVT::fp_vector_valuetypes())
1297       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8f32, Legal);
1298
1299     setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i32, MVT::v16i8, Legal);
1300     setLoadExtAction(ISD::SEXTLOAD, MVT::v16i32, MVT::v16i8, Legal);
1301     setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i32, MVT::v16i16, Legal);
1302     setLoadExtAction(ISD::SEXTLOAD, MVT::v16i32, MVT::v16i16, Legal);
1303     setLoadExtAction(ISD::ZEXTLOAD, MVT::v32i16, MVT::v32i8, Legal);
1304     setLoadExtAction(ISD::SEXTLOAD, MVT::v32i16, MVT::v32i8, Legal);
1305     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i8,  Legal);
1306     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i8,  Legal);
1307     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i16,  Legal);
1308     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i16,  Legal);
1309     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i32,  Legal);
1310     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i32,  Legal);
1311
1312     setOperationAction(ISD::BR_CC,              MVT::i1,    Expand);
1313     setOperationAction(ISD::SETCC,              MVT::i1,    Custom);
1314     setOperationAction(ISD::SELECT_CC,          MVT::i1,    Expand);
1315     setOperationAction(ISD::XOR,                MVT::i1,    Legal);
1316     setOperationAction(ISD::OR,                 MVT::i1,    Legal);
1317     setOperationAction(ISD::AND,                MVT::i1,    Legal);
1318     setOperationAction(ISD::SUB,                MVT::i1,    Custom);
1319     setOperationAction(ISD::ADD,                MVT::i1,    Custom);
1320     setOperationAction(ISD::MUL,                MVT::i1,    Custom);
1321     setOperationAction(ISD::LOAD,               MVT::v16f32, Legal);
1322     setOperationAction(ISD::LOAD,               MVT::v8f64, Legal);
1323     setOperationAction(ISD::LOAD,               MVT::v8i64, Legal);
1324     setOperationAction(ISD::LOAD,               MVT::v16i32, Legal);
1325     setOperationAction(ISD::LOAD,               MVT::v16i1, Legal);
1326
1327     setOperationAction(ISD::FADD,               MVT::v16f32, Legal);
1328     setOperationAction(ISD::FSUB,               MVT::v16f32, Legal);
1329     setOperationAction(ISD::FMUL,               MVT::v16f32, Legal);
1330     setOperationAction(ISD::FDIV,               MVT::v16f32, Legal);
1331     setOperationAction(ISD::FSQRT,              MVT::v16f32, Legal);
1332     setOperationAction(ISD::FNEG,               MVT::v16f32, Custom);
1333
1334     setOperationAction(ISD::FADD,               MVT::v8f64, Legal);
1335     setOperationAction(ISD::FSUB,               MVT::v8f64, Legal);
1336     setOperationAction(ISD::FMUL,               MVT::v8f64, Legal);
1337     setOperationAction(ISD::FDIV,               MVT::v8f64, Legal);
1338     setOperationAction(ISD::FSQRT,              MVT::v8f64, Legal);
1339     setOperationAction(ISD::FNEG,               MVT::v8f64, Custom);
1340     setOperationAction(ISD::FMA,                MVT::v8f64, Legal);
1341     setOperationAction(ISD::FMA,                MVT::v16f32, Legal);
1342
1343     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1344     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1345     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1346     setOperationAction(ISD::FP_TO_UINT,         MVT::v4i32, Legal);
1347     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1348     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i1,   Custom);
1349     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i1,  Custom);
1350     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i8,  Promote);
1351     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i16, Promote);
1352     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1353     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1354     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Legal);
1355     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i8, Custom);
1356     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i16, Custom);
1357     setOperationAction(ISD::FP_ROUND,           MVT::v8f32, Legal);
1358     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Legal);
1359
1360     setTruncStoreAction(MVT::v8i64,   MVT::v8i8,   Legal);
1361     setTruncStoreAction(MVT::v8i64,   MVT::v8i16,  Legal);
1362     setTruncStoreAction(MVT::v8i64,   MVT::v8i32,  Legal);
1363     setTruncStoreAction(MVT::v16i32,  MVT::v16i8,  Legal);
1364     setTruncStoreAction(MVT::v16i32,  MVT::v16i16, Legal);
1365     if (Subtarget->hasVLX()){
1366       setTruncStoreAction(MVT::v4i64, MVT::v4i8,  Legal);
1367       setTruncStoreAction(MVT::v4i64, MVT::v4i16, Legal);
1368       setTruncStoreAction(MVT::v4i64, MVT::v4i32, Legal);
1369       setTruncStoreAction(MVT::v8i32, MVT::v8i8,  Legal);
1370       setTruncStoreAction(MVT::v8i32, MVT::v8i16, Legal);
1371
1372       setTruncStoreAction(MVT::v2i64, MVT::v2i8,  Legal);
1373       setTruncStoreAction(MVT::v2i64, MVT::v2i16, Legal);
1374       setTruncStoreAction(MVT::v2i64, MVT::v2i32, Legal);
1375       setTruncStoreAction(MVT::v4i32, MVT::v4i8,  Legal);
1376       setTruncStoreAction(MVT::v4i32, MVT::v4i16, Legal);
1377     }
1378     setOperationAction(ISD::TRUNCATE,           MVT::i1, Custom);
1379     setOperationAction(ISD::TRUNCATE,           MVT::v16i8, Custom);
1380     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1381     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v8i1,  Custom);
1382     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v16i1, Custom);
1383     if (Subtarget->hasDQI()) {
1384       setOperationAction(ISD::TRUNCATE,         MVT::v2i1, Custom);
1385       setOperationAction(ISD::TRUNCATE,         MVT::v4i1, Custom);
1386
1387       setOperationAction(ISD::SINT_TO_FP,       MVT::v8i64, Legal);
1388       setOperationAction(ISD::UINT_TO_FP,       MVT::v8i64, Legal);
1389       setOperationAction(ISD::FP_TO_SINT,       MVT::v8i64, Legal);
1390       setOperationAction(ISD::FP_TO_UINT,       MVT::v8i64, Legal);
1391       if (Subtarget->hasVLX()) {
1392         setOperationAction(ISD::SINT_TO_FP,    MVT::v4i64, Legal);
1393         setOperationAction(ISD::SINT_TO_FP,    MVT::v2i64, Legal);
1394         setOperationAction(ISD::UINT_TO_FP,    MVT::v4i64, Legal);
1395         setOperationAction(ISD::UINT_TO_FP,    MVT::v2i64, Legal);
1396         setOperationAction(ISD::FP_TO_SINT,    MVT::v4i64, Legal);
1397         setOperationAction(ISD::FP_TO_SINT,    MVT::v2i64, Legal);
1398         setOperationAction(ISD::FP_TO_UINT,    MVT::v4i64, Legal);
1399         setOperationAction(ISD::FP_TO_UINT,    MVT::v2i64, Legal);
1400       }
1401     }
1402     if (Subtarget->hasVLX()) {
1403       setOperationAction(ISD::SINT_TO_FP,       MVT::v8i32, Legal);
1404       setOperationAction(ISD::UINT_TO_FP,       MVT::v8i32, Legal);
1405       setOperationAction(ISD::FP_TO_SINT,       MVT::v8i32, Legal);
1406       setOperationAction(ISD::FP_TO_UINT,       MVT::v8i32, Legal);
1407       setOperationAction(ISD::SINT_TO_FP,       MVT::v4i32, Legal);
1408       setOperationAction(ISD::UINT_TO_FP,       MVT::v4i32, Legal);
1409       setOperationAction(ISD::FP_TO_SINT,       MVT::v4i32, Legal);
1410       setOperationAction(ISD::FP_TO_UINT,       MVT::v4i32, Legal);
1411     }
1412     setOperationAction(ISD::TRUNCATE,           MVT::v8i1, Custom);
1413     setOperationAction(ISD::TRUNCATE,           MVT::v16i1, Custom);
1414     setOperationAction(ISD::TRUNCATE,           MVT::v16i16, Custom);
1415     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1416     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1417     setOperationAction(ISD::ANY_EXTEND,         MVT::v16i32, Custom);
1418     setOperationAction(ISD::ANY_EXTEND,         MVT::v8i64, Custom);
1419     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1420     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1421     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i8, Custom);
1422     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i16, Custom);
1423     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i16, Custom);
1424     if (Subtarget->hasDQI()) {
1425       setOperationAction(ISD::SIGN_EXTEND,        MVT::v4i32, Custom);
1426       setOperationAction(ISD::SIGN_EXTEND,        MVT::v2i64, Custom);
1427     }
1428     setOperationAction(ISD::FFLOOR,             MVT::v16f32, Legal);
1429     setOperationAction(ISD::FFLOOR,             MVT::v8f64, Legal);
1430     setOperationAction(ISD::FCEIL,              MVT::v16f32, Legal);
1431     setOperationAction(ISD::FCEIL,              MVT::v8f64, Legal);
1432     setOperationAction(ISD::FTRUNC,             MVT::v16f32, Legal);
1433     setOperationAction(ISD::FTRUNC,             MVT::v8f64, Legal);
1434     setOperationAction(ISD::FRINT,              MVT::v16f32, Legal);
1435     setOperationAction(ISD::FRINT,              MVT::v8f64, Legal);
1436     setOperationAction(ISD::FNEARBYINT,         MVT::v16f32, Legal);
1437     setOperationAction(ISD::FNEARBYINT,         MVT::v8f64, Legal);
1438
1439     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1440     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1441     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1442     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1443     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i1, Legal);
1444
1445     setOperationAction(ISD::SETCC,              MVT::v16i1, Custom);
1446     setOperationAction(ISD::SETCC,              MVT::v8i1, Custom);
1447
1448     setOperationAction(ISD::MUL,              MVT::v8i64, Custom);
1449
1450     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1,  Custom);
1451     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1452     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i1, Custom);
1453     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i1, Custom);
1454     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i1, Custom);
1455     setOperationAction(ISD::BUILD_VECTOR,       MVT::v16i1, Custom);
1456     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1457     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1458     setOperationAction(ISD::SELECT,             MVT::v16f32, Custom);
1459     setOperationAction(ISD::SELECT,             MVT::v16i1, Custom);
1460     setOperationAction(ISD::SELECT,             MVT::v8i1,  Custom);
1461
1462     setOperationAction(ISD::SMAX,               MVT::v16i32, Legal);
1463     setOperationAction(ISD::SMAX,               MVT::v8i64, Legal);
1464     setOperationAction(ISD::UMAX,               MVT::v16i32, Legal);
1465     setOperationAction(ISD::UMAX,               MVT::v8i64, Legal);
1466     setOperationAction(ISD::SMIN,               MVT::v16i32, Legal);
1467     setOperationAction(ISD::SMIN,               MVT::v8i64, Legal);
1468     setOperationAction(ISD::UMIN,               MVT::v16i32, Legal);
1469     setOperationAction(ISD::UMIN,               MVT::v8i64, Legal);
1470
1471     setOperationAction(ISD::ADD,                MVT::v8i64, Legal);
1472     setOperationAction(ISD::ADD,                MVT::v16i32, Legal);
1473
1474     setOperationAction(ISD::SUB,                MVT::v8i64, Legal);
1475     setOperationAction(ISD::SUB,                MVT::v16i32, Legal);
1476
1477     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1478
1479     setOperationAction(ISD::SRL,                MVT::v8i64, Custom);
1480     setOperationAction(ISD::SRL,                MVT::v16i32, Custom);
1481
1482     setOperationAction(ISD::SHL,                MVT::v8i64, Custom);
1483     setOperationAction(ISD::SHL,                MVT::v16i32, Custom);
1484
1485     setOperationAction(ISD::SRA,                MVT::v8i64, Custom);
1486     setOperationAction(ISD::SRA,                MVT::v16i32, Custom);
1487
1488     setOperationAction(ISD::AND,                MVT::v8i64, Legal);
1489     setOperationAction(ISD::OR,                 MVT::v8i64, Legal);
1490     setOperationAction(ISD::XOR,                MVT::v8i64, Legal);
1491     setOperationAction(ISD::AND,                MVT::v16i32, Legal);
1492     setOperationAction(ISD::OR,                 MVT::v16i32, Legal);
1493     setOperationAction(ISD::XOR,                MVT::v16i32, Legal);
1494
1495     if (Subtarget->hasCDI()) {
1496       setOperationAction(ISD::CTLZ,             MVT::v8i64,  Legal);
1497       setOperationAction(ISD::CTLZ,             MVT::v16i32, Legal);
1498       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v8i64,  Legal);
1499       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v16i32, Legal);
1500
1501       setOperationAction(ISD::CTLZ,             MVT::v8i16,  Custom);
1502       setOperationAction(ISD::CTLZ,             MVT::v16i8,  Custom);
1503       setOperationAction(ISD::CTLZ,             MVT::v16i16, Custom);
1504       setOperationAction(ISD::CTLZ,             MVT::v32i8,  Custom);
1505       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v8i16,  Custom);
1506       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v16i8,  Custom);
1507       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v16i16, Custom);
1508       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v32i8,  Custom);
1509
1510       setOperationAction(ISD::CTTZ_ZERO_UNDEF,  MVT::v8i64,  Custom);
1511       setOperationAction(ISD::CTTZ_ZERO_UNDEF,  MVT::v16i32, Custom);
1512
1513       if (Subtarget->hasVLX()) {
1514         setOperationAction(ISD::CTLZ,             MVT::v4i64, Legal);
1515         setOperationAction(ISD::CTLZ,             MVT::v8i32, Legal);
1516         setOperationAction(ISD::CTLZ,             MVT::v2i64, Legal);
1517         setOperationAction(ISD::CTLZ,             MVT::v4i32, Legal);
1518         setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v4i64, Legal);
1519         setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v8i32, Legal);
1520         setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v2i64, Legal);
1521         setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v4i32, Legal);
1522
1523         setOperationAction(ISD::CTTZ_ZERO_UNDEF,  MVT::v4i64, Custom);
1524         setOperationAction(ISD::CTTZ_ZERO_UNDEF,  MVT::v8i32, Custom);
1525         setOperationAction(ISD::CTTZ_ZERO_UNDEF,  MVT::v2i64, Custom);
1526         setOperationAction(ISD::CTTZ_ZERO_UNDEF,  MVT::v4i32, Custom);
1527       } else {
1528         setOperationAction(ISD::CTLZ,             MVT::v4i64, Custom);
1529         setOperationAction(ISD::CTLZ,             MVT::v8i32, Custom);
1530         setOperationAction(ISD::CTLZ,             MVT::v2i64, Custom);
1531         setOperationAction(ISD::CTLZ,             MVT::v4i32, Custom);
1532         setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v4i64, Custom);
1533         setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v8i32, Custom);
1534         setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v2i64, Custom);
1535         setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v4i32, Custom);
1536       }
1537     } // Subtarget->hasCDI()
1538
1539     if (Subtarget->hasDQI()) {
1540       setOperationAction(ISD::MUL,             MVT::v2i64, Legal);
1541       setOperationAction(ISD::MUL,             MVT::v4i64, Legal);
1542       setOperationAction(ISD::MUL,             MVT::v8i64, Legal);
1543     }
1544     // Custom lower several nodes.
1545     for (MVT VT : MVT::vector_valuetypes()) {
1546       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1547       if (EltSize == 1) {
1548         setOperationAction(ISD::AND, VT, Legal);
1549         setOperationAction(ISD::OR,  VT, Legal);
1550         setOperationAction(ISD::XOR,  VT, Legal);
1551       }
1552       if (EltSize >= 32 && VT.getSizeInBits() <= 512) {
1553         setOperationAction(ISD::MGATHER,  VT, Custom);
1554         setOperationAction(ISD::MSCATTER, VT, Custom);
1555       }
1556       // Extract subvector is special because the value type
1557       // (result) is 256/128-bit but the source is 512-bit wide.
1558       if (VT.is128BitVector() || VT.is256BitVector()) {
1559         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1560       }
1561       if (VT.getVectorElementType() == MVT::i1)
1562         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1563
1564       // Do not attempt to custom lower other non-512-bit vectors
1565       if (!VT.is512BitVector())
1566         continue;
1567
1568       if (EltSize >= 32) {
1569         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1570         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1571         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1572         setOperationAction(ISD::VSELECT,             VT, Legal);
1573         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1574         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1575         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1576         setOperationAction(ISD::MLOAD,               VT, Legal);
1577         setOperationAction(ISD::MSTORE,              VT, Legal);
1578       }
1579     }
1580     for (auto VT : { MVT::v64i8, MVT::v32i16, MVT::v16i32 }) {
1581       setOperationAction(ISD::SELECT, VT, Promote);
1582       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1583     }
1584   }// has  AVX-512
1585
1586   if (!Subtarget->useSoftFloat() && Subtarget->hasBWI()) {
1587     addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1588     addRegisterClass(MVT::v64i8,  &X86::VR512RegClass);
1589
1590     addRegisterClass(MVT::v32i1,  &X86::VK32RegClass);
1591     addRegisterClass(MVT::v64i1,  &X86::VK64RegClass);
1592
1593     setOperationAction(ISD::LOAD,               MVT::v32i16, Legal);
1594     setOperationAction(ISD::LOAD,               MVT::v64i8, Legal);
1595     setOperationAction(ISD::SETCC,              MVT::v32i1, Custom);
1596     setOperationAction(ISD::SETCC,              MVT::v64i1, Custom);
1597     setOperationAction(ISD::ADD,                MVT::v32i16, Legal);
1598     setOperationAction(ISD::ADD,                MVT::v64i8, Legal);
1599     setOperationAction(ISD::SUB,                MVT::v32i16, Legal);
1600     setOperationAction(ISD::SUB,                MVT::v64i8, Legal);
1601     setOperationAction(ISD::MUL,                MVT::v32i16, Legal);
1602     setOperationAction(ISD::MULHS,              MVT::v32i16, Legal);
1603     setOperationAction(ISD::MULHU,              MVT::v32i16, Legal);
1604     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v32i1, Legal);
1605     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v64i1, Legal);
1606     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v32i16, Custom);
1607     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v64i8, Custom);
1608     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v32i1, Custom);
1609     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v64i1, Custom);
1610     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v32i16, Custom);
1611     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v64i8, Custom);
1612     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v32i16, Custom);
1613     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v64i8, Custom);
1614     setOperationAction(ISD::SELECT,             MVT::v32i1, Custom);
1615     setOperationAction(ISD::SELECT,             MVT::v64i1, Custom);
1616     setOperationAction(ISD::SIGN_EXTEND,        MVT::v32i8, Custom);
1617     setOperationAction(ISD::ZERO_EXTEND,        MVT::v32i8, Custom);
1618     setOperationAction(ISD::SIGN_EXTEND,        MVT::v32i16, Custom);
1619     setOperationAction(ISD::ZERO_EXTEND,        MVT::v32i16, Custom);
1620     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v32i16, Custom);
1621     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v64i8, Custom);
1622     setOperationAction(ISD::SIGN_EXTEND,        MVT::v64i8, Custom);
1623     setOperationAction(ISD::ZERO_EXTEND,        MVT::v64i8, Custom);
1624     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v32i1, Custom);
1625     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v64i1, Custom);
1626     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v32i16, Custom);
1627     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v64i8, Custom);
1628     setOperationAction(ISD::VSELECT,            MVT::v32i16, Legal);
1629     setOperationAction(ISD::VSELECT,            MVT::v64i8, Legal);
1630     setOperationAction(ISD::TRUNCATE,           MVT::v32i1, Custom);
1631     setOperationAction(ISD::TRUNCATE,           MVT::v64i1, Custom);
1632     setOperationAction(ISD::TRUNCATE,           MVT::v32i8, Custom);
1633     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v32i1, Custom);
1634     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v64i1, Custom);
1635
1636     setOperationAction(ISD::SMAX,               MVT::v64i8, Legal);
1637     setOperationAction(ISD::SMAX,               MVT::v32i16, Legal);
1638     setOperationAction(ISD::UMAX,               MVT::v64i8, Legal);
1639     setOperationAction(ISD::UMAX,               MVT::v32i16, Legal);
1640     setOperationAction(ISD::SMIN,               MVT::v64i8, Legal);
1641     setOperationAction(ISD::SMIN,               MVT::v32i16, Legal);
1642     setOperationAction(ISD::UMIN,               MVT::v64i8, Legal);
1643     setOperationAction(ISD::UMIN,               MVT::v32i16, Legal);
1644
1645     setTruncStoreAction(MVT::v32i16,  MVT::v32i8, Legal);
1646     setTruncStoreAction(MVT::v16i16,  MVT::v16i8, Legal);
1647     if (Subtarget->hasVLX())
1648       setTruncStoreAction(MVT::v8i16,   MVT::v8i8,  Legal);
1649
1650     if (Subtarget->hasCDI()) {
1651       setOperationAction(ISD::CTLZ,            MVT::v32i16, Custom);
1652       setOperationAction(ISD::CTLZ,            MVT::v64i8,  Custom);
1653       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v32i16, Custom);
1654       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v64i8,  Custom);
1655     }
1656
1657     for (auto VT : { MVT::v64i8, MVT::v32i16 }) {
1658       setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1659       setOperationAction(ISD::VSELECT,             VT, Legal);
1660     }
1661   }
1662
1663   if (!Subtarget->useSoftFloat() && Subtarget->hasVLX()) {
1664     addRegisterClass(MVT::v4i1,   &X86::VK4RegClass);
1665     addRegisterClass(MVT::v2i1,   &X86::VK2RegClass);
1666
1667     setOperationAction(ISD::SETCC,              MVT::v4i1, Custom);
1668     setOperationAction(ISD::SETCC,              MVT::v2i1, Custom);
1669     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i1, Custom);
1670     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1, Custom);
1671     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v8i1, Custom);
1672     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v4i1, Custom);
1673     setOperationAction(ISD::SELECT,             MVT::v4i1, Custom);
1674     setOperationAction(ISD::SELECT,             MVT::v2i1, Custom);
1675     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4i1, Custom);
1676     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i1, Custom);
1677     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i1, Custom);
1678     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4i1, Custom);
1679
1680     setOperationAction(ISD::AND,                MVT::v8i32, Legal);
1681     setOperationAction(ISD::OR,                 MVT::v8i32, Legal);
1682     setOperationAction(ISD::XOR,                MVT::v8i32, Legal);
1683     setOperationAction(ISD::AND,                MVT::v4i32, Legal);
1684     setOperationAction(ISD::OR,                 MVT::v4i32, Legal);
1685     setOperationAction(ISD::XOR,                MVT::v4i32, Legal);
1686     setOperationAction(ISD::SRA,                MVT::v2i64, Custom);
1687     setOperationAction(ISD::SRA,                MVT::v4i64, Custom);
1688
1689     setOperationAction(ISD::SMAX,               MVT::v2i64, Legal);
1690     setOperationAction(ISD::SMAX,               MVT::v4i64, Legal);
1691     setOperationAction(ISD::UMAX,               MVT::v2i64, Legal);
1692     setOperationAction(ISD::UMAX,               MVT::v4i64, Legal);
1693     setOperationAction(ISD::SMIN,               MVT::v2i64, Legal);
1694     setOperationAction(ISD::SMIN,               MVT::v4i64, Legal);
1695     setOperationAction(ISD::UMIN,               MVT::v2i64, Legal);
1696     setOperationAction(ISD::UMIN,               MVT::v4i64, Legal);
1697   }
1698
1699   // We want to custom lower some of our intrinsics.
1700   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1701   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1702   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1703   if (!Subtarget->is64Bit())
1704     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1705
1706   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1707   // handle type legalization for these operations here.
1708   //
1709   // FIXME: We really should do custom legalization for addition and
1710   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1711   // than generic legalization for 64-bit multiplication-with-overflow, though.
1712   for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
1713     if (VT == MVT::i64 && !Subtarget->is64Bit())
1714       continue;
1715     // Add/Sub/Mul with overflow operations are custom lowered.
1716     setOperationAction(ISD::SADDO, VT, Custom);
1717     setOperationAction(ISD::UADDO, VT, Custom);
1718     setOperationAction(ISD::SSUBO, VT, Custom);
1719     setOperationAction(ISD::USUBO, VT, Custom);
1720     setOperationAction(ISD::SMULO, VT, Custom);
1721     setOperationAction(ISD::UMULO, VT, Custom);
1722   }
1723
1724   if (!Subtarget->is64Bit()) {
1725     // These libcalls are not available in 32-bit.
1726     setLibcallName(RTLIB::SHL_I128, nullptr);
1727     setLibcallName(RTLIB::SRL_I128, nullptr);
1728     setLibcallName(RTLIB::SRA_I128, nullptr);
1729   }
1730
1731   // Combine sin / cos into one node or libcall if possible.
1732   if (Subtarget->hasSinCos()) {
1733     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1734     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1735     if (Subtarget->isTargetDarwin()) {
1736       // For MacOSX, we don't want the normal expansion of a libcall to sincos.
1737       // We want to issue a libcall to __sincos_stret to avoid memory traffic.
1738       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1739       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1740     }
1741   }
1742
1743   if (Subtarget->isTargetWin64()) {
1744     setOperationAction(ISD::SDIV, MVT::i128, Custom);
1745     setOperationAction(ISD::UDIV, MVT::i128, Custom);
1746     setOperationAction(ISD::SREM, MVT::i128, Custom);
1747     setOperationAction(ISD::UREM, MVT::i128, Custom);
1748     setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1749     setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1750   }
1751
1752   // We have target-specific dag combine patterns for the following nodes:
1753   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1754   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1755   setTargetDAGCombine(ISD::BITCAST);
1756   setTargetDAGCombine(ISD::VSELECT);
1757   setTargetDAGCombine(ISD::SELECT);
1758   setTargetDAGCombine(ISD::SHL);
1759   setTargetDAGCombine(ISD::SRA);
1760   setTargetDAGCombine(ISD::SRL);
1761   setTargetDAGCombine(ISD::OR);
1762   setTargetDAGCombine(ISD::AND);
1763   setTargetDAGCombine(ISD::ADD);
1764   setTargetDAGCombine(ISD::FADD);
1765   setTargetDAGCombine(ISD::FSUB);
1766   setTargetDAGCombine(ISD::FMA);
1767   setTargetDAGCombine(ISD::SUB);
1768   setTargetDAGCombine(ISD::LOAD);
1769   setTargetDAGCombine(ISD::MLOAD);
1770   setTargetDAGCombine(ISD::STORE);
1771   setTargetDAGCombine(ISD::MSTORE);
1772   setTargetDAGCombine(ISD::ZERO_EXTEND);
1773   setTargetDAGCombine(ISD::ANY_EXTEND);
1774   setTargetDAGCombine(ISD::SIGN_EXTEND);
1775   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1776   setTargetDAGCombine(ISD::SINT_TO_FP);
1777   setTargetDAGCombine(ISD::UINT_TO_FP);
1778   setTargetDAGCombine(ISD::SETCC);
1779   setTargetDAGCombine(ISD::BUILD_VECTOR);
1780   setTargetDAGCombine(ISD::MUL);
1781   setTargetDAGCombine(ISD::XOR);
1782
1783   computeRegisterProperties(Subtarget->getRegisterInfo());
1784
1785   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1786   MaxStoresPerMemsetOptSize = 8;
1787   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1788   MaxStoresPerMemcpyOptSize = 4;
1789   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1790   MaxStoresPerMemmoveOptSize = 4;
1791   setPrefLoopAlignment(4); // 2^4 bytes.
1792
1793   // A predictable cmov does not hurt on an in-order CPU.
1794   // FIXME: Use a CPU attribute to trigger this, not a CPU model.
1795   PredictableSelectIsExpensive = !Subtarget->isAtom();
1796   EnableExtLdPromotion = true;
1797   setPrefFunctionAlignment(4); // 2^4 bytes.
1798
1799   verifyIntrinsicTables();
1800 }
1801
1802 // This has so far only been implemented for 64-bit MachO.
1803 bool X86TargetLowering::useLoadStackGuardNode() const {
1804   return Subtarget->isTargetMachO() && Subtarget->is64Bit();
1805 }
1806
1807 TargetLoweringBase::LegalizeTypeAction
1808 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1809   if (ExperimentalVectorWideningLegalization &&
1810       VT.getVectorNumElements() != 1 &&
1811       VT.getVectorElementType().getSimpleVT() != MVT::i1)
1812     return TypeWidenVector;
1813
1814   return TargetLoweringBase::getPreferredVectorAction(VT);
1815 }
1816
1817 EVT X86TargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1818                                           EVT VT) const {
1819   if (!VT.isVector())
1820     return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1821
1822   if (VT.isSimple()) {
1823     MVT VVT = VT.getSimpleVT();
1824     const unsigned NumElts = VVT.getVectorNumElements();
1825     const MVT EltVT = VVT.getVectorElementType();
1826     if (VVT.is512BitVector()) {
1827       if (Subtarget->hasAVX512())
1828         if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1829             EltVT == MVT::f32 || EltVT == MVT::f64)
1830           switch(NumElts) {
1831           case  8: return MVT::v8i1;
1832           case 16: return MVT::v16i1;
1833         }
1834       if (Subtarget->hasBWI())
1835         if (EltVT == MVT::i8 || EltVT == MVT::i16)
1836           switch(NumElts) {
1837           case 32: return MVT::v32i1;
1838           case 64: return MVT::v64i1;
1839         }
1840     }
1841
1842     if (VVT.is256BitVector() || VVT.is128BitVector()) {
1843       if (Subtarget->hasVLX())
1844         if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1845             EltVT == MVT::f32 || EltVT == MVT::f64)
1846           switch(NumElts) {
1847           case 2: return MVT::v2i1;
1848           case 4: return MVT::v4i1;
1849           case 8: return MVT::v8i1;
1850         }
1851       if (Subtarget->hasBWI() && Subtarget->hasVLX())
1852         if (EltVT == MVT::i8 || EltVT == MVT::i16)
1853           switch(NumElts) {
1854           case  8: return MVT::v8i1;
1855           case 16: return MVT::v16i1;
1856           case 32: return MVT::v32i1;
1857         }
1858     }
1859   }
1860
1861   return VT.changeVectorElementTypeToInteger();
1862 }
1863
1864 /// Helper for getByValTypeAlignment to determine
1865 /// the desired ByVal argument alignment.
1866 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1867   if (MaxAlign == 16)
1868     return;
1869   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1870     if (VTy->getBitWidth() == 128)
1871       MaxAlign = 16;
1872   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1873     unsigned EltAlign = 0;
1874     getMaxByValAlign(ATy->getElementType(), EltAlign);
1875     if (EltAlign > MaxAlign)
1876       MaxAlign = EltAlign;
1877   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1878     for (auto *EltTy : STy->elements()) {
1879       unsigned EltAlign = 0;
1880       getMaxByValAlign(EltTy, EltAlign);
1881       if (EltAlign > MaxAlign)
1882         MaxAlign = EltAlign;
1883       if (MaxAlign == 16)
1884         break;
1885     }
1886   }
1887 }
1888
1889 /// Return the desired alignment for ByVal aggregate
1890 /// function arguments in the caller parameter area. For X86, aggregates
1891 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1892 /// are at 4-byte boundaries.
1893 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty,
1894                                                   const DataLayout &DL) const {
1895   if (Subtarget->is64Bit()) {
1896     // Max of 8 and alignment of type.
1897     unsigned TyAlign = DL.getABITypeAlignment(Ty);
1898     if (TyAlign > 8)
1899       return TyAlign;
1900     return 8;
1901   }
1902
1903   unsigned Align = 4;
1904   if (Subtarget->hasSSE1())
1905     getMaxByValAlign(Ty, Align);
1906   return Align;
1907 }
1908
1909 /// Returns the target specific optimal type for load
1910 /// and store operations as a result of memset, memcpy, and memmove
1911 /// lowering. If DstAlign is zero that means it's safe to destination
1912 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1913 /// means there isn't a need to check it against alignment requirement,
1914 /// probably because the source does not need to be loaded. If 'IsMemset' is
1915 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1916 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1917 /// source is constant so it does not need to be loaded.
1918 /// It returns EVT::Other if the type should be determined using generic
1919 /// target-independent logic.
1920 EVT
1921 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1922                                        unsigned DstAlign, unsigned SrcAlign,
1923                                        bool IsMemset, bool ZeroMemset,
1924                                        bool MemcpyStrSrc,
1925                                        MachineFunction &MF) const {
1926   const Function *F = MF.getFunction();
1927   if ((!IsMemset || ZeroMemset) &&
1928       !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1929     if (Size >= 16 &&
1930         (!Subtarget->isUnalignedMem16Slow() ||
1931          ((DstAlign == 0 || DstAlign >= 16) &&
1932           (SrcAlign == 0 || SrcAlign >= 16)))) {
1933       if (Size >= 32) {
1934         // FIXME: Check if unaligned 32-byte accesses are slow.
1935         if (Subtarget->hasInt256())
1936           return MVT::v8i32;
1937         if (Subtarget->hasFp256())
1938           return MVT::v8f32;
1939       }
1940       if (Subtarget->hasSSE2())
1941         return MVT::v4i32;
1942       if (Subtarget->hasSSE1())
1943         return MVT::v4f32;
1944     } else if (!MemcpyStrSrc && Size >= 8 &&
1945                !Subtarget->is64Bit() &&
1946                Subtarget->hasSSE2()) {
1947       // Do not use f64 to lower memcpy if source is string constant. It's
1948       // better to use i32 to avoid the loads.
1949       return MVT::f64;
1950     }
1951   }
1952   // This is a compromise. If we reach here, unaligned accesses may be slow on
1953   // this target. However, creating smaller, aligned accesses could be even
1954   // slower and would certainly be a lot more code.
1955   if (Subtarget->is64Bit() && Size >= 8)
1956     return MVT::i64;
1957   return MVT::i32;
1958 }
1959
1960 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1961   if (VT == MVT::f32)
1962     return X86ScalarSSEf32;
1963   else if (VT == MVT::f64)
1964     return X86ScalarSSEf64;
1965   return true;
1966 }
1967
1968 bool
1969 X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1970                                                   unsigned,
1971                                                   unsigned,
1972                                                   bool *Fast) const {
1973   if (Fast) {
1974     switch (VT.getSizeInBits()) {
1975     default:
1976       // 8-byte and under are always assumed to be fast.
1977       *Fast = true;
1978       break;
1979     case 128:
1980       *Fast = !Subtarget->isUnalignedMem16Slow();
1981       break;
1982     case 256:
1983       *Fast = !Subtarget->isUnalignedMem32Slow();
1984       break;
1985     // TODO: What about AVX-512 (512-bit) accesses?
1986     }
1987   }
1988   // Misaligned accesses of any size are always allowed.
1989   return true;
1990 }
1991
1992 /// Return the entry encoding for a jump table in the
1993 /// current function.  The returned value is a member of the
1994 /// MachineJumpTableInfo::JTEntryKind enum.
1995 unsigned X86TargetLowering::getJumpTableEncoding() const {
1996   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1997   // symbol.
1998   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1999       Subtarget->isPICStyleGOT())
2000     return MachineJumpTableInfo::EK_Custom32;
2001
2002   // Otherwise, use the normal jump table encoding heuristics.
2003   return TargetLowering::getJumpTableEncoding();
2004 }
2005
2006 bool X86TargetLowering::useSoftFloat() const {
2007   return Subtarget->useSoftFloat();
2008 }
2009
2010 const MCExpr *
2011 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
2012                                              const MachineBasicBlock *MBB,
2013                                              unsigned uid,MCContext &Ctx) const{
2014   assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
2015          Subtarget->isPICStyleGOT());
2016   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
2017   // entries.
2018   return MCSymbolRefExpr::create(MBB->getSymbol(),
2019                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
2020 }
2021
2022 /// Returns relocation base for the given PIC jumptable.
2023 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
2024                                                     SelectionDAG &DAG) const {
2025   if (!Subtarget->is64Bit())
2026     // This doesn't have SDLoc associated with it, but is not really the
2027     // same as a Register.
2028     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
2029                        getPointerTy(DAG.getDataLayout()));
2030   return Table;
2031 }
2032
2033 /// This returns the relocation base for the given PIC jumptable,
2034 /// the same as getPICJumpTableRelocBase, but as an MCExpr.
2035 const MCExpr *X86TargetLowering::
2036 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
2037                              MCContext &Ctx) const {
2038   // X86-64 uses RIP relative addressing based on the jump table label.
2039   if (Subtarget->isPICStyleRIPRel())
2040     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2041
2042   // Otherwise, the reference is relative to the PIC base.
2043   return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
2044 }
2045
2046 std::pair<const TargetRegisterClass *, uint8_t>
2047 X86TargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
2048                                            MVT VT) const {
2049   const TargetRegisterClass *RRC = nullptr;
2050   uint8_t Cost = 1;
2051   switch (VT.SimpleTy) {
2052   default:
2053     return TargetLowering::findRepresentativeClass(TRI, VT);
2054   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
2055     RRC = Subtarget->is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
2056     break;
2057   case MVT::x86mmx:
2058     RRC = &X86::VR64RegClass;
2059     break;
2060   case MVT::f32: case MVT::f64:
2061   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
2062   case MVT::v4f32: case MVT::v2f64:
2063   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
2064   case MVT::v4f64:
2065     RRC = &X86::VR128RegClass;
2066     break;
2067   }
2068   return std::make_pair(RRC, Cost);
2069 }
2070
2071 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
2072                                                unsigned &Offset) const {
2073   if (!Subtarget->isTargetLinux())
2074     return false;
2075
2076   if (Subtarget->is64Bit()) {
2077     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
2078     Offset = 0x28;
2079     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
2080       AddressSpace = 256;
2081     else
2082       AddressSpace = 257;
2083   } else {
2084     // %gs:0x14 on i386
2085     Offset = 0x14;
2086     AddressSpace = 256;
2087   }
2088   return true;
2089 }
2090
2091 Value *X86TargetLowering::getSafeStackPointerLocation(IRBuilder<> &IRB) const {
2092   if (!Subtarget->isTargetAndroid())
2093     return TargetLowering::getSafeStackPointerLocation(IRB);
2094
2095   // Android provides a fixed TLS slot for the SafeStack pointer. See the
2096   // definition of TLS_SLOT_SAFESTACK in
2097   // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
2098   unsigned AddressSpace, Offset;
2099   if (Subtarget->is64Bit()) {
2100     // %fs:0x48, unless we're using a Kernel code model, in which case it's %gs:
2101     Offset = 0x48;
2102     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
2103       AddressSpace = 256;
2104     else
2105       AddressSpace = 257;
2106   } else {
2107     // %gs:0x24 on i386
2108     Offset = 0x24;
2109     AddressSpace = 256;
2110   }
2111
2112   return ConstantExpr::getIntToPtr(
2113       ConstantInt::get(Type::getInt32Ty(IRB.getContext()), Offset),
2114       Type::getInt8PtrTy(IRB.getContext())->getPointerTo(AddressSpace));
2115 }
2116
2117 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
2118                                             unsigned DestAS) const {
2119   assert(SrcAS != DestAS && "Expected different address spaces!");
2120
2121   return SrcAS < 256 && DestAS < 256;
2122 }
2123
2124 //===----------------------------------------------------------------------===//
2125 //               Return Value Calling Convention Implementation
2126 //===----------------------------------------------------------------------===//
2127
2128 #include "X86GenCallingConv.inc"
2129
2130 bool X86TargetLowering::CanLowerReturn(
2131     CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
2132     const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
2133   SmallVector<CCValAssign, 16> RVLocs;
2134   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2135   return CCInfo.CheckReturn(Outs, RetCC_X86);
2136 }
2137
2138 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
2139   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
2140   return ScratchRegs;
2141 }
2142
2143 SDValue
2144 X86TargetLowering::LowerReturn(SDValue Chain,
2145                                CallingConv::ID CallConv, bool isVarArg,
2146                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2147                                const SmallVectorImpl<SDValue> &OutVals,
2148                                SDLoc dl, SelectionDAG &DAG) const {
2149   MachineFunction &MF = DAG.getMachineFunction();
2150   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2151
2152   SmallVector<CCValAssign, 16> RVLocs;
2153   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
2154   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
2155
2156   SDValue Flag;
2157   SmallVector<SDValue, 6> RetOps;
2158   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2159   // Operand #1 = Bytes To Pop
2160   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(), dl,
2161                    MVT::i16));
2162
2163   // Copy the result values into the output registers.
2164   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2165     CCValAssign &VA = RVLocs[i];
2166     assert(VA.isRegLoc() && "Can only return in registers!");
2167     SDValue ValToCopy = OutVals[i];
2168     EVT ValVT = ValToCopy.getValueType();
2169
2170     // Promote values to the appropriate types.
2171     if (VA.getLocInfo() == CCValAssign::SExt)
2172       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2173     else if (VA.getLocInfo() == CCValAssign::ZExt)
2174       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
2175     else if (VA.getLocInfo() == CCValAssign::AExt) {
2176       if (ValVT.isVector() && ValVT.getVectorElementType() == MVT::i1)
2177         ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2178       else
2179         ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
2180     }
2181     else if (VA.getLocInfo() == CCValAssign::BCvt)
2182       ValToCopy = DAG.getBitcast(VA.getLocVT(), ValToCopy);
2183
2184     assert(VA.getLocInfo() != CCValAssign::FPExt &&
2185            "Unexpected FP-extend for return value.");
2186
2187     // If this is x86-64, and we disabled SSE, we can't return FP values,
2188     // or SSE or MMX vectors.
2189     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
2190          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
2191           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
2192       report_fatal_error("SSE register return with SSE disabled");
2193     }
2194     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
2195     // llvm-gcc has never done it right and no one has noticed, so this
2196     // should be OK for now.
2197     if (ValVT == MVT::f64 &&
2198         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
2199       report_fatal_error("SSE2 register return with SSE2 disabled");
2200
2201     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
2202     // the RET instruction and handled by the FP Stackifier.
2203     if (VA.getLocReg() == X86::FP0 ||
2204         VA.getLocReg() == X86::FP1) {
2205       // If this is a copy from an xmm register to ST(0), use an FPExtend to
2206       // change the value to the FP stack register class.
2207       if (isScalarFPTypeInSSEReg(VA.getValVT()))
2208         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
2209       RetOps.push_back(ValToCopy);
2210       // Don't emit a copytoreg.
2211       continue;
2212     }
2213
2214     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
2215     // which is returned in RAX / RDX.
2216     if (Subtarget->is64Bit()) {
2217       if (ValVT == MVT::x86mmx) {
2218         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
2219           ValToCopy = DAG.getBitcast(MVT::i64, ValToCopy);
2220           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
2221                                   ValToCopy);
2222           // If we don't have SSE2 available, convert to v4f32 so the generated
2223           // register is legal.
2224           if (!Subtarget->hasSSE2())
2225             ValToCopy = DAG.getBitcast(MVT::v4f32, ValToCopy);
2226         }
2227       }
2228     }
2229
2230     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
2231     Flag = Chain.getValue(1);
2232     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2233   }
2234
2235   // All x86 ABIs require that for returning structs by value we copy
2236   // the sret argument into %rax/%eax (depending on ABI) for the return.
2237   // We saved the argument into a virtual register in the entry block,
2238   // so now we copy the value out and into %rax/%eax.
2239   //
2240   // Checking Function.hasStructRetAttr() here is insufficient because the IR
2241   // may not have an explicit sret argument. If FuncInfo.CanLowerReturn is
2242   // false, then an sret argument may be implicitly inserted in the SelDAG. In
2243   // either case FuncInfo->setSRetReturnReg() will have been called.
2244   if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
2245     SDValue Val = DAG.getCopyFromReg(Chain, dl, SRetReg,
2246                                      getPointerTy(MF.getDataLayout()));
2247
2248     unsigned RetValReg
2249         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
2250           X86::RAX : X86::EAX;
2251     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2252     Flag = Chain.getValue(1);
2253
2254     // RAX/EAX now acts like a return value.
2255     RetOps.push_back(
2256         DAG.getRegister(RetValReg, getPointerTy(DAG.getDataLayout())));
2257   }
2258
2259   RetOps[0] = Chain;  // Update chain.
2260
2261   // Add the flag if we have it.
2262   if (Flag.getNode())
2263     RetOps.push_back(Flag);
2264
2265   return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
2266 }
2267
2268 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2269   if (N->getNumValues() != 1)
2270     return false;
2271   if (!N->hasNUsesOfValue(1, 0))
2272     return false;
2273
2274   SDValue TCChain = Chain;
2275   SDNode *Copy = *N->use_begin();
2276   if (Copy->getOpcode() == ISD::CopyToReg) {
2277     // If the copy has a glue operand, we conservatively assume it isn't safe to
2278     // perform a tail call.
2279     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2280       return false;
2281     TCChain = Copy->getOperand(0);
2282   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2283     return false;
2284
2285   bool HasRet = false;
2286   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2287        UI != UE; ++UI) {
2288     if (UI->getOpcode() != X86ISD::RET_FLAG)
2289       return false;
2290     // If we are returning more than one value, we can definitely
2291     // not make a tail call see PR19530
2292     if (UI->getNumOperands() > 4)
2293       return false;
2294     if (UI->getNumOperands() == 4 &&
2295         UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2296       return false;
2297     HasRet = true;
2298   }
2299
2300   if (!HasRet)
2301     return false;
2302
2303   Chain = TCChain;
2304   return true;
2305 }
2306
2307 EVT
2308 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
2309                                             ISD::NodeType ExtendKind) const {
2310   MVT ReturnMVT;
2311   // TODO: Is this also valid on 32-bit?
2312   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2313     ReturnMVT = MVT::i8;
2314   else
2315     ReturnMVT = MVT::i32;
2316
2317   EVT MinVT = getRegisterType(Context, ReturnMVT);
2318   return VT.bitsLT(MinVT) ? MinVT : VT;
2319 }
2320
2321 /// Lower the result values of a call into the
2322 /// appropriate copies out of appropriate physical registers.
2323 ///
2324 SDValue
2325 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2326                                    CallingConv::ID CallConv, bool isVarArg,
2327                                    const SmallVectorImpl<ISD::InputArg> &Ins,
2328                                    SDLoc dl, SelectionDAG &DAG,
2329                                    SmallVectorImpl<SDValue> &InVals) const {
2330
2331   // Assign locations to each value returned by this call.
2332   SmallVector<CCValAssign, 16> RVLocs;
2333   bool Is64Bit = Subtarget->is64Bit();
2334   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2335                  *DAG.getContext());
2336   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2337
2338   // Copy all of the result registers out of their specified physreg.
2339   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2340     CCValAssign &VA = RVLocs[i];
2341     EVT CopyVT = VA.getLocVT();
2342
2343     // If this is x86-64, and we disabled SSE, we can't return FP values
2344     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2345         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2346       report_fatal_error("SSE register return with SSE disabled");
2347     }
2348
2349     // If we prefer to use the value in xmm registers, copy it out as f80 and
2350     // use a truncate to move it from fp stack reg to xmm reg.
2351     bool RoundAfterCopy = false;
2352     if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2353         isScalarFPTypeInSSEReg(VA.getValVT())) {
2354       CopyVT = MVT::f80;
2355       RoundAfterCopy = (CopyVT != VA.getLocVT());
2356     }
2357
2358     Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2359                                CopyVT, InFlag).getValue(1);
2360     SDValue Val = Chain.getValue(0);
2361
2362     if (RoundAfterCopy)
2363       Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2364                         // This truncation won't change the value.
2365                         DAG.getIntPtrConstant(1, dl));
2366
2367     if (VA.isExtInLoc() && VA.getValVT().getScalarType() == MVT::i1)
2368       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
2369
2370     InFlag = Chain.getValue(2);
2371     InVals.push_back(Val);
2372   }
2373
2374   return Chain;
2375 }
2376
2377 //===----------------------------------------------------------------------===//
2378 //                C & StdCall & Fast Calling Convention implementation
2379 //===----------------------------------------------------------------------===//
2380 //  StdCall calling convention seems to be standard for many Windows' API
2381 //  routines and around. It differs from C calling convention just a little:
2382 //  callee should clean up the stack, not caller. Symbols should be also
2383 //  decorated in some fancy way :) It doesn't support any vector arguments.
2384 //  For info on fast calling convention see Fast Calling Convention (tail call)
2385 //  implementation LowerX86_32FastCCCallTo.
2386
2387 /// CallIsStructReturn - Determines whether a call uses struct return
2388 /// semantics.
2389 enum StructReturnType {
2390   NotStructReturn,
2391   RegStructReturn,
2392   StackStructReturn
2393 };
2394 static StructReturnType
2395 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2396   if (Outs.empty())
2397     return NotStructReturn;
2398
2399   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2400   if (!Flags.isSRet())
2401     return NotStructReturn;
2402   if (Flags.isInReg())
2403     return RegStructReturn;
2404   return StackStructReturn;
2405 }
2406
2407 /// Determines whether a function uses struct return semantics.
2408 static StructReturnType
2409 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2410   if (Ins.empty())
2411     return NotStructReturn;
2412
2413   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2414   if (!Flags.isSRet())
2415     return NotStructReturn;
2416   if (Flags.isInReg())
2417     return RegStructReturn;
2418   return StackStructReturn;
2419 }
2420
2421 /// Make a copy of an aggregate at address specified by "Src" to address
2422 /// "Dst" with size and alignment information specified by the specific
2423 /// parameter attribute. The copy will be passed as a byval function parameter.
2424 static SDValue
2425 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2426                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2427                           SDLoc dl) {
2428   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
2429
2430   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2431                        /*isVolatile*/false, /*AlwaysInline=*/true,
2432                        /*isTailCall*/false,
2433                        MachinePointerInfo(), MachinePointerInfo());
2434 }
2435
2436 /// Return true if the calling convention is one that we can guarantee TCO for.
2437 static bool canGuaranteeTCO(CallingConv::ID CC) {
2438   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2439           CC == CallingConv::HiPE || CC == CallingConv::HHVM);
2440 }
2441
2442 /// Return true if we might ever do TCO for calls with this calling convention.
2443 static bool mayTailCallThisCC(CallingConv::ID CC) {
2444   switch (CC) {
2445   // C calling conventions:
2446   case CallingConv::C:
2447   case CallingConv::X86_64_Win64:
2448   case CallingConv::X86_64_SysV:
2449   // Callee pop conventions:
2450   case CallingConv::X86_ThisCall:
2451   case CallingConv::X86_StdCall:
2452   case CallingConv::X86_VectorCall:
2453   case CallingConv::X86_FastCall:
2454     return true;
2455   default:
2456     return canGuaranteeTCO(CC);
2457   }
2458 }
2459
2460 /// Return true if the function is being made into a tailcall target by
2461 /// changing its ABI.
2462 static bool shouldGuaranteeTCO(CallingConv::ID CC, bool GuaranteedTailCallOpt) {
2463   return GuaranteedTailCallOpt && canGuaranteeTCO(CC);
2464 }
2465
2466 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2467   auto Attr =
2468       CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2469   if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2470     return false;
2471
2472   CallSite CS(CI);
2473   CallingConv::ID CalleeCC = CS.getCallingConv();
2474   if (!mayTailCallThisCC(CalleeCC))
2475     return false;
2476
2477   return true;
2478 }
2479
2480 SDValue
2481 X86TargetLowering::LowerMemArgument(SDValue Chain,
2482                                     CallingConv::ID CallConv,
2483                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2484                                     SDLoc dl, SelectionDAG &DAG,
2485                                     const CCValAssign &VA,
2486                                     MachineFrameInfo *MFI,
2487                                     unsigned i) const {
2488   // Create the nodes corresponding to a load from this parameter slot.
2489   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2490   bool AlwaysUseMutable = shouldGuaranteeTCO(
2491       CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2492   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2493   EVT ValVT;
2494
2495   // If value is passed by pointer we have address passed instead of the value
2496   // itself.
2497   bool ExtendedInMem = VA.isExtInLoc() &&
2498     VA.getValVT().getScalarType() == MVT::i1;
2499
2500   if (VA.getLocInfo() == CCValAssign::Indirect || ExtendedInMem)
2501     ValVT = VA.getLocVT();
2502   else
2503     ValVT = VA.getValVT();
2504
2505   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2506   // changed with more analysis.
2507   // In case of tail call optimization mark all arguments mutable. Since they
2508   // could be overwritten by lowering of arguments in case of a tail call.
2509   if (Flags.isByVal()) {
2510     unsigned Bytes = Flags.getByValSize();
2511     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2512     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2513     return DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2514   } else {
2515     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2516                                     VA.getLocMemOffset(), isImmutable);
2517     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2518     SDValue Val = DAG.getLoad(
2519         ValVT, dl, Chain, FIN,
2520         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), false,
2521         false, false, 0);
2522     return ExtendedInMem ?
2523       DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val) : Val;
2524   }
2525 }
2526
2527 // FIXME: Get this from tablegen.
2528 static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
2529                                                 const X86Subtarget *Subtarget) {
2530   assert(Subtarget->is64Bit());
2531
2532   if (Subtarget->isCallingConvWin64(CallConv)) {
2533     static const MCPhysReg GPR64ArgRegsWin64[] = {
2534       X86::RCX, X86::RDX, X86::R8,  X86::R9
2535     };
2536     return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
2537   }
2538
2539   static const MCPhysReg GPR64ArgRegs64Bit[] = {
2540     X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2541   };
2542   return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
2543 }
2544
2545 // FIXME: Get this from tablegen.
2546 static ArrayRef<MCPhysReg> get64BitArgumentXMMs(MachineFunction &MF,
2547                                                 CallingConv::ID CallConv,
2548                                                 const X86Subtarget *Subtarget) {
2549   assert(Subtarget->is64Bit());
2550   if (Subtarget->isCallingConvWin64(CallConv)) {
2551     // The XMM registers which might contain var arg parameters are shadowed
2552     // in their paired GPR.  So we only need to save the GPR to their home
2553     // slots.
2554     // TODO: __vectorcall will change this.
2555     return None;
2556   }
2557
2558   const Function *Fn = MF.getFunction();
2559   bool NoImplicitFloatOps = Fn->hasFnAttribute(Attribute::NoImplicitFloat);
2560   bool isSoftFloat = Subtarget->useSoftFloat();
2561   assert(!(isSoftFloat && NoImplicitFloatOps) &&
2562          "SSE register cannot be used when SSE is disabled!");
2563   if (isSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
2564     // Kernel mode asks for SSE to be disabled, so there are no XMM argument
2565     // registers.
2566     return None;
2567
2568   static const MCPhysReg XMMArgRegs64Bit[] = {
2569     X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2570     X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2571   };
2572   return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
2573 }
2574
2575 SDValue X86TargetLowering::LowerFormalArguments(
2576     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2577     const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc dl, SelectionDAG &DAG,
2578     SmallVectorImpl<SDValue> &InVals) const {
2579   MachineFunction &MF = DAG.getMachineFunction();
2580   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2581   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
2582
2583   const Function* Fn = MF.getFunction();
2584   if (Fn->hasExternalLinkage() &&
2585       Subtarget->isTargetCygMing() &&
2586       Fn->getName() == "main")
2587     FuncInfo->setForceFramePointer(true);
2588
2589   MachineFrameInfo *MFI = MF.getFrameInfo();
2590   bool Is64Bit = Subtarget->is64Bit();
2591   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2592
2593   assert(!(isVarArg && canGuaranteeTCO(CallConv)) &&
2594          "Var args not supported with calling convention fastcc, ghc or hipe");
2595
2596   // Assign locations to all of the incoming arguments.
2597   SmallVector<CCValAssign, 16> ArgLocs;
2598   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2599
2600   // Allocate shadow area for Win64
2601   if (IsWin64)
2602     CCInfo.AllocateStack(32, 8);
2603
2604   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2605
2606   unsigned LastVal = ~0U;
2607   SDValue ArgValue;
2608   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2609     CCValAssign &VA = ArgLocs[i];
2610     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2611     // places.
2612     assert(VA.getValNo() != LastVal &&
2613            "Don't support value assigned to multiple locs yet");
2614     (void)LastVal;
2615     LastVal = VA.getValNo();
2616
2617     if (VA.isRegLoc()) {
2618       EVT RegVT = VA.getLocVT();
2619       const TargetRegisterClass *RC;
2620       if (RegVT == MVT::i32)
2621         RC = &X86::GR32RegClass;
2622       else if (Is64Bit && RegVT == MVT::i64)
2623         RC = &X86::GR64RegClass;
2624       else if (RegVT == MVT::f32)
2625         RC = &X86::FR32RegClass;
2626       else if (RegVT == MVT::f64)
2627         RC = &X86::FR64RegClass;
2628       else if (RegVT.is512BitVector())
2629         RC = &X86::VR512RegClass;
2630       else if (RegVT.is256BitVector())
2631         RC = &X86::VR256RegClass;
2632       else if (RegVT.is128BitVector())
2633         RC = &X86::VR128RegClass;
2634       else if (RegVT == MVT::x86mmx)
2635         RC = &X86::VR64RegClass;
2636       else if (RegVT == MVT::i1)
2637         RC = &X86::VK1RegClass;
2638       else if (RegVT == MVT::v8i1)
2639         RC = &X86::VK8RegClass;
2640       else if (RegVT == MVT::v16i1)
2641         RC = &X86::VK16RegClass;
2642       else if (RegVT == MVT::v32i1)
2643         RC = &X86::VK32RegClass;
2644       else if (RegVT == MVT::v64i1)
2645         RC = &X86::VK64RegClass;
2646       else
2647         llvm_unreachable("Unknown argument type!");
2648
2649       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2650       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2651
2652       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2653       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2654       // right size.
2655       if (VA.getLocInfo() == CCValAssign::SExt)
2656         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2657                                DAG.getValueType(VA.getValVT()));
2658       else if (VA.getLocInfo() == CCValAssign::ZExt)
2659         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2660                                DAG.getValueType(VA.getValVT()));
2661       else if (VA.getLocInfo() == CCValAssign::BCvt)
2662         ArgValue = DAG.getBitcast(VA.getValVT(), ArgValue);
2663
2664       if (VA.isExtInLoc()) {
2665         // Handle MMX values passed in XMM regs.
2666         if (RegVT.isVector() && VA.getValVT().getScalarType() != MVT::i1)
2667           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2668         else
2669           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2670       }
2671     } else {
2672       assert(VA.isMemLoc());
2673       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2674     }
2675
2676     // If value is passed via pointer - do a load.
2677     if (VA.getLocInfo() == CCValAssign::Indirect)
2678       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2679                              MachinePointerInfo(), false, false, false, 0);
2680
2681     InVals.push_back(ArgValue);
2682   }
2683
2684   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2685     // All x86 ABIs require that for returning structs by value we copy the
2686     // sret argument into %rax/%eax (depending on ABI) for the return. Save
2687     // the argument into a virtual register so that we can access it from the
2688     // return points.
2689     if (Ins[i].Flags.isSRet()) {
2690       unsigned Reg = FuncInfo->getSRetReturnReg();
2691       if (!Reg) {
2692         MVT PtrTy = getPointerTy(DAG.getDataLayout());
2693         Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2694         FuncInfo->setSRetReturnReg(Reg);
2695       }
2696       SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2697       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2698       break;
2699     }
2700   }
2701
2702   unsigned StackSize = CCInfo.getNextStackOffset();
2703   // Align stack specially for tail calls.
2704   if (shouldGuaranteeTCO(CallConv,
2705                          MF.getTarget().Options.GuaranteedTailCallOpt))
2706     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2707
2708   // If the function takes variable number of arguments, make a frame index for
2709   // the start of the first vararg value... for expansion of llvm.va_start. We
2710   // can skip this if there are no va_start calls.
2711   if (MFI->hasVAStart() &&
2712       (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2713                    CallConv != CallingConv::X86_ThisCall))) {
2714     FuncInfo->setVarArgsFrameIndex(
2715         MFI->CreateFixedObject(1, StackSize, true));
2716   }
2717
2718   MachineModuleInfo &MMI = MF.getMMI();
2719
2720   // Figure out if XMM registers are in use.
2721   assert(!(Subtarget->useSoftFloat() &&
2722            Fn->hasFnAttribute(Attribute::NoImplicitFloat)) &&
2723          "SSE register cannot be used when SSE is disabled!");
2724
2725   // 64-bit calling conventions support varargs and register parameters, so we
2726   // have to do extra work to spill them in the prologue.
2727   if (Is64Bit && isVarArg && MFI->hasVAStart()) {
2728     // Find the first unallocated argument registers.
2729     ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
2730     ArrayRef<MCPhysReg> ArgXMMs = get64BitArgumentXMMs(MF, CallConv, Subtarget);
2731     unsigned NumIntRegs = CCInfo.getFirstUnallocated(ArgGPRs);
2732     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(ArgXMMs);
2733     assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2734            "SSE register cannot be used when SSE is disabled!");
2735
2736     // Gather all the live in physical registers.
2737     SmallVector<SDValue, 6> LiveGPRs;
2738     SmallVector<SDValue, 8> LiveXMMRegs;
2739     SDValue ALVal;
2740     for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
2741       unsigned GPR = MF.addLiveIn(Reg, &X86::GR64RegClass);
2742       LiveGPRs.push_back(
2743           DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64));
2744     }
2745     if (!ArgXMMs.empty()) {
2746       unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2747       ALVal = DAG.getCopyFromReg(Chain, dl, AL, MVT::i8);
2748       for (MCPhysReg Reg : ArgXMMs.slice(NumXMMRegs)) {
2749         unsigned XMMReg = MF.addLiveIn(Reg, &X86::VR128RegClass);
2750         LiveXMMRegs.push_back(
2751             DAG.getCopyFromReg(Chain, dl, XMMReg, MVT::v4f32));
2752       }
2753     }
2754
2755     if (IsWin64) {
2756       // Get to the caller-allocated home save location.  Add 8 to account
2757       // for the return address.
2758       int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2759       FuncInfo->setRegSaveFrameIndex(
2760           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2761       // Fixup to set vararg frame on shadow area (4 x i64).
2762       if (NumIntRegs < 4)
2763         FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2764     } else {
2765       // For X86-64, if there are vararg parameters that are passed via
2766       // registers, then we must store them to their spots on the stack so
2767       // they may be loaded by deferencing the result of va_next.
2768       FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2769       FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
2770       FuncInfo->setRegSaveFrameIndex(MFI->CreateStackObject(
2771           ArgGPRs.size() * 8 + ArgXMMs.size() * 16, 16, false));
2772     }
2773
2774     // Store the integer parameter registers.
2775     SmallVector<SDValue, 8> MemOps;
2776     SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2777                                       getPointerTy(DAG.getDataLayout()));
2778     unsigned Offset = FuncInfo->getVarArgsGPOffset();
2779     for (SDValue Val : LiveGPRs) {
2780       SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2781                                 RSFIN, DAG.getIntPtrConstant(Offset, dl));
2782       SDValue Store =
2783           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2784                        MachinePointerInfo::getFixedStack(
2785                            DAG.getMachineFunction(),
2786                            FuncInfo->getRegSaveFrameIndex(), Offset),
2787                        false, false, 0);
2788       MemOps.push_back(Store);
2789       Offset += 8;
2790     }
2791
2792     if (!ArgXMMs.empty() && NumXMMRegs != ArgXMMs.size()) {
2793       // Now store the XMM (fp + vector) parameter registers.
2794       SmallVector<SDValue, 12> SaveXMMOps;
2795       SaveXMMOps.push_back(Chain);
2796       SaveXMMOps.push_back(ALVal);
2797       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2798                              FuncInfo->getRegSaveFrameIndex(), dl));
2799       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2800                              FuncInfo->getVarArgsFPOffset(), dl));
2801       SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
2802                         LiveXMMRegs.end());
2803       MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2804                                    MVT::Other, SaveXMMOps));
2805     }
2806
2807     if (!MemOps.empty())
2808       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2809   }
2810
2811   if (isVarArg && MFI->hasMustTailInVarArgFunc()) {
2812     // Find the largest legal vector type.
2813     MVT VecVT = MVT::Other;
2814     // FIXME: Only some x86_32 calling conventions support AVX512.
2815     if (Subtarget->hasAVX512() &&
2816         (Is64Bit || (CallConv == CallingConv::X86_VectorCall ||
2817                      CallConv == CallingConv::Intel_OCL_BI)))
2818       VecVT = MVT::v16f32;
2819     else if (Subtarget->hasAVX())
2820       VecVT = MVT::v8f32;
2821     else if (Subtarget->hasSSE2())
2822       VecVT = MVT::v4f32;
2823
2824     // We forward some GPRs and some vector types.
2825     SmallVector<MVT, 2> RegParmTypes;
2826     MVT IntVT = Is64Bit ? MVT::i64 : MVT::i32;
2827     RegParmTypes.push_back(IntVT);
2828     if (VecVT != MVT::Other)
2829       RegParmTypes.push_back(VecVT);
2830
2831     // Compute the set of forwarded registers. The rest are scratch.
2832     SmallVectorImpl<ForwardedRegister> &Forwards =
2833         FuncInfo->getForwardedMustTailRegParms();
2834     CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, CC_X86);
2835
2836     // Conservatively forward AL on x86_64, since it might be used for varargs.
2837     if (Is64Bit && !CCInfo.isAllocated(X86::AL)) {
2838       unsigned ALVReg = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2839       Forwards.push_back(ForwardedRegister(ALVReg, X86::AL, MVT::i8));
2840     }
2841
2842     // Copy all forwards from physical to virtual registers.
2843     for (ForwardedRegister &F : Forwards) {
2844       // FIXME: Can we use a less constrained schedule?
2845       SDValue RegVal = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2846       F.VReg = MF.getRegInfo().createVirtualRegister(getRegClassFor(F.VT));
2847       Chain = DAG.getCopyToReg(Chain, dl, F.VReg, RegVal);
2848     }
2849   }
2850
2851   // Some CCs need callee pop.
2852   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2853                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2854     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2855   } else {
2856     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2857     // If this is an sret function, the return should pop the hidden pointer.
2858     if (!Is64Bit && !canGuaranteeTCO(CallConv) &&
2859         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2860         argsAreStructReturn(Ins) == StackStructReturn)
2861       FuncInfo->setBytesToPopOnReturn(4);
2862   }
2863
2864   if (!Is64Bit) {
2865     // RegSaveFrameIndex is X86-64 only.
2866     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2867     if (CallConv == CallingConv::X86_FastCall ||
2868         CallConv == CallingConv::X86_ThisCall)
2869       // fastcc functions can't have varargs.
2870       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2871   }
2872
2873   FuncInfo->setArgumentStackSize(StackSize);
2874
2875   if (MMI.hasWinEHFuncInfo(Fn)) {
2876     if (Is64Bit) {
2877       int UnwindHelpFI = MFI->CreateStackObject(8, 8, /*isSS=*/false);
2878       SDValue StackSlot = DAG.getFrameIndex(UnwindHelpFI, MVT::i64);
2879       MMI.getWinEHFuncInfo(MF.getFunction()).UnwindHelpFrameIdx = UnwindHelpFI;
2880       SDValue Neg2 = DAG.getConstant(-2, dl, MVT::i64);
2881       Chain = DAG.getStore(Chain, dl, Neg2, StackSlot,
2882                            MachinePointerInfo::getFixedStack(
2883                                DAG.getMachineFunction(), UnwindHelpFI),
2884                            /*isVolatile=*/true,
2885                            /*isNonTemporal=*/false, /*Alignment=*/0);
2886     }
2887   }
2888
2889   return Chain;
2890 }
2891
2892 SDValue
2893 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2894                                     SDValue StackPtr, SDValue Arg,
2895                                     SDLoc dl, SelectionDAG &DAG,
2896                                     const CCValAssign &VA,
2897                                     ISD::ArgFlagsTy Flags) const {
2898   unsigned LocMemOffset = VA.getLocMemOffset();
2899   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
2900   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2901                        StackPtr, PtrOff);
2902   if (Flags.isByVal())
2903     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2904
2905   return DAG.getStore(
2906       Chain, dl, Arg, PtrOff,
2907       MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset),
2908       false, false, 0);
2909 }
2910
2911 /// Emit a load of return address if tail call
2912 /// optimization is performed and it is required.
2913 SDValue
2914 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2915                                            SDValue &OutRetAddr, SDValue Chain,
2916                                            bool IsTailCall, bool Is64Bit,
2917                                            int FPDiff, SDLoc dl) const {
2918   // Adjust the Return address stack slot.
2919   EVT VT = getPointerTy(DAG.getDataLayout());
2920   OutRetAddr = getReturnAddressFrameIndex(DAG);
2921
2922   // Load the "old" Return address.
2923   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2924                            false, false, false, 0);
2925   return SDValue(OutRetAddr.getNode(), 1);
2926 }
2927
2928 /// Emit a store of the return address if tail call
2929 /// optimization is performed and it is required (FPDiff!=0).
2930 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2931                                         SDValue Chain, SDValue RetAddrFrIdx,
2932                                         EVT PtrVT, unsigned SlotSize,
2933                                         int FPDiff, SDLoc dl) {
2934   // Store the return address to the appropriate stack slot.
2935   if (!FPDiff) return Chain;
2936   // Calculate the new stack slot for the return address.
2937   int NewReturnAddrFI =
2938     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2939                                          false);
2940   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2941   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2942                        MachinePointerInfo::getFixedStack(
2943                            DAG.getMachineFunction(), NewReturnAddrFI),
2944                        false, false, 0);
2945   return Chain;
2946 }
2947
2948 /// Returns a vector_shuffle mask for an movs{s|d}, movd
2949 /// operation of specified width.
2950 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
2951                        SDValue V2) {
2952   unsigned NumElems = VT.getVectorNumElements();
2953   SmallVector<int, 8> Mask;
2954   Mask.push_back(NumElems);
2955   for (unsigned i = 1; i != NumElems; ++i)
2956     Mask.push_back(i);
2957   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
2958 }
2959
2960 SDValue
2961 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2962                              SmallVectorImpl<SDValue> &InVals) const {
2963   SelectionDAG &DAG                     = CLI.DAG;
2964   SDLoc &dl                             = CLI.DL;
2965   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2966   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2967   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2968   SDValue Chain                         = CLI.Chain;
2969   SDValue Callee                        = CLI.Callee;
2970   CallingConv::ID CallConv              = CLI.CallConv;
2971   bool &isTailCall                      = CLI.IsTailCall;
2972   bool isVarArg                         = CLI.IsVarArg;
2973
2974   MachineFunction &MF = DAG.getMachineFunction();
2975   bool Is64Bit        = Subtarget->is64Bit();
2976   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2977   StructReturnType SR = callIsStructReturn(Outs);
2978   bool IsSibcall      = false;
2979   X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2980   auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls");
2981
2982   if (Attr.getValueAsString() == "true")
2983     isTailCall = false;
2984
2985   if (Subtarget->isPICStyleGOT() &&
2986       !MF.getTarget().Options.GuaranteedTailCallOpt) {
2987     // If we are using a GOT, disable tail calls to external symbols with
2988     // default visibility. Tail calling such a symbol requires using a GOT
2989     // relocation, which forces early binding of the symbol. This breaks code
2990     // that require lazy function symbol resolution. Using musttail or
2991     // GuaranteedTailCallOpt will override this.
2992     GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2993     if (!G || (!G->getGlobal()->hasLocalLinkage() &&
2994                G->getGlobal()->hasDefaultVisibility()))
2995       isTailCall = false;
2996   }
2997
2998   bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2999   if (IsMustTail) {
3000     // Force this to be a tail call.  The verifier rules are enough to ensure
3001     // that we can lower this successfully without moving the return address
3002     // around.
3003     isTailCall = true;
3004   } else if (isTailCall) {
3005     // Check if it's really possible to do a tail call.
3006     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
3007                     isVarArg, SR != NotStructReturn,
3008                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
3009                     Outs, OutVals, Ins, DAG);
3010
3011     // Sibcalls are automatically detected tailcalls which do not require
3012     // ABI changes.
3013     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
3014       IsSibcall = true;
3015
3016     if (isTailCall)
3017       ++NumTailCalls;
3018   }
3019
3020   assert(!(isVarArg && canGuaranteeTCO(CallConv)) &&
3021          "Var args not supported with calling convention fastcc, ghc or hipe");
3022
3023   // Analyze operands of the call, assigning locations to each operand.
3024   SmallVector<CCValAssign, 16> ArgLocs;
3025   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
3026
3027   // Allocate shadow area for Win64
3028   if (IsWin64)
3029     CCInfo.AllocateStack(32, 8);
3030
3031   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3032
3033   // Get a count of how many bytes are to be pushed on the stack.
3034   unsigned NumBytes = CCInfo.getAlignedCallFrameSize();
3035   if (IsSibcall)
3036     // This is a sibcall. The memory operands are available in caller's
3037     // own caller's stack.
3038     NumBytes = 0;
3039   else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
3040            canGuaranteeTCO(CallConv))
3041     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
3042
3043   int FPDiff = 0;
3044   if (isTailCall && !IsSibcall && !IsMustTail) {
3045     // Lower arguments at fp - stackoffset + fpdiff.
3046     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
3047
3048     FPDiff = NumBytesCallerPushed - NumBytes;
3049
3050     // Set the delta of movement of the returnaddr stackslot.
3051     // But only set if delta is greater than previous delta.
3052     if (FPDiff < X86Info->getTCReturnAddrDelta())
3053       X86Info->setTCReturnAddrDelta(FPDiff);
3054   }
3055
3056   unsigned NumBytesToPush = NumBytes;
3057   unsigned NumBytesToPop = NumBytes;
3058
3059   // If we have an inalloca argument, all stack space has already been allocated
3060   // for us and be right at the top of the stack.  We don't support multiple
3061   // arguments passed in memory when using inalloca.
3062   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
3063     NumBytesToPush = 0;
3064     if (!ArgLocs.back().isMemLoc())
3065       report_fatal_error("cannot use inalloca attribute on a register "
3066                          "parameter");
3067     if (ArgLocs.back().getLocMemOffset() != 0)
3068       report_fatal_error("any parameter with the inalloca attribute must be "
3069                          "the only memory argument");
3070   }
3071
3072   if (!IsSibcall)
3073     Chain = DAG.getCALLSEQ_START(
3074         Chain, DAG.getIntPtrConstant(NumBytesToPush, dl, true), dl);
3075
3076   SDValue RetAddrFrIdx;
3077   // Load return address for tail calls.
3078   if (isTailCall && FPDiff)
3079     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
3080                                     Is64Bit, FPDiff, dl);
3081
3082   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3083   SmallVector<SDValue, 8> MemOpChains;
3084   SDValue StackPtr;
3085
3086   // Walk the register/memloc assignments, inserting copies/loads.  In the case
3087   // of tail call optimization arguments are handle later.
3088   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3089   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3090     // Skip inalloca arguments, they have already been written.
3091     ISD::ArgFlagsTy Flags = Outs[i].Flags;
3092     if (Flags.isInAlloca())
3093       continue;
3094
3095     CCValAssign &VA = ArgLocs[i];
3096     EVT RegVT = VA.getLocVT();
3097     SDValue Arg = OutVals[i];
3098     bool isByVal = Flags.isByVal();
3099
3100     // Promote the value if needed.
3101     switch (VA.getLocInfo()) {
3102     default: llvm_unreachable("Unknown loc info!");
3103     case CCValAssign::Full: break;
3104     case CCValAssign::SExt:
3105       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
3106       break;
3107     case CCValAssign::ZExt:
3108       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
3109       break;
3110     case CCValAssign::AExt:
3111       if (Arg.getValueType().isVector() &&
3112           Arg.getValueType().getVectorElementType() == MVT::i1)
3113         Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
3114       else if (RegVT.is128BitVector()) {
3115         // Special case: passing MMX values in XMM registers.
3116         Arg = DAG.getBitcast(MVT::i64, Arg);
3117         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
3118         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
3119       } else
3120         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
3121       break;
3122     case CCValAssign::BCvt:
3123       Arg = DAG.getBitcast(RegVT, Arg);
3124       break;
3125     case CCValAssign::Indirect: {
3126       // Store the argument.
3127       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
3128       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
3129       Chain = DAG.getStore(
3130           Chain, dl, Arg, SpillSlot,
3131           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3132           false, false, 0);
3133       Arg = SpillSlot;
3134       break;
3135     }
3136     }
3137
3138     if (VA.isRegLoc()) {
3139       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3140       if (isVarArg && IsWin64) {
3141         // Win64 ABI requires argument XMM reg to be copied to the corresponding
3142         // shadow reg if callee is a varargs function.
3143         unsigned ShadowReg = 0;
3144         switch (VA.getLocReg()) {
3145         case X86::XMM0: ShadowReg = X86::RCX; break;
3146         case X86::XMM1: ShadowReg = X86::RDX; break;
3147         case X86::XMM2: ShadowReg = X86::R8; break;
3148         case X86::XMM3: ShadowReg = X86::R9; break;
3149         }
3150         if (ShadowReg)
3151           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
3152       }
3153     } else if (!IsSibcall && (!isTailCall || isByVal)) {
3154       assert(VA.isMemLoc());
3155       if (!StackPtr.getNode())
3156         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3157                                       getPointerTy(DAG.getDataLayout()));
3158       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
3159                                              dl, DAG, VA, Flags));
3160     }
3161   }
3162
3163   if (!MemOpChains.empty())
3164     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
3165
3166   if (Subtarget->isPICStyleGOT()) {
3167     // ELF / PIC requires GOT in the EBX register before function calls via PLT
3168     // GOT pointer.
3169     if (!isTailCall) {
3170       RegsToPass.push_back(std::make_pair(
3171           unsigned(X86::EBX), DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
3172                                           getPointerTy(DAG.getDataLayout()))));
3173     } else {
3174       // If we are tail calling and generating PIC/GOT style code load the
3175       // address of the callee into ECX. The value in ecx is used as target of
3176       // the tail jump. This is done to circumvent the ebx/callee-saved problem
3177       // for tail calls on PIC/GOT architectures. Normally we would just put the
3178       // address of GOT into ebx and then call target@PLT. But for tail calls
3179       // ebx would be restored (since ebx is callee saved) before jumping to the
3180       // target@PLT.
3181
3182       // Note: The actual moving to ECX is done further down.
3183       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
3184       if (G && !G->getGlobal()->hasLocalLinkage() &&
3185           G->getGlobal()->hasDefaultVisibility())
3186         Callee = LowerGlobalAddress(Callee, DAG);
3187       else if (isa<ExternalSymbolSDNode>(Callee))
3188         Callee = LowerExternalSymbol(Callee, DAG);
3189     }
3190   }
3191
3192   if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail) {
3193     // From AMD64 ABI document:
3194     // For calls that may call functions that use varargs or stdargs
3195     // (prototype-less calls or calls to functions containing ellipsis (...) in
3196     // the declaration) %al is used as hidden argument to specify the number
3197     // of SSE registers used. The contents of %al do not need to match exactly
3198     // the number of registers, but must be an ubound on the number of SSE
3199     // registers used and is in the range 0 - 8 inclusive.
3200
3201     // Count the number of XMM registers allocated.
3202     static const MCPhysReg XMMArgRegs[] = {
3203       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3204       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
3205     };
3206     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
3207     assert((Subtarget->hasSSE1() || !NumXMMRegs)
3208            && "SSE registers cannot be used when SSE is disabled");
3209
3210     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
3211                                         DAG.getConstant(NumXMMRegs, dl,
3212                                                         MVT::i8)));
3213   }
3214
3215   if (isVarArg && IsMustTail) {
3216     const auto &Forwards = X86Info->getForwardedMustTailRegParms();
3217     for (const auto &F : Forwards) {
3218       SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
3219       RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
3220     }
3221   }
3222
3223   // For tail calls lower the arguments to the 'real' stack slots.  Sibcalls
3224   // don't need this because the eligibility check rejects calls that require
3225   // shuffling arguments passed in memory.
3226   if (!IsSibcall && isTailCall) {
3227     // Force all the incoming stack arguments to be loaded from the stack
3228     // before any new outgoing arguments are stored to the stack, because the
3229     // outgoing stack slots may alias the incoming argument stack slots, and
3230     // the alias isn't otherwise explicit. This is slightly more conservative
3231     // than necessary, because it means that each store effectively depends
3232     // on every argument instead of just those arguments it would clobber.
3233     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
3234
3235     SmallVector<SDValue, 8> MemOpChains2;
3236     SDValue FIN;
3237     int FI = 0;
3238     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3239       CCValAssign &VA = ArgLocs[i];
3240       if (VA.isRegLoc())
3241         continue;
3242       assert(VA.isMemLoc());
3243       SDValue Arg = OutVals[i];
3244       ISD::ArgFlagsTy Flags = Outs[i].Flags;
3245       // Skip inalloca arguments.  They don't require any work.
3246       if (Flags.isInAlloca())
3247         continue;
3248       // Create frame index.
3249       int32_t Offset = VA.getLocMemOffset()+FPDiff;
3250       uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
3251       FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3252       FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3253
3254       if (Flags.isByVal()) {
3255         // Copy relative to framepointer.
3256         SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset(), dl);
3257         if (!StackPtr.getNode())
3258           StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3259                                         getPointerTy(DAG.getDataLayout()));
3260         Source = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
3261                              StackPtr, Source);
3262
3263         MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
3264                                                          ArgChain,
3265                                                          Flags, DAG, dl));
3266       } else {
3267         // Store relative to framepointer.
3268         MemOpChains2.push_back(DAG.getStore(
3269             ArgChain, dl, Arg, FIN,
3270             MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3271             false, false, 0));
3272       }
3273     }
3274
3275     if (!MemOpChains2.empty())
3276       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3277
3278     // Store the return address to the appropriate stack slot.
3279     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
3280                                      getPointerTy(DAG.getDataLayout()),
3281                                      RegInfo->getSlotSize(), FPDiff, dl);
3282   }
3283
3284   // Build a sequence of copy-to-reg nodes chained together with token chain
3285   // and flag operands which copy the outgoing args into registers.
3286   SDValue InFlag;
3287   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3288     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3289                              RegsToPass[i].second, InFlag);
3290     InFlag = Chain.getValue(1);
3291   }
3292
3293   if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
3294     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
3295     // In the 64-bit large code model, we have to make all calls
3296     // through a register, since the call instruction's 32-bit
3297     // pc-relative offset may not be large enough to hold the whole
3298     // address.
3299   } else if (Callee->getOpcode() == ISD::GlobalAddress) {
3300     // If the callee is a GlobalAddress node (quite common, every direct call
3301     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
3302     // it.
3303     GlobalAddressSDNode* G = cast<GlobalAddressSDNode>(Callee);
3304
3305     // We should use extra load for direct calls to dllimported functions in
3306     // non-JIT mode.
3307     const GlobalValue *GV = G->getGlobal();
3308     if (!GV->hasDLLImportStorageClass()) {
3309       unsigned char OpFlags = 0;
3310       bool ExtraLoad = false;
3311       unsigned WrapperKind = ISD::DELETED_NODE;
3312
3313       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
3314       // external symbols most go through the PLT in PIC mode.  If the symbol
3315       // has hidden or protected visibility, or if it is static or local, then
3316       // we don't need to use the PLT - we can directly call it.
3317       if (Subtarget->isTargetELF() &&
3318           DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
3319           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
3320         OpFlags = X86II::MO_PLT;
3321       } else if (Subtarget->isPICStyleStubAny() &&
3322                  !GV->isStrongDefinitionForLinker() &&
3323                  (!Subtarget->getTargetTriple().isMacOSX() ||
3324                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3325         // PC-relative references to external symbols should go through $stub,
3326         // unless we're building with the leopard linker or later, which
3327         // automatically synthesizes these stubs.
3328         OpFlags = X86II::MO_DARWIN_STUB;
3329       } else if (Subtarget->isPICStyleRIPRel() && isa<Function>(GV) &&
3330                  cast<Function>(GV)->hasFnAttribute(Attribute::NonLazyBind)) {
3331         // If the function is marked as non-lazy, generate an indirect call
3332         // which loads from the GOT directly. This avoids runtime overhead
3333         // at the cost of eager binding (and one extra byte of encoding).
3334         OpFlags = X86II::MO_GOTPCREL;
3335         WrapperKind = X86ISD::WrapperRIP;
3336         ExtraLoad = true;
3337       }
3338
3339       Callee = DAG.getTargetGlobalAddress(
3340           GV, dl, getPointerTy(DAG.getDataLayout()), G->getOffset(), OpFlags);
3341
3342       // Add a wrapper if needed.
3343       if (WrapperKind != ISD::DELETED_NODE)
3344         Callee = DAG.getNode(X86ISD::WrapperRIP, dl,
3345                              getPointerTy(DAG.getDataLayout()), Callee);
3346       // Add extra indirection if needed.
3347       if (ExtraLoad)
3348         Callee = DAG.getLoad(
3349             getPointerTy(DAG.getDataLayout()), dl, DAG.getEntryNode(), Callee,
3350             MachinePointerInfo::getGOT(DAG.getMachineFunction()), false, false,
3351             false, 0);
3352     }
3353   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3354     unsigned char OpFlags = 0;
3355
3356     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
3357     // external symbols should go through the PLT.
3358     if (Subtarget->isTargetELF() &&
3359         DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
3360       OpFlags = X86II::MO_PLT;
3361     } else if (Subtarget->isPICStyleStubAny() &&
3362                (!Subtarget->getTargetTriple().isMacOSX() ||
3363                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3364       // PC-relative references to external symbols should go through $stub,
3365       // unless we're building with the leopard linker or later, which
3366       // automatically synthesizes these stubs.
3367       OpFlags = X86II::MO_DARWIN_STUB;
3368     }
3369
3370     Callee = DAG.getTargetExternalSymbol(
3371         S->getSymbol(), getPointerTy(DAG.getDataLayout()), OpFlags);
3372   } else if (Subtarget->isTarget64BitILP32() &&
3373              Callee->getValueType(0) == MVT::i32) {
3374     // Zero-extend the 32-bit Callee address into a 64-bit according to x32 ABI
3375     Callee = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Callee);
3376   }
3377
3378   // Returns a chain & a flag for retval copy to use.
3379   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3380   SmallVector<SDValue, 8> Ops;
3381
3382   if (!IsSibcall && isTailCall) {
3383     Chain = DAG.getCALLSEQ_END(Chain,
3384                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3385                                DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
3386     InFlag = Chain.getValue(1);
3387   }
3388
3389   Ops.push_back(Chain);
3390   Ops.push_back(Callee);
3391
3392   if (isTailCall)
3393     Ops.push_back(DAG.getConstant(FPDiff, dl, MVT::i32));
3394
3395   // Add argument registers to the end of the list so that they are known live
3396   // into the call.
3397   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3398     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3399                                   RegsToPass[i].second.getValueType()));
3400
3401   // Add a register mask operand representing the call-preserved registers.
3402   const uint32_t *Mask = RegInfo->getCallPreservedMask(MF, CallConv);
3403   assert(Mask && "Missing call preserved mask for calling convention");
3404
3405   // If this is an invoke in a 32-bit function using a funclet-based
3406   // personality, assume the function clobbers all registers. If an exception
3407   // is thrown, the runtime will not restore CSRs.
3408   // FIXME: Model this more precisely so that we can register allocate across
3409   // the normal edge and spill and fill across the exceptional edge.
3410   if (!Is64Bit && CLI.CS && CLI.CS->isInvoke()) {
3411     const Function *CallerFn = MF.getFunction();
3412     EHPersonality Pers =
3413         CallerFn->hasPersonalityFn()
3414             ? classifyEHPersonality(CallerFn->getPersonalityFn())
3415             : EHPersonality::Unknown;
3416     if (isFuncletEHPersonality(Pers))
3417       Mask = RegInfo->getNoPreservedMask();
3418   }
3419
3420   Ops.push_back(DAG.getRegisterMask(Mask));
3421
3422   if (InFlag.getNode())
3423     Ops.push_back(InFlag);
3424
3425   if (isTailCall) {
3426     // We used to do:
3427     //// If this is the first return lowered for this function, add the regs
3428     //// to the liveout set for the function.
3429     // This isn't right, although it's probably harmless on x86; liveouts
3430     // should be computed from returns not tail calls.  Consider a void
3431     // function making a tail call to a function returning int.
3432     MF.getFrameInfo()->setHasTailCall();
3433     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3434   }
3435
3436   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3437   InFlag = Chain.getValue(1);
3438
3439   // Create the CALLSEQ_END node.
3440   unsigned NumBytesForCalleeToPop;
3441   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3442                        DAG.getTarget().Options.GuaranteedTailCallOpt))
3443     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
3444   else if (!Is64Bit && !canGuaranteeTCO(CallConv) &&
3445            !Subtarget->getTargetTriple().isOSMSVCRT() &&
3446            SR == StackStructReturn)
3447     // If this is a call to a struct-return function, the callee
3448     // pops the hidden struct pointer, so we have to push it back.
3449     // This is common for Darwin/X86, Linux & Mingw32 targets.
3450     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3451     NumBytesForCalleeToPop = 4;
3452   else
3453     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
3454
3455   // Returns a flag for retval copy to use.
3456   if (!IsSibcall) {
3457     Chain = DAG.getCALLSEQ_END(Chain,
3458                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3459                                DAG.getIntPtrConstant(NumBytesForCalleeToPop, dl,
3460                                                      true),
3461                                InFlag, dl);
3462     InFlag = Chain.getValue(1);
3463   }
3464
3465   // Handle result values, copying them out of physregs into vregs that we
3466   // return.
3467   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3468                          Ins, dl, DAG, InVals);
3469 }
3470
3471 //===----------------------------------------------------------------------===//
3472 //                Fast Calling Convention (tail call) implementation
3473 //===----------------------------------------------------------------------===//
3474
3475 //  Like std call, callee cleans arguments, convention except that ECX is
3476 //  reserved for storing the tail called function address. Only 2 registers are
3477 //  free for argument passing (inreg). Tail call optimization is performed
3478 //  provided:
3479 //                * tailcallopt is enabled
3480 //                * caller/callee are fastcc
3481 //  On X86_64 architecture with GOT-style position independent code only local
3482 //  (within module) calls are supported at the moment.
3483 //  To keep the stack aligned according to platform abi the function
3484 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
3485 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3486 //  If a tail called function callee has more arguments than the caller the
3487 //  caller needs to make sure that there is room to move the RETADDR to. This is
3488 //  achieved by reserving an area the size of the argument delta right after the
3489 //  original RETADDR, but before the saved framepointer or the spilled registers
3490 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3491 //  stack layout:
3492 //    arg1
3493 //    arg2
3494 //    RETADDR
3495 //    [ new RETADDR
3496 //      move area ]
3497 //    (possible EBP)
3498 //    ESI
3499 //    EDI
3500 //    local1 ..
3501
3502 /// Make the stack size align e.g 16n + 12 aligned for a 16-byte align
3503 /// requirement.
3504 unsigned
3505 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3506                                                SelectionDAG& DAG) const {
3507   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3508   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
3509   unsigned StackAlignment = TFI.getStackAlignment();
3510   uint64_t AlignMask = StackAlignment - 1;
3511   int64_t Offset = StackSize;
3512   unsigned SlotSize = RegInfo->getSlotSize();
3513   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3514     // Number smaller than 12 so just add the difference.
3515     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3516   } else {
3517     // Mask out lower bits, add stackalignment once plus the 12 bytes.
3518     Offset = ((~AlignMask) & Offset) + StackAlignment +
3519       (StackAlignment-SlotSize);
3520   }
3521   return Offset;
3522 }
3523
3524 /// Return true if the given stack call argument is already available in the
3525 /// same position (relatively) of the caller's incoming argument stack.
3526 static
3527 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3528                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3529                          const X86InstrInfo *TII) {
3530   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3531   int FI = INT_MAX;
3532   if (Arg.getOpcode() == ISD::CopyFromReg) {
3533     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3534     if (!TargetRegisterInfo::isVirtualRegister(VR))
3535       return false;
3536     MachineInstr *Def = MRI->getVRegDef(VR);
3537     if (!Def)
3538       return false;
3539     if (!Flags.isByVal()) {
3540       if (!TII->isLoadFromStackSlot(Def, FI))
3541         return false;
3542     } else {
3543       unsigned Opcode = Def->getOpcode();
3544       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r ||
3545            Opcode == X86::LEA64_32r) &&
3546           Def->getOperand(1).isFI()) {
3547         FI = Def->getOperand(1).getIndex();
3548         Bytes = Flags.getByValSize();
3549       } else
3550         return false;
3551     }
3552   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3553     if (Flags.isByVal())
3554       // ByVal argument is passed in as a pointer but it's now being
3555       // dereferenced. e.g.
3556       // define @foo(%struct.X* %A) {
3557       //   tail call @bar(%struct.X* byval %A)
3558       // }
3559       return false;
3560     SDValue Ptr = Ld->getBasePtr();
3561     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3562     if (!FINode)
3563       return false;
3564     FI = FINode->getIndex();
3565   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3566     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3567     FI = FINode->getIndex();
3568     Bytes = Flags.getByValSize();
3569   } else
3570     return false;
3571
3572   assert(FI != INT_MAX);
3573   if (!MFI->isFixedObjectIndex(FI))
3574     return false;
3575   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3576 }
3577
3578 /// Check whether the call is eligible for tail call optimization. Targets
3579 /// that want to do tail call optimization should implement this function.
3580 bool X86TargetLowering::IsEligibleForTailCallOptimization(
3581     SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
3582     bool isCalleeStructRet, bool isCallerStructRet, Type *RetTy,
3583     const SmallVectorImpl<ISD::OutputArg> &Outs,
3584     const SmallVectorImpl<SDValue> &OutVals,
3585     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
3586   if (!mayTailCallThisCC(CalleeCC))
3587     return false;
3588
3589   // If -tailcallopt is specified, make fastcc functions tail-callable.
3590   MachineFunction &MF = DAG.getMachineFunction();
3591   const Function *CallerF = MF.getFunction();
3592
3593   // If the function return type is x86_fp80 and the callee return type is not,
3594   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3595   // perform a tailcall optimization here.
3596   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3597     return false;
3598
3599   CallingConv::ID CallerCC = CallerF->getCallingConv();
3600   bool CCMatch = CallerCC == CalleeCC;
3601   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3602   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3603
3604   // Win64 functions have extra shadow space for argument homing. Don't do the
3605   // sibcall if the caller and callee have mismatched expectations for this
3606   // space.
3607   if (IsCalleeWin64 != IsCallerWin64)
3608     return false;
3609
3610   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3611     if (canGuaranteeTCO(CalleeCC) && CCMatch)
3612       return true;
3613     return false;
3614   }
3615
3616   // Look for obvious safe cases to perform tail call optimization that do not
3617   // require ABI changes. This is what gcc calls sibcall.
3618
3619   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3620   // emit a special epilogue.
3621   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3622   if (RegInfo->needsStackRealignment(MF))
3623     return false;
3624
3625   // Also avoid sibcall optimization if either caller or callee uses struct
3626   // return semantics.
3627   if (isCalleeStructRet || isCallerStructRet)
3628     return false;
3629
3630   // Do not sibcall optimize vararg calls unless all arguments are passed via
3631   // registers.
3632   if (isVarArg && !Outs.empty()) {
3633     // Optimizing for varargs on Win64 is unlikely to be safe without
3634     // additional testing.
3635     if (IsCalleeWin64 || IsCallerWin64)
3636       return false;
3637
3638     SmallVector<CCValAssign, 16> ArgLocs;
3639     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3640                    *DAG.getContext());
3641
3642     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3643     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3644       if (!ArgLocs[i].isRegLoc())
3645         return false;
3646   }
3647
3648   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3649   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3650   // this into a sibcall.
3651   bool Unused = false;
3652   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3653     if (!Ins[i].Used) {
3654       Unused = true;
3655       break;
3656     }
3657   }
3658   if (Unused) {
3659     SmallVector<CCValAssign, 16> RVLocs;
3660     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), RVLocs,
3661                    *DAG.getContext());
3662     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3663     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3664       CCValAssign &VA = RVLocs[i];
3665       if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3666         return false;
3667     }
3668   }
3669
3670   // If the calling conventions do not match, then we'd better make sure the
3671   // results are returned in the same way as what the caller expects.
3672   if (!CCMatch) {
3673     SmallVector<CCValAssign, 16> RVLocs1;
3674     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
3675                     *DAG.getContext());
3676     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3677
3678     SmallVector<CCValAssign, 16> RVLocs2;
3679     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
3680                     *DAG.getContext());
3681     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3682
3683     if (RVLocs1.size() != RVLocs2.size())
3684       return false;
3685     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3686       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3687         return false;
3688       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3689         return false;
3690       if (RVLocs1[i].isRegLoc()) {
3691         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3692           return false;
3693       } else {
3694         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3695           return false;
3696       }
3697     }
3698   }
3699
3700   unsigned StackArgsSize = 0;
3701
3702   // If the callee takes no arguments then go on to check the results of the
3703   // call.
3704   if (!Outs.empty()) {
3705     // Check if stack adjustment is needed. For now, do not do this if any
3706     // argument is passed on the stack.
3707     SmallVector<CCValAssign, 16> ArgLocs;
3708     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3709                    *DAG.getContext());
3710
3711     // Allocate shadow area for Win64
3712     if (IsCalleeWin64)
3713       CCInfo.AllocateStack(32, 8);
3714
3715     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3716     StackArgsSize = CCInfo.getNextStackOffset();
3717
3718     if (CCInfo.getNextStackOffset()) {
3719       // Check if the arguments are already laid out in the right way as
3720       // the caller's fixed stack objects.
3721       MachineFrameInfo *MFI = MF.getFrameInfo();
3722       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3723       const X86InstrInfo *TII = Subtarget->getInstrInfo();
3724       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3725         CCValAssign &VA = ArgLocs[i];
3726         SDValue Arg = OutVals[i];
3727         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3728         if (VA.getLocInfo() == CCValAssign::Indirect)
3729           return false;
3730         if (!VA.isRegLoc()) {
3731           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3732                                    MFI, MRI, TII))
3733             return false;
3734         }
3735       }
3736     }
3737
3738     // If the tailcall address may be in a register, then make sure it's
3739     // possible to register allocate for it. In 32-bit, the call address can
3740     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3741     // callee-saved registers are restored. These happen to be the same
3742     // registers used to pass 'inreg' arguments so watch out for those.
3743     if (!Subtarget->is64Bit() &&
3744         ((!isa<GlobalAddressSDNode>(Callee) &&
3745           !isa<ExternalSymbolSDNode>(Callee)) ||
3746          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3747       unsigned NumInRegs = 0;
3748       // In PIC we need an extra register to formulate the address computation
3749       // for the callee.
3750       unsigned MaxInRegs =
3751         (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3752
3753       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3754         CCValAssign &VA = ArgLocs[i];
3755         if (!VA.isRegLoc())
3756           continue;
3757         unsigned Reg = VA.getLocReg();
3758         switch (Reg) {
3759         default: break;
3760         case X86::EAX: case X86::EDX: case X86::ECX:
3761           if (++NumInRegs == MaxInRegs)
3762             return false;
3763           break;
3764         }
3765       }
3766     }
3767   }
3768
3769   bool CalleeWillPop =
3770       X86::isCalleePop(CalleeCC, Subtarget->is64Bit(), isVarArg,
3771                        MF.getTarget().Options.GuaranteedTailCallOpt);
3772
3773   if (unsigned BytesToPop =
3774           MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn()) {
3775     // If we have bytes to pop, the callee must pop them.
3776     bool CalleePopMatches = CalleeWillPop && BytesToPop == StackArgsSize;
3777     if (!CalleePopMatches)
3778       return false;
3779   } else if (CalleeWillPop && StackArgsSize > 0) {
3780     // If we don't have bytes to pop, make sure the callee doesn't pop any.
3781     return false;
3782   }
3783
3784   return true;
3785 }
3786
3787 FastISel *
3788 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3789                                   const TargetLibraryInfo *libInfo) const {
3790   return X86::createFastISel(funcInfo, libInfo);
3791 }
3792
3793 //===----------------------------------------------------------------------===//
3794 //                           Other Lowering Hooks
3795 //===----------------------------------------------------------------------===//
3796
3797 static bool MayFoldLoad(SDValue Op) {
3798   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3799 }
3800
3801 static bool MayFoldIntoStore(SDValue Op) {
3802   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3803 }
3804
3805 static bool isTargetShuffle(unsigned Opcode) {
3806   switch(Opcode) {
3807   default: return false;
3808   case X86ISD::BLENDI:
3809   case X86ISD::PSHUFB:
3810   case X86ISD::PSHUFD:
3811   case X86ISD::PSHUFHW:
3812   case X86ISD::PSHUFLW:
3813   case X86ISD::SHUFP:
3814   case X86ISD::PALIGNR:
3815   case X86ISD::MOVLHPS:
3816   case X86ISD::MOVLHPD:
3817   case X86ISD::MOVHLPS:
3818   case X86ISD::MOVLPS:
3819   case X86ISD::MOVLPD:
3820   case X86ISD::MOVSHDUP:
3821   case X86ISD::MOVSLDUP:
3822   case X86ISD::MOVDDUP:
3823   case X86ISD::MOVSS:
3824   case X86ISD::MOVSD:
3825   case X86ISD::UNPCKL:
3826   case X86ISD::UNPCKH:
3827   case X86ISD::VPERMILPI:
3828   case X86ISD::VPERM2X128:
3829   case X86ISD::VPERMI:
3830   case X86ISD::VPERMV:
3831   case X86ISD::VPERMV3:
3832     return true;
3833   }
3834 }
3835
3836 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, MVT VT,
3837                                     SDValue V1, unsigned TargetMask,
3838                                     SelectionDAG &DAG) {
3839   switch(Opc) {
3840   default: llvm_unreachable("Unknown x86 shuffle node");
3841   case X86ISD::PSHUFD:
3842   case X86ISD::PSHUFHW:
3843   case X86ISD::PSHUFLW:
3844   case X86ISD::VPERMILPI:
3845   case X86ISD::VPERMI:
3846     return DAG.getNode(Opc, dl, VT, V1,
3847                        DAG.getConstant(TargetMask, dl, MVT::i8));
3848   }
3849 }
3850
3851 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, MVT VT,
3852                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3853   switch(Opc) {
3854   default: llvm_unreachable("Unknown x86 shuffle node");
3855   case X86ISD::MOVLHPS:
3856   case X86ISD::MOVLHPD:
3857   case X86ISD::MOVHLPS:
3858   case X86ISD::MOVLPS:
3859   case X86ISD::MOVLPD:
3860   case X86ISD::MOVSS:
3861   case X86ISD::MOVSD:
3862   case X86ISD::UNPCKL:
3863   case X86ISD::UNPCKH:
3864     return DAG.getNode(Opc, dl, VT, V1, V2);
3865   }
3866 }
3867
3868 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3869   MachineFunction &MF = DAG.getMachineFunction();
3870   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3871   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3872   int ReturnAddrIndex = FuncInfo->getRAIndex();
3873
3874   if (ReturnAddrIndex == 0) {
3875     // Set up a frame object for the return address.
3876     unsigned SlotSize = RegInfo->getSlotSize();
3877     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3878                                                            -(int64_t)SlotSize,
3879                                                            false);
3880     FuncInfo->setRAIndex(ReturnAddrIndex);
3881   }
3882
3883   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy(DAG.getDataLayout()));
3884 }
3885
3886 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3887                                        bool hasSymbolicDisplacement) {
3888   // Offset should fit into 32 bit immediate field.
3889   if (!isInt<32>(Offset))
3890     return false;
3891
3892   // If we don't have a symbolic displacement - we don't have any extra
3893   // restrictions.
3894   if (!hasSymbolicDisplacement)
3895     return true;
3896
3897   // FIXME: Some tweaks might be needed for medium code model.
3898   if (M != CodeModel::Small && M != CodeModel::Kernel)
3899     return false;
3900
3901   // For small code model we assume that latest object is 16MB before end of 31
3902   // bits boundary. We may also accept pretty large negative constants knowing
3903   // that all objects are in the positive half of address space.
3904   if (M == CodeModel::Small && Offset < 16*1024*1024)
3905     return true;
3906
3907   // For kernel code model we know that all object resist in the negative half
3908   // of 32bits address space. We may not accept negative offsets, since they may
3909   // be just off and we may accept pretty large positive ones.
3910   if (M == CodeModel::Kernel && Offset >= 0)
3911     return true;
3912
3913   return false;
3914 }
3915
3916 /// Determines whether the callee is required to pop its own arguments.
3917 /// Callee pop is necessary to support tail calls.
3918 bool X86::isCalleePop(CallingConv::ID CallingConv,
3919                       bool is64Bit, bool IsVarArg, bool GuaranteeTCO) {
3920   // If GuaranteeTCO is true, we force some calls to be callee pop so that we
3921   // can guarantee TCO.
3922   if (!IsVarArg && shouldGuaranteeTCO(CallingConv, GuaranteeTCO))
3923     return true;
3924
3925   switch (CallingConv) {
3926   default:
3927     return false;
3928   case CallingConv::X86_StdCall:
3929   case CallingConv::X86_FastCall:
3930   case CallingConv::X86_ThisCall:
3931   case CallingConv::X86_VectorCall:
3932     return !is64Bit;
3933   }
3934 }
3935
3936 /// \brief Return true if the condition is an unsigned comparison operation.
3937 static bool isX86CCUnsigned(unsigned X86CC) {
3938   switch (X86CC) {
3939   default: llvm_unreachable("Invalid integer condition!");
3940   case X86::COND_E:     return true;
3941   case X86::COND_G:     return false;
3942   case X86::COND_GE:    return false;
3943   case X86::COND_L:     return false;
3944   case X86::COND_LE:    return false;
3945   case X86::COND_NE:    return true;
3946   case X86::COND_B:     return true;
3947   case X86::COND_A:     return true;
3948   case X86::COND_BE:    return true;
3949   case X86::COND_AE:    return true;
3950   }
3951 }
3952
3953 /// Do a one-to-one translation of a ISD::CondCode to the X86-specific
3954 /// condition code, returning the condition code and the LHS/RHS of the
3955 /// comparison to make.
3956 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, SDLoc DL, bool isFP,
3957                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3958   if (!isFP) {
3959     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3960       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3961         // X > -1   -> X == 0, jump !sign.
3962         RHS = DAG.getConstant(0, DL, RHS.getValueType());
3963         return X86::COND_NS;
3964       }
3965       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3966         // X < 0   -> X == 0, jump on sign.
3967         return X86::COND_S;
3968       }
3969       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3970         // X < 1   -> X <= 0
3971         RHS = DAG.getConstant(0, DL, RHS.getValueType());
3972         return X86::COND_LE;
3973       }
3974     }
3975
3976     switch (SetCCOpcode) {
3977     default: llvm_unreachable("Invalid integer condition!");
3978     case ISD::SETEQ:  return X86::COND_E;
3979     case ISD::SETGT:  return X86::COND_G;
3980     case ISD::SETGE:  return X86::COND_GE;
3981     case ISD::SETLT:  return X86::COND_L;
3982     case ISD::SETLE:  return X86::COND_LE;
3983     case ISD::SETNE:  return X86::COND_NE;
3984     case ISD::SETULT: return X86::COND_B;
3985     case ISD::SETUGT: return X86::COND_A;
3986     case ISD::SETULE: return X86::COND_BE;
3987     case ISD::SETUGE: return X86::COND_AE;
3988     }
3989   }
3990
3991   // First determine if it is required or is profitable to flip the operands.
3992
3993   // If LHS is a foldable load, but RHS is not, flip the condition.
3994   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3995       !ISD::isNON_EXTLoad(RHS.getNode())) {
3996     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3997     std::swap(LHS, RHS);
3998   }
3999
4000   switch (SetCCOpcode) {
4001   default: break;
4002   case ISD::SETOLT:
4003   case ISD::SETOLE:
4004   case ISD::SETUGT:
4005   case ISD::SETUGE:
4006     std::swap(LHS, RHS);
4007     break;
4008   }
4009
4010   // On a floating point condition, the flags are set as follows:
4011   // ZF  PF  CF   op
4012   //  0 | 0 | 0 | X > Y
4013   //  0 | 0 | 1 | X < Y
4014   //  1 | 0 | 0 | X == Y
4015   //  1 | 1 | 1 | unordered
4016   switch (SetCCOpcode) {
4017   default: llvm_unreachable("Condcode should be pre-legalized away");
4018   case ISD::SETUEQ:
4019   case ISD::SETEQ:   return X86::COND_E;
4020   case ISD::SETOLT:              // flipped
4021   case ISD::SETOGT:
4022   case ISD::SETGT:   return X86::COND_A;
4023   case ISD::SETOLE:              // flipped
4024   case ISD::SETOGE:
4025   case ISD::SETGE:   return X86::COND_AE;
4026   case ISD::SETUGT:              // flipped
4027   case ISD::SETULT:
4028   case ISD::SETLT:   return X86::COND_B;
4029   case ISD::SETUGE:              // flipped
4030   case ISD::SETULE:
4031   case ISD::SETLE:   return X86::COND_BE;
4032   case ISD::SETONE:
4033   case ISD::SETNE:   return X86::COND_NE;
4034   case ISD::SETUO:   return X86::COND_P;
4035   case ISD::SETO:    return X86::COND_NP;
4036   case ISD::SETOEQ:
4037   case ISD::SETUNE:  return X86::COND_INVALID;
4038   }
4039 }
4040
4041 /// Is there a floating point cmov for the specific X86 condition code?
4042 /// Current x86 isa includes the following FP cmov instructions:
4043 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
4044 static bool hasFPCMov(unsigned X86CC) {
4045   switch (X86CC) {
4046   default:
4047     return false;
4048   case X86::COND_B:
4049   case X86::COND_BE:
4050   case X86::COND_E:
4051   case X86::COND_P:
4052   case X86::COND_A:
4053   case X86::COND_AE:
4054   case X86::COND_NE:
4055   case X86::COND_NP:
4056     return true;
4057   }
4058 }
4059
4060 /// Returns true if the target can instruction select the
4061 /// specified FP immediate natively. If false, the legalizer will
4062 /// materialize the FP immediate as a load from a constant pool.
4063 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
4064   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
4065     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
4066       return true;
4067   }
4068   return false;
4069 }
4070
4071 bool X86TargetLowering::shouldReduceLoadWidth(SDNode *Load,
4072                                               ISD::LoadExtType ExtTy,
4073                                               EVT NewVT) const {
4074   // "ELF Handling for Thread-Local Storage" specifies that R_X86_64_GOTTPOFF
4075   // relocation target a movq or addq instruction: don't let the load shrink.
4076   SDValue BasePtr = cast<LoadSDNode>(Load)->getBasePtr();
4077   if (BasePtr.getOpcode() == X86ISD::WrapperRIP)
4078     if (const auto *GA = dyn_cast<GlobalAddressSDNode>(BasePtr.getOperand(0)))
4079       return GA->getTargetFlags() != X86II::MO_GOTTPOFF;
4080   return true;
4081 }
4082
4083 /// \brief Returns true if it is beneficial to convert a load of a constant
4084 /// to just the constant itself.
4085 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
4086                                                           Type *Ty) const {
4087   assert(Ty->isIntegerTy());
4088
4089   unsigned BitSize = Ty->getPrimitiveSizeInBits();
4090   if (BitSize == 0 || BitSize > 64)
4091     return false;
4092   return true;
4093 }
4094
4095 bool X86TargetLowering::isExtractSubvectorCheap(EVT ResVT,
4096                                                 unsigned Index) const {
4097   if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
4098     return false;
4099
4100   return (Index == 0 || Index == ResVT.getVectorNumElements());
4101 }
4102
4103 bool X86TargetLowering::isCheapToSpeculateCttz() const {
4104   // Speculate cttz only if we can directly use TZCNT.
4105   return Subtarget->hasBMI();
4106 }
4107
4108 bool X86TargetLowering::isCheapToSpeculateCtlz() const {
4109   // Speculate ctlz only if we can directly use LZCNT.
4110   return Subtarget->hasLZCNT();
4111 }
4112
4113 /// Return true if every element in Mask, beginning
4114 /// from position Pos and ending in Pos+Size is undef.
4115 static bool isUndefInRange(ArrayRef<int> Mask, unsigned Pos, unsigned Size) {
4116   for (unsigned i = Pos, e = Pos + Size; i != e; ++i)
4117     if (0 <= Mask[i])
4118       return false;
4119   return true;
4120 }
4121
4122 /// Return true if Val is undef or if its value falls within the
4123 /// specified range (L, H].
4124 static bool isUndefOrInRange(int Val, int Low, int Hi) {
4125   return (Val < 0) || (Val >= Low && Val < Hi);
4126 }
4127
4128 /// Val is either less than zero (undef) or equal to the specified value.
4129 static bool isUndefOrEqual(int Val, int CmpVal) {
4130   return (Val < 0 || Val == CmpVal);
4131 }
4132
4133 /// Return true if every element in Mask, beginning
4134 /// from position Pos and ending in Pos+Size, falls within the specified
4135 /// sequential range (Low, Low+Size]. or is undef.
4136 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
4137                                        unsigned Pos, unsigned Size, int Low) {
4138   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
4139     if (!isUndefOrEqual(Mask[i], Low))
4140       return false;
4141   return true;
4142 }
4143
4144 /// Return true if the specified EXTRACT_SUBVECTOR operand specifies a vector
4145 /// extract that is suitable for instruction that extract 128 or 256 bit vectors
4146 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4147   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4148   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4149     return false;
4150
4151   // The index should be aligned on a vecWidth-bit boundary.
4152   uint64_t Index =
4153     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4154
4155   MVT VT = N->getSimpleValueType(0);
4156   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4157   bool Result = (Index * ElSize) % vecWidth == 0;
4158
4159   return Result;
4160 }
4161
4162 /// Return true if the specified INSERT_SUBVECTOR
4163 /// operand specifies a subvector insert that is suitable for input to
4164 /// insertion of 128 or 256-bit subvectors
4165 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4166   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4167   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4168     return false;
4169   // The index should be aligned on a vecWidth-bit boundary.
4170   uint64_t Index =
4171     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4172
4173   MVT VT = N->getSimpleValueType(0);
4174   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4175   bool Result = (Index * ElSize) % vecWidth == 0;
4176
4177   return Result;
4178 }
4179
4180 bool X86::isVINSERT128Index(SDNode *N) {
4181   return isVINSERTIndex(N, 128);
4182 }
4183
4184 bool X86::isVINSERT256Index(SDNode *N) {
4185   return isVINSERTIndex(N, 256);
4186 }
4187
4188 bool X86::isVEXTRACT128Index(SDNode *N) {
4189   return isVEXTRACTIndex(N, 128);
4190 }
4191
4192 bool X86::isVEXTRACT256Index(SDNode *N) {
4193   return isVEXTRACTIndex(N, 256);
4194 }
4195
4196 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4197   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4198   assert(isa<ConstantSDNode>(N->getOperand(1).getNode()) &&
4199          "Illegal extract subvector for VEXTRACT");
4200
4201   uint64_t Index =
4202     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4203
4204   MVT VecVT = N->getOperand(0).getSimpleValueType();
4205   MVT ElVT = VecVT.getVectorElementType();
4206
4207   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4208   return Index / NumElemsPerChunk;
4209 }
4210
4211 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4212   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4213   assert(isa<ConstantSDNode>(N->getOperand(2).getNode()) &&
4214          "Illegal insert subvector for VINSERT");
4215
4216   uint64_t Index =
4217     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4218
4219   MVT VecVT = N->getSimpleValueType(0);
4220   MVT ElVT = VecVT.getVectorElementType();
4221
4222   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4223   return Index / NumElemsPerChunk;
4224 }
4225
4226 /// Return the appropriate immediate to extract the specified
4227 /// EXTRACT_SUBVECTOR index with VEXTRACTF128 and VINSERTI128 instructions.
4228 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4229   return getExtractVEXTRACTImmediate(N, 128);
4230 }
4231
4232 /// Return the appropriate immediate to extract the specified
4233 /// EXTRACT_SUBVECTOR index with VEXTRACTF64x4 and VINSERTI64x4 instructions.
4234 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4235   return getExtractVEXTRACTImmediate(N, 256);
4236 }
4237
4238 /// Return the appropriate immediate to insert at the specified
4239 /// INSERT_SUBVECTOR index with VINSERTF128 and VINSERTI128 instructions.
4240 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4241   return getInsertVINSERTImmediate(N, 128);
4242 }
4243
4244 /// Return the appropriate immediate to insert at the specified
4245 /// INSERT_SUBVECTOR index with VINSERTF46x4 and VINSERTI64x4 instructions.
4246 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4247   return getInsertVINSERTImmediate(N, 256);
4248 }
4249
4250 /// Returns true if V is a constant integer zero.
4251 static bool isZero(SDValue V) {
4252   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4253   return C && C->isNullValue();
4254 }
4255
4256 /// Returns true if Elt is a constant zero or a floating point constant +0.0.
4257 bool X86::isZeroNode(SDValue Elt) {
4258   if (isZero(Elt))
4259     return true;
4260   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4261     return CFP->getValueAPF().isPosZero();
4262   return false;
4263 }
4264
4265 // Build a vector of constants
4266 // Use an UNDEF node if MaskElt == -1.
4267 // Spilt 64-bit constants in the 32-bit mode.
4268 static SDValue getConstVector(ArrayRef<int> Values, MVT VT,
4269                               SelectionDAG &DAG,
4270                               SDLoc dl, bool IsMask = false) {
4271
4272   SmallVector<SDValue, 32>  Ops;
4273   bool Split = false;
4274
4275   MVT ConstVecVT = VT;
4276   unsigned NumElts = VT.getVectorNumElements();
4277   bool In64BitMode = DAG.getTargetLoweringInfo().isTypeLegal(MVT::i64);
4278   if (!In64BitMode && VT.getVectorElementType() == MVT::i64) {
4279     ConstVecVT = MVT::getVectorVT(MVT::i32, NumElts * 2);
4280     Split = true;
4281   }
4282
4283   MVT EltVT = ConstVecVT.getVectorElementType();
4284   for (unsigned i = 0; i < NumElts; ++i) {
4285     bool IsUndef = Values[i] < 0 && IsMask;
4286     SDValue OpNode = IsUndef ? DAG.getUNDEF(EltVT) :
4287       DAG.getConstant(Values[i], dl, EltVT);
4288     Ops.push_back(OpNode);
4289     if (Split)
4290       Ops.push_back(IsUndef ? DAG.getUNDEF(EltVT) :
4291                     DAG.getConstant(0, dl, EltVT));
4292   }
4293   SDValue ConstsNode = DAG.getNode(ISD::BUILD_VECTOR, dl, ConstVecVT, Ops);
4294   if (Split)
4295     ConstsNode = DAG.getBitcast(VT, ConstsNode);
4296   return ConstsNode;
4297 }
4298
4299 /// Returns a vector of specified type with all zero elements.
4300 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4301                              SelectionDAG &DAG, SDLoc dl) {
4302   assert(VT.isVector() && "Expected a vector type");
4303
4304   // Always build SSE zero vectors as <4 x i32> bitcasted
4305   // to their dest type. This ensures they get CSE'd.
4306   SDValue Vec;
4307   if (VT.is128BitVector()) {  // SSE
4308     if (Subtarget->hasSSE2()) {  // SSE2
4309       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4310       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4311     } else { // SSE1
4312       SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4313       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4314     }
4315   } else if (VT.is256BitVector()) { // AVX
4316     if (Subtarget->hasInt256()) { // AVX2
4317       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4318       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4319       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4320     } else {
4321       // 256-bit logic and arithmetic instructions in AVX are all
4322       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4323       SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4324       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4325       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4326     }
4327   } else if (VT.is512BitVector()) { // AVX-512
4328       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4329       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4330                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4331       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4332   } else if (VT.getVectorElementType() == MVT::i1) {
4333
4334     assert((Subtarget->hasBWI() || VT.getVectorNumElements() <= 16)
4335             && "Unexpected vector type");
4336     assert((Subtarget->hasVLX() || VT.getVectorNumElements() >= 8)
4337             && "Unexpected vector type");
4338     SDValue Cst = DAG.getConstant(0, dl, MVT::i1);
4339     SmallVector<SDValue, 64> Ops(VT.getVectorNumElements(), Cst);
4340     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4341   } else
4342     llvm_unreachable("Unexpected vector type");
4343
4344   return DAG.getBitcast(VT, Vec);
4345 }
4346
4347 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
4348                                 SelectionDAG &DAG, SDLoc dl,
4349                                 unsigned vectorWidth) {
4350   assert((vectorWidth == 128 || vectorWidth == 256) &&
4351          "Unsupported vector width");
4352   EVT VT = Vec.getValueType();
4353   EVT ElVT = VT.getVectorElementType();
4354   unsigned Factor = VT.getSizeInBits()/vectorWidth;
4355   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
4356                                   VT.getVectorNumElements()/Factor);
4357
4358   // Extract from UNDEF is UNDEF.
4359   if (Vec.getOpcode() == ISD::UNDEF)
4360     return DAG.getUNDEF(ResultVT);
4361
4362   // Extract the relevant vectorWidth bits.  Generate an EXTRACT_SUBVECTOR
4363   unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
4364   assert(isPowerOf2_32(ElemsPerChunk) && "Elements per chunk not power of 2");
4365
4366   // This is the index of the first element of the vectorWidth-bit chunk
4367   // we want. Since ElemsPerChunk is a power of 2 just need to clear bits.
4368   IdxVal &= ~(ElemsPerChunk - 1);
4369
4370   // If the input is a buildvector just emit a smaller one.
4371   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
4372     return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
4373                        makeArrayRef(Vec->op_begin() + IdxVal, ElemsPerChunk));
4374
4375   SDValue VecIdx = DAG.getIntPtrConstant(IdxVal, dl);
4376   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec, VecIdx);
4377 }
4378
4379 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
4380 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
4381 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
4382 /// instructions or a simple subregister reference. Idx is an index in the
4383 /// 128 bits we want.  It need not be aligned to a 128-bit boundary.  That makes
4384 /// lowering EXTRACT_VECTOR_ELT operations easier.
4385 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
4386                                    SelectionDAG &DAG, SDLoc dl) {
4387   assert((Vec.getValueType().is256BitVector() ||
4388           Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
4389   return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
4390 }
4391
4392 /// Generate a DAG to grab 256-bits from a 512-bit vector.
4393 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
4394                                    SelectionDAG &DAG, SDLoc dl) {
4395   assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
4396   return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
4397 }
4398
4399 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
4400                                unsigned IdxVal, SelectionDAG &DAG,
4401                                SDLoc dl, unsigned vectorWidth) {
4402   assert((vectorWidth == 128 || vectorWidth == 256) &&
4403          "Unsupported vector width");
4404   // Inserting UNDEF is Result
4405   if (Vec.getOpcode() == ISD::UNDEF)
4406     return Result;
4407   EVT VT = Vec.getValueType();
4408   EVT ElVT = VT.getVectorElementType();
4409   EVT ResultVT = Result.getValueType();
4410
4411   // Insert the relevant vectorWidth bits.
4412   unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
4413   assert(isPowerOf2_32(ElemsPerChunk) && "Elements per chunk not power of 2");
4414
4415   // This is the index of the first element of the vectorWidth-bit chunk
4416   // we want. Since ElemsPerChunk is a power of 2 just need to clear bits.
4417   IdxVal &= ~(ElemsPerChunk - 1);
4418
4419   SDValue VecIdx = DAG.getIntPtrConstant(IdxVal, dl);
4420   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec, VecIdx);
4421 }
4422
4423 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
4424 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
4425 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
4426 /// simple superregister reference.  Idx is an index in the 128 bits
4427 /// we want.  It need not be aligned to a 128-bit boundary.  That makes
4428 /// lowering INSERT_VECTOR_ELT operations easier.
4429 static SDValue Insert128BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4430                                   SelectionDAG &DAG, SDLoc dl) {
4431   assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
4432
4433   // For insertion into the zero index (low half) of a 256-bit vector, it is
4434   // more efficient to generate a blend with immediate instead of an insert*128.
4435   // We are still creating an INSERT_SUBVECTOR below with an undef node to
4436   // extend the subvector to the size of the result vector. Make sure that
4437   // we are not recursing on that node by checking for undef here.
4438   if (IdxVal == 0 && Result.getValueType().is256BitVector() &&
4439       Result.getOpcode() != ISD::UNDEF) {
4440     EVT ResultVT = Result.getValueType();
4441     SDValue ZeroIndex = DAG.getIntPtrConstant(0, dl);
4442     SDValue Undef = DAG.getUNDEF(ResultVT);
4443     SDValue Vec256 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Undef,
4444                                  Vec, ZeroIndex);
4445
4446     // The blend instruction, and therefore its mask, depend on the data type.
4447     MVT ScalarType = ResultVT.getVectorElementType().getSimpleVT();
4448     if (ScalarType.isFloatingPoint()) {
4449       // Choose either vblendps (float) or vblendpd (double).
4450       unsigned ScalarSize = ScalarType.getSizeInBits();
4451       assert((ScalarSize == 64 || ScalarSize == 32) && "Unknown float type");
4452       unsigned MaskVal = (ScalarSize == 64) ? 0x03 : 0x0f;
4453       SDValue Mask = DAG.getConstant(MaskVal, dl, MVT::i8);
4454       return DAG.getNode(X86ISD::BLENDI, dl, ResultVT, Result, Vec256, Mask);
4455     }
4456
4457     const X86Subtarget &Subtarget =
4458     static_cast<const X86Subtarget &>(DAG.getSubtarget());
4459
4460     // AVX2 is needed for 256-bit integer blend support.
4461     // Integers must be cast to 32-bit because there is only vpblendd;
4462     // vpblendw can't be used for this because it has a handicapped mask.
4463
4464     // If we don't have AVX2, then cast to float. Using a wrong domain blend
4465     // is still more efficient than using the wrong domain vinsertf128 that
4466     // will be created by InsertSubVector().
4467     MVT CastVT = Subtarget.hasAVX2() ? MVT::v8i32 : MVT::v8f32;
4468
4469     SDValue Mask = DAG.getConstant(0x0f, dl, MVT::i8);
4470     Vec256 = DAG.getBitcast(CastVT, Vec256);
4471     Vec256 = DAG.getNode(X86ISD::BLENDI, dl, CastVT, Result, Vec256, Mask);
4472     return DAG.getBitcast(ResultVT, Vec256);
4473   }
4474
4475   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
4476 }
4477
4478 static SDValue Insert256BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4479                                   SelectionDAG &DAG, SDLoc dl) {
4480   assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
4481   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
4482 }
4483
4484 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
4485 /// instructions. This is used because creating CONCAT_VECTOR nodes of
4486 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
4487 /// large BUILD_VECTORS.
4488 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
4489                                    unsigned NumElems, SelectionDAG &DAG,
4490                                    SDLoc dl) {
4491   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4492   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
4493 }
4494
4495 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
4496                                    unsigned NumElems, SelectionDAG &DAG,
4497                                    SDLoc dl) {
4498   SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4499   return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
4500 }
4501
4502 /// Returns a vector of specified type with all bits set.
4503 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4504 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4505 /// Then bitcast to their original type, ensuring they get CSE'd.
4506 static SDValue getOnesVector(EVT VT, const X86Subtarget *Subtarget,
4507                              SelectionDAG &DAG, SDLoc dl) {
4508   assert(VT.isVector() && "Expected a vector type");
4509
4510   SDValue Cst = DAG.getConstant(~0U, dl, MVT::i32);
4511   SDValue Vec;
4512   if (VT.is512BitVector()) {
4513     SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4514                       Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4515     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4516   } else if (VT.is256BitVector()) {
4517     if (Subtarget->hasInt256()) { // AVX2
4518       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4519       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4520     } else { // AVX
4521       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4522       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4523     }
4524   } else if (VT.is128BitVector()) {
4525     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4526   } else
4527     llvm_unreachable("Unexpected vector type");
4528
4529   return DAG.getBitcast(VT, Vec);
4530 }
4531
4532 /// Returns a vector_shuffle node for an unpackl operation.
4533 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4534                           SDValue V2) {
4535   unsigned NumElems = VT.getVectorNumElements();
4536   SmallVector<int, 8> Mask;
4537   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4538     Mask.push_back(i);
4539     Mask.push_back(i + NumElems);
4540   }
4541   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4542 }
4543
4544 /// Returns a vector_shuffle node for an unpackh operation.
4545 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4546                           SDValue V2) {
4547   unsigned NumElems = VT.getVectorNumElements();
4548   SmallVector<int, 8> Mask;
4549   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4550     Mask.push_back(i + Half);
4551     Mask.push_back(i + NumElems + Half);
4552   }
4553   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4554 }
4555
4556 /// Return a vector_shuffle of the specified vector of zero or undef vector.
4557 /// This produces a shuffle where the low element of V2 is swizzled into the
4558 /// zero/undef vector, landing at element Idx.
4559 /// This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4560 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4561                                            bool IsZero,
4562                                            const X86Subtarget *Subtarget,
4563                                            SelectionDAG &DAG) {
4564   MVT VT = V2.getSimpleValueType();
4565   SDValue V1 = IsZero
4566     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
4567   unsigned NumElems = VT.getVectorNumElements();
4568   SmallVector<int, 16> MaskVec;
4569   for (unsigned i = 0; i != NumElems; ++i)
4570     // If this is the insertion idx, put the low elt of V2 here.
4571     MaskVec.push_back(i == Idx ? NumElems : i);
4572   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
4573 }
4574
4575 /// Calculates the shuffle mask corresponding to the target-specific opcode.
4576 /// Returns true if the Mask could be calculated. Sets IsUnary to true if only
4577 /// uses one source. Note that this will set IsUnary for shuffles which use a
4578 /// single input multiple times, and in those cases it will
4579 /// adjust the mask to only have indices within that single input.
4580 /// FIXME: Add support for Decode*Mask functions that return SM_SentinelZero.
4581 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4582                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
4583   unsigned NumElems = VT.getVectorNumElements();
4584   SDValue ImmN;
4585
4586   IsUnary = false;
4587   bool IsFakeUnary = false;
4588   switch(N->getOpcode()) {
4589   case X86ISD::BLENDI:
4590     ImmN = N->getOperand(N->getNumOperands()-1);
4591     DecodeBLENDMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4592     break;
4593   case X86ISD::SHUFP:
4594     ImmN = N->getOperand(N->getNumOperands()-1);
4595     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4596     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4597     break;
4598   case X86ISD::UNPCKH:
4599     DecodeUNPCKHMask(VT, Mask);
4600     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4601     break;
4602   case X86ISD::UNPCKL:
4603     DecodeUNPCKLMask(VT, Mask);
4604     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4605     break;
4606   case X86ISD::MOVHLPS:
4607     DecodeMOVHLPSMask(NumElems, Mask);
4608     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4609     break;
4610   case X86ISD::MOVLHPS:
4611     DecodeMOVLHPSMask(NumElems, Mask);
4612     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4613     break;
4614   case X86ISD::PALIGNR:
4615     ImmN = N->getOperand(N->getNumOperands()-1);
4616     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4617     break;
4618   case X86ISD::PSHUFD:
4619   case X86ISD::VPERMILPI:
4620     ImmN = N->getOperand(N->getNumOperands()-1);
4621     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4622     IsUnary = true;
4623     break;
4624   case X86ISD::PSHUFHW:
4625     ImmN = N->getOperand(N->getNumOperands()-1);
4626     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4627     IsUnary = true;
4628     break;
4629   case X86ISD::PSHUFLW:
4630     ImmN = N->getOperand(N->getNumOperands()-1);
4631     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4632     IsUnary = true;
4633     break;
4634   case X86ISD::PSHUFB: {
4635     IsUnary = true;
4636     SDValue MaskNode = N->getOperand(1);
4637     while (MaskNode->getOpcode() == ISD::BITCAST)
4638       MaskNode = MaskNode->getOperand(0);
4639
4640     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4641       // If we have a build-vector, then things are easy.
4642       MVT VT = MaskNode.getSimpleValueType();
4643       assert(VT.isVector() &&
4644              "Can't produce a non-vector with a build_vector!");
4645       if (!VT.isInteger())
4646         return false;
4647
4648       int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
4649
4650       SmallVector<uint64_t, 32> RawMask;
4651       for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
4652         SDValue Op = MaskNode->getOperand(i);
4653         if (Op->getOpcode() == ISD::UNDEF) {
4654           RawMask.push_back((uint64_t)SM_SentinelUndef);
4655           continue;
4656         }
4657         auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4658         if (!CN)
4659           return false;
4660         APInt MaskElement = CN->getAPIntValue();
4661
4662         // We now have to decode the element which could be any integer size and
4663         // extract each byte of it.
4664         for (int j = 0; j < NumBytesPerElement; ++j) {
4665           // Note that this is x86 and so always little endian: the low byte is
4666           // the first byte of the mask.
4667           RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
4668           MaskElement = MaskElement.lshr(8);
4669         }
4670       }
4671       DecodePSHUFBMask(RawMask, Mask);
4672       break;
4673     }
4674
4675     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4676     if (!MaskLoad)
4677       return false;
4678
4679     SDValue Ptr = MaskLoad->getBasePtr();
4680     if (Ptr->getOpcode() == X86ISD::Wrapper ||
4681         Ptr->getOpcode() == X86ISD::WrapperRIP)
4682       Ptr = Ptr->getOperand(0);
4683
4684     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4685     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4686       return false;
4687
4688     if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
4689       DecodePSHUFBMask(C, Mask);
4690       if (Mask.empty())
4691         return false;
4692       break;
4693     }
4694
4695     return false;
4696   }
4697   case X86ISD::VPERMI:
4698     ImmN = N->getOperand(N->getNumOperands()-1);
4699     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4700     IsUnary = true;
4701     break;
4702   case X86ISD::MOVSS:
4703   case X86ISD::MOVSD:
4704     DecodeScalarMoveMask(VT, /* IsLoad */ false, Mask);
4705     break;
4706   case X86ISD::VPERM2X128:
4707     ImmN = N->getOperand(N->getNumOperands()-1);
4708     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4709     if (Mask.empty()) return false;
4710     // Mask only contains negative index if an element is zero.
4711     if (std::any_of(Mask.begin(), Mask.end(),
4712                     [](int M){ return M == SM_SentinelZero; }))
4713       return false;
4714     break;
4715   case X86ISD::MOVSLDUP:
4716     DecodeMOVSLDUPMask(VT, Mask);
4717     IsUnary = true;
4718     break;
4719   case X86ISD::MOVSHDUP:
4720     DecodeMOVSHDUPMask(VT, Mask);
4721     IsUnary = true;
4722     break;
4723   case X86ISD::MOVDDUP:
4724     DecodeMOVDDUPMask(VT, Mask);
4725     IsUnary = true;
4726     break;
4727   case X86ISD::MOVLHPD:
4728   case X86ISD::MOVLPD:
4729   case X86ISD::MOVLPS:
4730     // Not yet implemented
4731     return false;
4732   case X86ISD::VPERMV: {
4733     IsUnary = true;
4734     SDValue MaskNode = N->getOperand(0);
4735     while (MaskNode->getOpcode() == ISD::BITCAST)
4736       MaskNode = MaskNode->getOperand(0);
4737
4738     unsigned MaskLoBits = Log2_64(VT.getVectorNumElements());
4739     SmallVector<uint64_t, 32> RawMask;
4740     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4741       // If we have a build-vector, then things are easy.
4742       assert(MaskNode.getSimpleValueType().isInteger() &&
4743              MaskNode.getSimpleValueType().getVectorNumElements() ==
4744              VT.getVectorNumElements());
4745
4746       for (unsigned i = 0; i < MaskNode->getNumOperands(); ++i) {
4747         SDValue Op = MaskNode->getOperand(i);
4748         if (Op->getOpcode() == ISD::UNDEF)
4749           RawMask.push_back((uint64_t)SM_SentinelUndef);
4750         else if (isa<ConstantSDNode>(Op)) {
4751           APInt MaskElement = cast<ConstantSDNode>(Op)->getAPIntValue();
4752           RawMask.push_back(MaskElement.getLoBits(MaskLoBits).getZExtValue());
4753         } else
4754           return false;
4755       }
4756       DecodeVPERMVMask(RawMask, Mask);
4757       break;
4758     }
4759     if (MaskNode->getOpcode() == X86ISD::VBROADCAST) {
4760       unsigned NumEltsInMask = MaskNode->getNumOperands();
4761       MaskNode = MaskNode->getOperand(0);
4762       auto *CN = dyn_cast<ConstantSDNode>(MaskNode);
4763       if (CN) {
4764         APInt MaskEltValue = CN->getAPIntValue();
4765         for (unsigned i = 0; i < NumEltsInMask; ++i)
4766           RawMask.push_back(MaskEltValue.getLoBits(MaskLoBits).getZExtValue());
4767         DecodeVPERMVMask(RawMask, Mask);
4768         break;
4769       }
4770       // It may be a scalar load
4771     }
4772
4773     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4774     if (!MaskLoad)
4775       return false;
4776
4777     SDValue Ptr = MaskLoad->getBasePtr();
4778     if (Ptr->getOpcode() == X86ISD::Wrapper ||
4779         Ptr->getOpcode() == X86ISD::WrapperRIP)
4780       Ptr = Ptr->getOperand(0);
4781
4782     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4783     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4784       return false;
4785
4786     auto *C = dyn_cast<Constant>(MaskCP->getConstVal());
4787     if (C) {
4788       DecodeVPERMVMask(C, VT, Mask);
4789       if (Mask.empty())
4790         return false;
4791       break;
4792     }
4793     return false;
4794   }
4795   case X86ISD::VPERMV3: {
4796     IsUnary = false;
4797     SDValue MaskNode = N->getOperand(1);
4798     while (MaskNode->getOpcode() == ISD::BITCAST)
4799       MaskNode = MaskNode->getOperand(1);
4800
4801     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4802       // If we have a build-vector, then things are easy.
4803       assert(MaskNode.getSimpleValueType().isInteger() &&
4804              MaskNode.getSimpleValueType().getVectorNumElements() ==
4805              VT.getVectorNumElements());
4806
4807       SmallVector<uint64_t, 32> RawMask;
4808       unsigned MaskLoBits = Log2_64(VT.getVectorNumElements()*2);
4809
4810       for (unsigned i = 0; i < MaskNode->getNumOperands(); ++i) {
4811         SDValue Op = MaskNode->getOperand(i);
4812         if (Op->getOpcode() == ISD::UNDEF)
4813           RawMask.push_back((uint64_t)SM_SentinelUndef);
4814         else {
4815           auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4816           if (!CN)
4817             return false;
4818           APInt MaskElement = CN->getAPIntValue();
4819           RawMask.push_back(MaskElement.getLoBits(MaskLoBits).getZExtValue());
4820         }
4821       }
4822       DecodeVPERMV3Mask(RawMask, Mask);
4823       break;
4824     }
4825
4826     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4827     if (!MaskLoad)
4828       return false;
4829
4830     SDValue Ptr = MaskLoad->getBasePtr();
4831     if (Ptr->getOpcode() == X86ISD::Wrapper ||
4832         Ptr->getOpcode() == X86ISD::WrapperRIP)
4833       Ptr = Ptr->getOperand(0);
4834
4835     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4836     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4837       return false;
4838
4839     auto *C = dyn_cast<Constant>(MaskCP->getConstVal());
4840     if (C) {
4841       DecodeVPERMV3Mask(C, VT, Mask);
4842       if (Mask.empty())
4843         return false;
4844       break;
4845     }
4846     return false;
4847   }
4848   default: llvm_unreachable("unknown target shuffle node");
4849   }
4850
4851   // If we have a fake unary shuffle, the shuffle mask is spread across two
4852   // inputs that are actually the same node. Re-map the mask to always point
4853   // into the first input.
4854   if (IsFakeUnary)
4855     for (int &M : Mask)
4856       if (M >= (int)Mask.size())
4857         M -= Mask.size();
4858
4859   return true;
4860 }
4861
4862 /// Returns the scalar element that will make up the ith
4863 /// element of the result of the vector shuffle.
4864 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4865                                    unsigned Depth) {
4866   if (Depth == 6)
4867     return SDValue();  // Limit search depth.
4868
4869   SDValue V = SDValue(N, 0);
4870   EVT VT = V.getValueType();
4871   unsigned Opcode = V.getOpcode();
4872
4873   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4874   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4875     int Elt = SV->getMaskElt(Index);
4876
4877     if (Elt < 0)
4878       return DAG.getUNDEF(VT.getVectorElementType());
4879
4880     unsigned NumElems = VT.getVectorNumElements();
4881     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4882                                          : SV->getOperand(1);
4883     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4884   }
4885
4886   // Recurse into target specific vector shuffles to find scalars.
4887   if (isTargetShuffle(Opcode)) {
4888     MVT ShufVT = V.getSimpleValueType();
4889     unsigned NumElems = ShufVT.getVectorNumElements();
4890     SmallVector<int, 16> ShuffleMask;
4891     bool IsUnary;
4892
4893     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4894       return SDValue();
4895
4896     int Elt = ShuffleMask[Index];
4897     if (Elt < 0)
4898       return DAG.getUNDEF(ShufVT.getVectorElementType());
4899
4900     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4901                                          : N->getOperand(1);
4902     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4903                                Depth+1);
4904   }
4905
4906   // Actual nodes that may contain scalar elements
4907   if (Opcode == ISD::BITCAST) {
4908     V = V.getOperand(0);
4909     EVT SrcVT = V.getValueType();
4910     unsigned NumElems = VT.getVectorNumElements();
4911
4912     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4913       return SDValue();
4914   }
4915
4916   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4917     return (Index == 0) ? V.getOperand(0)
4918                         : DAG.getUNDEF(VT.getVectorElementType());
4919
4920   if (V.getOpcode() == ISD::BUILD_VECTOR)
4921     return V.getOperand(Index);
4922
4923   return SDValue();
4924 }
4925
4926 /// Custom lower build_vector of v16i8.
4927 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4928                                        unsigned NumNonZero, unsigned NumZero,
4929                                        SelectionDAG &DAG,
4930                                        const X86Subtarget* Subtarget,
4931                                        const TargetLowering &TLI) {
4932   if (NumNonZero > 8)
4933     return SDValue();
4934
4935   SDLoc dl(Op);
4936   SDValue V;
4937   bool First = true;
4938
4939   // SSE4.1 - use PINSRB to insert each byte directly.
4940   if (Subtarget->hasSSE41()) {
4941     for (unsigned i = 0; i < 16; ++i) {
4942       bool isNonZero = (NonZeros & (1 << i)) != 0;
4943       if (isNonZero) {
4944         if (First) {
4945           if (NumZero)
4946             V = getZeroVector(MVT::v16i8, Subtarget, DAG, dl);
4947           else
4948             V = DAG.getUNDEF(MVT::v16i8);
4949           First = false;
4950         }
4951         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4952                         MVT::v16i8, V, Op.getOperand(i),
4953                         DAG.getIntPtrConstant(i, dl));
4954       }
4955     }
4956
4957     return V;
4958   }
4959
4960   // Pre-SSE4.1 - merge byte pairs and insert with PINSRW.
4961   for (unsigned i = 0; i < 16; ++i) {
4962     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4963     if (ThisIsNonZero && First) {
4964       if (NumZero)
4965         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4966       else
4967         V = DAG.getUNDEF(MVT::v8i16);
4968       First = false;
4969     }
4970
4971     if ((i & 1) != 0) {
4972       SDValue ThisElt, LastElt;
4973       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4974       if (LastIsNonZero) {
4975         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4976                               MVT::i16, Op.getOperand(i-1));
4977       }
4978       if (ThisIsNonZero) {
4979         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4980         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4981                               ThisElt, DAG.getConstant(8, dl, MVT::i8));
4982         if (LastIsNonZero)
4983           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4984       } else
4985         ThisElt = LastElt;
4986
4987       if (ThisElt.getNode())
4988         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4989                         DAG.getIntPtrConstant(i/2, dl));
4990     }
4991   }
4992
4993   return DAG.getBitcast(MVT::v16i8, V);
4994 }
4995
4996 /// Custom lower build_vector of v8i16.
4997 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4998                                      unsigned NumNonZero, unsigned NumZero,
4999                                      SelectionDAG &DAG,
5000                                      const X86Subtarget* Subtarget,
5001                                      const TargetLowering &TLI) {
5002   if (NumNonZero > 4)
5003     return SDValue();
5004
5005   SDLoc dl(Op);
5006   SDValue V;
5007   bool First = true;
5008   for (unsigned i = 0; i < 8; ++i) {
5009     bool isNonZero = (NonZeros & (1 << i)) != 0;
5010     if (isNonZero) {
5011       if (First) {
5012         if (NumZero)
5013           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5014         else
5015           V = DAG.getUNDEF(MVT::v8i16);
5016         First = false;
5017       }
5018       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5019                       MVT::v8i16, V, Op.getOperand(i),
5020                       DAG.getIntPtrConstant(i, dl));
5021     }
5022   }
5023
5024   return V;
5025 }
5026
5027 /// Custom lower build_vector of v4i32 or v4f32.
5028 static SDValue LowerBuildVectorv4x32(SDValue Op, SelectionDAG &DAG,
5029                                      const X86Subtarget *Subtarget,
5030                                      const TargetLowering &TLI) {
5031   // Find all zeroable elements.
5032   std::bitset<4> Zeroable;
5033   for (int i=0; i < 4; ++i) {
5034     SDValue Elt = Op->getOperand(i);
5035     Zeroable[i] = (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt));
5036   }
5037   assert(Zeroable.size() - Zeroable.count() > 1 &&
5038          "We expect at least two non-zero elements!");
5039
5040   // We only know how to deal with build_vector nodes where elements are either
5041   // zeroable or extract_vector_elt with constant index.
5042   SDValue FirstNonZero;
5043   unsigned FirstNonZeroIdx;
5044   for (unsigned i=0; i < 4; ++i) {
5045     if (Zeroable[i])
5046       continue;
5047     SDValue Elt = Op->getOperand(i);
5048     if (Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5049         !isa<ConstantSDNode>(Elt.getOperand(1)))
5050       return SDValue();
5051     // Make sure that this node is extracting from a 128-bit vector.
5052     MVT VT = Elt.getOperand(0).getSimpleValueType();
5053     if (!VT.is128BitVector())
5054       return SDValue();
5055     if (!FirstNonZero.getNode()) {
5056       FirstNonZero = Elt;
5057       FirstNonZeroIdx = i;
5058     }
5059   }
5060
5061   assert(FirstNonZero.getNode() && "Unexpected build vector of all zeros!");
5062   SDValue V1 = FirstNonZero.getOperand(0);
5063   MVT VT = V1.getSimpleValueType();
5064
5065   // See if this build_vector can be lowered as a blend with zero.
5066   SDValue Elt;
5067   unsigned EltMaskIdx, EltIdx;
5068   int Mask[4];
5069   for (EltIdx = 0; EltIdx < 4; ++EltIdx) {
5070     if (Zeroable[EltIdx]) {
5071       // The zero vector will be on the right hand side.
5072       Mask[EltIdx] = EltIdx+4;
5073       continue;
5074     }
5075
5076     Elt = Op->getOperand(EltIdx);
5077     // By construction, Elt is a EXTRACT_VECTOR_ELT with constant index.
5078     EltMaskIdx = cast<ConstantSDNode>(Elt.getOperand(1))->getZExtValue();
5079     if (Elt.getOperand(0) != V1 || EltMaskIdx != EltIdx)
5080       break;
5081     Mask[EltIdx] = EltIdx;
5082   }
5083
5084   if (EltIdx == 4) {
5085     // Let the shuffle legalizer deal with blend operations.
5086     SDValue VZero = getZeroVector(VT, Subtarget, DAG, SDLoc(Op));
5087     if (V1.getSimpleValueType() != VT)
5088       V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), VT, V1);
5089     return DAG.getVectorShuffle(VT, SDLoc(V1), V1, VZero, &Mask[0]);
5090   }
5091
5092   // See if we can lower this build_vector to a INSERTPS.
5093   if (!Subtarget->hasSSE41())
5094     return SDValue();
5095
5096   SDValue V2 = Elt.getOperand(0);
5097   if (Elt == FirstNonZero && EltIdx == FirstNonZeroIdx)
5098     V1 = SDValue();
5099
5100   bool CanFold = true;
5101   for (unsigned i = EltIdx + 1; i < 4 && CanFold; ++i) {
5102     if (Zeroable[i])
5103       continue;
5104
5105     SDValue Current = Op->getOperand(i);
5106     SDValue SrcVector = Current->getOperand(0);
5107     if (!V1.getNode())
5108       V1 = SrcVector;
5109     CanFold = SrcVector == V1 &&
5110       cast<ConstantSDNode>(Current.getOperand(1))->getZExtValue() == i;
5111   }
5112
5113   if (!CanFold)
5114     return SDValue();
5115
5116   assert(V1.getNode() && "Expected at least two non-zero elements!");
5117   if (V1.getSimpleValueType() != MVT::v4f32)
5118     V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), MVT::v4f32, V1);
5119   if (V2.getSimpleValueType() != MVT::v4f32)
5120     V2 = DAG.getNode(ISD::BITCAST, SDLoc(V2), MVT::v4f32, V2);
5121
5122   // Ok, we can emit an INSERTPS instruction.
5123   unsigned ZMask = Zeroable.to_ulong();
5124
5125   unsigned InsertPSMask = EltMaskIdx << 6 | EltIdx << 4 | ZMask;
5126   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
5127   SDLoc DL(Op);
5128   SDValue Result = DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
5129                                DAG.getIntPtrConstant(InsertPSMask, DL));
5130   return DAG.getBitcast(VT, Result);
5131 }
5132
5133 /// Return a vector logical shift node.
5134 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5135                          unsigned NumBits, SelectionDAG &DAG,
5136                          const TargetLowering &TLI, SDLoc dl) {
5137   assert(VT.is128BitVector() && "Unknown type for VShift");
5138   MVT ShVT = MVT::v2i64;
5139   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5140   SrcOp = DAG.getBitcast(ShVT, SrcOp);
5141   MVT ScalarShiftTy = TLI.getScalarShiftAmountTy(DAG.getDataLayout(), VT);
5142   assert(NumBits % 8 == 0 && "Only support byte sized shifts");
5143   SDValue ShiftVal = DAG.getConstant(NumBits/8, dl, ScalarShiftTy);
5144   return DAG.getBitcast(VT, DAG.getNode(Opc, dl, ShVT, SrcOp, ShiftVal));
5145 }
5146
5147 static SDValue
5148 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5149
5150   // Check if the scalar load can be widened into a vector load. And if
5151   // the address is "base + cst" see if the cst can be "absorbed" into
5152   // the shuffle mask.
5153   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5154     SDValue Ptr = LD->getBasePtr();
5155     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5156       return SDValue();
5157     EVT PVT = LD->getValueType(0);
5158     if (PVT != MVT::i32 && PVT != MVT::f32)
5159       return SDValue();
5160
5161     int FI = -1;
5162     int64_t Offset = 0;
5163     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5164       FI = FINode->getIndex();
5165       Offset = 0;
5166     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5167                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5168       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5169       Offset = Ptr.getConstantOperandVal(1);
5170       Ptr = Ptr.getOperand(0);
5171     } else {
5172       return SDValue();
5173     }
5174
5175     // FIXME: 256-bit vector instructions don't require a strict alignment,
5176     // improve this code to support it better.
5177     unsigned RequiredAlign = VT.getSizeInBits()/8;
5178     SDValue Chain = LD->getChain();
5179     // Make sure the stack object alignment is at least 16 or 32.
5180     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5181     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5182       if (MFI->isFixedObjectIndex(FI)) {
5183         // Can't change the alignment. FIXME: It's possible to compute
5184         // the exact stack offset and reference FI + adjust offset instead.
5185         // If someone *really* cares about this. That's the way to implement it.
5186         return SDValue();
5187       } else {
5188         MFI->setObjectAlignment(FI, RequiredAlign);
5189       }
5190     }
5191
5192     // (Offset % 16 or 32) must be multiple of 4. Then address is then
5193     // Ptr + (Offset & ~15).
5194     if (Offset < 0)
5195       return SDValue();
5196     if ((Offset % RequiredAlign) & 3)
5197       return SDValue();
5198     int64_t StartOffset = Offset & ~int64_t(RequiredAlign - 1);
5199     if (StartOffset) {
5200       SDLoc DL(Ptr);
5201       Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5202                         DAG.getConstant(StartOffset, DL, Ptr.getValueType()));
5203     }
5204
5205     int EltNo = (Offset - StartOffset) >> 2;
5206     unsigned NumElems = VT.getVectorNumElements();
5207
5208     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5209     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5210                              LD->getPointerInfo().getWithOffset(StartOffset),
5211                              false, false, false, 0);
5212
5213     SmallVector<int, 8> Mask(NumElems, EltNo);
5214
5215     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5216   }
5217
5218   return SDValue();
5219 }
5220
5221 /// Given the initializing elements 'Elts' of a vector of type 'VT', see if the
5222 /// elements can be replaced by a single large load which has the same value as
5223 /// a build_vector or insert_subvector whose loaded operands are 'Elts'.
5224 ///
5225 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5226 ///
5227 /// FIXME: we'd also like to handle the case where the last elements are zero
5228 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5229 /// There's even a handy isZeroNode for that purpose.
5230 static SDValue EltsFromConsecutiveLoads(EVT VT, ArrayRef<SDValue> Elts,
5231                                         SDLoc &DL, SelectionDAG &DAG,
5232                                         bool isAfterLegalize) {
5233   unsigned NumElems = Elts.size();
5234
5235   LoadSDNode *LDBase = nullptr;
5236   unsigned LastLoadedElt = -1U;
5237
5238   // For each element in the initializer, see if we've found a load or an undef.
5239   // If we don't find an initial load element, or later load elements are
5240   // non-consecutive, bail out.
5241   for (unsigned i = 0; i < NumElems; ++i) {
5242     SDValue Elt = Elts[i];
5243     // Look through a bitcast.
5244     if (Elt.getNode() && Elt.getOpcode() == ISD::BITCAST)
5245       Elt = Elt.getOperand(0);
5246     if (!Elt.getNode() ||
5247         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5248       return SDValue();
5249     if (!LDBase) {
5250       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5251         return SDValue();
5252       LDBase = cast<LoadSDNode>(Elt.getNode());
5253       LastLoadedElt = i;
5254       continue;
5255     }
5256     if (Elt.getOpcode() == ISD::UNDEF)
5257       continue;
5258
5259     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5260     EVT LdVT = Elt.getValueType();
5261     // Each loaded element must be the correct fractional portion of the
5262     // requested vector load.
5263     if (LdVT.getSizeInBits() != VT.getSizeInBits() / NumElems)
5264       return SDValue();
5265     if (!DAG.isConsecutiveLoad(LD, LDBase, LdVT.getSizeInBits() / 8, i))
5266       return SDValue();
5267     LastLoadedElt = i;
5268   }
5269
5270   // If we have found an entire vector of loads and undefs, then return a large
5271   // load of the entire vector width starting at the base pointer.  If we found
5272   // consecutive loads for the low half, generate a vzext_load node.
5273   if (LastLoadedElt == NumElems - 1) {
5274     assert(LDBase && "Did not find base load for merging consecutive loads");
5275     EVT EltVT = LDBase->getValueType(0);
5276     // Ensure that the input vector size for the merged loads matches the
5277     // cumulative size of the input elements.
5278     if (VT.getSizeInBits() != EltVT.getSizeInBits() * NumElems)
5279       return SDValue();
5280
5281     if (isAfterLegalize &&
5282         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5283       return SDValue();
5284
5285     SDValue NewLd = SDValue();
5286
5287     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5288                         LDBase->getPointerInfo(), LDBase->isVolatile(),
5289                         LDBase->isNonTemporal(), LDBase->isInvariant(),
5290                         LDBase->getAlignment());
5291
5292     if (LDBase->hasAnyUseOfValue(1)) {
5293       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5294                                      SDValue(LDBase, 1),
5295                                      SDValue(NewLd.getNode(), 1));
5296       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5297       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5298                              SDValue(NewLd.getNode(), 1));
5299     }
5300
5301     return NewLd;
5302   }
5303
5304   //TODO: The code below fires only for for loading the low v2i32 / v2f32
5305   //of a v4i32 / v4f32. It's probably worth generalizing.
5306   EVT EltVT = VT.getVectorElementType();
5307   if (NumElems == 4 && LastLoadedElt == 1 && (EltVT.getSizeInBits() == 32) &&
5308       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5309     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5310     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5311     SDValue ResNode =
5312         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5313                                 LDBase->getPointerInfo(),
5314                                 LDBase->getAlignment(),
5315                                 false/*isVolatile*/, true/*ReadMem*/,
5316                                 false/*WriteMem*/);
5317
5318     // Make sure the newly-created LOAD is in the same position as LDBase in
5319     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5320     // update uses of LDBase's output chain to use the TokenFactor.
5321     if (LDBase->hasAnyUseOfValue(1)) {
5322       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5323                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5324       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5325       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5326                              SDValue(ResNode.getNode(), 1));
5327     }
5328
5329     return DAG.getBitcast(VT, ResNode);
5330   }
5331   return SDValue();
5332 }
5333
5334 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5335 /// to generate a splat value for the following cases:
5336 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5337 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5338 /// a scalar load, or a constant.
5339 /// The VBROADCAST node is returned when a pattern is found,
5340 /// or SDValue() otherwise.
5341 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5342                                     SelectionDAG &DAG) {
5343   // VBROADCAST requires AVX.
5344   // TODO: Splats could be generated for non-AVX CPUs using SSE
5345   // instructions, but there's less potential gain for only 128-bit vectors.
5346   if (!Subtarget->hasAVX())
5347     return SDValue();
5348
5349   MVT VT = Op.getSimpleValueType();
5350   SDLoc dl(Op);
5351
5352   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5353          "Unsupported vector type for broadcast.");
5354
5355   SDValue Ld;
5356   bool ConstSplatVal;
5357
5358   switch (Op.getOpcode()) {
5359     default:
5360       // Unknown pattern found.
5361       return SDValue();
5362
5363     case ISD::BUILD_VECTOR: {
5364       auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
5365       BitVector UndefElements;
5366       SDValue Splat = BVOp->getSplatValue(&UndefElements);
5367
5368       // We need a splat of a single value to use broadcast, and it doesn't
5369       // make any sense if the value is only in one element of the vector.
5370       if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
5371         return SDValue();
5372
5373       Ld = Splat;
5374       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5375                        Ld.getOpcode() == ISD::ConstantFP);
5376
5377       // Make sure that all of the users of a non-constant load are from the
5378       // BUILD_VECTOR node.
5379       if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
5380         return SDValue();
5381       break;
5382     }
5383
5384     case ISD::VECTOR_SHUFFLE: {
5385       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5386
5387       // Shuffles must have a splat mask where the first element is
5388       // broadcasted.
5389       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5390         return SDValue();
5391
5392       SDValue Sc = Op.getOperand(0);
5393       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5394           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5395
5396         if (!Subtarget->hasInt256())
5397           return SDValue();
5398
5399         // Use the register form of the broadcast instruction available on AVX2.
5400         if (VT.getSizeInBits() >= 256)
5401           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5402         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5403       }
5404
5405       Ld = Sc.getOperand(0);
5406       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5407                        Ld.getOpcode() == ISD::ConstantFP);
5408
5409       // The scalar_to_vector node and the suspected
5410       // load node must have exactly one user.
5411       // Constants may have multiple users.
5412
5413       // AVX-512 has register version of the broadcast
5414       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5415         Ld.getValueType().getSizeInBits() >= 32;
5416       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5417           !hasRegVer))
5418         return SDValue();
5419       break;
5420     }
5421   }
5422
5423   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5424   bool IsGE256 = (VT.getSizeInBits() >= 256);
5425
5426   // When optimizing for size, generate up to 5 extra bytes for a broadcast
5427   // instruction to save 8 or more bytes of constant pool data.
5428   // TODO: If multiple splats are generated to load the same constant,
5429   // it may be detrimental to overall size. There needs to be a way to detect
5430   // that condition to know if this is truly a size win.
5431   bool OptForSize = DAG.getMachineFunction().getFunction()->optForSize();
5432
5433   // Handle broadcasting a single constant scalar from the constant pool
5434   // into a vector.
5435   // On Sandybridge (no AVX2), it is still better to load a constant vector
5436   // from the constant pool and not to broadcast it from a scalar.
5437   // But override that restriction when optimizing for size.
5438   // TODO: Check if splatting is recommended for other AVX-capable CPUs.
5439   if (ConstSplatVal && (Subtarget->hasAVX2() || OptForSize)) {
5440     EVT CVT = Ld.getValueType();
5441     assert(!CVT.isVector() && "Must not broadcast a vector type");
5442
5443     // Splat f32, i32, v4f64, v4i64 in all cases with AVX2.
5444     // For size optimization, also splat v2f64 and v2i64, and for size opt
5445     // with AVX2, also splat i8 and i16.
5446     // With pattern matching, the VBROADCAST node may become a VMOVDDUP.
5447     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5448         (OptForSize && (ScalarSize == 64 || Subtarget->hasAVX2()))) {
5449       const Constant *C = nullptr;
5450       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5451         C = CI->getConstantIntValue();
5452       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5453         C = CF->getConstantFPValue();
5454
5455       assert(C && "Invalid constant type");
5456
5457       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5458       SDValue CP =
5459           DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
5460       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5461       Ld = DAG.getLoad(
5462           CVT, dl, DAG.getEntryNode(), CP,
5463           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
5464           false, false, Alignment);
5465
5466       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5467     }
5468   }
5469
5470   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5471
5472   // Handle AVX2 in-register broadcasts.
5473   if (!IsLoad && Subtarget->hasInt256() &&
5474       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5475     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5476
5477   // The scalar source must be a normal load.
5478   if (!IsLoad)
5479     return SDValue();
5480
5481   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5482       (Subtarget->hasVLX() && ScalarSize == 64))
5483     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5484
5485   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5486   // double since there is no vbroadcastsd xmm
5487   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5488     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5489       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5490   }
5491
5492   // Unsupported broadcast.
5493   return SDValue();
5494 }
5495
5496 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5497 /// underlying vector and index.
5498 ///
5499 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5500 /// index.
5501 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5502                                          SDValue ExtIdx) {
5503   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5504   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5505     return Idx;
5506
5507   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5508   // lowered this:
5509   //   (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5510   // to:
5511   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
5512   //                           (extract_subvector (v8f32 %vreg0), Constant<4>),
5513   //                           undef)
5514   //                       Constant<0>)
5515   // In this case the vector is the extract_subvector expression and the index
5516   // is 2, as specified by the shuffle.
5517   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5518   SDValue ShuffleVec = SVOp->getOperand(0);
5519   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5520   assert(ShuffleVecVT.getVectorElementType() ==
5521          ExtractedFromVec.getSimpleValueType().getVectorElementType());
5522
5523   int ShuffleIdx = SVOp->getMaskElt(Idx);
5524   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5525     ExtractedFromVec = ShuffleVec;
5526     return ShuffleIdx;
5527   }
5528   return Idx;
5529 }
5530
5531 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5532   MVT VT = Op.getSimpleValueType();
5533
5534   // Skip if insert_vec_elt is not supported.
5535   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5536   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5537     return SDValue();
5538
5539   SDLoc DL(Op);
5540   unsigned NumElems = Op.getNumOperands();
5541
5542   SDValue VecIn1;
5543   SDValue VecIn2;
5544   SmallVector<unsigned, 4> InsertIndices;
5545   SmallVector<int, 8> Mask(NumElems, -1);
5546
5547   for (unsigned i = 0; i != NumElems; ++i) {
5548     unsigned Opc = Op.getOperand(i).getOpcode();
5549
5550     if (Opc == ISD::UNDEF)
5551       continue;
5552
5553     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5554       // Quit if more than 1 elements need inserting.
5555       if (InsertIndices.size() > 1)
5556         return SDValue();
5557
5558       InsertIndices.push_back(i);
5559       continue;
5560     }
5561
5562     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5563     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5564     // Quit if non-constant index.
5565     if (!isa<ConstantSDNode>(ExtIdx))
5566       return SDValue();
5567     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5568
5569     // Quit if extracted from vector of different type.
5570     if (ExtractedFromVec.getValueType() != VT)
5571       return SDValue();
5572
5573     if (!VecIn1.getNode())
5574       VecIn1 = ExtractedFromVec;
5575     else if (VecIn1 != ExtractedFromVec) {
5576       if (!VecIn2.getNode())
5577         VecIn2 = ExtractedFromVec;
5578       else if (VecIn2 != ExtractedFromVec)
5579         // Quit if more than 2 vectors to shuffle
5580         return SDValue();
5581     }
5582
5583     if (ExtractedFromVec == VecIn1)
5584       Mask[i] = Idx;
5585     else if (ExtractedFromVec == VecIn2)
5586       Mask[i] = Idx + NumElems;
5587   }
5588
5589   if (!VecIn1.getNode())
5590     return SDValue();
5591
5592   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5593   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5594   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5595     unsigned Idx = InsertIndices[i];
5596     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5597                      DAG.getIntPtrConstant(Idx, DL));
5598   }
5599
5600   return NV;
5601 }
5602
5603 static SDValue ConvertI1VectorToInteger(SDValue Op, SelectionDAG &DAG) {
5604   assert(ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
5605          Op.getScalarValueSizeInBits() == 1 &&
5606          "Can not convert non-constant vector");
5607   uint64_t Immediate = 0;
5608   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5609     SDValue In = Op.getOperand(idx);
5610     if (In.getOpcode() != ISD::UNDEF)
5611       Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5612   }
5613   SDLoc dl(Op);
5614   MVT VT =
5615    MVT::getIntegerVT(std::max((int)Op.getValueType().getSizeInBits(), 8));
5616   return DAG.getConstant(Immediate, dl, VT);
5617 }
5618 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5619 SDValue
5620 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5621
5622   MVT VT = Op.getSimpleValueType();
5623   assert((VT.getVectorElementType() == MVT::i1) &&
5624          "Unexpected type in LowerBUILD_VECTORvXi1!");
5625
5626   SDLoc dl(Op);
5627   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5628     SDValue Cst = DAG.getTargetConstant(0, dl, MVT::i1);
5629     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5630     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5631   }
5632
5633   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5634     SDValue Cst = DAG.getTargetConstant(1, dl, MVT::i1);
5635     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5636     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5637   }
5638
5639   if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
5640     SDValue Imm = ConvertI1VectorToInteger(Op, DAG);
5641     if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5642       return DAG.getBitcast(VT, Imm);
5643     SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5644     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5645                         DAG.getIntPtrConstant(0, dl));
5646   }
5647
5648   // Vector has one or more non-const elements
5649   uint64_t Immediate = 0;
5650   SmallVector<unsigned, 16> NonConstIdx;
5651   bool IsSplat = true;
5652   bool HasConstElts = false;
5653   int SplatIdx = -1;
5654   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5655     SDValue In = Op.getOperand(idx);
5656     if (In.getOpcode() == ISD::UNDEF)
5657       continue;
5658     if (!isa<ConstantSDNode>(In))
5659       NonConstIdx.push_back(idx);
5660     else {
5661       Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5662       HasConstElts = true;
5663     }
5664     if (SplatIdx == -1)
5665       SplatIdx = idx;
5666     else if (In != Op.getOperand(SplatIdx))
5667       IsSplat = false;
5668   }
5669
5670   // for splat use " (select i1 splat_elt, all-ones, all-zeroes)"
5671   if (IsSplat)
5672     return DAG.getNode(ISD::SELECT, dl, VT, Op.getOperand(SplatIdx),
5673                        DAG.getConstant(1, dl, VT),
5674                        DAG.getConstant(0, dl, VT));
5675
5676   // insert elements one by one
5677   SDValue DstVec;
5678   SDValue Imm;
5679   if (Immediate) {
5680     MVT ImmVT = MVT::getIntegerVT(std::max((int)VT.getSizeInBits(), 8));
5681     Imm = DAG.getConstant(Immediate, dl, ImmVT);
5682   }
5683   else if (HasConstElts)
5684     Imm = DAG.getConstant(0, dl, VT);
5685   else
5686     Imm = DAG.getUNDEF(VT);
5687   if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5688     DstVec = DAG.getBitcast(VT, Imm);
5689   else {
5690     SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5691     DstVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5692                          DAG.getIntPtrConstant(0, dl));
5693   }
5694
5695   for (unsigned i = 0; i < NonConstIdx.size(); ++i) {
5696     unsigned InsertIdx = NonConstIdx[i];
5697     DstVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5698                          Op.getOperand(InsertIdx),
5699                          DAG.getIntPtrConstant(InsertIdx, dl));
5700   }
5701   return DstVec;
5702 }
5703
5704 /// \brief Return true if \p N implements a horizontal binop and return the
5705 /// operands for the horizontal binop into V0 and V1.
5706 ///
5707 /// This is a helper function of LowerToHorizontalOp().
5708 /// This function checks that the build_vector \p N in input implements a
5709 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
5710 /// operation to match.
5711 /// For example, if \p Opcode is equal to ISD::ADD, then this function
5712 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
5713 /// is equal to ISD::SUB, then this function checks if this is a horizontal
5714 /// arithmetic sub.
5715 ///
5716 /// This function only analyzes elements of \p N whose indices are
5717 /// in range [BaseIdx, LastIdx).
5718 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
5719                               SelectionDAG &DAG,
5720                               unsigned BaseIdx, unsigned LastIdx,
5721                               SDValue &V0, SDValue &V1) {
5722   EVT VT = N->getValueType(0);
5723
5724   assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
5725   assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
5726          "Invalid Vector in input!");
5727
5728   bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
5729   bool CanFold = true;
5730   unsigned ExpectedVExtractIdx = BaseIdx;
5731   unsigned NumElts = LastIdx - BaseIdx;
5732   V0 = DAG.getUNDEF(VT);
5733   V1 = DAG.getUNDEF(VT);
5734
5735   // Check if N implements a horizontal binop.
5736   for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
5737     SDValue Op = N->getOperand(i + BaseIdx);
5738
5739     // Skip UNDEFs.
5740     if (Op->getOpcode() == ISD::UNDEF) {
5741       // Update the expected vector extract index.
5742       if (i * 2 == NumElts)
5743         ExpectedVExtractIdx = BaseIdx;
5744       ExpectedVExtractIdx += 2;
5745       continue;
5746     }
5747
5748     CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
5749
5750     if (!CanFold)
5751       break;
5752
5753     SDValue Op0 = Op.getOperand(0);
5754     SDValue Op1 = Op.getOperand(1);
5755
5756     // Try to match the following pattern:
5757     // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
5758     CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5759         Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5760         Op0.getOperand(0) == Op1.getOperand(0) &&
5761         isa<ConstantSDNode>(Op0.getOperand(1)) &&
5762         isa<ConstantSDNode>(Op1.getOperand(1)));
5763     if (!CanFold)
5764       break;
5765
5766     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5767     unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
5768
5769     if (i * 2 < NumElts) {
5770       if (V0.getOpcode() == ISD::UNDEF) {
5771         V0 = Op0.getOperand(0);
5772         if (V0.getValueType() != VT)
5773           return false;
5774       }
5775     } else {
5776       if (V1.getOpcode() == ISD::UNDEF) {
5777         V1 = Op0.getOperand(0);
5778         if (V1.getValueType() != VT)
5779           return false;
5780       }
5781       if (i * 2 == NumElts)
5782         ExpectedVExtractIdx = BaseIdx;
5783     }
5784
5785     SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
5786     if (I0 == ExpectedVExtractIdx)
5787       CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
5788     else if (IsCommutable && I1 == ExpectedVExtractIdx) {
5789       // Try to match the following dag sequence:
5790       // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
5791       CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
5792     } else
5793       CanFold = false;
5794
5795     ExpectedVExtractIdx += 2;
5796   }
5797
5798   return CanFold;
5799 }
5800
5801 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
5802 /// a concat_vector.
5803 ///
5804 /// This is a helper function of LowerToHorizontalOp().
5805 /// This function expects two 256-bit vectors called V0 and V1.
5806 /// At first, each vector is split into two separate 128-bit vectors.
5807 /// Then, the resulting 128-bit vectors are used to implement two
5808 /// horizontal binary operations.
5809 ///
5810 /// The kind of horizontal binary operation is defined by \p X86Opcode.
5811 ///
5812 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
5813 /// the two new horizontal binop.
5814 /// When Mode is set, the first horizontal binop dag node would take as input
5815 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
5816 /// horizontal binop dag node would take as input the lower 128-bit of V1
5817 /// and the upper 128-bit of V1.
5818 ///   Example:
5819 ///     HADD V0_LO, V0_HI
5820 ///     HADD V1_LO, V1_HI
5821 ///
5822 /// Otherwise, the first horizontal binop dag node takes as input the lower
5823 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
5824 /// dag node takes the upper 128-bit of V0 and the upper 128-bit of V1.
5825 ///   Example:
5826 ///     HADD V0_LO, V1_LO
5827 ///     HADD V0_HI, V1_HI
5828 ///
5829 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
5830 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
5831 /// the upper 128-bits of the result.
5832 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
5833                                      SDLoc DL, SelectionDAG &DAG,
5834                                      unsigned X86Opcode, bool Mode,
5835                                      bool isUndefLO, bool isUndefHI) {
5836   EVT VT = V0.getValueType();
5837   assert(VT.is256BitVector() && VT == V1.getValueType() &&
5838          "Invalid nodes in input!");
5839
5840   unsigned NumElts = VT.getVectorNumElements();
5841   SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
5842   SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
5843   SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
5844   SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
5845   EVT NewVT = V0_LO.getValueType();
5846
5847   SDValue LO = DAG.getUNDEF(NewVT);
5848   SDValue HI = DAG.getUNDEF(NewVT);
5849
5850   if (Mode) {
5851     // Don't emit a horizontal binop if the result is expected to be UNDEF.
5852     if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
5853       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
5854     if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
5855       HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
5856   } else {
5857     // Don't emit a horizontal binop if the result is expected to be UNDEF.
5858     if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
5859                        V1_LO->getOpcode() != ISD::UNDEF))
5860       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
5861
5862     if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
5863                        V1_HI->getOpcode() != ISD::UNDEF))
5864       HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
5865   }
5866
5867   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
5868 }
5869
5870 /// Try to fold a build_vector that performs an 'addsub' to an X86ISD::ADDSUB
5871 /// node.
5872 static SDValue LowerToAddSub(const BuildVectorSDNode *BV,
5873                              const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5874   MVT VT = BV->getSimpleValueType(0);
5875   if ((!Subtarget->hasSSE3() || (VT != MVT::v4f32 && VT != MVT::v2f64)) &&
5876       (!Subtarget->hasAVX() || (VT != MVT::v8f32 && VT != MVT::v4f64)))
5877     return SDValue();
5878
5879   SDLoc DL(BV);
5880   unsigned NumElts = VT.getVectorNumElements();
5881   SDValue InVec0 = DAG.getUNDEF(VT);
5882   SDValue InVec1 = DAG.getUNDEF(VT);
5883
5884   assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
5885           VT == MVT::v2f64) && "build_vector with an invalid type found!");
5886
5887   // Odd-numbered elements in the input build vector are obtained from
5888   // adding two integer/float elements.
5889   // Even-numbered elements in the input build vector are obtained from
5890   // subtracting two integer/float elements.
5891   unsigned ExpectedOpcode = ISD::FSUB;
5892   unsigned NextExpectedOpcode = ISD::FADD;
5893   bool AddFound = false;
5894   bool SubFound = false;
5895
5896   for (unsigned i = 0, e = NumElts; i != e; ++i) {
5897     SDValue Op = BV->getOperand(i);
5898
5899     // Skip 'undef' values.
5900     unsigned Opcode = Op.getOpcode();
5901     if (Opcode == ISD::UNDEF) {
5902       std::swap(ExpectedOpcode, NextExpectedOpcode);
5903       continue;
5904     }
5905
5906     // Early exit if we found an unexpected opcode.
5907     if (Opcode != ExpectedOpcode)
5908       return SDValue();
5909
5910     SDValue Op0 = Op.getOperand(0);
5911     SDValue Op1 = Op.getOperand(1);
5912
5913     // Try to match the following pattern:
5914     // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
5915     // Early exit if we cannot match that sequence.
5916     if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5917         Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5918         !isa<ConstantSDNode>(Op0.getOperand(1)) ||
5919         !isa<ConstantSDNode>(Op1.getOperand(1)) ||
5920         Op0.getOperand(1) != Op1.getOperand(1))
5921       return SDValue();
5922
5923     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5924     if (I0 != i)
5925       return SDValue();
5926
5927     // We found a valid add/sub node. Update the information accordingly.
5928     if (i & 1)
5929       AddFound = true;
5930     else
5931       SubFound = true;
5932
5933     // Update InVec0 and InVec1.
5934     if (InVec0.getOpcode() == ISD::UNDEF) {
5935       InVec0 = Op0.getOperand(0);
5936       if (InVec0.getSimpleValueType() != VT)
5937         return SDValue();
5938     }
5939     if (InVec1.getOpcode() == ISD::UNDEF) {
5940       InVec1 = Op1.getOperand(0);
5941       if (InVec1.getSimpleValueType() != VT)
5942         return SDValue();
5943     }
5944
5945     // Make sure that operands in input to each add/sub node always
5946     // come from a same pair of vectors.
5947     if (InVec0 != Op0.getOperand(0)) {
5948       if (ExpectedOpcode == ISD::FSUB)
5949         return SDValue();
5950
5951       // FADD is commutable. Try to commute the operands
5952       // and then test again.
5953       std::swap(Op0, Op1);
5954       if (InVec0 != Op0.getOperand(0))
5955         return SDValue();
5956     }
5957
5958     if (InVec1 != Op1.getOperand(0))
5959       return SDValue();
5960
5961     // Update the pair of expected opcodes.
5962     std::swap(ExpectedOpcode, NextExpectedOpcode);
5963   }
5964
5965   // Don't try to fold this build_vector into an ADDSUB if the inputs are undef.
5966   if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
5967       InVec1.getOpcode() != ISD::UNDEF)
5968     return DAG.getNode(X86ISD::ADDSUB, DL, VT, InVec0, InVec1);
5969
5970   return SDValue();
5971 }
5972
5973 /// Lower BUILD_VECTOR to a horizontal add/sub operation if possible.
5974 static SDValue LowerToHorizontalOp(const BuildVectorSDNode *BV,
5975                                    const X86Subtarget *Subtarget,
5976                                    SelectionDAG &DAG) {
5977   MVT VT = BV->getSimpleValueType(0);
5978   unsigned NumElts = VT.getVectorNumElements();
5979   unsigned NumUndefsLO = 0;
5980   unsigned NumUndefsHI = 0;
5981   unsigned Half = NumElts/2;
5982
5983   // Count the number of UNDEF operands in the build_vector in input.
5984   for (unsigned i = 0, e = Half; i != e; ++i)
5985     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5986       NumUndefsLO++;
5987
5988   for (unsigned i = Half, e = NumElts; i != e; ++i)
5989     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5990       NumUndefsHI++;
5991
5992   // Early exit if this is either a build_vector of all UNDEFs or all the
5993   // operands but one are UNDEF.
5994   if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
5995     return SDValue();
5996
5997   SDLoc DL(BV);
5998   SDValue InVec0, InVec1;
5999   if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
6000     // Try to match an SSE3 float HADD/HSUB.
6001     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6002       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6003
6004     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6005       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6006   } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
6007     // Try to match an SSSE3 integer HADD/HSUB.
6008     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6009       return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
6010
6011     if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6012       return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
6013   }
6014
6015   if (!Subtarget->hasAVX())
6016     return SDValue();
6017
6018   if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
6019     // Try to match an AVX horizontal add/sub of packed single/double
6020     // precision floating point values from 256-bit vectors.
6021     SDValue InVec2, InVec3;
6022     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
6023         isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
6024         ((InVec0.getOpcode() == ISD::UNDEF ||
6025           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6026         ((InVec1.getOpcode() == ISD::UNDEF ||
6027           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6028       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6029
6030     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
6031         isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
6032         ((InVec0.getOpcode() == ISD::UNDEF ||
6033           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6034         ((InVec1.getOpcode() == ISD::UNDEF ||
6035           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6036       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6037   } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
6038     // Try to match an AVX2 horizontal add/sub of signed integers.
6039     SDValue InVec2, InVec3;
6040     unsigned X86Opcode;
6041     bool CanFold = true;
6042
6043     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
6044         isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
6045         ((InVec0.getOpcode() == ISD::UNDEF ||
6046           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6047         ((InVec1.getOpcode() == ISD::UNDEF ||
6048           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6049       X86Opcode = X86ISD::HADD;
6050     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
6051         isHorizontalBinOp(BV, ISD::SUB, 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::HSUB;
6057     else
6058       CanFold = false;
6059
6060     if (CanFold) {
6061       // Fold this build_vector into a single horizontal add/sub.
6062       // Do this only if the target has AVX2.
6063       if (Subtarget->hasAVX2())
6064         return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
6065
6066       // Do not try to expand this build_vector into a pair of horizontal
6067       // add/sub if we can emit a pair of scalar add/sub.
6068       if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6069         return SDValue();
6070
6071       // Convert this build_vector into a pair of horizontal binop followed by
6072       // a concat vector.
6073       bool isUndefLO = NumUndefsLO == Half;
6074       bool isUndefHI = NumUndefsHI == Half;
6075       return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
6076                                    isUndefLO, isUndefHI);
6077     }
6078   }
6079
6080   if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
6081        VT == MVT::v16i16) && Subtarget->hasAVX()) {
6082     unsigned X86Opcode;
6083     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6084       X86Opcode = X86ISD::HADD;
6085     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6086       X86Opcode = X86ISD::HSUB;
6087     else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6088       X86Opcode = X86ISD::FHADD;
6089     else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6090       X86Opcode = X86ISD::FHSUB;
6091     else
6092       return SDValue();
6093
6094     // Don't try to expand this build_vector into a pair of horizontal add/sub
6095     // if we can simply emit a pair of scalar add/sub.
6096     if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6097       return SDValue();
6098
6099     // Convert this build_vector into two horizontal add/sub followed by
6100     // a concat vector.
6101     bool isUndefLO = NumUndefsLO == Half;
6102     bool isUndefHI = NumUndefsHI == Half;
6103     return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
6104                                  isUndefLO, isUndefHI);
6105   }
6106
6107   return SDValue();
6108 }
6109
6110 SDValue
6111 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6112   SDLoc dl(Op);
6113
6114   MVT VT = Op.getSimpleValueType();
6115   MVT ExtVT = VT.getVectorElementType();
6116   unsigned NumElems = Op.getNumOperands();
6117
6118   // Generate vectors for predicate vectors.
6119   if (VT.getVectorElementType() == MVT::i1 && Subtarget->hasAVX512())
6120     return LowerBUILD_VECTORvXi1(Op, DAG);
6121
6122   // Vectors containing all zeros can be matched by pxor and xorps later
6123   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6124     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
6125     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
6126     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
6127       return Op;
6128
6129     return getZeroVector(VT, Subtarget, DAG, dl);
6130   }
6131
6132   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
6133   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
6134   // vpcmpeqd on 256-bit vectors.
6135   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
6136     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
6137       return Op;
6138
6139     if (!VT.is512BitVector())
6140       return getOnesVector(VT, Subtarget, DAG, dl);
6141   }
6142
6143   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(Op.getNode());
6144   if (SDValue AddSub = LowerToAddSub(BV, Subtarget, DAG))
6145     return AddSub;
6146   if (SDValue HorizontalOp = LowerToHorizontalOp(BV, Subtarget, DAG))
6147     return HorizontalOp;
6148   if (SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG))
6149     return Broadcast;
6150
6151   unsigned EVTBits = ExtVT.getSizeInBits();
6152
6153   unsigned NumZero  = 0;
6154   unsigned NumNonZero = 0;
6155   unsigned NonZeros = 0;
6156   bool IsAllConstants = true;
6157   SmallSet<SDValue, 8> Values;
6158   for (unsigned i = 0; i < NumElems; ++i) {
6159     SDValue Elt = Op.getOperand(i);
6160     if (Elt.getOpcode() == ISD::UNDEF)
6161       continue;
6162     Values.insert(Elt);
6163     if (Elt.getOpcode() != ISD::Constant &&
6164         Elt.getOpcode() != ISD::ConstantFP)
6165       IsAllConstants = false;
6166     if (X86::isZeroNode(Elt))
6167       NumZero++;
6168     else {
6169       NonZeros |= (1 << i);
6170       NumNonZero++;
6171     }
6172   }
6173
6174   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
6175   if (NumNonZero == 0)
6176     return DAG.getUNDEF(VT);
6177
6178   // Special case for single non-zero, non-undef, element.
6179   if (NumNonZero == 1) {
6180     unsigned Idx = countTrailingZeros(NonZeros);
6181     SDValue Item = Op.getOperand(Idx);
6182
6183     // If this is an insertion of an i64 value on x86-32, and if the top bits of
6184     // the value are obviously zero, truncate the value to i32 and do the
6185     // insertion that way.  Only do this if the value is non-constant or if the
6186     // value is a constant being inserted into element 0.  It is cheaper to do
6187     // a constant pool load than it is to do a movd + shuffle.
6188     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
6189         (!IsAllConstants || Idx == 0)) {
6190       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
6191         // Handle SSE only.
6192         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
6193         MVT VecVT = MVT::v4i32;
6194
6195         // Truncate the value (which may itself be a constant) to i32, and
6196         // convert it to a vector with movd (S2V+shuffle to zero extend).
6197         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6198         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6199         return DAG.getBitcast(VT, getShuffleVectorZeroOrUndef(
6200                                       Item, Idx * 2, true, Subtarget, DAG));
6201       }
6202     }
6203
6204     // If we have a constant or non-constant insertion into the low element of
6205     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6206     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
6207     // depending on what the source datatype is.
6208     if (Idx == 0) {
6209       if (NumZero == 0)
6210         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6211
6212       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6213           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6214         if (VT.is512BitVector()) {
6215           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6216           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6217                              Item, DAG.getIntPtrConstant(0, dl));
6218         }
6219         assert((VT.is128BitVector() || VT.is256BitVector()) &&
6220                "Expected an SSE value type!");
6221         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6222         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6223         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6224       }
6225
6226       // We can't directly insert an i8 or i16 into a vector, so zero extend
6227       // it to i32 first.
6228       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6229         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6230         if (VT.is256BitVector()) {
6231           if (Subtarget->hasAVX()) {
6232             Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v8i32, Item);
6233             Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6234           } else {
6235             // Without AVX, we need to extend to a 128-bit vector and then
6236             // insert into the 256-bit vector.
6237             Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6238             SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6239             Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6240           }
6241         } else {
6242           assert(VT.is128BitVector() && "Expected an SSE value type!");
6243           Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6244           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6245         }
6246         return DAG.getBitcast(VT, Item);
6247       }
6248     }
6249
6250     // Is it a vector logical left shift?
6251     if (NumElems == 2 && Idx == 1 &&
6252         X86::isZeroNode(Op.getOperand(0)) &&
6253         !X86::isZeroNode(Op.getOperand(1))) {
6254       unsigned NumBits = VT.getSizeInBits();
6255       return getVShift(true, VT,
6256                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6257                                    VT, Op.getOperand(1)),
6258                        NumBits/2, DAG, *this, dl);
6259     }
6260
6261     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6262       return SDValue();
6263
6264     // Otherwise, if this is a vector with i32 or f32 elements, and the element
6265     // is a non-constant being inserted into an element other than the low one,
6266     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
6267     // movd/movss) to move this into the low element, then shuffle it into
6268     // place.
6269     if (EVTBits == 32) {
6270       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6271       return getShuffleVectorZeroOrUndef(Item, Idx, NumZero > 0, Subtarget, DAG);
6272     }
6273   }
6274
6275   // Splat is obviously ok. Let legalizer expand it to a shuffle.
6276   if (Values.size() == 1) {
6277     if (EVTBits == 32) {
6278       // Instead of a shuffle like this:
6279       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6280       // Check if it's possible to issue this instead.
6281       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6282       unsigned Idx = countTrailingZeros(NonZeros);
6283       SDValue Item = Op.getOperand(Idx);
6284       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6285         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6286     }
6287     return SDValue();
6288   }
6289
6290   // A vector full of immediates; various special cases are already
6291   // handled, so this is best done with a single constant-pool load.
6292   if (IsAllConstants)
6293     return SDValue();
6294
6295   // For AVX-length vectors, see if we can use a vector load to get all of the
6296   // elements, otherwise build the individual 128-bit pieces and use
6297   // shuffles to put them in place.
6298   if (VT.is256BitVector() || VT.is512BitVector()) {
6299     SmallVector<SDValue, 64> V(Op->op_begin(), Op->op_begin() + NumElems);
6300
6301     // Check for a build vector of consecutive loads.
6302     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6303       return LD;
6304
6305     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6306
6307     // Build both the lower and upper subvector.
6308     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6309                                 makeArrayRef(&V[0], NumElems/2));
6310     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6311                                 makeArrayRef(&V[NumElems / 2], NumElems/2));
6312
6313     // Recreate the wider vector with the lower and upper part.
6314     if (VT.is256BitVector())
6315       return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6316     return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6317   }
6318
6319   // Let legalizer expand 2-wide build_vectors.
6320   if (EVTBits == 64) {
6321     if (NumNonZero == 1) {
6322       // One half is zero or undef.
6323       unsigned Idx = countTrailingZeros(NonZeros);
6324       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6325                                  Op.getOperand(Idx));
6326       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6327     }
6328     return SDValue();
6329   }
6330
6331   // If element VT is < 32 bits, convert it to inserts into a zero vector.
6332   if (EVTBits == 8 && NumElems == 16)
6333     if (SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6334                                         Subtarget, *this))
6335       return V;
6336
6337   if (EVTBits == 16 && NumElems == 8)
6338     if (SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6339                                       Subtarget, *this))
6340       return V;
6341
6342   // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6343   if (EVTBits == 32 && NumElems == 4)
6344     if (SDValue V = LowerBuildVectorv4x32(Op, DAG, Subtarget, *this))
6345       return V;
6346
6347   // If element VT is == 32 bits, turn it into a number of shuffles.
6348   SmallVector<SDValue, 8> V(NumElems);
6349   if (NumElems == 4 && NumZero > 0) {
6350     for (unsigned i = 0; i < 4; ++i) {
6351       bool isZero = !(NonZeros & (1 << i));
6352       if (isZero)
6353         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6354       else
6355         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6356     }
6357
6358     for (unsigned i = 0; i < 2; ++i) {
6359       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6360         default: break;
6361         case 0:
6362           V[i] = V[i*2];  // Must be a zero vector.
6363           break;
6364         case 1:
6365           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6366           break;
6367         case 2:
6368           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6369           break;
6370         case 3:
6371           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6372           break;
6373       }
6374     }
6375
6376     bool Reverse1 = (NonZeros & 0x3) == 2;
6377     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6378     int MaskVec[] = {
6379       Reverse1 ? 1 : 0,
6380       Reverse1 ? 0 : 1,
6381       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6382       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
6383     };
6384     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6385   }
6386
6387   if (Values.size() > 1 && VT.is128BitVector()) {
6388     // Check for a build vector of consecutive loads.
6389     for (unsigned i = 0; i < NumElems; ++i)
6390       V[i] = Op.getOperand(i);
6391
6392     // Check for elements which are consecutive loads.
6393     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6394       return LD;
6395
6396     // Check for a build vector from mostly shuffle plus few inserting.
6397     if (SDValue Sh = buildFromShuffleMostly(Op, DAG))
6398       return Sh;
6399
6400     // For SSE 4.1, use insertps to put the high elements into the low element.
6401     if (Subtarget->hasSSE41()) {
6402       SDValue Result;
6403       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6404         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6405       else
6406         Result = DAG.getUNDEF(VT);
6407
6408       for (unsigned i = 1; i < NumElems; ++i) {
6409         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6410         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6411                              Op.getOperand(i), DAG.getIntPtrConstant(i, dl));
6412       }
6413       return Result;
6414     }
6415
6416     // Otherwise, expand into a number of unpckl*, start by extending each of
6417     // our (non-undef) elements to the full vector width with the element in the
6418     // bottom slot of the vector (which generates no code for SSE).
6419     for (unsigned i = 0; i < NumElems; ++i) {
6420       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6421         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6422       else
6423         V[i] = DAG.getUNDEF(VT);
6424     }
6425
6426     // Next, we iteratively mix elements, e.g. for v4f32:
6427     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6428     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6429     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
6430     unsigned EltStride = NumElems >> 1;
6431     while (EltStride != 0) {
6432       for (unsigned i = 0; i < EltStride; ++i) {
6433         // If V[i+EltStride] is undef and this is the first round of mixing,
6434         // then it is safe to just drop this shuffle: V[i] is already in the
6435         // right place, the one element (since it's the first round) being
6436         // inserted as undef can be dropped.  This isn't safe for successive
6437         // rounds because they will permute elements within both vectors.
6438         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6439             EltStride == NumElems/2)
6440           continue;
6441
6442         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6443       }
6444       EltStride >>= 1;
6445     }
6446     return V[0];
6447   }
6448   return SDValue();
6449 }
6450
6451 // 256-bit AVX can use the vinsertf128 instruction
6452 // to create 256-bit vectors from two other 128-bit ones.
6453 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6454   SDLoc dl(Op);
6455   MVT ResVT = Op.getSimpleValueType();
6456
6457   assert((ResVT.is256BitVector() ||
6458           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6459
6460   SDValue V1 = Op.getOperand(0);
6461   SDValue V2 = Op.getOperand(1);
6462   unsigned NumElems = ResVT.getVectorNumElements();
6463   if (ResVT.is256BitVector())
6464     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6465
6466   if (Op.getNumOperands() == 4) {
6467     MVT HalfVT = MVT::getVectorVT(ResVT.getVectorElementType(),
6468                                   ResVT.getVectorNumElements()/2);
6469     SDValue V3 = Op.getOperand(2);
6470     SDValue V4 = Op.getOperand(3);
6471     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6472       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6473   }
6474   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6475 }
6476
6477 static SDValue LowerCONCAT_VECTORSvXi1(SDValue Op,
6478                                        const X86Subtarget *Subtarget,
6479                                        SelectionDAG & DAG) {
6480   SDLoc dl(Op);
6481   MVT ResVT = Op.getSimpleValueType();
6482   unsigned NumOfOperands = Op.getNumOperands();
6483
6484   assert(isPowerOf2_32(NumOfOperands) &&
6485          "Unexpected number of operands in CONCAT_VECTORS");
6486
6487   if (NumOfOperands > 2) {
6488     MVT HalfVT = MVT::getVectorVT(ResVT.getVectorElementType(),
6489                                   ResVT.getVectorNumElements()/2);
6490     SmallVector<SDValue, 2> Ops;
6491     for (unsigned i = 0; i < NumOfOperands/2; i++)
6492       Ops.push_back(Op.getOperand(i));
6493     SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6494     Ops.clear();
6495     for (unsigned i = NumOfOperands/2; i < NumOfOperands; i++)
6496       Ops.push_back(Op.getOperand(i));
6497     SDValue Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6498     return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Lo, Hi);
6499   }
6500
6501   SDValue V1 = Op.getOperand(0);
6502   SDValue V2 = Op.getOperand(1);
6503   bool IsZeroV1 = ISD::isBuildVectorAllZeros(V1.getNode());
6504   bool IsZeroV2 = ISD::isBuildVectorAllZeros(V2.getNode());
6505
6506   if (IsZeroV1 && IsZeroV2)
6507     return getZeroVector(ResVT, Subtarget, DAG, dl);
6508
6509   SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
6510   SDValue Undef = DAG.getUNDEF(ResVT);
6511   unsigned NumElems = ResVT.getVectorNumElements();
6512   SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
6513
6514   V2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V2, ZeroIdx);
6515   V2 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V2, ShiftBits);
6516   if (IsZeroV1)
6517     return V2;
6518
6519   V1 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V1, ZeroIdx);
6520   // Zero the upper bits of V1
6521   V1 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V1, ShiftBits);
6522   V1 = DAG.getNode(X86ISD::VSRLI, dl, ResVT, V1, ShiftBits);
6523   if (IsZeroV2)
6524     return V1;
6525   return DAG.getNode(ISD::OR, dl, ResVT, V1, V2);
6526 }
6527
6528 static SDValue LowerCONCAT_VECTORS(SDValue Op,
6529                                    const X86Subtarget *Subtarget,
6530                                    SelectionDAG &DAG) {
6531   MVT VT = Op.getSimpleValueType();
6532   if (VT.getVectorElementType() == MVT::i1)
6533     return LowerCONCAT_VECTORSvXi1(Op, Subtarget, DAG);
6534
6535   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6536          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6537           Op.getNumOperands() == 4)));
6538
6539   // AVX can use the vinsertf128 instruction to create 256-bit vectors
6540   // from two other 128-bit ones.
6541
6542   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6543   return LowerAVXCONCAT_VECTORS(Op, DAG);
6544 }
6545
6546 //===----------------------------------------------------------------------===//
6547 // Vector shuffle lowering
6548 //
6549 // This is an experimental code path for lowering vector shuffles on x86. It is
6550 // designed to handle arbitrary vector shuffles and blends, gracefully
6551 // degrading performance as necessary. It works hard to recognize idiomatic
6552 // shuffles and lower them to optimal instruction patterns without leaving
6553 // a framework that allows reasonably efficient handling of all vector shuffle
6554 // patterns.
6555 //===----------------------------------------------------------------------===//
6556
6557 /// \brief Tiny helper function to identify a no-op mask.
6558 ///
6559 /// This is a somewhat boring predicate function. It checks whether the mask
6560 /// array input, which is assumed to be a single-input shuffle mask of the kind
6561 /// used by the X86 shuffle instructions (not a fully general
6562 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
6563 /// in-place shuffle are 'no-op's.
6564 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
6565   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6566     if (Mask[i] != -1 && Mask[i] != i)
6567       return false;
6568   return true;
6569 }
6570
6571 /// \brief Helper function to classify a mask as a single-input mask.
6572 ///
6573 /// This isn't a generic single-input test because in the vector shuffle
6574 /// lowering we canonicalize single inputs to be the first input operand. This
6575 /// means we can more quickly test for a single input by only checking whether
6576 /// an input from the second operand exists. We also assume that the size of
6577 /// mask corresponds to the size of the input vectors which isn't true in the
6578 /// fully general case.
6579 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
6580   for (int M : Mask)
6581     if (M >= (int)Mask.size())
6582       return false;
6583   return true;
6584 }
6585
6586 /// \brief Test whether there are elements crossing 128-bit lanes in this
6587 /// shuffle mask.
6588 ///
6589 /// X86 divides up its shuffles into in-lane and cross-lane shuffle operations
6590 /// and we routinely test for these.
6591 static bool is128BitLaneCrossingShuffleMask(MVT VT, ArrayRef<int> Mask) {
6592   int LaneSize = 128 / VT.getScalarSizeInBits();
6593   int Size = Mask.size();
6594   for (int i = 0; i < Size; ++i)
6595     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
6596       return true;
6597   return false;
6598 }
6599
6600 /// \brief Test whether a shuffle mask is equivalent within each 128-bit lane.
6601 ///
6602 /// This checks a shuffle mask to see if it is performing the same
6603 /// 128-bit lane-relative shuffle in each 128-bit lane. This trivially implies
6604 /// that it is also not lane-crossing. It may however involve a blend from the
6605 /// same lane of a second vector.
6606 ///
6607 /// The specific repeated shuffle mask is populated in \p RepeatedMask, as it is
6608 /// non-trivial to compute in the face of undef lanes. The representation is
6609 /// *not* suitable for use with existing 128-bit shuffles as it will contain
6610 /// entries from both V1 and V2 inputs to the wider mask.
6611 static bool
6612 is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
6613                                 SmallVectorImpl<int> &RepeatedMask) {
6614   int LaneSize = 128 / VT.getScalarSizeInBits();
6615   RepeatedMask.resize(LaneSize, -1);
6616   int Size = Mask.size();
6617   for (int i = 0; i < Size; ++i) {
6618     if (Mask[i] < 0)
6619       continue;
6620     if ((Mask[i] % Size) / LaneSize != i / LaneSize)
6621       // This entry crosses lanes, so there is no way to model this shuffle.
6622       return false;
6623
6624     // Ok, handle the in-lane shuffles by detecting if and when they repeat.
6625     if (RepeatedMask[i % LaneSize] == -1)
6626       // This is the first non-undef entry in this slot of a 128-bit lane.
6627       RepeatedMask[i % LaneSize] =
6628           Mask[i] < Size ? Mask[i] % LaneSize : Mask[i] % LaneSize + Size;
6629     else if (RepeatedMask[i % LaneSize] + (i / LaneSize) * LaneSize != Mask[i])
6630       // Found a mismatch with the repeated mask.
6631       return false;
6632   }
6633   return true;
6634 }
6635
6636 /// \brief Checks whether a shuffle mask is equivalent to an explicit list of
6637 /// arguments.
6638 ///
6639 /// This is a fast way to test a shuffle mask against a fixed pattern:
6640 ///
6641 ///   if (isShuffleEquivalent(Mask, 3, 2, {1, 0})) { ... }
6642 ///
6643 /// It returns true if the mask is exactly as wide as the argument list, and
6644 /// each element of the mask is either -1 (signifying undef) or the value given
6645 /// in the argument.
6646 static bool isShuffleEquivalent(SDValue V1, SDValue V2, ArrayRef<int> Mask,
6647                                 ArrayRef<int> ExpectedMask) {
6648   if (Mask.size() != ExpectedMask.size())
6649     return false;
6650
6651   int Size = Mask.size();
6652
6653   // If the values are build vectors, we can look through them to find
6654   // equivalent inputs that make the shuffles equivalent.
6655   auto *BV1 = dyn_cast<BuildVectorSDNode>(V1);
6656   auto *BV2 = dyn_cast<BuildVectorSDNode>(V2);
6657
6658   for (int i = 0; i < Size; ++i)
6659     if (Mask[i] != -1 && Mask[i] != ExpectedMask[i]) {
6660       auto *MaskBV = Mask[i] < Size ? BV1 : BV2;
6661       auto *ExpectedBV = ExpectedMask[i] < Size ? BV1 : BV2;
6662       if (!MaskBV || !ExpectedBV ||
6663           MaskBV->getOperand(Mask[i] % Size) !=
6664               ExpectedBV->getOperand(ExpectedMask[i] % Size))
6665         return false;
6666     }
6667
6668   return true;
6669 }
6670
6671 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
6672 ///
6673 /// This helper function produces an 8-bit shuffle immediate corresponding to
6674 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
6675 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
6676 /// example.
6677 ///
6678 /// NB: We rely heavily on "undef" masks preserving the input lane.
6679 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask, SDLoc DL,
6680                                           SelectionDAG &DAG) {
6681   assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
6682   assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
6683   assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
6684   assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
6685   assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
6686
6687   unsigned Imm = 0;
6688   Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
6689   Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
6690   Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
6691   Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
6692   return DAG.getConstant(Imm, DL, MVT::i8);
6693 }
6694
6695 /// \brief Compute whether each element of a shuffle is zeroable.
6696 ///
6697 /// A "zeroable" vector shuffle element is one which can be lowered to zero.
6698 /// Either it is an undef element in the shuffle mask, the element of the input
6699 /// referenced is undef, or the element of the input referenced is known to be
6700 /// zero. Many x86 shuffles can zero lanes cheaply and we often want to handle
6701 /// as many lanes with this technique as possible to simplify the remaining
6702 /// shuffle.
6703 static SmallBitVector computeZeroableShuffleElements(ArrayRef<int> Mask,
6704                                                      SDValue V1, SDValue V2) {
6705   SmallBitVector Zeroable(Mask.size(), false);
6706
6707   while (V1.getOpcode() == ISD::BITCAST)
6708     V1 = V1->getOperand(0);
6709   while (V2.getOpcode() == ISD::BITCAST)
6710     V2 = V2->getOperand(0);
6711
6712   bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
6713   bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
6714
6715   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6716     int M = Mask[i];
6717     // Handle the easy cases.
6718     if (M < 0 || (M >= 0 && M < Size && V1IsZero) || (M >= Size && V2IsZero)) {
6719       Zeroable[i] = true;
6720       continue;
6721     }
6722
6723     // If this is an index into a build_vector node (which has the same number
6724     // of elements), dig out the input value and use it.
6725     SDValue V = M < Size ? V1 : V2;
6726     if (V.getOpcode() != ISD::BUILD_VECTOR || Size != (int)V.getNumOperands())
6727       continue;
6728
6729     SDValue Input = V.getOperand(M % Size);
6730     // The UNDEF opcode check really should be dead code here, but not quite
6731     // worth asserting on (it isn't invalid, just unexpected).
6732     if (Input.getOpcode() == ISD::UNDEF || X86::isZeroNode(Input))
6733       Zeroable[i] = true;
6734   }
6735
6736   return Zeroable;
6737 }
6738
6739 // X86 has dedicated unpack instructions that can handle specific blend
6740 // operations: UNPCKH and UNPCKL.
6741 static SDValue lowerVectorShuffleWithUNPCK(SDLoc DL, MVT VT, ArrayRef<int> Mask,
6742                                            SDValue V1, SDValue V2,
6743                                            SelectionDAG &DAG) {
6744   int NumElts = VT.getVectorNumElements();
6745   int NumEltsInLane = 128 / VT.getScalarSizeInBits();
6746   SmallVector<int, 8> Unpckl;
6747   SmallVector<int, 8> Unpckh;
6748
6749   for (int i = 0; i < NumElts; ++i) {
6750     unsigned LaneStart = (i / NumEltsInLane) * NumEltsInLane;
6751     int LoPos = (i % NumEltsInLane) / 2 + LaneStart + NumElts * (i % 2);
6752     int HiPos = LoPos + NumEltsInLane / 2;
6753     Unpckl.push_back(LoPos);
6754     Unpckh.push_back(HiPos);
6755   }
6756
6757   if (isShuffleEquivalent(V1, V2, Mask, Unpckl))
6758     return DAG.getNode(X86ISD::UNPCKL, DL, VT, V1, V2);
6759   if (isShuffleEquivalent(V1, V2, Mask, Unpckh))
6760     return DAG.getNode(X86ISD::UNPCKH, DL, VT, V1, V2);
6761
6762   // Commute and try again.
6763   ShuffleVectorSDNode::commuteMask(Unpckl);
6764   if (isShuffleEquivalent(V1, V2, Mask, Unpckl))
6765     return DAG.getNode(X86ISD::UNPCKL, DL, VT, V2, V1);
6766
6767   ShuffleVectorSDNode::commuteMask(Unpckh);
6768   if (isShuffleEquivalent(V1, V2, Mask, Unpckh))
6769     return DAG.getNode(X86ISD::UNPCKH, DL, VT, V2, V1);
6770
6771   return SDValue();
6772 }
6773
6774 /// \brief Try to emit a bitmask instruction for a shuffle.
6775 ///
6776 /// This handles cases where we can model a blend exactly as a bitmask due to
6777 /// one of the inputs being zeroable.
6778 static SDValue lowerVectorShuffleAsBitMask(SDLoc DL, MVT VT, SDValue V1,
6779                                            SDValue V2, ArrayRef<int> Mask,
6780                                            SelectionDAG &DAG) {
6781   MVT EltVT = VT.getVectorElementType();
6782   int NumEltBits = EltVT.getSizeInBits();
6783   MVT IntEltVT = MVT::getIntegerVT(NumEltBits);
6784   SDValue Zero = DAG.getConstant(0, DL, IntEltVT);
6785   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6786                                     IntEltVT);
6787   if (EltVT.isFloatingPoint()) {
6788     Zero = DAG.getBitcast(EltVT, Zero);
6789     AllOnes = DAG.getBitcast(EltVT, AllOnes);
6790   }
6791   SmallVector<SDValue, 16> VMaskOps(Mask.size(), Zero);
6792   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6793   SDValue V;
6794   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6795     if (Zeroable[i])
6796       continue;
6797     if (Mask[i] % Size != i)
6798       return SDValue(); // Not a blend.
6799     if (!V)
6800       V = Mask[i] < Size ? V1 : V2;
6801     else if (V != (Mask[i] < Size ? V1 : V2))
6802       return SDValue(); // Can only let one input through the mask.
6803
6804     VMaskOps[i] = AllOnes;
6805   }
6806   if (!V)
6807     return SDValue(); // No non-zeroable elements!
6808
6809   SDValue VMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, VMaskOps);
6810   V = DAG.getNode(VT.isFloatingPoint()
6811                   ? (unsigned) X86ISD::FAND : (unsigned) ISD::AND,
6812                   DL, VT, V, VMask);
6813   return V;
6814 }
6815
6816 /// \brief Try to emit a blend instruction for a shuffle using bit math.
6817 ///
6818 /// This is used as a fallback approach when first class blend instructions are
6819 /// unavailable. Currently it is only suitable for integer vectors, but could
6820 /// be generalized for floating point vectors if desirable.
6821 static SDValue lowerVectorShuffleAsBitBlend(SDLoc DL, MVT VT, SDValue V1,
6822                                             SDValue V2, ArrayRef<int> Mask,
6823                                             SelectionDAG &DAG) {
6824   assert(VT.isInteger() && "Only supports integer vector types!");
6825   MVT EltVT = VT.getVectorElementType();
6826   int NumEltBits = EltVT.getSizeInBits();
6827   SDValue Zero = DAG.getConstant(0, DL, EltVT);
6828   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6829                                     EltVT);
6830   SmallVector<SDValue, 16> MaskOps;
6831   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6832     if (Mask[i] != -1 && Mask[i] != i && Mask[i] != i + Size)
6833       return SDValue(); // Shuffled input!
6834     MaskOps.push_back(Mask[i] < Size ? AllOnes : Zero);
6835   }
6836
6837   SDValue V1Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, MaskOps);
6838   V1 = DAG.getNode(ISD::AND, DL, VT, V1, V1Mask);
6839   // We have to cast V2 around.
6840   MVT MaskVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
6841   V2 = DAG.getBitcast(VT, DAG.getNode(X86ISD::ANDNP, DL, MaskVT,
6842                                       DAG.getBitcast(MaskVT, V1Mask),
6843                                       DAG.getBitcast(MaskVT, V2)));
6844   return DAG.getNode(ISD::OR, DL, VT, V1, V2);
6845 }
6846
6847 /// \brief Try to emit a blend instruction for a shuffle.
6848 ///
6849 /// This doesn't do any checks for the availability of instructions for blending
6850 /// these values. It relies on the availability of the X86ISD::BLENDI pattern to
6851 /// be matched in the backend with the type given. What it does check for is
6852 /// that the shuffle mask is a blend, or convertible into a blend with zero.
6853 static SDValue lowerVectorShuffleAsBlend(SDLoc DL, MVT VT, SDValue V1,
6854                                          SDValue V2, ArrayRef<int> Original,
6855                                          const X86Subtarget *Subtarget,
6856                                          SelectionDAG &DAG) {
6857   bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
6858   bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
6859   SmallVector<int, 8> Mask(Original.begin(), Original.end());
6860   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6861   bool ForceV1Zero = false, ForceV2Zero = false;
6862
6863   // Attempt to generate the binary blend mask. If an input is zero then
6864   // we can use any lane.
6865   // TODO: generalize the zero matching to any scalar like isShuffleEquivalent.
6866   unsigned BlendMask = 0;
6867   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6868     int M = Mask[i];
6869     if (M < 0)
6870       continue;
6871     if (M == i)
6872       continue;
6873     if (M == i + Size) {
6874       BlendMask |= 1u << i;
6875       continue;
6876     }
6877     if (Zeroable[i]) {
6878       if (V1IsZero) {
6879         ForceV1Zero = true;
6880         Mask[i] = i;
6881         continue;
6882       }
6883       if (V2IsZero) {
6884         ForceV2Zero = true;
6885         BlendMask |= 1u << i;
6886         Mask[i] = i + Size;
6887         continue;
6888       }
6889     }
6890     return SDValue(); // Shuffled input!
6891   }
6892
6893   // Create a REAL zero vector - ISD::isBuildVectorAllZeros allows UNDEFs.
6894   if (ForceV1Zero)
6895     V1 = getZeroVector(VT, Subtarget, DAG, DL);
6896   if (ForceV2Zero)
6897     V2 = getZeroVector(VT, Subtarget, DAG, DL);
6898
6899   auto ScaleBlendMask = [](unsigned BlendMask, int Size, int Scale) {
6900     unsigned ScaledMask = 0;
6901     for (int i = 0; i != Size; ++i)
6902       if (BlendMask & (1u << i))
6903         for (int j = 0; j != Scale; ++j)
6904           ScaledMask |= 1u << (i * Scale + j);
6905     return ScaledMask;
6906   };
6907
6908   switch (VT.SimpleTy) {
6909   case MVT::v2f64:
6910   case MVT::v4f32:
6911   case MVT::v4f64:
6912   case MVT::v8f32:
6913     return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V2,
6914                        DAG.getConstant(BlendMask, DL, MVT::i8));
6915
6916   case MVT::v4i64:
6917   case MVT::v8i32:
6918     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6919     // FALLTHROUGH
6920   case MVT::v2i64:
6921   case MVT::v4i32:
6922     // If we have AVX2 it is faster to use VPBLENDD when the shuffle fits into
6923     // that instruction.
6924     if (Subtarget->hasAVX2()) {
6925       // Scale the blend by the number of 32-bit dwords per element.
6926       int Scale =  VT.getScalarSizeInBits() / 32;
6927       BlendMask = ScaleBlendMask(BlendMask, Mask.size(), Scale);
6928       MVT BlendVT = VT.getSizeInBits() > 128 ? MVT::v8i32 : MVT::v4i32;
6929       V1 = DAG.getBitcast(BlendVT, V1);
6930       V2 = DAG.getBitcast(BlendVT, V2);
6931       return DAG.getBitcast(
6932           VT, DAG.getNode(X86ISD::BLENDI, DL, BlendVT, V1, V2,
6933                           DAG.getConstant(BlendMask, DL, MVT::i8)));
6934     }
6935     // FALLTHROUGH
6936   case MVT::v8i16: {
6937     // For integer shuffles we need to expand the mask and cast the inputs to
6938     // v8i16s prior to blending.
6939     int Scale = 8 / VT.getVectorNumElements();
6940     BlendMask = ScaleBlendMask(BlendMask, Mask.size(), Scale);
6941     V1 = DAG.getBitcast(MVT::v8i16, V1);
6942     V2 = DAG.getBitcast(MVT::v8i16, V2);
6943     return DAG.getBitcast(VT,
6944                           DAG.getNode(X86ISD::BLENDI, DL, MVT::v8i16, V1, V2,
6945                                       DAG.getConstant(BlendMask, DL, MVT::i8)));
6946   }
6947
6948   case MVT::v16i16: {
6949     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6950     SmallVector<int, 8> RepeatedMask;
6951     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
6952       // We can lower these with PBLENDW which is mirrored across 128-bit lanes.
6953       assert(RepeatedMask.size() == 8 && "Repeated mask size doesn't match!");
6954       BlendMask = 0;
6955       for (int i = 0; i < 8; ++i)
6956         if (RepeatedMask[i] >= 16)
6957           BlendMask |= 1u << i;
6958       return DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
6959                          DAG.getConstant(BlendMask, DL, MVT::i8));
6960     }
6961   }
6962     // FALLTHROUGH
6963   case MVT::v16i8:
6964   case MVT::v32i8: {
6965     assert((VT.is128BitVector() || Subtarget->hasAVX2()) &&
6966            "256-bit byte-blends require AVX2 support!");
6967
6968     // Attempt to lower to a bitmask if we can. VPAND is faster than VPBLENDVB.
6969     if (SDValue Masked = lowerVectorShuffleAsBitMask(DL, VT, V1, V2, Mask, DAG))
6970       return Masked;
6971
6972     // Scale the blend by the number of bytes per element.
6973     int Scale = VT.getScalarSizeInBits() / 8;
6974
6975     // This form of blend is always done on bytes. Compute the byte vector
6976     // type.
6977     MVT BlendVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
6978
6979     // Compute the VSELECT mask. Note that VSELECT is really confusing in the
6980     // mix of LLVM's code generator and the x86 backend. We tell the code
6981     // generator that boolean values in the elements of an x86 vector register
6982     // are -1 for true and 0 for false. We then use the LLVM semantics of 'true'
6983     // mapping a select to operand #1, and 'false' mapping to operand #2. The
6984     // reality in x86 is that vector masks (pre-AVX-512) use only the high bit
6985     // of the element (the remaining are ignored) and 0 in that high bit would
6986     // mean operand #1 while 1 in the high bit would mean operand #2. So while
6987     // the LLVM model for boolean values in vector elements gets the relevant
6988     // bit set, it is set backwards and over constrained relative to x86's
6989     // actual model.
6990     SmallVector<SDValue, 32> VSELECTMask;
6991     for (int i = 0, Size = Mask.size(); i < Size; ++i)
6992       for (int j = 0; j < Scale; ++j)
6993         VSELECTMask.push_back(
6994             Mask[i] < 0 ? DAG.getUNDEF(MVT::i8)
6995                         : DAG.getConstant(Mask[i] < Size ? -1 : 0, DL,
6996                                           MVT::i8));
6997
6998     V1 = DAG.getBitcast(BlendVT, V1);
6999     V2 = DAG.getBitcast(BlendVT, V2);
7000     return DAG.getBitcast(VT, DAG.getNode(ISD::VSELECT, DL, BlendVT,
7001                                           DAG.getNode(ISD::BUILD_VECTOR, DL,
7002                                                       BlendVT, VSELECTMask),
7003                                           V1, V2));
7004   }
7005
7006   default:
7007     llvm_unreachable("Not a supported integer vector type!");
7008   }
7009 }
7010
7011 /// \brief Try to lower as a blend of elements from two inputs followed by
7012 /// a single-input permutation.
7013 ///
7014 /// This matches the pattern where we can blend elements from two inputs and
7015 /// then reduce the shuffle to a single-input permutation.
7016 static SDValue lowerVectorShuffleAsBlendAndPermute(SDLoc DL, MVT VT, SDValue V1,
7017                                                    SDValue V2,
7018                                                    ArrayRef<int> Mask,
7019                                                    SelectionDAG &DAG) {
7020   // We build up the blend mask while checking whether a blend is a viable way
7021   // to reduce the shuffle.
7022   SmallVector<int, 32> BlendMask(Mask.size(), -1);
7023   SmallVector<int, 32> PermuteMask(Mask.size(), -1);
7024
7025   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7026     if (Mask[i] < 0)
7027       continue;
7028
7029     assert(Mask[i] < Size * 2 && "Shuffle input is out of bounds.");
7030
7031     if (BlendMask[Mask[i] % Size] == -1)
7032       BlendMask[Mask[i] % Size] = Mask[i];
7033     else if (BlendMask[Mask[i] % Size] != Mask[i])
7034       return SDValue(); // Can't blend in the needed input!
7035
7036     PermuteMask[i] = Mask[i] % Size;
7037   }
7038
7039   SDValue V = DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
7040   return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), PermuteMask);
7041 }
7042
7043 /// \brief Generic routine to decompose a shuffle and blend into indepndent
7044 /// blends and permutes.
7045 ///
7046 /// This matches the extremely common pattern for handling combined
7047 /// shuffle+blend operations on newer X86 ISAs where we have very fast blend
7048 /// operations. It will try to pick the best arrangement of shuffles and
7049 /// blends.
7050 static SDValue lowerVectorShuffleAsDecomposedShuffleBlend(SDLoc DL, MVT VT,
7051                                                           SDValue V1,
7052                                                           SDValue V2,
7053                                                           ArrayRef<int> Mask,
7054                                                           SelectionDAG &DAG) {
7055   // Shuffle the input elements into the desired positions in V1 and V2 and
7056   // blend them together.
7057   SmallVector<int, 32> V1Mask(Mask.size(), -1);
7058   SmallVector<int, 32> V2Mask(Mask.size(), -1);
7059   SmallVector<int, 32> BlendMask(Mask.size(), -1);
7060   for (int i = 0, Size = Mask.size(); i < Size; ++i)
7061     if (Mask[i] >= 0 && Mask[i] < Size) {
7062       V1Mask[i] = Mask[i];
7063       BlendMask[i] = i;
7064     } else if (Mask[i] >= Size) {
7065       V2Mask[i] = Mask[i] - Size;
7066       BlendMask[i] = i + Size;
7067     }
7068
7069   // Try to lower with the simpler initial blend strategy unless one of the
7070   // input shuffles would be a no-op. We prefer to shuffle inputs as the
7071   // shuffle may be able to fold with a load or other benefit. However, when
7072   // we'll have to do 2x as many shuffles in order to achieve this, blending
7073   // first is a better strategy.
7074   if (!isNoopShuffleMask(V1Mask) && !isNoopShuffleMask(V2Mask))
7075     if (SDValue BlendPerm =
7076             lowerVectorShuffleAsBlendAndPermute(DL, VT, V1, V2, Mask, DAG))
7077       return BlendPerm;
7078
7079   V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
7080   V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
7081   return DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
7082 }
7083
7084 /// \brief Try to lower a vector shuffle as a byte rotation.
7085 ///
7086 /// SSSE3 has a generic PALIGNR instruction in x86 that will do an arbitrary
7087 /// byte-rotation of the concatenation of two vectors; pre-SSSE3 can use
7088 /// a PSRLDQ/PSLLDQ/POR pattern to get a similar effect. This routine will
7089 /// try to generically lower a vector shuffle through such an pattern. It
7090 /// does not check for the profitability of lowering either as PALIGNR or
7091 /// PSRLDQ/PSLLDQ/POR, only whether the mask is valid to lower in that form.
7092 /// This matches shuffle vectors that look like:
7093 ///
7094 ///   v8i16 [11, 12, 13, 14, 15, 0, 1, 2]
7095 ///
7096 /// Essentially it concatenates V1 and V2, shifts right by some number of
7097 /// elements, and takes the low elements as the result. Note that while this is
7098 /// specified as a *right shift* because x86 is little-endian, it is a *left
7099 /// rotate* of the vector lanes.
7100 static SDValue lowerVectorShuffleAsByteRotate(SDLoc DL, MVT VT, SDValue V1,
7101                                               SDValue V2,
7102                                               ArrayRef<int> Mask,
7103                                               const X86Subtarget *Subtarget,
7104                                               SelectionDAG &DAG) {
7105   assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
7106
7107   int NumElts = Mask.size();
7108   int NumLanes = VT.getSizeInBits() / 128;
7109   int NumLaneElts = NumElts / NumLanes;
7110
7111   // We need to detect various ways of spelling a rotation:
7112   //   [11, 12, 13, 14, 15,  0,  1,  2]
7113   //   [-1, 12, 13, 14, -1, -1,  1, -1]
7114   //   [-1, -1, -1, -1, -1, -1,  1,  2]
7115   //   [ 3,  4,  5,  6,  7,  8,  9, 10]
7116   //   [-1,  4,  5,  6, -1, -1,  9, -1]
7117   //   [-1,  4,  5,  6, -1, -1, -1, -1]
7118   int Rotation = 0;
7119   SDValue Lo, Hi;
7120   for (int l = 0; l < NumElts; l += NumLaneElts) {
7121     for (int i = 0; i < NumLaneElts; ++i) {
7122       if (Mask[l + i] == -1)
7123         continue;
7124       assert(Mask[l + i] >= 0 && "Only -1 is a valid negative mask element!");
7125
7126       // Get the mod-Size index and lane correct it.
7127       int LaneIdx = (Mask[l + i] % NumElts) - l;
7128       // Make sure it was in this lane.
7129       if (LaneIdx < 0 || LaneIdx >= NumLaneElts)
7130         return SDValue();
7131
7132       // Determine where a rotated vector would have started.
7133       int StartIdx = i - LaneIdx;
7134       if (StartIdx == 0)
7135         // The identity rotation isn't interesting, stop.
7136         return SDValue();
7137
7138       // If we found the tail of a vector the rotation must be the missing
7139       // front. If we found the head of a vector, it must be how much of the
7140       // head.
7141       int CandidateRotation = StartIdx < 0 ? -StartIdx : NumLaneElts - StartIdx;
7142
7143       if (Rotation == 0)
7144         Rotation = CandidateRotation;
7145       else if (Rotation != CandidateRotation)
7146         // The rotations don't match, so we can't match this mask.
7147         return SDValue();
7148
7149       // Compute which value this mask is pointing at.
7150       SDValue MaskV = Mask[l + i] < NumElts ? V1 : V2;
7151
7152       // Compute which of the two target values this index should be assigned
7153       // to. This reflects whether the high elements are remaining or the low
7154       // elements are remaining.
7155       SDValue &TargetV = StartIdx < 0 ? Hi : Lo;
7156
7157       // Either set up this value if we've not encountered it before, or check
7158       // that it remains consistent.
7159       if (!TargetV)
7160         TargetV = MaskV;
7161       else if (TargetV != MaskV)
7162         // This may be a rotation, but it pulls from the inputs in some
7163         // unsupported interleaving.
7164         return SDValue();
7165     }
7166   }
7167
7168   // Check that we successfully analyzed the mask, and normalize the results.
7169   assert(Rotation != 0 && "Failed to locate a viable rotation!");
7170   assert((Lo || Hi) && "Failed to find a rotated input vector!");
7171   if (!Lo)
7172     Lo = Hi;
7173   else if (!Hi)
7174     Hi = Lo;
7175
7176   // The actual rotate instruction rotates bytes, so we need to scale the
7177   // rotation based on how many bytes are in the vector lane.
7178   int Scale = 16 / NumLaneElts;
7179
7180   // SSSE3 targets can use the palignr instruction.
7181   if (Subtarget->hasSSSE3()) {
7182     // Cast the inputs to i8 vector of correct length to match PALIGNR.
7183     MVT AlignVT = MVT::getVectorVT(MVT::i8, 16 * NumLanes);
7184     Lo = DAG.getBitcast(AlignVT, Lo);
7185     Hi = DAG.getBitcast(AlignVT, Hi);
7186
7187     return DAG.getBitcast(
7188         VT, DAG.getNode(X86ISD::PALIGNR, DL, AlignVT, Lo, Hi,
7189                         DAG.getConstant(Rotation * Scale, DL, MVT::i8)));
7190   }
7191
7192   assert(VT.is128BitVector() &&
7193          "Rotate-based lowering only supports 128-bit lowering!");
7194   assert(Mask.size() <= 16 &&
7195          "Can shuffle at most 16 bytes in a 128-bit vector!");
7196
7197   // Default SSE2 implementation
7198   int LoByteShift = 16 - Rotation * Scale;
7199   int HiByteShift = Rotation * Scale;
7200
7201   // Cast the inputs to v2i64 to match PSLLDQ/PSRLDQ.
7202   Lo = DAG.getBitcast(MVT::v2i64, Lo);
7203   Hi = DAG.getBitcast(MVT::v2i64, Hi);
7204
7205   SDValue LoShift = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v2i64, Lo,
7206                                 DAG.getConstant(LoByteShift, DL, MVT::i8));
7207   SDValue HiShift = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v2i64, Hi,
7208                                 DAG.getConstant(HiByteShift, DL, MVT::i8));
7209   return DAG.getBitcast(VT,
7210                         DAG.getNode(ISD::OR, DL, MVT::v2i64, LoShift, HiShift));
7211 }
7212
7213 /// \brief Try to lower a vector shuffle as a bit shift (shifts in zeros).
7214 ///
7215 /// Attempts to match a shuffle mask against the PSLL(W/D/Q/DQ) and
7216 /// PSRL(W/D/Q/DQ) SSE2 and AVX2 logical bit-shift instructions. The function
7217 /// matches elements from one of the input vectors shuffled to the left or
7218 /// right with zeroable elements 'shifted in'. It handles both the strictly
7219 /// bit-wise element shifts and the byte shift across an entire 128-bit double
7220 /// quad word lane.
7221 ///
7222 /// PSHL : (little-endian) left bit shift.
7223 /// [ zz, 0, zz,  2 ]
7224 /// [ -1, 4, zz, -1 ]
7225 /// PSRL : (little-endian) right bit shift.
7226 /// [  1, zz,  3, zz]
7227 /// [ -1, -1,  7, zz]
7228 /// PSLLDQ : (little-endian) left byte shift
7229 /// [ zz,  0,  1,  2,  3,  4,  5,  6]
7230 /// [ zz, zz, -1, -1,  2,  3,  4, -1]
7231 /// [ zz, zz, zz, zz, zz, zz, -1,  1]
7232 /// PSRLDQ : (little-endian) right byte shift
7233 /// [  5, 6,  7, zz, zz, zz, zz, zz]
7234 /// [ -1, 5,  6,  7, zz, zz, zz, zz]
7235 /// [  1, 2, -1, -1, -1, -1, zz, zz]
7236 static SDValue lowerVectorShuffleAsShift(SDLoc DL, MVT VT, SDValue V1,
7237                                          SDValue V2, ArrayRef<int> Mask,
7238                                          SelectionDAG &DAG) {
7239   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7240
7241   int Size = Mask.size();
7242   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
7243
7244   auto CheckZeros = [&](int Shift, int Scale, bool Left) {
7245     for (int i = 0; i < Size; i += Scale)
7246       for (int j = 0; j < Shift; ++j)
7247         if (!Zeroable[i + j + (Left ? 0 : (Scale - Shift))])
7248           return false;
7249
7250     return true;
7251   };
7252
7253   auto MatchShift = [&](int Shift, int Scale, bool Left, SDValue V) {
7254     for (int i = 0; i != Size; i += Scale) {
7255       unsigned Pos = Left ? i + Shift : i;
7256       unsigned Low = Left ? i : i + Shift;
7257       unsigned Len = Scale - Shift;
7258       if (!isSequentialOrUndefInRange(Mask, Pos, Len,
7259                                       Low + (V == V1 ? 0 : Size)))
7260         return SDValue();
7261     }
7262
7263     int ShiftEltBits = VT.getScalarSizeInBits() * Scale;
7264     bool ByteShift = ShiftEltBits > 64;
7265     unsigned OpCode = Left ? (ByteShift ? X86ISD::VSHLDQ : X86ISD::VSHLI)
7266                            : (ByteShift ? X86ISD::VSRLDQ : X86ISD::VSRLI);
7267     int ShiftAmt = Shift * VT.getScalarSizeInBits() / (ByteShift ? 8 : 1);
7268
7269     // Normalize the scale for byte shifts to still produce an i64 element
7270     // type.
7271     Scale = ByteShift ? Scale / 2 : Scale;
7272
7273     // We need to round trip through the appropriate type for the shift.
7274     MVT ShiftSVT = MVT::getIntegerVT(VT.getScalarSizeInBits() * Scale);
7275     MVT ShiftVT = MVT::getVectorVT(ShiftSVT, Size / Scale);
7276     assert(DAG.getTargetLoweringInfo().isTypeLegal(ShiftVT) &&
7277            "Illegal integer vector type");
7278     V = DAG.getBitcast(ShiftVT, V);
7279
7280     V = DAG.getNode(OpCode, DL, ShiftVT, V,
7281                     DAG.getConstant(ShiftAmt, DL, MVT::i8));
7282     return DAG.getBitcast(VT, V);
7283   };
7284
7285   // SSE/AVX supports logical shifts up to 64-bit integers - so we can just
7286   // keep doubling the size of the integer elements up to that. We can
7287   // then shift the elements of the integer vector by whole multiples of
7288   // their width within the elements of the larger integer vector. Test each
7289   // multiple to see if we can find a match with the moved element indices
7290   // and that the shifted in elements are all zeroable.
7291   for (int Scale = 2; Scale * VT.getScalarSizeInBits() <= 128; Scale *= 2)
7292     for (int Shift = 1; Shift != Scale; ++Shift)
7293       for (bool Left : {true, false})
7294         if (CheckZeros(Shift, Scale, Left))
7295           for (SDValue V : {V1, V2})
7296             if (SDValue Match = MatchShift(Shift, Scale, Left, V))
7297               return Match;
7298
7299   // no match
7300   return SDValue();
7301 }
7302
7303 /// \brief Try to lower a vector shuffle using SSE4a EXTRQ/INSERTQ.
7304 static SDValue lowerVectorShuffleWithSSE4A(SDLoc DL, MVT VT, SDValue V1,
7305                                            SDValue V2, ArrayRef<int> Mask,
7306                                            SelectionDAG &DAG) {
7307   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7308   assert(!Zeroable.all() && "Fully zeroable shuffle mask");
7309
7310   int Size = Mask.size();
7311   int HalfSize = Size / 2;
7312   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
7313
7314   // Upper half must be undefined.
7315   if (!isUndefInRange(Mask, HalfSize, HalfSize))
7316     return SDValue();
7317
7318   // EXTRQ: Extract Len elements from lower half of source, starting at Idx.
7319   // Remainder of lower half result is zero and upper half is all undef.
7320   auto LowerAsEXTRQ = [&]() {
7321     // Determine the extraction length from the part of the
7322     // lower half that isn't zeroable.
7323     int Len = HalfSize;
7324     for (; Len > 0; --Len)
7325       if (!Zeroable[Len - 1])
7326         break;
7327     assert(Len > 0 && "Zeroable shuffle mask");
7328
7329     // Attempt to match first Len sequential elements from the lower half.
7330     SDValue Src;
7331     int Idx = -1;
7332     for (int i = 0; i != Len; ++i) {
7333       int M = Mask[i];
7334       if (M < 0)
7335         continue;
7336       SDValue &V = (M < Size ? V1 : V2);
7337       M = M % Size;
7338
7339       // All mask elements must be in the lower half.
7340       if (M >= HalfSize)
7341         return SDValue();
7342
7343       if (Idx < 0 || (Src == V && Idx == (M - i))) {
7344         Src = V;
7345         Idx = M - i;
7346         continue;
7347       }
7348       return SDValue();
7349     }
7350
7351     if (Idx < 0)
7352       return SDValue();
7353
7354     assert((Idx + Len) <= HalfSize && "Illegal extraction mask");
7355     int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
7356     int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
7357     return DAG.getNode(X86ISD::EXTRQI, DL, VT, Src,
7358                        DAG.getConstant(BitLen, DL, MVT::i8),
7359                        DAG.getConstant(BitIdx, DL, MVT::i8));
7360   };
7361
7362   if (SDValue ExtrQ = LowerAsEXTRQ())
7363     return ExtrQ;
7364
7365   // INSERTQ: Extract lowest Len elements from lower half of second source and
7366   // insert over first source, starting at Idx.
7367   // { A[0], .., A[Idx-1], B[0], .., B[Len-1], A[Idx+Len], .., UNDEF, ... }
7368   auto LowerAsInsertQ = [&]() {
7369     for (int Idx = 0; Idx != HalfSize; ++Idx) {
7370       SDValue Base;
7371
7372       // Attempt to match first source from mask before insertion point.
7373       if (isUndefInRange(Mask, 0, Idx)) {
7374         /* EMPTY */
7375       } else if (isSequentialOrUndefInRange(Mask, 0, Idx, 0)) {
7376         Base = V1;
7377       } else if (isSequentialOrUndefInRange(Mask, 0, Idx, Size)) {
7378         Base = V2;
7379       } else {
7380         continue;
7381       }
7382
7383       // Extend the extraction length looking to match both the insertion of
7384       // the second source and the remaining elements of the first.
7385       for (int Hi = Idx + 1; Hi <= HalfSize; ++Hi) {
7386         SDValue Insert;
7387         int Len = Hi - Idx;
7388
7389         // Match insertion.
7390         if (isSequentialOrUndefInRange(Mask, Idx, Len, 0)) {
7391           Insert = V1;
7392         } else if (isSequentialOrUndefInRange(Mask, Idx, Len, Size)) {
7393           Insert = V2;
7394         } else {
7395           continue;
7396         }
7397
7398         // Match the remaining elements of the lower half.
7399         if (isUndefInRange(Mask, Hi, HalfSize - Hi)) {
7400           /* EMPTY */
7401         } else if ((!Base || (Base == V1)) &&
7402                    isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi, Hi)) {
7403           Base = V1;
7404         } else if ((!Base || (Base == V2)) &&
7405                    isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi,
7406                                               Size + Hi)) {
7407           Base = V2;
7408         } else {
7409           continue;
7410         }
7411
7412         // We may not have a base (first source) - this can safely be undefined.
7413         if (!Base)
7414           Base = DAG.getUNDEF(VT);
7415
7416         int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
7417         int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
7418         return DAG.getNode(X86ISD::INSERTQI, DL, VT, Base, Insert,
7419                            DAG.getConstant(BitLen, DL, MVT::i8),
7420                            DAG.getConstant(BitIdx, DL, MVT::i8));
7421       }
7422     }
7423
7424     return SDValue();
7425   };
7426
7427   if (SDValue InsertQ = LowerAsInsertQ())
7428     return InsertQ;
7429
7430   return SDValue();
7431 }
7432
7433 /// \brief Lower a vector shuffle as a zero or any extension.
7434 ///
7435 /// Given a specific number of elements, element bit width, and extension
7436 /// stride, produce either a zero or any extension based on the available
7437 /// features of the subtarget. The extended elements are consecutive and
7438 /// begin and can start from an offseted element index in the input; to
7439 /// avoid excess shuffling the offset must either being in the bottom lane
7440 /// or at the start of a higher lane. All extended elements must be from
7441 /// the same lane.
7442 static SDValue lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7443     SDLoc DL, MVT VT, int Scale, int Offset, bool AnyExt, SDValue InputV,
7444     ArrayRef<int> Mask, const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7445   assert(Scale > 1 && "Need a scale to extend.");
7446   int EltBits = VT.getScalarSizeInBits();
7447   int NumElements = VT.getVectorNumElements();
7448   int NumEltsPerLane = 128 / EltBits;
7449   int OffsetLane = Offset / NumEltsPerLane;
7450   assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
7451          "Only 8, 16, and 32 bit elements can be extended.");
7452   assert(Scale * EltBits <= 64 && "Cannot zero extend past 64 bits.");
7453   assert(0 <= Offset && "Extension offset must be positive.");
7454   assert((Offset < NumEltsPerLane || Offset % NumEltsPerLane == 0) &&
7455          "Extension offset must be in the first lane or start an upper lane.");
7456
7457   // Check that an index is in same lane as the base offset.
7458   auto SafeOffset = [&](int Idx) {
7459     return OffsetLane == (Idx / NumEltsPerLane);
7460   };
7461
7462   // Shift along an input so that the offset base moves to the first element.
7463   auto ShuffleOffset = [&](SDValue V) {
7464     if (!Offset)
7465       return V;
7466
7467     SmallVector<int, 8> ShMask((unsigned)NumElements, -1);
7468     for (int i = 0; i * Scale < NumElements; ++i) {
7469       int SrcIdx = i + Offset;
7470       ShMask[i] = SafeOffset(SrcIdx) ? SrcIdx : -1;
7471     }
7472     return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), ShMask);
7473   };
7474
7475   // Found a valid zext mask! Try various lowering strategies based on the
7476   // input type and available ISA extensions.
7477   if (Subtarget->hasSSE41()) {
7478     // Not worth offseting 128-bit vectors if scale == 2, a pattern using
7479     // PUNPCK will catch this in a later shuffle match.
7480     if (Offset && Scale == 2 && VT.is128BitVector())
7481       return SDValue();
7482     MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits * Scale),
7483                                  NumElements / Scale);
7484     InputV = DAG.getNode(X86ISD::VZEXT, DL, ExtVT, ShuffleOffset(InputV));
7485     return DAG.getBitcast(VT, InputV);
7486   }
7487
7488   assert(VT.is128BitVector() && "Only 128-bit vectors can be extended.");
7489
7490   // For any extends we can cheat for larger element sizes and use shuffle
7491   // instructions that can fold with a load and/or copy.
7492   if (AnyExt && EltBits == 32) {
7493     int PSHUFDMask[4] = {Offset, -1, SafeOffset(Offset + 1) ? Offset + 1 : -1,
7494                          -1};
7495     return DAG.getBitcast(
7496         VT, DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7497                         DAG.getBitcast(MVT::v4i32, InputV),
7498                         getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
7499   }
7500   if (AnyExt && EltBits == 16 && Scale > 2) {
7501     int PSHUFDMask[4] = {Offset / 2, -1,
7502                          SafeOffset(Offset + 1) ? (Offset + 1) / 2 : -1, -1};
7503     InputV = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7504                          DAG.getBitcast(MVT::v4i32, InputV),
7505                          getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG));
7506     int PSHUFWMask[4] = {1, -1, -1, -1};
7507     unsigned OddEvenOp = (Offset & 1 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW);
7508     return DAG.getBitcast(
7509         VT, DAG.getNode(OddEvenOp, DL, MVT::v8i16,
7510                         DAG.getBitcast(MVT::v8i16, InputV),
7511                         getV4X86ShuffleImm8ForMask(PSHUFWMask, DL, DAG)));
7512   }
7513
7514   // The SSE4A EXTRQ instruction can efficiently extend the first 2 lanes
7515   // to 64-bits.
7516   if ((Scale * EltBits) == 64 && EltBits < 32 && Subtarget->hasSSE4A()) {
7517     assert(NumElements == (int)Mask.size() && "Unexpected shuffle mask size!");
7518     assert(VT.is128BitVector() && "Unexpected vector width!");
7519
7520     int LoIdx = Offset * EltBits;
7521     SDValue Lo = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7522                              DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7523                                          DAG.getConstant(EltBits, DL, MVT::i8),
7524                                          DAG.getConstant(LoIdx, DL, MVT::i8)));
7525
7526     if (isUndefInRange(Mask, NumElements / 2, NumElements / 2) ||
7527         !SafeOffset(Offset + 1))
7528       return DAG.getNode(ISD::BITCAST, DL, VT, Lo);
7529
7530     int HiIdx = (Offset + 1) * EltBits;
7531     SDValue Hi = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7532                              DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7533                                          DAG.getConstant(EltBits, DL, MVT::i8),
7534                                          DAG.getConstant(HiIdx, DL, MVT::i8)));
7535     return DAG.getNode(ISD::BITCAST, DL, VT,
7536                        DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, Lo, Hi));
7537   }
7538
7539   // If this would require more than 2 unpack instructions to expand, use
7540   // pshufb when available. We can only use more than 2 unpack instructions
7541   // when zero extending i8 elements which also makes it easier to use pshufb.
7542   if (Scale > 4 && EltBits == 8 && Subtarget->hasSSSE3()) {
7543     assert(NumElements == 16 && "Unexpected byte vector width!");
7544     SDValue PSHUFBMask[16];
7545     for (int i = 0; i < 16; ++i) {
7546       int Idx = Offset + (i / Scale);
7547       PSHUFBMask[i] = DAG.getConstant(
7548           (i % Scale == 0 && SafeOffset(Idx)) ? Idx : 0x80, DL, MVT::i8);
7549     }
7550     InputV = DAG.getBitcast(MVT::v16i8, InputV);
7551     return DAG.getBitcast(VT,
7552                           DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, InputV,
7553                                       DAG.getNode(ISD::BUILD_VECTOR, DL,
7554                                                   MVT::v16i8, PSHUFBMask)));
7555   }
7556
7557   // If we are extending from an offset, ensure we start on a boundary that
7558   // we can unpack from.
7559   int AlignToUnpack = Offset % (NumElements / Scale);
7560   if (AlignToUnpack) {
7561     SmallVector<int, 8> ShMask((unsigned)NumElements, -1);
7562     for (int i = AlignToUnpack; i < NumElements; ++i)
7563       ShMask[i - AlignToUnpack] = i;
7564     InputV = DAG.getVectorShuffle(VT, DL, InputV, DAG.getUNDEF(VT), ShMask);
7565     Offset -= AlignToUnpack;
7566   }
7567
7568   // Otherwise emit a sequence of unpacks.
7569   do {
7570     unsigned UnpackLoHi = X86ISD::UNPCKL;
7571     if (Offset >= (NumElements / 2)) {
7572       UnpackLoHi = X86ISD::UNPCKH;
7573       Offset -= (NumElements / 2);
7574     }
7575
7576     MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
7577     SDValue Ext = AnyExt ? DAG.getUNDEF(InputVT)
7578                          : getZeroVector(InputVT, Subtarget, DAG, DL);
7579     InputV = DAG.getBitcast(InputVT, InputV);
7580     InputV = DAG.getNode(UnpackLoHi, DL, InputVT, InputV, Ext);
7581     Scale /= 2;
7582     EltBits *= 2;
7583     NumElements /= 2;
7584   } while (Scale > 1);
7585   return DAG.getBitcast(VT, InputV);
7586 }
7587
7588 /// \brief Try to lower a vector shuffle as a zero extension on any microarch.
7589 ///
7590 /// This routine will try to do everything in its power to cleverly lower
7591 /// a shuffle which happens to match the pattern of a zero extend. It doesn't
7592 /// check for the profitability of this lowering,  it tries to aggressively
7593 /// match this pattern. It will use all of the micro-architectural details it
7594 /// can to emit an efficient lowering. It handles both blends with all-zero
7595 /// inputs to explicitly zero-extend and undef-lanes (sometimes undef due to
7596 /// masking out later).
7597 ///
7598 /// The reason we have dedicated lowering for zext-style shuffles is that they
7599 /// are both incredibly common and often quite performance sensitive.
7600 static SDValue lowerVectorShuffleAsZeroOrAnyExtend(
7601     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7602     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7603   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7604
7605   int Bits = VT.getSizeInBits();
7606   int NumLanes = Bits / 128;
7607   int NumElements = VT.getVectorNumElements();
7608   int NumEltsPerLane = NumElements / NumLanes;
7609   assert(VT.getScalarSizeInBits() <= 32 &&
7610          "Exceeds 32-bit integer zero extension limit");
7611   assert((int)Mask.size() == NumElements && "Unexpected shuffle mask size");
7612
7613   // Define a helper function to check a particular ext-scale and lower to it if
7614   // valid.
7615   auto Lower = [&](int Scale) -> SDValue {
7616     SDValue InputV;
7617     bool AnyExt = true;
7618     int Offset = 0;
7619     int Matches = 0;
7620     for (int i = 0; i < NumElements; ++i) {
7621       int M = Mask[i];
7622       if (M == -1)
7623         continue; // Valid anywhere but doesn't tell us anything.
7624       if (i % Scale != 0) {
7625         // Each of the extended elements need to be zeroable.
7626         if (!Zeroable[i])
7627           return SDValue();
7628
7629         // We no longer are in the anyext case.
7630         AnyExt = false;
7631         continue;
7632       }
7633
7634       // Each of the base elements needs to be consecutive indices into the
7635       // same input vector.
7636       SDValue V = M < NumElements ? V1 : V2;
7637       M = M % NumElements;
7638       if (!InputV) {
7639         InputV = V;
7640         Offset = M - (i / Scale);
7641       } else if (InputV != V)
7642         return SDValue(); // Flip-flopping inputs.
7643
7644       // Offset must start in the lowest 128-bit lane or at the start of an
7645       // upper lane.
7646       // FIXME: Is it ever worth allowing a negative base offset?
7647       if (!((0 <= Offset && Offset < NumEltsPerLane) ||
7648             (Offset % NumEltsPerLane) == 0))
7649         return SDValue();
7650
7651       // If we are offsetting, all referenced entries must come from the same
7652       // lane.
7653       if (Offset && (Offset / NumEltsPerLane) != (M / NumEltsPerLane))
7654         return SDValue();
7655
7656       if ((M % NumElements) != (Offset + (i / Scale)))
7657         return SDValue(); // Non-consecutive strided elements.
7658       Matches++;
7659     }
7660
7661     // If we fail to find an input, we have a zero-shuffle which should always
7662     // have already been handled.
7663     // FIXME: Maybe handle this here in case during blending we end up with one?
7664     if (!InputV)
7665       return SDValue();
7666
7667     // If we are offsetting, don't extend if we only match a single input, we
7668     // can always do better by using a basic PSHUF or PUNPCK.
7669     if (Offset != 0 && Matches < 2)
7670       return SDValue();
7671
7672     return lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7673         DL, VT, Scale, Offset, AnyExt, InputV, Mask, Subtarget, DAG);
7674   };
7675
7676   // The widest scale possible for extending is to a 64-bit integer.
7677   assert(Bits % 64 == 0 &&
7678          "The number of bits in a vector must be divisible by 64 on x86!");
7679   int NumExtElements = Bits / 64;
7680
7681   // Each iteration, try extending the elements half as much, but into twice as
7682   // many elements.
7683   for (; NumExtElements < NumElements; NumExtElements *= 2) {
7684     assert(NumElements % NumExtElements == 0 &&
7685            "The input vector size must be divisible by the extended size.");
7686     if (SDValue V = Lower(NumElements / NumExtElements))
7687       return V;
7688   }
7689
7690   // General extends failed, but 128-bit vectors may be able to use MOVQ.
7691   if (Bits != 128)
7692     return SDValue();
7693
7694   // Returns one of the source operands if the shuffle can be reduced to a
7695   // MOVQ, copying the lower 64-bits and zero-extending to the upper 64-bits.
7696   auto CanZExtLowHalf = [&]() {
7697     for (int i = NumElements / 2; i != NumElements; ++i)
7698       if (!Zeroable[i])
7699         return SDValue();
7700     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, 0))
7701       return V1;
7702     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, NumElements))
7703       return V2;
7704     return SDValue();
7705   };
7706
7707   if (SDValue V = CanZExtLowHalf()) {
7708     V = DAG.getBitcast(MVT::v2i64, V);
7709     V = DAG.getNode(X86ISD::VZEXT_MOVL, DL, MVT::v2i64, V);
7710     return DAG.getBitcast(VT, V);
7711   }
7712
7713   // No viable ext lowering found.
7714   return SDValue();
7715 }
7716
7717 /// \brief Try to get a scalar value for a specific element of a vector.
7718 ///
7719 /// Looks through BUILD_VECTOR and SCALAR_TO_VECTOR nodes to find a scalar.
7720 static SDValue getScalarValueForVectorElement(SDValue V, int Idx,
7721                                               SelectionDAG &DAG) {
7722   MVT VT = V.getSimpleValueType();
7723   MVT EltVT = VT.getVectorElementType();
7724   while (V.getOpcode() == ISD::BITCAST)
7725     V = V.getOperand(0);
7726   // If the bitcasts shift the element size, we can't extract an equivalent
7727   // element from it.
7728   MVT NewVT = V.getSimpleValueType();
7729   if (!NewVT.isVector() || NewVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
7730     return SDValue();
7731
7732   if (V.getOpcode() == ISD::BUILD_VECTOR ||
7733       (Idx == 0 && V.getOpcode() == ISD::SCALAR_TO_VECTOR)) {
7734     // Ensure the scalar operand is the same size as the destination.
7735     // FIXME: Add support for scalar truncation where possible.
7736     SDValue S = V.getOperand(Idx);
7737     if (EltVT.getSizeInBits() == S.getSimpleValueType().getSizeInBits())
7738       return DAG.getNode(ISD::BITCAST, SDLoc(V), EltVT, S);
7739   }
7740
7741   return SDValue();
7742 }
7743
7744 /// \brief Helper to test for a load that can be folded with x86 shuffles.
7745 ///
7746 /// This is particularly important because the set of instructions varies
7747 /// significantly based on whether the operand is a load or not.
7748 static bool isShuffleFoldableLoad(SDValue V) {
7749   while (V.getOpcode() == ISD::BITCAST)
7750     V = V.getOperand(0);
7751
7752   return ISD::isNON_EXTLoad(V.getNode());
7753 }
7754
7755 /// \brief Try to lower insertion of a single element into a zero vector.
7756 ///
7757 /// This is a common pattern that we have especially efficient patterns to lower
7758 /// across all subtarget feature sets.
7759 static SDValue lowerVectorShuffleAsElementInsertion(
7760     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7761     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7762   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7763   MVT ExtVT = VT;
7764   MVT EltVT = VT.getVectorElementType();
7765
7766   int V2Index = std::find_if(Mask.begin(), Mask.end(),
7767                              [&Mask](int M) { return M >= (int)Mask.size(); }) -
7768                 Mask.begin();
7769   bool IsV1Zeroable = true;
7770   for (int i = 0, Size = Mask.size(); i < Size; ++i)
7771     if (i != V2Index && !Zeroable[i]) {
7772       IsV1Zeroable = false;
7773       break;
7774     }
7775
7776   // Check for a single input from a SCALAR_TO_VECTOR node.
7777   // FIXME: All of this should be canonicalized into INSERT_VECTOR_ELT and
7778   // all the smarts here sunk into that routine. However, the current
7779   // lowering of BUILD_VECTOR makes that nearly impossible until the old
7780   // vector shuffle lowering is dead.
7781   SDValue V2S = getScalarValueForVectorElement(V2, Mask[V2Index] - Mask.size(),
7782                                                DAG);
7783   if (V2S && DAG.getTargetLoweringInfo().isTypeLegal(V2S.getValueType())) {
7784     // We need to zext the scalar if it is smaller than an i32.
7785     V2S = DAG.getBitcast(EltVT, V2S);
7786     if (EltVT == MVT::i8 || EltVT == MVT::i16) {
7787       // Using zext to expand a narrow element won't work for non-zero
7788       // insertions.
7789       if (!IsV1Zeroable)
7790         return SDValue();
7791
7792       // Zero-extend directly to i32.
7793       ExtVT = MVT::v4i32;
7794       V2S = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, V2S);
7795     }
7796     V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
7797   } else if (Mask[V2Index] != (int)Mask.size() || EltVT == MVT::i8 ||
7798              EltVT == MVT::i16) {
7799     // Either not inserting from the low element of the input or the input
7800     // element size is too small to use VZEXT_MOVL to clear the high bits.
7801     return SDValue();
7802   }
7803
7804   if (!IsV1Zeroable) {
7805     // If V1 can't be treated as a zero vector we have fewer options to lower
7806     // this. We can't support integer vectors or non-zero targets cheaply, and
7807     // the V1 elements can't be permuted in any way.
7808     assert(VT == ExtVT && "Cannot change extended type when non-zeroable!");
7809     if (!VT.isFloatingPoint() || V2Index != 0)
7810       return SDValue();
7811     SmallVector<int, 8> V1Mask(Mask.begin(), Mask.end());
7812     V1Mask[V2Index] = -1;
7813     if (!isNoopShuffleMask(V1Mask))
7814       return SDValue();
7815     // This is essentially a special case blend operation, but if we have
7816     // general purpose blend operations, they are always faster. Bail and let
7817     // the rest of the lowering handle these as blends.
7818     if (Subtarget->hasSSE41())
7819       return SDValue();
7820
7821     // Otherwise, use MOVSD or MOVSS.
7822     assert((EltVT == MVT::f32 || EltVT == MVT::f64) &&
7823            "Only two types of floating point element types to handle!");
7824     return DAG.getNode(EltVT == MVT::f32 ? X86ISD::MOVSS : X86ISD::MOVSD, DL,
7825                        ExtVT, V1, V2);
7826   }
7827
7828   // This lowering only works for the low element with floating point vectors.
7829   if (VT.isFloatingPoint() && V2Index != 0)
7830     return SDValue();
7831
7832   V2 = DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2);
7833   if (ExtVT != VT)
7834     V2 = DAG.getBitcast(VT, V2);
7835
7836   if (V2Index != 0) {
7837     // If we have 4 or fewer lanes we can cheaply shuffle the element into
7838     // the desired position. Otherwise it is more efficient to do a vector
7839     // shift left. We know that we can do a vector shift left because all
7840     // the inputs are zero.
7841     if (VT.isFloatingPoint() || VT.getVectorNumElements() <= 4) {
7842       SmallVector<int, 4> V2Shuffle(Mask.size(), 1);
7843       V2Shuffle[V2Index] = 0;
7844       V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Shuffle);
7845     } else {
7846       V2 = DAG.getBitcast(MVT::v2i64, V2);
7847       V2 = DAG.getNode(
7848           X86ISD::VSHLDQ, DL, MVT::v2i64, V2,
7849           DAG.getConstant(V2Index * EltVT.getSizeInBits() / 8, DL,
7850                           DAG.getTargetLoweringInfo().getScalarShiftAmountTy(
7851                               DAG.getDataLayout(), VT)));
7852       V2 = DAG.getBitcast(VT, V2);
7853     }
7854   }
7855   return V2;
7856 }
7857
7858 /// \brief Try to lower broadcast of a single - truncated - integer element,
7859 /// coming from a scalar_to_vector/build_vector node \p V0 with larger elements.
7860 ///
7861 /// This assumes we have AVX2.
7862 static SDValue lowerVectorShuffleAsTruncBroadcast(SDLoc DL, MVT VT, SDValue V0,
7863                                                   int BroadcastIdx,
7864                                                   const X86Subtarget *Subtarget,
7865                                                   SelectionDAG &DAG) {
7866   assert(Subtarget->hasAVX2() &&
7867          "We can only lower integer broadcasts with AVX2!");
7868
7869   EVT EltVT = VT.getVectorElementType();
7870   EVT V0VT = V0.getValueType();
7871
7872   assert(VT.isInteger() && "Unexpected non-integer trunc broadcast!");
7873   assert(V0VT.isVector() && "Unexpected non-vector vector-sized value!");
7874
7875   EVT V0EltVT = V0VT.getVectorElementType();
7876   if (!V0EltVT.isInteger())
7877     return SDValue();
7878
7879   const unsigned EltSize = EltVT.getSizeInBits();
7880   const unsigned V0EltSize = V0EltVT.getSizeInBits();
7881
7882   // This is only a truncation if the original element type is larger.
7883   if (V0EltSize <= EltSize)
7884     return SDValue();
7885
7886   assert(((V0EltSize % EltSize) == 0) &&
7887          "Scalar type sizes must all be powers of 2 on x86!");
7888
7889   const unsigned V0Opc = V0.getOpcode();
7890   const unsigned Scale = V0EltSize / EltSize;
7891   const unsigned V0BroadcastIdx = BroadcastIdx / Scale;
7892
7893   if ((V0Opc != ISD::SCALAR_TO_VECTOR || V0BroadcastIdx != 0) &&
7894       V0Opc != ISD::BUILD_VECTOR)
7895     return SDValue();
7896
7897   SDValue Scalar = V0.getOperand(V0BroadcastIdx);
7898
7899   // If we're extracting non-least-significant bits, shift so we can truncate.
7900   // Hopefully, we can fold away the trunc/srl/load into the broadcast.
7901   // Even if we can't (and !isShuffleFoldableLoad(Scalar)), prefer
7902   // vpbroadcast+vmovd+shr to vpshufb(m)+vmovd.
7903   if (const int OffsetIdx = BroadcastIdx % Scale)
7904     Scalar = DAG.getNode(ISD::SRL, DL, Scalar.getValueType(), Scalar,
7905             DAG.getConstant(OffsetIdx * EltSize, DL, Scalar.getValueType()));
7906
7907   return DAG.getNode(X86ISD::VBROADCAST, DL, VT,
7908                      DAG.getNode(ISD::TRUNCATE, DL, EltVT, Scalar));
7909 }
7910
7911 /// \brief Try to lower broadcast of a single element.
7912 ///
7913 /// For convenience, this code also bundles all of the subtarget feature set
7914 /// filtering. While a little annoying to re-dispatch on type here, there isn't
7915 /// a convenient way to factor it out.
7916 static SDValue lowerVectorShuffleAsBroadcast(SDLoc DL, MVT VT, SDValue V,
7917                                              ArrayRef<int> Mask,
7918                                              const X86Subtarget *Subtarget,
7919                                              SelectionDAG &DAG) {
7920   if (!Subtarget->hasAVX())
7921     return SDValue();
7922   if (VT.isInteger() && !Subtarget->hasAVX2())
7923     return SDValue();
7924
7925   // Check that the mask is a broadcast.
7926   int BroadcastIdx = -1;
7927   for (int M : Mask)
7928     if (M >= 0 && BroadcastIdx == -1)
7929       BroadcastIdx = M;
7930     else if (M >= 0 && M != BroadcastIdx)
7931       return SDValue();
7932
7933   assert(BroadcastIdx < (int)Mask.size() && "We only expect to be called with "
7934                                             "a sorted mask where the broadcast "
7935                                             "comes from V1.");
7936
7937   // Go up the chain of (vector) values to find a scalar load that we can
7938   // combine with the broadcast.
7939   for (;;) {
7940     switch (V.getOpcode()) {
7941     case ISD::CONCAT_VECTORS: {
7942       int OperandSize = Mask.size() / V.getNumOperands();
7943       V = V.getOperand(BroadcastIdx / OperandSize);
7944       BroadcastIdx %= OperandSize;
7945       continue;
7946     }
7947
7948     case ISD::INSERT_SUBVECTOR: {
7949       SDValue VOuter = V.getOperand(0), VInner = V.getOperand(1);
7950       auto ConstantIdx = dyn_cast<ConstantSDNode>(V.getOperand(2));
7951       if (!ConstantIdx)
7952         break;
7953
7954       int BeginIdx = (int)ConstantIdx->getZExtValue();
7955       int EndIdx =
7956           BeginIdx + (int)VInner.getSimpleValueType().getVectorNumElements();
7957       if (BroadcastIdx >= BeginIdx && BroadcastIdx < EndIdx) {
7958         BroadcastIdx -= BeginIdx;
7959         V = VInner;
7960       } else {
7961         V = VOuter;
7962       }
7963       continue;
7964     }
7965     }
7966     break;
7967   }
7968
7969   // Check if this is a broadcast of a scalar. We special case lowering
7970   // for scalars so that we can more effectively fold with loads.
7971   // First, look through bitcast: if the original value has a larger element
7972   // type than the shuffle, the broadcast element is in essence truncated.
7973   // Make that explicit to ease folding.
7974   if (V.getOpcode() == ISD::BITCAST && VT.isInteger())
7975     if (SDValue TruncBroadcast = lowerVectorShuffleAsTruncBroadcast(
7976             DL, VT, V.getOperand(0), BroadcastIdx, Subtarget, DAG))
7977       return TruncBroadcast;
7978
7979   // Also check the simpler case, where we can directly reuse the scalar.
7980   if (V.getOpcode() == ISD::BUILD_VECTOR ||
7981       (V.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)) {
7982     V = V.getOperand(BroadcastIdx);
7983
7984     // If the scalar isn't a load, we can't broadcast from it in AVX1.
7985     // Only AVX2 has register broadcasts.
7986     if (!Subtarget->hasAVX2() && !isShuffleFoldableLoad(V))
7987       return SDValue();
7988   } else if (BroadcastIdx != 0 || !Subtarget->hasAVX2()) {
7989     // We can't broadcast from a vector register without AVX2, and we can only
7990     // broadcast from the zero-element of a vector register.
7991     return SDValue();
7992   }
7993
7994   return DAG.getNode(X86ISD::VBROADCAST, DL, VT, V);
7995 }
7996
7997 // Check for whether we can use INSERTPS to perform the shuffle. We only use
7998 // INSERTPS when the V1 elements are already in the correct locations
7999 // because otherwise we can just always use two SHUFPS instructions which
8000 // are much smaller to encode than a SHUFPS and an INSERTPS. We can also
8001 // perform INSERTPS if a single V1 element is out of place and all V2
8002 // elements are zeroable.
8003 static SDValue lowerVectorShuffleAsInsertPS(SDValue Op, SDValue V1, SDValue V2,
8004                                             ArrayRef<int> Mask,
8005                                             SelectionDAG &DAG) {
8006   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
8007   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8008   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8009   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8010
8011   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
8012
8013   unsigned ZMask = 0;
8014   int V1DstIndex = -1;
8015   int V2DstIndex = -1;
8016   bool V1UsedInPlace = false;
8017
8018   for (int i = 0; i < 4; ++i) {
8019     // Synthesize a zero mask from the zeroable elements (includes undefs).
8020     if (Zeroable[i]) {
8021       ZMask |= 1 << i;
8022       continue;
8023     }
8024
8025     // Flag if we use any V1 inputs in place.
8026     if (i == Mask[i]) {
8027       V1UsedInPlace = true;
8028       continue;
8029     }
8030
8031     // We can only insert a single non-zeroable element.
8032     if (V1DstIndex != -1 || V2DstIndex != -1)
8033       return SDValue();
8034
8035     if (Mask[i] < 4) {
8036       // V1 input out of place for insertion.
8037       V1DstIndex = i;
8038     } else {
8039       // V2 input for insertion.
8040       V2DstIndex = i;
8041     }
8042   }
8043
8044   // Don't bother if we have no (non-zeroable) element for insertion.
8045   if (V1DstIndex == -1 && V2DstIndex == -1)
8046     return SDValue();
8047
8048   // Determine element insertion src/dst indices. The src index is from the
8049   // start of the inserted vector, not the start of the concatenated vector.
8050   unsigned V2SrcIndex = 0;
8051   if (V1DstIndex != -1) {
8052     // If we have a V1 input out of place, we use V1 as the V2 element insertion
8053     // and don't use the original V2 at all.
8054     V2SrcIndex = Mask[V1DstIndex];
8055     V2DstIndex = V1DstIndex;
8056     V2 = V1;
8057   } else {
8058     V2SrcIndex = Mask[V2DstIndex] - 4;
8059   }
8060
8061   // If no V1 inputs are used in place, then the result is created only from
8062   // the zero mask and the V2 insertion - so remove V1 dependency.
8063   if (!V1UsedInPlace)
8064     V1 = DAG.getUNDEF(MVT::v4f32);
8065
8066   unsigned InsertPSMask = V2SrcIndex << 6 | V2DstIndex << 4 | ZMask;
8067   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
8068
8069   // Insert the V2 element into the desired position.
8070   SDLoc DL(Op);
8071   return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
8072                      DAG.getConstant(InsertPSMask, DL, MVT::i8));
8073 }
8074
8075 /// \brief Try to lower a shuffle as a permute of the inputs followed by an
8076 /// UNPCK instruction.
8077 ///
8078 /// This specifically targets cases where we end up with alternating between
8079 /// the two inputs, and so can permute them into something that feeds a single
8080 /// UNPCK instruction. Note that this routine only targets integer vectors
8081 /// because for floating point vectors we have a generalized SHUFPS lowering
8082 /// strategy that handles everything that doesn't *exactly* match an unpack,
8083 /// making this clever lowering unnecessary.
8084 static SDValue lowerVectorShuffleAsPermuteAndUnpack(SDLoc DL, MVT VT,
8085                                                     SDValue V1, SDValue V2,
8086                                                     ArrayRef<int> Mask,
8087                                                     SelectionDAG &DAG) {
8088   assert(!VT.isFloatingPoint() &&
8089          "This routine only supports integer vectors.");
8090   assert(!isSingleInputShuffleMask(Mask) &&
8091          "This routine should only be used when blending two inputs.");
8092   assert(Mask.size() >= 2 && "Single element masks are invalid.");
8093
8094   int Size = Mask.size();
8095
8096   int NumLoInputs = std::count_if(Mask.begin(), Mask.end(), [Size](int M) {
8097     return M >= 0 && M % Size < Size / 2;
8098   });
8099   int NumHiInputs = std::count_if(
8100       Mask.begin(), Mask.end(), [Size](int M) { return M % Size >= Size / 2; });
8101
8102   bool UnpackLo = NumLoInputs >= NumHiInputs;
8103
8104   auto TryUnpack = [&](MVT UnpackVT, int Scale) {
8105     SmallVector<int, 32> V1Mask(Mask.size(), -1);
8106     SmallVector<int, 32> V2Mask(Mask.size(), -1);
8107
8108     for (int i = 0; i < Size; ++i) {
8109       if (Mask[i] < 0)
8110         continue;
8111
8112       // Each element of the unpack contains Scale elements from this mask.
8113       int UnpackIdx = i / Scale;
8114
8115       // We only handle the case where V1 feeds the first slots of the unpack.
8116       // We rely on canonicalization to ensure this is the case.
8117       if ((UnpackIdx % 2 == 0) != (Mask[i] < Size))
8118         return SDValue();
8119
8120       // Setup the mask for this input. The indexing is tricky as we have to
8121       // handle the unpack stride.
8122       SmallVectorImpl<int> &VMask = (UnpackIdx % 2 == 0) ? V1Mask : V2Mask;
8123       VMask[(UnpackIdx / 2) * Scale + i % Scale + (UnpackLo ? 0 : Size / 2)] =
8124           Mask[i] % Size;
8125     }
8126
8127     // If we will have to shuffle both inputs to use the unpack, check whether
8128     // we can just unpack first and shuffle the result. If so, skip this unpack.
8129     if ((NumLoInputs == 0 || NumHiInputs == 0) && !isNoopShuffleMask(V1Mask) &&
8130         !isNoopShuffleMask(V2Mask))
8131       return SDValue();
8132
8133     // Shuffle the inputs into place.
8134     V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
8135     V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
8136
8137     // Cast the inputs to the type we will use to unpack them.
8138     V1 = DAG.getBitcast(UnpackVT, V1);
8139     V2 = DAG.getBitcast(UnpackVT, V2);
8140
8141     // Unpack the inputs and cast the result back to the desired type.
8142     return DAG.getBitcast(
8143         VT, DAG.getNode(UnpackLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
8144                         UnpackVT, V1, V2));
8145   };
8146
8147   // We try each unpack from the largest to the smallest to try and find one
8148   // that fits this mask.
8149   int OrigNumElements = VT.getVectorNumElements();
8150   int OrigScalarSize = VT.getScalarSizeInBits();
8151   for (int ScalarSize = 64; ScalarSize >= OrigScalarSize; ScalarSize /= 2) {
8152     int Scale = ScalarSize / OrigScalarSize;
8153     int NumElements = OrigNumElements / Scale;
8154     MVT UnpackVT = MVT::getVectorVT(MVT::getIntegerVT(ScalarSize), NumElements);
8155     if (SDValue Unpack = TryUnpack(UnpackVT, Scale))
8156       return Unpack;
8157   }
8158
8159   // If none of the unpack-rooted lowerings worked (or were profitable) try an
8160   // initial unpack.
8161   if (NumLoInputs == 0 || NumHiInputs == 0) {
8162     assert((NumLoInputs > 0 || NumHiInputs > 0) &&
8163            "We have to have *some* inputs!");
8164     int HalfOffset = NumLoInputs == 0 ? Size / 2 : 0;
8165
8166     // FIXME: We could consider the total complexity of the permute of each
8167     // possible unpacking. Or at the least we should consider how many
8168     // half-crossings are created.
8169     // FIXME: We could consider commuting the unpacks.
8170
8171     SmallVector<int, 32> PermMask;
8172     PermMask.assign(Size, -1);
8173     for (int i = 0; i < Size; ++i) {
8174       if (Mask[i] < 0)
8175         continue;
8176
8177       assert(Mask[i] % Size >= HalfOffset && "Found input from wrong half!");
8178
8179       PermMask[i] =
8180           2 * ((Mask[i] % Size) - HalfOffset) + (Mask[i] < Size ? 0 : 1);
8181     }
8182     return DAG.getVectorShuffle(
8183         VT, DL, DAG.getNode(NumLoInputs == 0 ? X86ISD::UNPCKH : X86ISD::UNPCKL,
8184                             DL, VT, V1, V2),
8185         DAG.getUNDEF(VT), PermMask);
8186   }
8187
8188   return SDValue();
8189 }
8190
8191 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
8192 ///
8193 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
8194 /// support for floating point shuffles but not integer shuffles. These
8195 /// instructions will incur a domain crossing penalty on some chips though so
8196 /// it is better to avoid lowering through this for integer vectors where
8197 /// possible.
8198 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8199                                        const X86Subtarget *Subtarget,
8200                                        SelectionDAG &DAG) {
8201   SDLoc DL(Op);
8202   assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
8203   assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
8204   assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
8205   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8206   ArrayRef<int> Mask = SVOp->getMask();
8207   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
8208
8209   if (isSingleInputShuffleMask(Mask)) {
8210     // Use low duplicate instructions for masks that match their pattern.
8211     if (Subtarget->hasSSE3())
8212       if (isShuffleEquivalent(V1, V2, Mask, {0, 0}))
8213         return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v2f64, V1);
8214
8215     // Straight shuffle of a single input vector. Simulate this by using the
8216     // single input as both of the "inputs" to this instruction..
8217     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
8218
8219     if (Subtarget->hasAVX()) {
8220       // If we have AVX, we can use VPERMILPS which will allow folding a load
8221       // into the shuffle.
8222       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v2f64, V1,
8223                          DAG.getConstant(SHUFPDMask, DL, MVT::i8));
8224     }
8225
8226     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V1,
8227                        DAG.getConstant(SHUFPDMask, DL, MVT::i8));
8228   }
8229   assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
8230   assert(Mask[1] >= 2 && "Non-canonicalized blend!");
8231
8232   // If we have a single input, insert that into V1 if we can do so cheaply.
8233   if ((Mask[0] >= 2) + (Mask[1] >= 2) == 1) {
8234     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8235             DL, MVT::v2f64, V1, V2, Mask, Subtarget, DAG))
8236       return Insertion;
8237     // Try inverting the insertion since for v2 masks it is easy to do and we
8238     // can't reliably sort the mask one way or the other.
8239     int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
8240                           Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
8241     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8242             DL, MVT::v2f64, V2, V1, InverseMask, Subtarget, DAG))
8243       return Insertion;
8244   }
8245
8246   // Try to use one of the special instruction patterns to handle two common
8247   // blend patterns if a zero-blend above didn't work.
8248   if (isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
8249       isShuffleEquivalent(V1, V2, Mask, {1, 3}))
8250     if (SDValue V1S = getScalarValueForVectorElement(V1, Mask[0], DAG))
8251       // We can either use a special instruction to load over the low double or
8252       // to move just the low double.
8253       return DAG.getNode(
8254           isShuffleFoldableLoad(V1S) ? X86ISD::MOVLPD : X86ISD::MOVSD,
8255           DL, MVT::v2f64, V2,
8256           DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V1S));
8257
8258   if (Subtarget->hasSSE41())
8259     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2f64, V1, V2, Mask,
8260                                                   Subtarget, DAG))
8261       return Blend;
8262
8263   // Use dedicated unpack instructions for masks that match their pattern.
8264   if (SDValue V =
8265           lowerVectorShuffleWithUNPCK(DL, MVT::v2f64, Mask, V1, V2, DAG))
8266     return V;
8267
8268   unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
8269   return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V2,
8270                      DAG.getConstant(SHUFPDMask, DL, MVT::i8));
8271 }
8272
8273 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
8274 ///
8275 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
8276 /// the integer unit to minimize domain crossing penalties. However, for blends
8277 /// it falls back to the floating point shuffle operation with appropriate bit
8278 /// casting.
8279 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8280                                        const X86Subtarget *Subtarget,
8281                                        SelectionDAG &DAG) {
8282   SDLoc DL(Op);
8283   assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
8284   assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
8285   assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
8286   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8287   ArrayRef<int> Mask = SVOp->getMask();
8288   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
8289
8290   if (isSingleInputShuffleMask(Mask)) {
8291     // Check for being able to broadcast a single element.
8292     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v2i64, V1,
8293                                                           Mask, Subtarget, DAG))
8294       return Broadcast;
8295
8296     // Straight shuffle of a single input vector. For everything from SSE2
8297     // onward this has a single fast instruction with no scary immediates.
8298     // We have to map the mask as it is actually a v4i32 shuffle instruction.
8299     V1 = DAG.getBitcast(MVT::v4i32, V1);
8300     int WidenedMask[4] = {
8301         std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
8302         std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
8303     return DAG.getBitcast(
8304         MVT::v2i64,
8305         DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
8306                     getV4X86ShuffleImm8ForMask(WidenedMask, DL, DAG)));
8307   }
8308   assert(Mask[0] != -1 && "No undef lanes in multi-input v2 shuffles!");
8309   assert(Mask[1] != -1 && "No undef lanes in multi-input v2 shuffles!");
8310   assert(Mask[0] < 2 && "We sort V1 to be the first input.");
8311   assert(Mask[1] >= 2 && "We sort V2 to be the second input.");
8312
8313   // If we have a blend of two PACKUS operations an the blend aligns with the
8314   // low and half halves, we can just merge the PACKUS operations. This is
8315   // particularly important as it lets us merge shuffles that this routine itself
8316   // creates.
8317   auto GetPackNode = [](SDValue V) {
8318     while (V.getOpcode() == ISD::BITCAST)
8319       V = V.getOperand(0);
8320
8321     return V.getOpcode() == X86ISD::PACKUS ? V : SDValue();
8322   };
8323   if (SDValue V1Pack = GetPackNode(V1))
8324     if (SDValue V2Pack = GetPackNode(V2))
8325       return DAG.getBitcast(MVT::v2i64,
8326                             DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8,
8327                                         Mask[0] == 0 ? V1Pack.getOperand(0)
8328                                                      : V1Pack.getOperand(1),
8329                                         Mask[1] == 2 ? V2Pack.getOperand(0)
8330                                                      : V2Pack.getOperand(1)));
8331
8332   // Try to use shift instructions.
8333   if (SDValue Shift =
8334           lowerVectorShuffleAsShift(DL, MVT::v2i64, V1, V2, Mask, DAG))
8335     return Shift;
8336
8337   // When loading a scalar and then shuffling it into a vector we can often do
8338   // the insertion cheaply.
8339   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8340           DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
8341     return Insertion;
8342   // Try inverting the insertion since for v2 masks it is easy to do and we
8343   // can't reliably sort the mask one way or the other.
8344   int InverseMask[2] = {Mask[0] ^ 2, Mask[1] ^ 2};
8345   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8346           DL, MVT::v2i64, V2, V1, InverseMask, Subtarget, DAG))
8347     return Insertion;
8348
8349   // We have different paths for blend lowering, but they all must use the
8350   // *exact* same predicate.
8351   bool IsBlendSupported = Subtarget->hasSSE41();
8352   if (IsBlendSupported)
8353     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2i64, V1, V2, Mask,
8354                                                   Subtarget, DAG))
8355       return Blend;
8356
8357   // Use dedicated unpack instructions for masks that match their pattern.
8358   if (SDValue V =
8359           lowerVectorShuffleWithUNPCK(DL, MVT::v2i64, Mask, V1, V2, DAG))
8360     return V;
8361
8362   // Try to use byte rotation instructions.
8363   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
8364   if (Subtarget->hasSSSE3())
8365     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8366             DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
8367       return Rotate;
8368
8369   // If we have direct support for blends, we should lower by decomposing into
8370   // a permute. That will be faster than the domain cross.
8371   if (IsBlendSupported)
8372     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v2i64, V1, V2,
8373                                                       Mask, DAG);
8374
8375   // We implement this with SHUFPD which is pretty lame because it will likely
8376   // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
8377   // However, all the alternatives are still more cycles and newer chips don't
8378   // have this problem. It would be really nice if x86 had better shuffles here.
8379   V1 = DAG.getBitcast(MVT::v2f64, V1);
8380   V2 = DAG.getBitcast(MVT::v2f64, V2);
8381   return DAG.getBitcast(MVT::v2i64,
8382                         DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
8383 }
8384
8385 /// \brief Test whether this can be lowered with a single SHUFPS instruction.
8386 ///
8387 /// This is used to disable more specialized lowerings when the shufps lowering
8388 /// will happen to be efficient.
8389 static bool isSingleSHUFPSMask(ArrayRef<int> Mask) {
8390   // This routine only handles 128-bit shufps.
8391   assert(Mask.size() == 4 && "Unsupported mask size!");
8392
8393   // To lower with a single SHUFPS we need to have the low half and high half
8394   // each requiring a single input.
8395   if (Mask[0] != -1 && Mask[1] != -1 && (Mask[0] < 4) != (Mask[1] < 4))
8396     return false;
8397   if (Mask[2] != -1 && Mask[3] != -1 && (Mask[2] < 4) != (Mask[3] < 4))
8398     return false;
8399
8400   return true;
8401 }
8402
8403 /// \brief Lower a vector shuffle using the SHUFPS instruction.
8404 ///
8405 /// This is a helper routine dedicated to lowering vector shuffles using SHUFPS.
8406 /// It makes no assumptions about whether this is the *best* lowering, it simply
8407 /// uses it.
8408 static SDValue lowerVectorShuffleWithSHUFPS(SDLoc DL, MVT VT,
8409                                             ArrayRef<int> Mask, SDValue V1,
8410                                             SDValue V2, SelectionDAG &DAG) {
8411   SDValue LowV = V1, HighV = V2;
8412   int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
8413
8414   int NumV2Elements =
8415       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8416
8417   if (NumV2Elements == 1) {
8418     int V2Index =
8419         std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
8420         Mask.begin();
8421
8422     // Compute the index adjacent to V2Index and in the same half by toggling
8423     // the low bit.
8424     int V2AdjIndex = V2Index ^ 1;
8425
8426     if (Mask[V2AdjIndex] == -1) {
8427       // Handles all the cases where we have a single V2 element and an undef.
8428       // This will only ever happen in the high lanes because we commute the
8429       // vector otherwise.
8430       if (V2Index < 2)
8431         std::swap(LowV, HighV);
8432       NewMask[V2Index] -= 4;
8433     } else {
8434       // Handle the case where the V2 element ends up adjacent to a V1 element.
8435       // To make this work, blend them together as the first step.
8436       int V1Index = V2AdjIndex;
8437       int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
8438       V2 = DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
8439                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
8440
8441       // Now proceed to reconstruct the final blend as we have the necessary
8442       // high or low half formed.
8443       if (V2Index < 2) {
8444         LowV = V2;
8445         HighV = V1;
8446       } else {
8447         HighV = V2;
8448       }
8449       NewMask[V1Index] = 2; // We put the V1 element in V2[2].
8450       NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
8451     }
8452   } else if (NumV2Elements == 2) {
8453     if (Mask[0] < 4 && Mask[1] < 4) {
8454       // Handle the easy case where we have V1 in the low lanes and V2 in the
8455       // high lanes.
8456       NewMask[2] -= 4;
8457       NewMask[3] -= 4;
8458     } else if (Mask[2] < 4 && Mask[3] < 4) {
8459       // We also handle the reversed case because this utility may get called
8460       // when we detect a SHUFPS pattern but can't easily commute the shuffle to
8461       // arrange things in the right direction.
8462       NewMask[0] -= 4;
8463       NewMask[1] -= 4;
8464       HighV = V1;
8465       LowV = V2;
8466     } else {
8467       // We have a mixture of V1 and V2 in both low and high lanes. Rather than
8468       // trying to place elements directly, just blend them and set up the final
8469       // shuffle to place them.
8470
8471       // The first two blend mask elements are for V1, the second two are for
8472       // V2.
8473       int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
8474                           Mask[2] < 4 ? Mask[2] : Mask[3],
8475                           (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
8476                           (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
8477       V1 = DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
8478                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
8479
8480       // Now we do a normal shuffle of V1 by giving V1 as both operands to
8481       // a blend.
8482       LowV = HighV = V1;
8483       NewMask[0] = Mask[0] < 4 ? 0 : 2;
8484       NewMask[1] = Mask[0] < 4 ? 2 : 0;
8485       NewMask[2] = Mask[2] < 4 ? 1 : 3;
8486       NewMask[3] = Mask[2] < 4 ? 3 : 1;
8487     }
8488   }
8489   return DAG.getNode(X86ISD::SHUFP, DL, VT, LowV, HighV,
8490                      getV4X86ShuffleImm8ForMask(NewMask, DL, DAG));
8491 }
8492
8493 /// \brief Lower 4-lane 32-bit floating point shuffles.
8494 ///
8495 /// Uses instructions exclusively from the floating point unit to minimize
8496 /// domain crossing penalties, as these are sufficient to implement all v4f32
8497 /// shuffles.
8498 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8499                                        const X86Subtarget *Subtarget,
8500                                        SelectionDAG &DAG) {
8501   SDLoc DL(Op);
8502   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
8503   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8504   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8505   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8506   ArrayRef<int> Mask = SVOp->getMask();
8507   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8508
8509   int NumV2Elements =
8510       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8511
8512   if (NumV2Elements == 0) {
8513     // Check for being able to broadcast a single element.
8514     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f32, V1,
8515                                                           Mask, Subtarget, DAG))
8516       return Broadcast;
8517
8518     // Use even/odd duplicate instructions for masks that match their pattern.
8519     if (Subtarget->hasSSE3()) {
8520       if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
8521         return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v4f32, V1);
8522       if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3}))
8523         return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v4f32, V1);
8524     }
8525
8526     if (Subtarget->hasAVX()) {
8527       // If we have AVX, we can use VPERMILPS which will allow folding a load
8528       // into the shuffle.
8529       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f32, V1,
8530                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8531     }
8532
8533     // Otherwise, use a straight shuffle of a single input vector. We pass the
8534     // input vector to both operands to simulate this with a SHUFPS.
8535     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
8536                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8537   }
8538
8539   // There are special ways we can lower some single-element blends. However, we
8540   // have custom ways we can lower more complex single-element blends below that
8541   // we defer to if both this and BLENDPS fail to match, so restrict this to
8542   // when the V2 input is targeting element 0 of the mask -- that is the fast
8543   // case here.
8544   if (NumV2Elements == 1 && Mask[0] >= 4)
8545     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4f32, V1, V2,
8546                                                          Mask, Subtarget, DAG))
8547       return V;
8548
8549   if (Subtarget->hasSSE41()) {
8550     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f32, V1, V2, Mask,
8551                                                   Subtarget, DAG))
8552       return Blend;
8553
8554     // Use INSERTPS if we can complete the shuffle efficiently.
8555     if (SDValue V = lowerVectorShuffleAsInsertPS(Op, V1, V2, Mask, DAG))
8556       return V;
8557
8558     if (!isSingleSHUFPSMask(Mask))
8559       if (SDValue BlendPerm = lowerVectorShuffleAsBlendAndPermute(
8560               DL, MVT::v4f32, V1, V2, Mask, DAG))
8561         return BlendPerm;
8562   }
8563
8564   // Use dedicated unpack instructions for masks that match their pattern.
8565   if (SDValue V =
8566           lowerVectorShuffleWithUNPCK(DL, MVT::v4f32, Mask, V1, V2, DAG))
8567     return V;
8568
8569   // Otherwise fall back to a SHUFPS lowering strategy.
8570   return lowerVectorShuffleWithSHUFPS(DL, MVT::v4f32, Mask, V1, V2, DAG);
8571 }
8572
8573 /// \brief Lower 4-lane i32 vector shuffles.
8574 ///
8575 /// We try to handle these with integer-domain shuffles where we can, but for
8576 /// blends we use the floating point domain blend instructions.
8577 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8578                                        const X86Subtarget *Subtarget,
8579                                        SelectionDAG &DAG) {
8580   SDLoc DL(Op);
8581   assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
8582   assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8583   assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8584   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8585   ArrayRef<int> Mask = SVOp->getMask();
8586   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8587
8588   // Whenever we can lower this as a zext, that instruction is strictly faster
8589   // than any alternative. It also allows us to fold memory operands into the
8590   // shuffle in many cases.
8591   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v4i32, V1, V2,
8592                                                          Mask, Subtarget, DAG))
8593     return ZExt;
8594
8595   int NumV2Elements =
8596       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8597
8598   if (NumV2Elements == 0) {
8599     // Check for being able to broadcast a single element.
8600     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i32, V1,
8601                                                           Mask, Subtarget, DAG))
8602       return Broadcast;
8603
8604     // Straight shuffle of a single input vector. For everything from SSE2
8605     // onward this has a single fast instruction with no scary immediates.
8606     // We coerce the shuffle pattern to be compatible with UNPCK instructions
8607     // but we aren't actually going to use the UNPCK instruction because doing
8608     // so prevents folding a load into this instruction or making a copy.
8609     const int UnpackLoMask[] = {0, 0, 1, 1};
8610     const int UnpackHiMask[] = {2, 2, 3, 3};
8611     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 1, 1}))
8612       Mask = UnpackLoMask;
8613     else if (isShuffleEquivalent(V1, V2, Mask, {2, 2, 3, 3}))
8614       Mask = UnpackHiMask;
8615
8616     return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
8617                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8618   }
8619
8620   // Try to use shift instructions.
8621   if (SDValue Shift =
8622           lowerVectorShuffleAsShift(DL, MVT::v4i32, V1, V2, Mask, DAG))
8623     return Shift;
8624
8625   // There are special ways we can lower some single-element blends.
8626   if (NumV2Elements == 1)
8627     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4i32, V1, V2,
8628                                                          Mask, Subtarget, DAG))
8629       return V;
8630
8631   // We have different paths for blend lowering, but they all must use the
8632   // *exact* same predicate.
8633   bool IsBlendSupported = Subtarget->hasSSE41();
8634   if (IsBlendSupported)
8635     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i32, V1, V2, Mask,
8636                                                   Subtarget, DAG))
8637       return Blend;
8638
8639   if (SDValue Masked =
8640           lowerVectorShuffleAsBitMask(DL, MVT::v4i32, V1, V2, Mask, DAG))
8641     return Masked;
8642
8643   // Use dedicated unpack instructions for masks that match their pattern.
8644   if (SDValue V =
8645           lowerVectorShuffleWithUNPCK(DL, MVT::v4i32, Mask, V1, V2, DAG))
8646     return V;
8647
8648   // Try to use byte rotation instructions.
8649   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
8650   if (Subtarget->hasSSSE3())
8651     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8652             DL, MVT::v4i32, V1, V2, Mask, Subtarget, DAG))
8653       return Rotate;
8654
8655   // If we have direct support for blends, we should lower by decomposing into
8656   // a permute. That will be faster than the domain cross.
8657   if (IsBlendSupported)
8658     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i32, V1, V2,
8659                                                       Mask, DAG);
8660
8661   // Try to lower by permuting the inputs into an unpack instruction.
8662   if (SDValue Unpack = lowerVectorShuffleAsPermuteAndUnpack(DL, MVT::v4i32, V1,
8663                                                             V2, Mask, DAG))
8664     return Unpack;
8665
8666   // We implement this with SHUFPS because it can blend from two vectors.
8667   // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
8668   // up the inputs, bypassing domain shift penalties that we would encur if we
8669   // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
8670   // relevant.
8671   return DAG.getBitcast(
8672       MVT::v4i32,
8673       DAG.getVectorShuffle(MVT::v4f32, DL, DAG.getBitcast(MVT::v4f32, V1),
8674                            DAG.getBitcast(MVT::v4f32, V2), Mask));
8675 }
8676
8677 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
8678 /// shuffle lowering, and the most complex part.
8679 ///
8680 /// The lowering strategy is to try to form pairs of input lanes which are
8681 /// targeted at the same half of the final vector, and then use a dword shuffle
8682 /// to place them onto the right half, and finally unpack the paired lanes into
8683 /// their final position.
8684 ///
8685 /// The exact breakdown of how to form these dword pairs and align them on the
8686 /// correct sides is really tricky. See the comments within the function for
8687 /// more of the details.
8688 ///
8689 /// This code also handles repeated 128-bit lanes of v8i16 shuffles, but each
8690 /// lane must shuffle the *exact* same way. In fact, you must pass a v8 Mask to
8691 /// this routine for it to work correctly. To shuffle a 256-bit or 512-bit i16
8692 /// vector, form the analogous 128-bit 8-element Mask.
8693 static SDValue lowerV8I16GeneralSingleInputVectorShuffle(
8694     SDLoc DL, MVT VT, SDValue V, MutableArrayRef<int> Mask,
8695     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
8696   assert(VT.getVectorElementType() == MVT::i16 && "Bad input type!");
8697   MVT PSHUFDVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
8698
8699   assert(Mask.size() == 8 && "Shuffle mask length doen't match!");
8700   MutableArrayRef<int> LoMask = Mask.slice(0, 4);
8701   MutableArrayRef<int> HiMask = Mask.slice(4, 4);
8702
8703   SmallVector<int, 4> LoInputs;
8704   std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
8705                [](int M) { return M >= 0; });
8706   std::sort(LoInputs.begin(), LoInputs.end());
8707   LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
8708   SmallVector<int, 4> HiInputs;
8709   std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
8710                [](int M) { return M >= 0; });
8711   std::sort(HiInputs.begin(), HiInputs.end());
8712   HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
8713   int NumLToL =
8714       std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
8715   int NumHToL = LoInputs.size() - NumLToL;
8716   int NumLToH =
8717       std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
8718   int NumHToH = HiInputs.size() - NumLToH;
8719   MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
8720   MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
8721   MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
8722   MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
8723
8724   // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
8725   // such inputs we can swap two of the dwords across the half mark and end up
8726   // with <=2 inputs to each half in each half. Once there, we can fall through
8727   // to the generic code below. For example:
8728   //
8729   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8730   // Mask:  [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
8731   //
8732   // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
8733   // and an existing 2-into-2 on the other half. In this case we may have to
8734   // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
8735   // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
8736   // Fortunately, we don't have to handle anything but a 2-into-2 pattern
8737   // because any other situation (including a 3-into-1 or 1-into-3 in the other
8738   // half than the one we target for fixing) will be fixed when we re-enter this
8739   // path. We will also combine away any sequence of PSHUFD instructions that
8740   // result into a single instruction. Here is an example of the tricky case:
8741   //
8742   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8743   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
8744   //
8745   // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
8746   //
8747   // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
8748   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
8749   //
8750   // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
8751   // Mask:  [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
8752   //
8753   // The result is fine to be handled by the generic logic.
8754   auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
8755                           ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
8756                           int AOffset, int BOffset) {
8757     assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
8758            "Must call this with A having 3 or 1 inputs from the A half.");
8759     assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
8760            "Must call this with B having 1 or 3 inputs from the B half.");
8761     assert(AToAInputs.size() + BToAInputs.size() == 4 &&
8762            "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
8763
8764     bool ThreeAInputs = AToAInputs.size() == 3;
8765
8766     // Compute the index of dword with only one word among the three inputs in
8767     // a half by taking the sum of the half with three inputs and subtracting
8768     // the sum of the actual three inputs. The difference is the remaining
8769     // slot.
8770     int ADWord, BDWord;
8771     int &TripleDWord = ThreeAInputs ? ADWord : BDWord;
8772     int &OneInputDWord = ThreeAInputs ? BDWord : ADWord;
8773     int TripleInputOffset = ThreeAInputs ? AOffset : BOffset;
8774     ArrayRef<int> TripleInputs = ThreeAInputs ? AToAInputs : BToAInputs;
8775     int OneInput = ThreeAInputs ? BToAInputs[0] : AToAInputs[0];
8776     int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
8777     int TripleNonInputIdx =
8778         TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
8779     TripleDWord = TripleNonInputIdx / 2;
8780
8781     // We use xor with one to compute the adjacent DWord to whichever one the
8782     // OneInput is in.
8783     OneInputDWord = (OneInput / 2) ^ 1;
8784
8785     // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
8786     // and BToA inputs. If there is also such a problem with the BToB and AToB
8787     // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
8788     // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
8789     // is essential that we don't *create* a 3<-1 as then we might oscillate.
8790     if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
8791       // Compute how many inputs will be flipped by swapping these DWords. We
8792       // need
8793       // to balance this to ensure we don't form a 3-1 shuffle in the other
8794       // half.
8795       int NumFlippedAToBInputs =
8796           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
8797           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
8798       int NumFlippedBToBInputs =
8799           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
8800           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
8801       if ((NumFlippedAToBInputs == 1 &&
8802            (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
8803           (NumFlippedBToBInputs == 1 &&
8804            (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
8805         // We choose whether to fix the A half or B half based on whether that
8806         // half has zero flipped inputs. At zero, we may not be able to fix it
8807         // with that half. We also bias towards fixing the B half because that
8808         // will more commonly be the high half, and we have to bias one way.
8809         auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
8810                                                        ArrayRef<int> Inputs) {
8811           int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
8812           bool IsFixIdxInput = std::find(Inputs.begin(), Inputs.end(),
8813                                          PinnedIdx ^ 1) != Inputs.end();
8814           // Determine whether the free index is in the flipped dword or the
8815           // unflipped dword based on where the pinned index is. We use this bit
8816           // in an xor to conditionally select the adjacent dword.
8817           int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
8818           bool IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8819                                              FixFreeIdx) != Inputs.end();
8820           if (IsFixIdxInput == IsFixFreeIdxInput)
8821             FixFreeIdx += 1;
8822           IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8823                                         FixFreeIdx) != Inputs.end();
8824           assert(IsFixIdxInput != IsFixFreeIdxInput &&
8825                  "We need to be changing the number of flipped inputs!");
8826           int PSHUFHalfMask[] = {0, 1, 2, 3};
8827           std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
8828           V = DAG.getNode(FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
8829                           MVT::v8i16, V,
8830                           getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DL, DAG));
8831
8832           for (int &M : Mask)
8833             if (M != -1 && M == FixIdx)
8834               M = FixFreeIdx;
8835             else if (M != -1 && M == FixFreeIdx)
8836               M = FixIdx;
8837         };
8838         if (NumFlippedBToBInputs != 0) {
8839           int BPinnedIdx =
8840               BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8841           FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
8842         } else {
8843           assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
8844           int APinnedIdx = ThreeAInputs ? TripleNonInputIdx : OneInput;
8845           FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
8846         }
8847       }
8848     }
8849
8850     int PSHUFDMask[] = {0, 1, 2, 3};
8851     PSHUFDMask[ADWord] = BDWord;
8852     PSHUFDMask[BDWord] = ADWord;
8853     V = DAG.getBitcast(
8854         VT,
8855         DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
8856                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
8857
8858     // Adjust the mask to match the new locations of A and B.
8859     for (int &M : Mask)
8860       if (M != -1 && M/2 == ADWord)
8861         M = 2 * BDWord + M % 2;
8862       else if (M != -1 && M/2 == BDWord)
8863         M = 2 * ADWord + M % 2;
8864
8865     // Recurse back into this routine to re-compute state now that this isn't
8866     // a 3 and 1 problem.
8867     return lowerV8I16GeneralSingleInputVectorShuffle(DL, VT, V, Mask, Subtarget,
8868                                                      DAG);
8869   };
8870   if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
8871     return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
8872   else if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
8873     return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
8874
8875   // At this point there are at most two inputs to the low and high halves from
8876   // each half. That means the inputs can always be grouped into dwords and
8877   // those dwords can then be moved to the correct half with a dword shuffle.
8878   // We use at most one low and one high word shuffle to collect these paired
8879   // inputs into dwords, and finally a dword shuffle to place them.
8880   int PSHUFLMask[4] = {-1, -1, -1, -1};
8881   int PSHUFHMask[4] = {-1, -1, -1, -1};
8882   int PSHUFDMask[4] = {-1, -1, -1, -1};
8883
8884   // First fix the masks for all the inputs that are staying in their
8885   // original halves. This will then dictate the targets of the cross-half
8886   // shuffles.
8887   auto fixInPlaceInputs =
8888       [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
8889                     MutableArrayRef<int> SourceHalfMask,
8890                     MutableArrayRef<int> HalfMask, int HalfOffset) {
8891     if (InPlaceInputs.empty())
8892       return;
8893     if (InPlaceInputs.size() == 1) {
8894       SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8895           InPlaceInputs[0] - HalfOffset;
8896       PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
8897       return;
8898     }
8899     if (IncomingInputs.empty()) {
8900       // Just fix all of the in place inputs.
8901       for (int Input : InPlaceInputs) {
8902         SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
8903         PSHUFDMask[Input / 2] = Input / 2;
8904       }
8905       return;
8906     }
8907
8908     assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
8909     SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8910         InPlaceInputs[0] - HalfOffset;
8911     // Put the second input next to the first so that they are packed into
8912     // a dword. We find the adjacent index by toggling the low bit.
8913     int AdjIndex = InPlaceInputs[0] ^ 1;
8914     SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
8915     std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
8916     PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
8917   };
8918   fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
8919   fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
8920
8921   // Now gather the cross-half inputs and place them into a free dword of
8922   // their target half.
8923   // FIXME: This operation could almost certainly be simplified dramatically to
8924   // look more like the 3-1 fixing operation.
8925   auto moveInputsToRightHalf = [&PSHUFDMask](
8926       MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
8927       MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
8928       MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
8929       int DestOffset) {
8930     auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
8931       return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
8932     };
8933     auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
8934                                                int Word) {
8935       int LowWord = Word & ~1;
8936       int HighWord = Word | 1;
8937       return isWordClobbered(SourceHalfMask, LowWord) ||
8938              isWordClobbered(SourceHalfMask, HighWord);
8939     };
8940
8941     if (IncomingInputs.empty())
8942       return;
8943
8944     if (ExistingInputs.empty()) {
8945       // Map any dwords with inputs from them into the right half.
8946       for (int Input : IncomingInputs) {
8947         // If the source half mask maps over the inputs, turn those into
8948         // swaps and use the swapped lane.
8949         if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
8950           if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
8951             SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
8952                 Input - SourceOffset;
8953             // We have to swap the uses in our half mask in one sweep.
8954             for (int &M : HalfMask)
8955               if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
8956                 M = Input;
8957               else if (M == Input)
8958                 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8959           } else {
8960             assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
8961                        Input - SourceOffset &&
8962                    "Previous placement doesn't match!");
8963           }
8964           // Note that this correctly re-maps both when we do a swap and when
8965           // we observe the other side of the swap above. We rely on that to
8966           // avoid swapping the members of the input list directly.
8967           Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8968         }
8969
8970         // Map the input's dword into the correct half.
8971         if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
8972           PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
8973         else
8974           assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
8975                      Input / 2 &&
8976                  "Previous placement doesn't match!");
8977       }
8978
8979       // And just directly shift any other-half mask elements to be same-half
8980       // as we will have mirrored the dword containing the element into the
8981       // same position within that half.
8982       for (int &M : HalfMask)
8983         if (M >= SourceOffset && M < SourceOffset + 4) {
8984           M = M - SourceOffset + DestOffset;
8985           assert(M >= 0 && "This should never wrap below zero!");
8986         }
8987       return;
8988     }
8989
8990     // Ensure we have the input in a viable dword of its current half. This
8991     // is particularly tricky because the original position may be clobbered
8992     // by inputs being moved and *staying* in that half.
8993     if (IncomingInputs.size() == 1) {
8994       if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8995         int InputFixed = std::find(std::begin(SourceHalfMask),
8996                                    std::end(SourceHalfMask), -1) -
8997                          std::begin(SourceHalfMask) + SourceOffset;
8998         SourceHalfMask[InputFixed - SourceOffset] =
8999             IncomingInputs[0] - SourceOffset;
9000         std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
9001                      InputFixed);
9002         IncomingInputs[0] = InputFixed;
9003       }
9004     } else if (IncomingInputs.size() == 2) {
9005       if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
9006           isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
9007         // We have two non-adjacent or clobbered inputs we need to extract from
9008         // the source half. To do this, we need to map them into some adjacent
9009         // dword slot in the source mask.
9010         int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
9011                               IncomingInputs[1] - SourceOffset};
9012
9013         // If there is a free slot in the source half mask adjacent to one of
9014         // the inputs, place the other input in it. We use (Index XOR 1) to
9015         // compute an adjacent index.
9016         if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
9017             SourceHalfMask[InputsFixed[0] ^ 1] == -1) {
9018           SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
9019           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
9020           InputsFixed[1] = InputsFixed[0] ^ 1;
9021         } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
9022                    SourceHalfMask[InputsFixed[1] ^ 1] == -1) {
9023           SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
9024           SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
9025           InputsFixed[0] = InputsFixed[1] ^ 1;
9026         } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] == -1 &&
9027                    SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] == -1) {
9028           // The two inputs are in the same DWord but it is clobbered and the
9029           // adjacent DWord isn't used at all. Move both inputs to the free
9030           // slot.
9031           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
9032           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
9033           InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
9034           InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
9035         } else {
9036           // The only way we hit this point is if there is no clobbering
9037           // (because there are no off-half inputs to this half) and there is no
9038           // free slot adjacent to one of the inputs. In this case, we have to
9039           // swap an input with a non-input.
9040           for (int i = 0; i < 4; ++i)
9041             assert((SourceHalfMask[i] == -1 || SourceHalfMask[i] == i) &&
9042                    "We can't handle any clobbers here!");
9043           assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
9044                  "Cannot have adjacent inputs here!");
9045
9046           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
9047           SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
9048
9049           // We also have to update the final source mask in this case because
9050           // it may need to undo the above swap.
9051           for (int &M : FinalSourceHalfMask)
9052             if (M == (InputsFixed[0] ^ 1) + SourceOffset)
9053               M = InputsFixed[1] + SourceOffset;
9054             else if (M == InputsFixed[1] + SourceOffset)
9055               M = (InputsFixed[0] ^ 1) + SourceOffset;
9056
9057           InputsFixed[1] = InputsFixed[0] ^ 1;
9058         }
9059
9060         // Point everything at the fixed inputs.
9061         for (int &M : HalfMask)
9062           if (M == IncomingInputs[0])
9063             M = InputsFixed[0] + SourceOffset;
9064           else if (M == IncomingInputs[1])
9065             M = InputsFixed[1] + SourceOffset;
9066
9067         IncomingInputs[0] = InputsFixed[0] + SourceOffset;
9068         IncomingInputs[1] = InputsFixed[1] + SourceOffset;
9069       }
9070     } else {
9071       llvm_unreachable("Unhandled input size!");
9072     }
9073
9074     // Now hoist the DWord down to the right half.
9075     int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
9076     assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
9077     PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
9078     for (int &M : HalfMask)
9079       for (int Input : IncomingInputs)
9080         if (M == Input)
9081           M = FreeDWord * 2 + Input % 2;
9082   };
9083   moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
9084                         /*SourceOffset*/ 4, /*DestOffset*/ 0);
9085   moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
9086                         /*SourceOffset*/ 0, /*DestOffset*/ 4);
9087
9088   // Now enact all the shuffles we've computed to move the inputs into their
9089   // target half.
9090   if (!isNoopShuffleMask(PSHUFLMask))
9091     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
9092                     getV4X86ShuffleImm8ForMask(PSHUFLMask, DL, DAG));
9093   if (!isNoopShuffleMask(PSHUFHMask))
9094     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
9095                     getV4X86ShuffleImm8ForMask(PSHUFHMask, DL, DAG));
9096   if (!isNoopShuffleMask(PSHUFDMask))
9097     V = DAG.getBitcast(
9098         VT,
9099         DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
9100                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
9101
9102   // At this point, each half should contain all its inputs, and we can then
9103   // just shuffle them into their final position.
9104   assert(std::count_if(LoMask.begin(), LoMask.end(),
9105                        [](int M) { return M >= 4; }) == 0 &&
9106          "Failed to lift all the high half inputs to the low mask!");
9107   assert(std::count_if(HiMask.begin(), HiMask.end(),
9108                        [](int M) { return M >= 0 && M < 4; }) == 0 &&
9109          "Failed to lift all the low half inputs to the high mask!");
9110
9111   // Do a half shuffle for the low mask.
9112   if (!isNoopShuffleMask(LoMask))
9113     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
9114                     getV4X86ShuffleImm8ForMask(LoMask, DL, DAG));
9115
9116   // Do a half shuffle with the high mask after shifting its values down.
9117   for (int &M : HiMask)
9118     if (M >= 0)
9119       M -= 4;
9120   if (!isNoopShuffleMask(HiMask))
9121     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
9122                     getV4X86ShuffleImm8ForMask(HiMask, DL, DAG));
9123
9124   return V;
9125 }
9126
9127 /// \brief Helper to form a PSHUFB-based shuffle+blend.
9128 static SDValue lowerVectorShuffleAsPSHUFB(SDLoc DL, MVT VT, SDValue V1,
9129                                           SDValue V2, ArrayRef<int> Mask,
9130                                           SelectionDAG &DAG, bool &V1InUse,
9131                                           bool &V2InUse) {
9132   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
9133   SDValue V1Mask[16];
9134   SDValue V2Mask[16];
9135   V1InUse = false;
9136   V2InUse = false;
9137
9138   int Size = Mask.size();
9139   int Scale = 16 / Size;
9140   for (int i = 0; i < 16; ++i) {
9141     if (Mask[i / Scale] == -1) {
9142       V1Mask[i] = V2Mask[i] = DAG.getUNDEF(MVT::i8);
9143     } else {
9144       const int ZeroMask = 0x80;
9145       int V1Idx = Mask[i / Scale] < Size ? Mask[i / Scale] * Scale + i % Scale
9146                                           : ZeroMask;
9147       int V2Idx = Mask[i / Scale] < Size
9148                       ? ZeroMask
9149                       : (Mask[i / Scale] - Size) * Scale + i % Scale;
9150       if (Zeroable[i / Scale])
9151         V1Idx = V2Idx = ZeroMask;
9152       V1Mask[i] = DAG.getConstant(V1Idx, DL, MVT::i8);
9153       V2Mask[i] = DAG.getConstant(V2Idx, DL, MVT::i8);
9154       V1InUse |= (ZeroMask != V1Idx);
9155       V2InUse |= (ZeroMask != V2Idx);
9156     }
9157   }
9158
9159   if (V1InUse)
9160     V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
9161                      DAG.getBitcast(MVT::v16i8, V1),
9162                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
9163   if (V2InUse)
9164     V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
9165                      DAG.getBitcast(MVT::v16i8, V2),
9166                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
9167
9168   // If we need shuffled inputs from both, blend the two.
9169   SDValue V;
9170   if (V1InUse && V2InUse)
9171     V = DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
9172   else
9173     V = V1InUse ? V1 : V2;
9174
9175   // Cast the result back to the correct type.
9176   return DAG.getBitcast(VT, V);
9177 }
9178
9179 /// \brief Generic lowering of 8-lane i16 shuffles.
9180 ///
9181 /// This handles both single-input shuffles and combined shuffle/blends with
9182 /// two inputs. The single input shuffles are immediately delegated to
9183 /// a dedicated lowering routine.
9184 ///
9185 /// The blends are lowered in one of three fundamental ways. If there are few
9186 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
9187 /// of the input is significantly cheaper when lowered as an interleaving of
9188 /// the two inputs, try to interleave them. Otherwise, blend the low and high
9189 /// halves of the inputs separately (making them have relatively few inputs)
9190 /// and then concatenate them.
9191 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9192                                        const X86Subtarget *Subtarget,
9193                                        SelectionDAG &DAG) {
9194   SDLoc DL(Op);
9195   assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
9196   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
9197   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
9198   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9199   ArrayRef<int> OrigMask = SVOp->getMask();
9200   int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
9201                         OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
9202   MutableArrayRef<int> Mask(MaskStorage);
9203
9204   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9205
9206   // Whenever we can lower this as a zext, that instruction is strictly faster
9207   // than any alternative.
9208   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
9209           DL, MVT::v8i16, V1, V2, OrigMask, Subtarget, DAG))
9210     return ZExt;
9211
9212   auto isV1 = [](int M) { return M >= 0 && M < 8; };
9213   (void)isV1;
9214   auto isV2 = [](int M) { return M >= 8; };
9215
9216   int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
9217
9218   if (NumV2Inputs == 0) {
9219     // Check for being able to broadcast a single element.
9220     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i16, V1,
9221                                                           Mask, Subtarget, DAG))
9222       return Broadcast;
9223
9224     // Try to use shift instructions.
9225     if (SDValue Shift =
9226             lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V1, Mask, DAG))
9227       return Shift;
9228
9229     // Use dedicated unpack instructions for masks that match their pattern.
9230     if (SDValue V =
9231             lowerVectorShuffleWithUNPCK(DL, MVT::v8i16, Mask, V1, V2, DAG))
9232       return V;
9233
9234     // Try to use byte rotation instructions.
9235     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(DL, MVT::v8i16, V1, V1,
9236                                                         Mask, Subtarget, DAG))
9237       return Rotate;
9238
9239     return lowerV8I16GeneralSingleInputVectorShuffle(DL, MVT::v8i16, V1, Mask,
9240                                                      Subtarget, DAG);
9241   }
9242
9243   assert(std::any_of(Mask.begin(), Mask.end(), isV1) &&
9244          "All single-input shuffles should be canonicalized to be V1-input "
9245          "shuffles.");
9246
9247   // Try to use shift instructions.
9248   if (SDValue Shift =
9249           lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V2, Mask, DAG))
9250     return Shift;
9251
9252   // See if we can use SSE4A Extraction / Insertion.
9253   if (Subtarget->hasSSE4A())
9254     if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v8i16, V1, V2, Mask, DAG))
9255       return V;
9256
9257   // There are special ways we can lower some single-element blends.
9258   if (NumV2Inputs == 1)
9259     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v8i16, V1, V2,
9260                                                          Mask, Subtarget, DAG))
9261       return V;
9262
9263   // We have different paths for blend lowering, but they all must use the
9264   // *exact* same predicate.
9265   bool IsBlendSupported = Subtarget->hasSSE41();
9266   if (IsBlendSupported)
9267     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i16, V1, V2, Mask,
9268                                                   Subtarget, DAG))
9269       return Blend;
9270
9271   if (SDValue Masked =
9272           lowerVectorShuffleAsBitMask(DL, MVT::v8i16, V1, V2, Mask, DAG))
9273     return Masked;
9274
9275   // Use dedicated unpack instructions for masks that match their pattern.
9276   if (SDValue V =
9277           lowerVectorShuffleWithUNPCK(DL, MVT::v8i16, Mask, V1, V2, DAG))
9278     return V;
9279
9280   // Try to use byte rotation instructions.
9281   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9282           DL, MVT::v8i16, V1, V2, Mask, Subtarget, DAG))
9283     return Rotate;
9284
9285   if (SDValue BitBlend =
9286           lowerVectorShuffleAsBitBlend(DL, MVT::v8i16, V1, V2, Mask, DAG))
9287     return BitBlend;
9288
9289   if (SDValue Unpack = lowerVectorShuffleAsPermuteAndUnpack(DL, MVT::v8i16, V1,
9290                                                             V2, Mask, DAG))
9291     return Unpack;
9292
9293   // If we can't directly blend but can use PSHUFB, that will be better as it
9294   // can both shuffle and set up the inefficient blend.
9295   if (!IsBlendSupported && Subtarget->hasSSSE3()) {
9296     bool V1InUse, V2InUse;
9297     return lowerVectorShuffleAsPSHUFB(DL, MVT::v8i16, V1, V2, Mask, DAG,
9298                                       V1InUse, V2InUse);
9299   }
9300
9301   // We can always bit-blend if we have to so the fallback strategy is to
9302   // decompose into single-input permutes and blends.
9303   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i16, V1, V2,
9304                                                       Mask, DAG);
9305 }
9306
9307 /// \brief Check whether a compaction lowering can be done by dropping even
9308 /// elements and compute how many times even elements must be dropped.
9309 ///
9310 /// This handles shuffles which take every Nth element where N is a power of
9311 /// two. Example shuffle masks:
9312 ///
9313 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14,  0,  2,  4,  6,  8, 10, 12, 14
9314 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
9315 ///  N = 2:  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12
9316 ///  N = 2:  0,  4,  8, 12, 16, 20, 24, 28,  0,  4,  8, 12, 16, 20, 24, 28
9317 ///  N = 3:  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8
9318 ///  N = 3:  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24
9319 ///
9320 /// Any of these lanes can of course be undef.
9321 ///
9322 /// This routine only supports N <= 3.
9323 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
9324 /// for larger N.
9325 ///
9326 /// \returns N above, or the number of times even elements must be dropped if
9327 /// there is such a number. Otherwise returns zero.
9328 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
9329   // Figure out whether we're looping over two inputs or just one.
9330   bool IsSingleInput = isSingleInputShuffleMask(Mask);
9331
9332   // The modulus for the shuffle vector entries is based on whether this is
9333   // a single input or not.
9334   int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
9335   assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
9336          "We should only be called with masks with a power-of-2 size!");
9337
9338   uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
9339
9340   // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
9341   // and 2^3 simultaneously. This is because we may have ambiguity with
9342   // partially undef inputs.
9343   bool ViableForN[3] = {true, true, true};
9344
9345   for (int i = 0, e = Mask.size(); i < e; ++i) {
9346     // Ignore undef lanes, we'll optimistically collapse them to the pattern we
9347     // want.
9348     if (Mask[i] == -1)
9349       continue;
9350
9351     bool IsAnyViable = false;
9352     for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
9353       if (ViableForN[j]) {
9354         uint64_t N = j + 1;
9355
9356         // The shuffle mask must be equal to (i * 2^N) % M.
9357         if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
9358           IsAnyViable = true;
9359         else
9360           ViableForN[j] = false;
9361       }
9362     // Early exit if we exhaust the possible powers of two.
9363     if (!IsAnyViable)
9364       break;
9365   }
9366
9367   for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
9368     if (ViableForN[j])
9369       return j + 1;
9370
9371   // Return 0 as there is no viable power of two.
9372   return 0;
9373 }
9374
9375 /// \brief Generic lowering of v16i8 shuffles.
9376 ///
9377 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
9378 /// detect any complexity reducing interleaving. If that doesn't help, it uses
9379 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
9380 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
9381 /// back together.
9382 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9383                                        const X86Subtarget *Subtarget,
9384                                        SelectionDAG &DAG) {
9385   SDLoc DL(Op);
9386   assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
9387   assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
9388   assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
9389   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9390   ArrayRef<int> Mask = SVOp->getMask();
9391   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
9392
9393   // Try to use shift instructions.
9394   if (SDValue Shift =
9395           lowerVectorShuffleAsShift(DL, MVT::v16i8, V1, V2, Mask, DAG))
9396     return Shift;
9397
9398   // Try to use byte rotation instructions.
9399   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9400           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
9401     return Rotate;
9402
9403   // Try to use a zext lowering.
9404   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
9405           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
9406     return ZExt;
9407
9408   // See if we can use SSE4A Extraction / Insertion.
9409   if (Subtarget->hasSSE4A())
9410     if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v16i8, V1, V2, Mask, DAG))
9411       return V;
9412
9413   int NumV2Elements =
9414       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 16; });
9415
9416   // For single-input shuffles, there are some nicer lowering tricks we can use.
9417   if (NumV2Elements == 0) {
9418     // Check for being able to broadcast a single element.
9419     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i8, V1,
9420                                                           Mask, Subtarget, DAG))
9421       return Broadcast;
9422
9423     // Check whether we can widen this to an i16 shuffle by duplicating bytes.
9424     // Notably, this handles splat and partial-splat shuffles more efficiently.
9425     // However, it only makes sense if the pre-duplication shuffle simplifies
9426     // things significantly. Currently, this means we need to be able to
9427     // express the pre-duplication shuffle as an i16 shuffle.
9428     //
9429     // FIXME: We should check for other patterns which can be widened into an
9430     // i16 shuffle as well.
9431     auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
9432       for (int i = 0; i < 16; i += 2)
9433         if (Mask[i] != -1 && Mask[i + 1] != -1 && Mask[i] != Mask[i + 1])
9434           return false;
9435
9436       return true;
9437     };
9438     auto tryToWidenViaDuplication = [&]() -> SDValue {
9439       if (!canWidenViaDuplication(Mask))
9440         return SDValue();
9441       SmallVector<int, 4> LoInputs;
9442       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
9443                    [](int M) { return M >= 0 && M < 8; });
9444       std::sort(LoInputs.begin(), LoInputs.end());
9445       LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
9446                      LoInputs.end());
9447       SmallVector<int, 4> HiInputs;
9448       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
9449                    [](int M) { return M >= 8; });
9450       std::sort(HiInputs.begin(), HiInputs.end());
9451       HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
9452                      HiInputs.end());
9453
9454       bool TargetLo = LoInputs.size() >= HiInputs.size();
9455       ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
9456       ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
9457
9458       int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
9459       SmallDenseMap<int, int, 8> LaneMap;
9460       for (int I : InPlaceInputs) {
9461         PreDupI16Shuffle[I/2] = I/2;
9462         LaneMap[I] = I;
9463       }
9464       int j = TargetLo ? 0 : 4, je = j + 4;
9465       for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
9466         // Check if j is already a shuffle of this input. This happens when
9467         // there are two adjacent bytes after we move the low one.
9468         if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
9469           // If we haven't yet mapped the input, search for a slot into which
9470           // we can map it.
9471           while (j < je && PreDupI16Shuffle[j] != -1)
9472             ++j;
9473
9474           if (j == je)
9475             // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
9476             return SDValue();
9477
9478           // Map this input with the i16 shuffle.
9479           PreDupI16Shuffle[j] = MovingInputs[i] / 2;
9480         }
9481
9482         // Update the lane map based on the mapping we ended up with.
9483         LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
9484       }
9485       V1 = DAG.getBitcast(
9486           MVT::v16i8,
9487           DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
9488                                DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
9489
9490       // Unpack the bytes to form the i16s that will be shuffled into place.
9491       V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
9492                        MVT::v16i8, V1, V1);
9493
9494       int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9495       for (int i = 0; i < 16; ++i)
9496         if (Mask[i] != -1) {
9497           int MappedMask = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
9498           assert(MappedMask < 8 && "Invalid v8 shuffle mask!");
9499           if (PostDupI16Shuffle[i / 2] == -1)
9500             PostDupI16Shuffle[i / 2] = MappedMask;
9501           else
9502             assert(PostDupI16Shuffle[i / 2] == MappedMask &&
9503                    "Conflicting entrties in the original shuffle!");
9504         }
9505       return DAG.getBitcast(
9506           MVT::v16i8,
9507           DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
9508                                DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
9509     };
9510     if (SDValue V = tryToWidenViaDuplication())
9511       return V;
9512   }
9513
9514   if (SDValue Masked =
9515           lowerVectorShuffleAsBitMask(DL, MVT::v16i8, V1, V2, Mask, DAG))
9516     return Masked;
9517
9518   // Use dedicated unpack instructions for masks that match their pattern.
9519   if (SDValue V =
9520           lowerVectorShuffleWithUNPCK(DL, MVT::v16i8, Mask, V1, V2, DAG))
9521     return V;
9522
9523   // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
9524   // with PSHUFB. It is important to do this before we attempt to generate any
9525   // blends but after all of the single-input lowerings. If the single input
9526   // lowerings can find an instruction sequence that is faster than a PSHUFB, we
9527   // want to preserve that and we can DAG combine any longer sequences into
9528   // a PSHUFB in the end. But once we start blending from multiple inputs,
9529   // the complexity of DAG combining bad patterns back into PSHUFB is too high,
9530   // and there are *very* few patterns that would actually be faster than the
9531   // PSHUFB approach because of its ability to zero lanes.
9532   //
9533   // FIXME: The only exceptions to the above are blends which are exact
9534   // interleavings with direct instructions supporting them. We currently don't
9535   // handle those well here.
9536   if (Subtarget->hasSSSE3()) {
9537     bool V1InUse = false;
9538     bool V2InUse = false;
9539
9540     SDValue PSHUFB = lowerVectorShuffleAsPSHUFB(DL, MVT::v16i8, V1, V2, Mask,
9541                                                 DAG, V1InUse, V2InUse);
9542
9543     // If both V1 and V2 are in use and we can use a direct blend or an unpack,
9544     // do so. This avoids using them to handle blends-with-zero which is
9545     // important as a single pshufb is significantly faster for that.
9546     if (V1InUse && V2InUse) {
9547       if (Subtarget->hasSSE41())
9548         if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i8, V1, V2,
9549                                                       Mask, Subtarget, DAG))
9550           return Blend;
9551
9552       // We can use an unpack to do the blending rather than an or in some
9553       // cases. Even though the or may be (very minorly) more efficient, we
9554       // preference this lowering because there are common cases where part of
9555       // the complexity of the shuffles goes away when we do the final blend as
9556       // an unpack.
9557       // FIXME: It might be worth trying to detect if the unpack-feeding
9558       // shuffles will both be pshufb, in which case we shouldn't bother with
9559       // this.
9560       if (SDValue Unpack = lowerVectorShuffleAsPermuteAndUnpack(
9561               DL, MVT::v16i8, V1, V2, Mask, DAG))
9562         return Unpack;
9563     }
9564
9565     return PSHUFB;
9566   }
9567
9568   // There are special ways we can lower some single-element blends.
9569   if (NumV2Elements == 1)
9570     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v16i8, V1, V2,
9571                                                          Mask, Subtarget, DAG))
9572       return V;
9573
9574   if (SDValue BitBlend =
9575           lowerVectorShuffleAsBitBlend(DL, MVT::v16i8, V1, V2, Mask, DAG))
9576     return BitBlend;
9577
9578   // Check whether a compaction lowering can be done. This handles shuffles
9579   // which take every Nth element for some even N. See the helper function for
9580   // details.
9581   //
9582   // We special case these as they can be particularly efficiently handled with
9583   // the PACKUSB instruction on x86 and they show up in common patterns of
9584   // rearranging bytes to truncate wide elements.
9585   if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
9586     // NumEvenDrops is the power of two stride of the elements. Another way of
9587     // thinking about it is that we need to drop the even elements this many
9588     // times to get the original input.
9589     bool IsSingleInput = isSingleInputShuffleMask(Mask);
9590
9591     // First we need to zero all the dropped bytes.
9592     assert(NumEvenDrops <= 3 &&
9593            "No support for dropping even elements more than 3 times.");
9594     // We use the mask type to pick which bytes are preserved based on how many
9595     // elements are dropped.
9596     MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
9597     SDValue ByteClearMask = DAG.getBitcast(
9598         MVT::v16i8, DAG.getConstant(0xFF, DL, MaskVTs[NumEvenDrops - 1]));
9599     V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
9600     if (!IsSingleInput)
9601       V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
9602
9603     // Now pack things back together.
9604     V1 = DAG.getBitcast(MVT::v8i16, V1);
9605     V2 = IsSingleInput ? V1 : DAG.getBitcast(MVT::v8i16, V2);
9606     SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
9607     for (int i = 1; i < NumEvenDrops; ++i) {
9608       Result = DAG.getBitcast(MVT::v8i16, Result);
9609       Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
9610     }
9611
9612     return Result;
9613   }
9614
9615   // Handle multi-input cases by blending single-input shuffles.
9616   if (NumV2Elements > 0)
9617     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v16i8, V1, V2,
9618                                                       Mask, DAG);
9619
9620   // The fallback path for single-input shuffles widens this into two v8i16
9621   // vectors with unpacks, shuffles those, and then pulls them back together
9622   // with a pack.
9623   SDValue V = V1;
9624
9625   int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9626   int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9627   for (int i = 0; i < 16; ++i)
9628     if (Mask[i] >= 0)
9629       (i < 8 ? LoBlendMask[i] : HiBlendMask[i % 8]) = Mask[i];
9630
9631   SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
9632
9633   SDValue VLoHalf, VHiHalf;
9634   // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
9635   // them out and avoid using UNPCK{L,H} to extract the elements of V as
9636   // i16s.
9637   if (std::none_of(std::begin(LoBlendMask), std::end(LoBlendMask),
9638                    [](int M) { return M >= 0 && M % 2 == 1; }) &&
9639       std::none_of(std::begin(HiBlendMask), std::end(HiBlendMask),
9640                    [](int M) { return M >= 0 && M % 2 == 1; })) {
9641     // Use a mask to drop the high bytes.
9642     VLoHalf = DAG.getBitcast(MVT::v8i16, V);
9643     VLoHalf = DAG.getNode(ISD::AND, DL, MVT::v8i16, VLoHalf,
9644                      DAG.getConstant(0x00FF, DL, MVT::v8i16));
9645
9646     // This will be a single vector shuffle instead of a blend so nuke VHiHalf.
9647     VHiHalf = DAG.getUNDEF(MVT::v8i16);
9648
9649     // Squash the masks to point directly into VLoHalf.
9650     for (int &M : LoBlendMask)
9651       if (M >= 0)
9652         M /= 2;
9653     for (int &M : HiBlendMask)
9654       if (M >= 0)
9655         M /= 2;
9656   } else {
9657     // Otherwise just unpack the low half of V into VLoHalf and the high half into
9658     // VHiHalf so that we can blend them as i16s.
9659     VLoHalf = DAG.getBitcast(
9660         MVT::v8i16, DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
9661     VHiHalf = DAG.getBitcast(
9662         MVT::v8i16, DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
9663   }
9664
9665   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, LoBlendMask);
9666   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, HiBlendMask);
9667
9668   return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
9669 }
9670
9671 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
9672 ///
9673 /// This routine breaks down the specific type of 128-bit shuffle and
9674 /// dispatches to the lowering routines accordingly.
9675 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9676                                         MVT VT, const X86Subtarget *Subtarget,
9677                                         SelectionDAG &DAG) {
9678   switch (VT.SimpleTy) {
9679   case MVT::v2i64:
9680     return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9681   case MVT::v2f64:
9682     return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9683   case MVT::v4i32:
9684     return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9685   case MVT::v4f32:
9686     return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9687   case MVT::v8i16:
9688     return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
9689   case MVT::v16i8:
9690     return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
9691
9692   default:
9693     llvm_unreachable("Unimplemented!");
9694   }
9695 }
9696
9697 /// \brief Helper function to test whether a shuffle mask could be
9698 /// simplified by widening the elements being shuffled.
9699 ///
9700 /// Appends the mask for wider elements in WidenedMask if valid. Otherwise
9701 /// leaves it in an unspecified state.
9702 ///
9703 /// NOTE: This must handle normal vector shuffle masks and *target* vector
9704 /// shuffle masks. The latter have the special property of a '-2' representing
9705 /// a zero-ed lane of a vector.
9706 static bool canWidenShuffleElements(ArrayRef<int> Mask,
9707                                     SmallVectorImpl<int> &WidenedMask) {
9708   for (int i = 0, Size = Mask.size(); i < Size; i += 2) {
9709     // If both elements are undef, its trivial.
9710     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] == SM_SentinelUndef) {
9711       WidenedMask.push_back(SM_SentinelUndef);
9712       continue;
9713     }
9714
9715     // Check for an undef mask and a mask value properly aligned to fit with
9716     // a pair of values. If we find such a case, use the non-undef mask's value.
9717     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] >= 0 && Mask[i + 1] % 2 == 1) {
9718       WidenedMask.push_back(Mask[i + 1] / 2);
9719       continue;
9720     }
9721     if (Mask[i + 1] == SM_SentinelUndef && Mask[i] >= 0 && Mask[i] % 2 == 0) {
9722       WidenedMask.push_back(Mask[i] / 2);
9723       continue;
9724     }
9725
9726     // When zeroing, we need to spread the zeroing across both lanes to widen.
9727     if (Mask[i] == SM_SentinelZero || Mask[i + 1] == SM_SentinelZero) {
9728       if ((Mask[i] == SM_SentinelZero || Mask[i] == SM_SentinelUndef) &&
9729           (Mask[i + 1] == SM_SentinelZero || Mask[i + 1] == SM_SentinelUndef)) {
9730         WidenedMask.push_back(SM_SentinelZero);
9731         continue;
9732       }
9733       return false;
9734     }
9735
9736     // Finally check if the two mask values are adjacent and aligned with
9737     // a pair.
9738     if (Mask[i] != SM_SentinelUndef && Mask[i] % 2 == 0 && Mask[i] + 1 == Mask[i + 1]) {
9739       WidenedMask.push_back(Mask[i] / 2);
9740       continue;
9741     }
9742
9743     // Otherwise we can't safely widen the elements used in this shuffle.
9744     return false;
9745   }
9746   assert(WidenedMask.size() == Mask.size() / 2 &&
9747          "Incorrect size of mask after widening the elements!");
9748
9749   return true;
9750 }
9751
9752 /// \brief Generic routine to split vector shuffle into half-sized shuffles.
9753 ///
9754 /// This routine just extracts two subvectors, shuffles them independently, and
9755 /// then concatenates them back together. This should work effectively with all
9756 /// AVX vector shuffle types.
9757 static SDValue splitAndLowerVectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9758                                           SDValue V2, ArrayRef<int> Mask,
9759                                           SelectionDAG &DAG) {
9760   assert(VT.getSizeInBits() >= 256 &&
9761          "Only for 256-bit or wider vector shuffles!");
9762   assert(V1.getSimpleValueType() == VT && "Bad operand type!");
9763   assert(V2.getSimpleValueType() == VT && "Bad operand type!");
9764
9765   ArrayRef<int> LoMask = Mask.slice(0, Mask.size() / 2);
9766   ArrayRef<int> HiMask = Mask.slice(Mask.size() / 2);
9767
9768   int NumElements = VT.getVectorNumElements();
9769   int SplitNumElements = NumElements / 2;
9770   MVT ScalarVT = VT.getVectorElementType();
9771   MVT SplitVT = MVT::getVectorVT(ScalarVT, NumElements / 2);
9772
9773   // Rather than splitting build-vectors, just build two narrower build
9774   // vectors. This helps shuffling with splats and zeros.
9775   auto SplitVector = [&](SDValue V) {
9776     while (V.getOpcode() == ISD::BITCAST)
9777       V = V->getOperand(0);
9778
9779     MVT OrigVT = V.getSimpleValueType();
9780     int OrigNumElements = OrigVT.getVectorNumElements();
9781     int OrigSplitNumElements = OrigNumElements / 2;
9782     MVT OrigScalarVT = OrigVT.getVectorElementType();
9783     MVT OrigSplitVT = MVT::getVectorVT(OrigScalarVT, OrigNumElements / 2);
9784
9785     SDValue LoV, HiV;
9786
9787     auto *BV = dyn_cast<BuildVectorSDNode>(V);
9788     if (!BV) {
9789       LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9790                         DAG.getIntPtrConstant(0, DL));
9791       HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9792                         DAG.getIntPtrConstant(OrigSplitNumElements, DL));
9793     } else {
9794
9795       SmallVector<SDValue, 16> LoOps, HiOps;
9796       for (int i = 0; i < OrigSplitNumElements; ++i) {
9797         LoOps.push_back(BV->getOperand(i));
9798         HiOps.push_back(BV->getOperand(i + OrigSplitNumElements));
9799       }
9800       LoV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, LoOps);
9801       HiV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, HiOps);
9802     }
9803     return std::make_pair(DAG.getBitcast(SplitVT, LoV),
9804                           DAG.getBitcast(SplitVT, HiV));
9805   };
9806
9807   SDValue LoV1, HiV1, LoV2, HiV2;
9808   std::tie(LoV1, HiV1) = SplitVector(V1);
9809   std::tie(LoV2, HiV2) = SplitVector(V2);
9810
9811   // Now create two 4-way blends of these half-width vectors.
9812   auto HalfBlend = [&](ArrayRef<int> HalfMask) {
9813     bool UseLoV1 = false, UseHiV1 = false, UseLoV2 = false, UseHiV2 = false;
9814     SmallVector<int, 32> V1BlendMask, V2BlendMask, BlendMask;
9815     for (int i = 0; i < SplitNumElements; ++i) {
9816       int M = HalfMask[i];
9817       if (M >= NumElements) {
9818         if (M >= NumElements + SplitNumElements)
9819           UseHiV2 = true;
9820         else
9821           UseLoV2 = true;
9822         V2BlendMask.push_back(M - NumElements);
9823         V1BlendMask.push_back(-1);
9824         BlendMask.push_back(SplitNumElements + i);
9825       } else if (M >= 0) {
9826         if (M >= SplitNumElements)
9827           UseHiV1 = true;
9828         else
9829           UseLoV1 = true;
9830         V2BlendMask.push_back(-1);
9831         V1BlendMask.push_back(M);
9832         BlendMask.push_back(i);
9833       } else {
9834         V2BlendMask.push_back(-1);
9835         V1BlendMask.push_back(-1);
9836         BlendMask.push_back(-1);
9837       }
9838     }
9839
9840     // Because the lowering happens after all combining takes place, we need to
9841     // manually combine these blend masks as much as possible so that we create
9842     // a minimal number of high-level vector shuffle nodes.
9843
9844     // First try just blending the halves of V1 or V2.
9845     if (!UseLoV1 && !UseHiV1 && !UseLoV2 && !UseHiV2)
9846       return DAG.getUNDEF(SplitVT);
9847     if (!UseLoV2 && !UseHiV2)
9848       return DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9849     if (!UseLoV1 && !UseHiV1)
9850       return DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9851
9852     SDValue V1Blend, V2Blend;
9853     if (UseLoV1 && UseHiV1) {
9854       V1Blend =
9855         DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9856     } else {
9857       // We only use half of V1 so map the usage down into the final blend mask.
9858       V1Blend = UseLoV1 ? LoV1 : HiV1;
9859       for (int i = 0; i < SplitNumElements; ++i)
9860         if (BlendMask[i] >= 0 && BlendMask[i] < SplitNumElements)
9861           BlendMask[i] = V1BlendMask[i] - (UseLoV1 ? 0 : SplitNumElements);
9862     }
9863     if (UseLoV2 && UseHiV2) {
9864       V2Blend =
9865         DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9866     } else {
9867       // We only use half of V2 so map the usage down into the final blend mask.
9868       V2Blend = UseLoV2 ? LoV2 : HiV2;
9869       for (int i = 0; i < SplitNumElements; ++i)
9870         if (BlendMask[i] >= SplitNumElements)
9871           BlendMask[i] = V2BlendMask[i] + (UseLoV2 ? SplitNumElements : 0);
9872     }
9873     return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
9874   };
9875   SDValue Lo = HalfBlend(LoMask);
9876   SDValue Hi = HalfBlend(HiMask);
9877   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
9878 }
9879
9880 /// \brief Either split a vector in halves or decompose the shuffles and the
9881 /// blend.
9882 ///
9883 /// This is provided as a good fallback for many lowerings of non-single-input
9884 /// shuffles with more than one 128-bit lane. In those cases, we want to select
9885 /// between splitting the shuffle into 128-bit components and stitching those
9886 /// back together vs. extracting the single-input shuffles and blending those
9887 /// results.
9888 static SDValue lowerVectorShuffleAsSplitOrBlend(SDLoc DL, MVT VT, SDValue V1,
9889                                                 SDValue V2, ArrayRef<int> Mask,
9890                                                 SelectionDAG &DAG) {
9891   assert(!isSingleInputShuffleMask(Mask) && "This routine must not be used to "
9892                                             "lower single-input shuffles as it "
9893                                             "could then recurse on itself.");
9894   int Size = Mask.size();
9895
9896   // If this can be modeled as a broadcast of two elements followed by a blend,
9897   // prefer that lowering. This is especially important because broadcasts can
9898   // often fold with memory operands.
9899   auto DoBothBroadcast = [&] {
9900     int V1BroadcastIdx = -1, V2BroadcastIdx = -1;
9901     for (int M : Mask)
9902       if (M >= Size) {
9903         if (V2BroadcastIdx == -1)
9904           V2BroadcastIdx = M - Size;
9905         else if (M - Size != V2BroadcastIdx)
9906           return false;
9907       } else if (M >= 0) {
9908         if (V1BroadcastIdx == -1)
9909           V1BroadcastIdx = M;
9910         else if (M != V1BroadcastIdx)
9911           return false;
9912       }
9913     return true;
9914   };
9915   if (DoBothBroadcast())
9916     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask,
9917                                                       DAG);
9918
9919   // If the inputs all stem from a single 128-bit lane of each input, then we
9920   // split them rather than blending because the split will decompose to
9921   // unusually few instructions.
9922   int LaneCount = VT.getSizeInBits() / 128;
9923   int LaneSize = Size / LaneCount;
9924   SmallBitVector LaneInputs[2];
9925   LaneInputs[0].resize(LaneCount, false);
9926   LaneInputs[1].resize(LaneCount, false);
9927   for (int i = 0; i < Size; ++i)
9928     if (Mask[i] >= 0)
9929       LaneInputs[Mask[i] / Size][(Mask[i] % Size) / LaneSize] = true;
9930   if (LaneInputs[0].count() <= 1 && LaneInputs[1].count() <= 1)
9931     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9932
9933   // Otherwise, just fall back to decomposed shuffles and a blend. This requires
9934   // that the decomposed single-input shuffles don't end up here.
9935   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9936 }
9937
9938 /// \brief Lower a vector shuffle crossing multiple 128-bit lanes as
9939 /// a permutation and blend of those lanes.
9940 ///
9941 /// This essentially blends the out-of-lane inputs to each lane into the lane
9942 /// from a permuted copy of the vector. This lowering strategy results in four
9943 /// instructions in the worst case for a single-input cross lane shuffle which
9944 /// is lower than any other fully general cross-lane shuffle strategy I'm aware
9945 /// of. Special cases for each particular shuffle pattern should be handled
9946 /// prior to trying this lowering.
9947 static SDValue lowerVectorShuffleAsLanePermuteAndBlend(SDLoc DL, MVT VT,
9948                                                        SDValue V1, SDValue V2,
9949                                                        ArrayRef<int> Mask,
9950                                                        SelectionDAG &DAG) {
9951   // FIXME: This should probably be generalized for 512-bit vectors as well.
9952   assert(VT.is256BitVector() && "Only for 256-bit vector shuffles!");
9953   int LaneSize = Mask.size() / 2;
9954
9955   // If there are only inputs from one 128-bit lane, splitting will in fact be
9956   // less expensive. The flags track whether the given lane contains an element
9957   // that crosses to another lane.
9958   bool LaneCrossing[2] = {false, false};
9959   for (int i = 0, Size = Mask.size(); i < Size; ++i)
9960     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
9961       LaneCrossing[(Mask[i] % Size) / LaneSize] = true;
9962   if (!LaneCrossing[0] || !LaneCrossing[1])
9963     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9964
9965   if (isSingleInputShuffleMask(Mask)) {
9966     SmallVector<int, 32> FlippedBlendMask;
9967     for (int i = 0, Size = Mask.size(); i < Size; ++i)
9968       FlippedBlendMask.push_back(
9969           Mask[i] < 0 ? -1 : (((Mask[i] % Size) / LaneSize == i / LaneSize)
9970                                   ? Mask[i]
9971                                   : Mask[i] % LaneSize +
9972                                         (i / LaneSize) * LaneSize + Size));
9973
9974     // Flip the vector, and blend the results which should now be in-lane. The
9975     // VPERM2X128 mask uses the low 2 bits for the low source and bits 4 and
9976     // 5 for the high source. The value 3 selects the high half of source 2 and
9977     // the value 2 selects the low half of source 2. We only use source 2 to
9978     // allow folding it into a memory operand.
9979     unsigned PERMMask = 3 | 2 << 4;
9980     SDValue Flipped = DAG.getNode(X86ISD::VPERM2X128, DL, VT, DAG.getUNDEF(VT),
9981                                   V1, DAG.getConstant(PERMMask, DL, MVT::i8));
9982     return DAG.getVectorShuffle(VT, DL, V1, Flipped, FlippedBlendMask);
9983   }
9984
9985   // This now reduces to two single-input shuffles of V1 and V2 which at worst
9986   // will be handled by the above logic and a blend of the results, much like
9987   // other patterns in AVX.
9988   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9989 }
9990
9991 /// \brief Handle lowering 2-lane 128-bit shuffles.
9992 static SDValue lowerV2X128VectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9993                                         SDValue V2, ArrayRef<int> Mask,
9994                                         const X86Subtarget *Subtarget,
9995                                         SelectionDAG &DAG) {
9996   // TODO: If minimizing size and one of the inputs is a zero vector and the
9997   // the zero vector has only one use, we could use a VPERM2X128 to save the
9998   // instruction bytes needed to explicitly generate the zero vector.
9999
10000   // Blends are faster and handle all the non-lane-crossing cases.
10001   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, VT, V1, V2, Mask,
10002                                                 Subtarget, DAG))
10003     return Blend;
10004
10005   bool IsV1Zero = ISD::isBuildVectorAllZeros(V1.getNode());
10006   bool IsV2Zero = ISD::isBuildVectorAllZeros(V2.getNode());
10007
10008   // If either input operand is a zero vector, use VPERM2X128 because its mask
10009   // allows us to replace the zero input with an implicit zero.
10010   if (!IsV1Zero && !IsV2Zero) {
10011     // Check for patterns which can be matched with a single insert of a 128-bit
10012     // subvector.
10013     bool OnlyUsesV1 = isShuffleEquivalent(V1, V2, Mask, {0, 1, 0, 1});
10014     if (OnlyUsesV1 || isShuffleEquivalent(V1, V2, Mask, {0, 1, 4, 5})) {
10015       MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(),
10016                                    VT.getVectorNumElements() / 2);
10017       SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
10018                                 DAG.getIntPtrConstant(0, DL));
10019       SDValue HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT,
10020                                 OnlyUsesV1 ? V1 : V2,
10021                                 DAG.getIntPtrConstant(0, DL));
10022       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoV, HiV);
10023     }
10024   }
10025
10026   // Otherwise form a 128-bit permutation. After accounting for undefs,
10027   // convert the 64-bit shuffle mask selection values into 128-bit
10028   // selection bits by dividing the indexes by 2 and shifting into positions
10029   // defined by a vperm2*128 instruction's immediate control byte.
10030
10031   // The immediate permute control byte looks like this:
10032   //    [1:0] - select 128 bits from sources for low half of destination
10033   //    [2]   - ignore
10034   //    [3]   - zero low half of destination
10035   //    [5:4] - select 128 bits from sources for high half of destination
10036   //    [6]   - ignore
10037   //    [7]   - zero high half of destination
10038
10039   int MaskLO = Mask[0];
10040   if (MaskLO == SM_SentinelUndef)
10041     MaskLO = Mask[1] == SM_SentinelUndef ? 0 : Mask[1];
10042
10043   int MaskHI = Mask[2];
10044   if (MaskHI == SM_SentinelUndef)
10045     MaskHI = Mask[3] == SM_SentinelUndef ? 0 : Mask[3];
10046
10047   unsigned PermMask = MaskLO / 2 | (MaskHI / 2) << 4;
10048
10049   // If either input is a zero vector, replace it with an undef input.
10050   // Shuffle mask values <  4 are selecting elements of V1.
10051   // Shuffle mask values >= 4 are selecting elements of V2.
10052   // Adjust each half of the permute mask by clearing the half that was
10053   // selecting the zero vector and setting the zero mask bit.
10054   if (IsV1Zero) {
10055     V1 = DAG.getUNDEF(VT);
10056     if (MaskLO < 4)
10057       PermMask = (PermMask & 0xf0) | 0x08;
10058     if (MaskHI < 4)
10059       PermMask = (PermMask & 0x0f) | 0x80;
10060   }
10061   if (IsV2Zero) {
10062     V2 = DAG.getUNDEF(VT);
10063     if (MaskLO >= 4)
10064       PermMask = (PermMask & 0xf0) | 0x08;
10065     if (MaskHI >= 4)
10066       PermMask = (PermMask & 0x0f) | 0x80;
10067   }
10068
10069   return DAG.getNode(X86ISD::VPERM2X128, DL, VT, V1, V2,
10070                      DAG.getConstant(PermMask, DL, MVT::i8));
10071 }
10072
10073 /// \brief Lower a vector shuffle by first fixing the 128-bit lanes and then
10074 /// shuffling each lane.
10075 ///
10076 /// This will only succeed when the result of fixing the 128-bit lanes results
10077 /// in a single-input non-lane-crossing shuffle with a repeating shuffle mask in
10078 /// each 128-bit lanes. This handles many cases where we can quickly blend away
10079 /// the lane crosses early and then use simpler shuffles within each lane.
10080 ///
10081 /// FIXME: It might be worthwhile at some point to support this without
10082 /// requiring the 128-bit lane-relative shuffles to be repeating, but currently
10083 /// in x86 only floating point has interesting non-repeating shuffles, and even
10084 /// those are still *marginally* more expensive.
10085 static SDValue lowerVectorShuffleByMerging128BitLanes(
10086     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
10087     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
10088   assert(!isSingleInputShuffleMask(Mask) &&
10089          "This is only useful with multiple inputs.");
10090
10091   int Size = Mask.size();
10092   int LaneSize = 128 / VT.getScalarSizeInBits();
10093   int NumLanes = Size / LaneSize;
10094   assert(NumLanes > 1 && "Only handles 256-bit and wider shuffles.");
10095
10096   // See if we can build a hypothetical 128-bit lane-fixing shuffle mask. Also
10097   // check whether the in-128-bit lane shuffles share a repeating pattern.
10098   SmallVector<int, 4> Lanes;
10099   Lanes.resize(NumLanes, -1);
10100   SmallVector<int, 4> InLaneMask;
10101   InLaneMask.resize(LaneSize, -1);
10102   for (int i = 0; i < Size; ++i) {
10103     if (Mask[i] < 0)
10104       continue;
10105
10106     int j = i / LaneSize;
10107
10108     if (Lanes[j] < 0) {
10109       // First entry we've seen for this lane.
10110       Lanes[j] = Mask[i] / LaneSize;
10111     } else if (Lanes[j] != Mask[i] / LaneSize) {
10112       // This doesn't match the lane selected previously!
10113       return SDValue();
10114     }
10115
10116     // Check that within each lane we have a consistent shuffle mask.
10117     int k = i % LaneSize;
10118     if (InLaneMask[k] < 0) {
10119       InLaneMask[k] = Mask[i] % LaneSize;
10120     } else if (InLaneMask[k] != Mask[i] % LaneSize) {
10121       // This doesn't fit a repeating in-lane mask.
10122       return SDValue();
10123     }
10124   }
10125
10126   // First shuffle the lanes into place.
10127   MVT LaneVT = MVT::getVectorVT(VT.isFloatingPoint() ? MVT::f64 : MVT::i64,
10128                                 VT.getSizeInBits() / 64);
10129   SmallVector<int, 8> LaneMask;
10130   LaneMask.resize(NumLanes * 2, -1);
10131   for (int i = 0; i < NumLanes; ++i)
10132     if (Lanes[i] >= 0) {
10133       LaneMask[2 * i + 0] = 2*Lanes[i] + 0;
10134       LaneMask[2 * i + 1] = 2*Lanes[i] + 1;
10135     }
10136
10137   V1 = DAG.getBitcast(LaneVT, V1);
10138   V2 = DAG.getBitcast(LaneVT, V2);
10139   SDValue LaneShuffle = DAG.getVectorShuffle(LaneVT, DL, V1, V2, LaneMask);
10140
10141   // Cast it back to the type we actually want.
10142   LaneShuffle = DAG.getBitcast(VT, LaneShuffle);
10143
10144   // Now do a simple shuffle that isn't lane crossing.
10145   SmallVector<int, 8> NewMask;
10146   NewMask.resize(Size, -1);
10147   for (int i = 0; i < Size; ++i)
10148     if (Mask[i] >= 0)
10149       NewMask[i] = (i / LaneSize) * LaneSize + Mask[i] % LaneSize;
10150   assert(!is128BitLaneCrossingShuffleMask(VT, NewMask) &&
10151          "Must not introduce lane crosses at this point!");
10152
10153   return DAG.getVectorShuffle(VT, DL, LaneShuffle, DAG.getUNDEF(VT), NewMask);
10154 }
10155
10156 /// \brief Test whether the specified input (0 or 1) is in-place blended by the
10157 /// given mask.
10158 ///
10159 /// This returns true if the elements from a particular input are already in the
10160 /// slot required by the given mask and require no permutation.
10161 static bool isShuffleMaskInputInPlace(int Input, ArrayRef<int> Mask) {
10162   assert((Input == 0 || Input == 1) && "Only two inputs to shuffles.");
10163   int Size = Mask.size();
10164   for (int i = 0; i < Size; ++i)
10165     if (Mask[i] >= 0 && Mask[i] / Size == Input && Mask[i] % Size != i)
10166       return false;
10167
10168   return true;
10169 }
10170
10171 static SDValue lowerVectorShuffleWithSHUFPD(SDLoc DL, MVT VT,
10172                                             ArrayRef<int> Mask, SDValue V1,
10173                                             SDValue V2, SelectionDAG &DAG) {
10174
10175   // Mask for V8F64: 0/1,  8/9,  2/3,  10/11, 4/5, ..
10176   // Mask for V4F64; 0/1,  4/5,  2/3,  6/7..
10177   assert(VT.getScalarSizeInBits() == 64 && "Unexpected data type for VSHUFPD");
10178   int NumElts = VT.getVectorNumElements();
10179   bool ShufpdMask = true;
10180   bool CommutableMask = true;
10181   unsigned Immediate = 0;
10182   for (int i = 0; i < NumElts; ++i) {
10183     if (Mask[i] < 0)
10184       continue;
10185     int Val = (i & 6) + NumElts * (i & 1);
10186     int CommutVal = (i & 0xe) + NumElts * ((i & 1)^1);
10187     if (Mask[i] < Val ||  Mask[i] > Val + 1)
10188       ShufpdMask = false;
10189     if (Mask[i] < CommutVal ||  Mask[i] > CommutVal + 1)
10190       CommutableMask = false;
10191     Immediate |= (Mask[i] % 2) << i;
10192   }
10193   if (ShufpdMask)
10194     return DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
10195                        DAG.getConstant(Immediate, DL, MVT::i8));
10196   if (CommutableMask)
10197     return DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
10198                        DAG.getConstant(Immediate, DL, MVT::i8));
10199   return SDValue();
10200 }
10201
10202 /// \brief Handle lowering of 4-lane 64-bit floating point shuffles.
10203 ///
10204 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
10205 /// isn't available.
10206 static SDValue lowerV4F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10207                                        const X86Subtarget *Subtarget,
10208                                        SelectionDAG &DAG) {
10209   SDLoc DL(Op);
10210   assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
10211   assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
10212   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10213   ArrayRef<int> Mask = SVOp->getMask();
10214   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
10215
10216   SmallVector<int, 4> WidenedMask;
10217   if (canWidenShuffleElements(Mask, WidenedMask))
10218     return lowerV2X128VectorShuffle(DL, MVT::v4f64, V1, V2, Mask, Subtarget,
10219                                     DAG);
10220
10221   if (isSingleInputShuffleMask(Mask)) {
10222     // Check for being able to broadcast a single element.
10223     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f64, V1,
10224                                                           Mask, Subtarget, DAG))
10225       return Broadcast;
10226
10227     // Use low duplicate instructions for masks that match their pattern.
10228     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
10229       return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v4f64, V1);
10230
10231     if (!is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask)) {
10232       // Non-half-crossing single input shuffles can be lowerid with an
10233       // interleaved permutation.
10234       unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
10235                               ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
10236       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f64, V1,
10237                          DAG.getConstant(VPERMILPMask, DL, MVT::i8));
10238     }
10239
10240     // With AVX2 we have direct support for this permutation.
10241     if (Subtarget->hasAVX2())
10242       return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4f64, V1,
10243                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
10244
10245     // Otherwise, fall back.
10246     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v4f64, V1, V2, Mask,
10247                                                    DAG);
10248   }
10249
10250   // Use dedicated unpack instructions for masks that match their pattern.
10251   if (SDValue V =
10252           lowerVectorShuffleWithUNPCK(DL, MVT::v4f64, Mask, V1, V2, DAG))
10253     return V;
10254
10255   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f64, V1, V2, Mask,
10256                                                 Subtarget, DAG))
10257     return Blend;
10258
10259   // Check if the blend happens to exactly fit that of SHUFPD.
10260   if (SDValue Op =
10261       lowerVectorShuffleWithSHUFPD(DL, MVT::v4f64, Mask, V1, V2, DAG))
10262     return Op;
10263
10264   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10265   // shuffle. However, if we have AVX2 and either inputs are already in place,
10266   // we will be able to shuffle even across lanes the other input in a single
10267   // instruction so skip this pattern.
10268   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
10269                                  isShuffleMaskInputInPlace(1, Mask))))
10270     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10271             DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
10272       return Result;
10273
10274   // If we have AVX2 then we always want to lower with a blend because an v4 we
10275   // can fully permute the elements.
10276   if (Subtarget->hasAVX2())
10277     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4f64, V1, V2,
10278                                                       Mask, DAG);
10279
10280   // Otherwise fall back on generic lowering.
10281   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v4f64, V1, V2, Mask, DAG);
10282 }
10283
10284 /// \brief Handle lowering of 4-lane 64-bit integer shuffles.
10285 ///
10286 /// This routine is only called when we have AVX2 and thus a reasonable
10287 /// instruction set for v4i64 shuffling..
10288 static SDValue lowerV4I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10289                                        const X86Subtarget *Subtarget,
10290                                        SelectionDAG &DAG) {
10291   SDLoc DL(Op);
10292   assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
10293   assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
10294   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10295   ArrayRef<int> Mask = SVOp->getMask();
10296   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
10297   assert(Subtarget->hasAVX2() && "We can only lower v4i64 with AVX2!");
10298
10299   SmallVector<int, 4> WidenedMask;
10300   if (canWidenShuffleElements(Mask, WidenedMask))
10301     return lowerV2X128VectorShuffle(DL, MVT::v4i64, V1, V2, Mask, Subtarget,
10302                                     DAG);
10303
10304   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i64, V1, V2, Mask,
10305                                                 Subtarget, DAG))
10306     return Blend;
10307
10308   // Check for being able to broadcast a single element.
10309   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i64, V1,
10310                                                         Mask, Subtarget, DAG))
10311     return Broadcast;
10312
10313   // When the shuffle is mirrored between the 128-bit lanes of the unit, we can
10314   // use lower latency instructions that will operate on both 128-bit lanes.
10315   SmallVector<int, 2> RepeatedMask;
10316   if (is128BitLaneRepeatedShuffleMask(MVT::v4i64, Mask, RepeatedMask)) {
10317     if (isSingleInputShuffleMask(Mask)) {
10318       int PSHUFDMask[] = {-1, -1, -1, -1};
10319       for (int i = 0; i < 2; ++i)
10320         if (RepeatedMask[i] >= 0) {
10321           PSHUFDMask[2 * i] = 2 * RepeatedMask[i];
10322           PSHUFDMask[2 * i + 1] = 2 * RepeatedMask[i] + 1;
10323         }
10324       return DAG.getBitcast(
10325           MVT::v4i64,
10326           DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32,
10327                       DAG.getBitcast(MVT::v8i32, V1),
10328                       getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
10329     }
10330   }
10331
10332   // AVX2 provides a direct instruction for permuting a single input across
10333   // lanes.
10334   if (isSingleInputShuffleMask(Mask))
10335     return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4i64, V1,
10336                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
10337
10338   // Try to use shift instructions.
10339   if (SDValue Shift =
10340           lowerVectorShuffleAsShift(DL, MVT::v4i64, V1, V2, Mask, DAG))
10341     return Shift;
10342
10343   // Use dedicated unpack instructions for masks that match their pattern.
10344   if (SDValue V =
10345           lowerVectorShuffleWithUNPCK(DL, MVT::v4i64, Mask, V1, V2, DAG))
10346     return V;
10347
10348   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10349   // shuffle. However, if we have AVX2 and either inputs are already in place,
10350   // we will be able to shuffle even across lanes the other input in a single
10351   // instruction so skip this pattern.
10352   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
10353                                  isShuffleMaskInputInPlace(1, Mask))))
10354     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10355             DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
10356       return Result;
10357
10358   // Otherwise fall back on generic blend lowering.
10359   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i64, V1, V2,
10360                                                     Mask, DAG);
10361 }
10362
10363 /// \brief Handle lowering of 8-lane 32-bit floating point shuffles.
10364 ///
10365 /// Also ends up handling lowering of 8-lane 32-bit integer shuffles when AVX2
10366 /// isn't available.
10367 static SDValue lowerV8F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10368                                        const X86Subtarget *Subtarget,
10369                                        SelectionDAG &DAG) {
10370   SDLoc DL(Op);
10371   assert(V1.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
10372   assert(V2.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
10373   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10374   ArrayRef<int> Mask = SVOp->getMask();
10375   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10376
10377   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8f32, V1, V2, Mask,
10378                                                 Subtarget, DAG))
10379     return Blend;
10380
10381   // Check for being able to broadcast a single element.
10382   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8f32, V1,
10383                                                         Mask, Subtarget, DAG))
10384     return Broadcast;
10385
10386   // If the shuffle mask is repeated in each 128-bit lane, we have many more
10387   // options to efficiently lower the shuffle.
10388   SmallVector<int, 4> RepeatedMask;
10389   if (is128BitLaneRepeatedShuffleMask(MVT::v8f32, Mask, RepeatedMask)) {
10390     assert(RepeatedMask.size() == 4 &&
10391            "Repeated masks must be half the mask width!");
10392
10393     // Use even/odd duplicate instructions for masks that match their pattern.
10394     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2, 4, 4, 6, 6}))
10395       return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v8f32, V1);
10396     if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3, 5, 5, 7, 7}))
10397       return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v8f32, V1);
10398
10399     if (isSingleInputShuffleMask(Mask))
10400       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, V1,
10401                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
10402
10403     // Use dedicated unpack instructions for masks that match their pattern.
10404     if (SDValue V =
10405             lowerVectorShuffleWithUNPCK(DL, MVT::v8f32, Mask, V1, V2, DAG))
10406       return V;
10407
10408     // Otherwise, fall back to a SHUFPS sequence. Here it is important that we
10409     // have already handled any direct blends. We also need to squash the
10410     // repeated mask into a simulated v4f32 mask.
10411     for (int i = 0; i < 4; ++i)
10412       if (RepeatedMask[i] >= 8)
10413         RepeatedMask[i] -= 4;
10414     return lowerVectorShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask, V1, V2, DAG);
10415   }
10416
10417   // If we have a single input shuffle with different shuffle patterns in the
10418   // two 128-bit lanes use the variable mask to VPERMILPS.
10419   if (isSingleInputShuffleMask(Mask)) {
10420     SDValue VPermMask[8];
10421     for (int i = 0; i < 8; ++i)
10422       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10423                                  : DAG.getConstant(Mask[i], DL, MVT::i32);
10424     if (!is128BitLaneCrossingShuffleMask(MVT::v8f32, Mask))
10425       return DAG.getNode(
10426           X86ISD::VPERMILPV, DL, MVT::v8f32, V1,
10427           DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask));
10428
10429     if (Subtarget->hasAVX2())
10430       return DAG.getNode(
10431           X86ISD::VPERMV, DL, MVT::v8f32,
10432           DAG.getBitcast(MVT::v8f32, DAG.getNode(ISD::BUILD_VECTOR, DL,
10433                                                  MVT::v8i32, VPermMask)),
10434           V1);
10435
10436     // Otherwise, fall back.
10437     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v8f32, V1, V2, Mask,
10438                                                    DAG);
10439   }
10440
10441   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10442   // shuffle.
10443   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10444           DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
10445     return Result;
10446
10447   // If we have AVX2 then we always want to lower with a blend because at v8 we
10448   // can fully permute the elements.
10449   if (Subtarget->hasAVX2())
10450     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8f32, V1, V2,
10451                                                       Mask, DAG);
10452
10453   // Otherwise fall back on generic lowering.
10454   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask, DAG);
10455 }
10456
10457 /// \brief Handle lowering of 8-lane 32-bit integer shuffles.
10458 ///
10459 /// This routine is only called when we have AVX2 and thus a reasonable
10460 /// instruction set for v8i32 shuffling..
10461 static SDValue lowerV8I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10462                                        const X86Subtarget *Subtarget,
10463                                        SelectionDAG &DAG) {
10464   SDLoc DL(Op);
10465   assert(V1.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10466   assert(V2.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10467   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10468   ArrayRef<int> Mask = SVOp->getMask();
10469   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10470   assert(Subtarget->hasAVX2() && "We can only lower v8i32 with AVX2!");
10471
10472   // Whenever we can lower this as a zext, that instruction is strictly faster
10473   // than any alternative. It also allows us to fold memory operands into the
10474   // shuffle in many cases.
10475   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v8i32, V1, V2,
10476                                                          Mask, Subtarget, DAG))
10477     return ZExt;
10478
10479   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i32, V1, V2, Mask,
10480                                                 Subtarget, DAG))
10481     return Blend;
10482
10483   // Check for being able to broadcast a single element.
10484   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i32, V1,
10485                                                         Mask, Subtarget, DAG))
10486     return Broadcast;
10487
10488   // If the shuffle mask is repeated in each 128-bit lane we can use more
10489   // efficient instructions that mirror the shuffles across the two 128-bit
10490   // lanes.
10491   SmallVector<int, 4> RepeatedMask;
10492   if (is128BitLaneRepeatedShuffleMask(MVT::v8i32, Mask, RepeatedMask)) {
10493     assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
10494     if (isSingleInputShuffleMask(Mask))
10495       return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32, V1,
10496                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
10497
10498     // Use dedicated unpack instructions for masks that match their pattern.
10499     if (SDValue V =
10500             lowerVectorShuffleWithUNPCK(DL, MVT::v8i32, Mask, V1, V2, DAG))
10501       return V;
10502   }
10503
10504   // Try to use shift instructions.
10505   if (SDValue Shift =
10506           lowerVectorShuffleAsShift(DL, MVT::v8i32, V1, V2, Mask, DAG))
10507     return Shift;
10508
10509   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10510           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10511     return Rotate;
10512
10513   // If the shuffle patterns aren't repeated but it is a single input, directly
10514   // generate a cross-lane VPERMD instruction.
10515   if (isSingleInputShuffleMask(Mask)) {
10516     SDValue VPermMask[8];
10517     for (int i = 0; i < 8; ++i)
10518       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10519                                  : DAG.getConstant(Mask[i], DL, MVT::i32);
10520     return DAG.getNode(
10521         X86ISD::VPERMV, DL, MVT::v8i32,
10522         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask), V1);
10523   }
10524
10525   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10526   // shuffle.
10527   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10528           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10529     return Result;
10530
10531   // Otherwise fall back on generic blend lowering.
10532   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i32, V1, V2,
10533                                                     Mask, DAG);
10534 }
10535
10536 /// \brief Handle lowering of 16-lane 16-bit integer shuffles.
10537 ///
10538 /// This routine is only called when we have AVX2 and thus a reasonable
10539 /// instruction set for v16i16 shuffling..
10540 static SDValue lowerV16I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10541                                         const X86Subtarget *Subtarget,
10542                                         SelectionDAG &DAG) {
10543   SDLoc DL(Op);
10544   assert(V1.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10545   assert(V2.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10546   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10547   ArrayRef<int> Mask = SVOp->getMask();
10548   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10549   assert(Subtarget->hasAVX2() && "We can only lower v16i16 with AVX2!");
10550
10551   // Whenever we can lower this as a zext, that instruction is strictly faster
10552   // than any alternative. It also allows us to fold memory operands into the
10553   // shuffle in many cases.
10554   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v16i16, V1, V2,
10555                                                          Mask, Subtarget, DAG))
10556     return ZExt;
10557
10558   // Check for being able to broadcast a single element.
10559   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i16, V1,
10560                                                         Mask, Subtarget, DAG))
10561     return Broadcast;
10562
10563   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i16, V1, V2, Mask,
10564                                                 Subtarget, DAG))
10565     return Blend;
10566
10567   // Use dedicated unpack instructions for masks that match their pattern.
10568   if (SDValue V =
10569           lowerVectorShuffleWithUNPCK(DL, MVT::v16i16, Mask, V1, V2, DAG))
10570     return V;
10571
10572   // Try to use shift instructions.
10573   if (SDValue Shift =
10574           lowerVectorShuffleAsShift(DL, MVT::v16i16, V1, V2, Mask, DAG))
10575     return Shift;
10576
10577   // Try to use byte rotation instructions.
10578   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10579           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10580     return Rotate;
10581
10582   if (isSingleInputShuffleMask(Mask)) {
10583     // There are no generalized cross-lane shuffle operations available on i16
10584     // element types.
10585     if (is128BitLaneCrossingShuffleMask(MVT::v16i16, Mask))
10586       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v16i16, V1, V2,
10587                                                      Mask, DAG);
10588
10589     SmallVector<int, 8> RepeatedMask;
10590     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
10591       // As this is a single-input shuffle, the repeated mask should be
10592       // a strictly valid v8i16 mask that we can pass through to the v8i16
10593       // lowering to handle even the v16 case.
10594       return lowerV8I16GeneralSingleInputVectorShuffle(
10595           DL, MVT::v16i16, V1, RepeatedMask, Subtarget, DAG);
10596     }
10597
10598     SDValue PSHUFBMask[32];
10599     for (int i = 0; i < 16; ++i) {
10600       if (Mask[i] == -1) {
10601         PSHUFBMask[2 * i] = PSHUFBMask[2 * i + 1] = DAG.getUNDEF(MVT::i8);
10602         continue;
10603       }
10604
10605       int M = i < 8 ? Mask[i] : Mask[i] - 8;
10606       assert(M >= 0 && M < 8 && "Invalid single-input mask!");
10607       PSHUFBMask[2 * i] = DAG.getConstant(2 * M, DL, MVT::i8);
10608       PSHUFBMask[2 * i + 1] = DAG.getConstant(2 * M + 1, DL, MVT::i8);
10609     }
10610     return DAG.getBitcast(MVT::v16i16,
10611                           DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8,
10612                                       DAG.getBitcast(MVT::v32i8, V1),
10613                                       DAG.getNode(ISD::BUILD_VECTOR, DL,
10614                                                   MVT::v32i8, PSHUFBMask)));
10615   }
10616
10617   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10618   // shuffle.
10619   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10620           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10621     return Result;
10622
10623   // Otherwise fall back on generic lowering.
10624   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v16i16, V1, V2, Mask, DAG);
10625 }
10626
10627 /// \brief Handle lowering of 32-lane 8-bit integer shuffles.
10628 ///
10629 /// This routine is only called when we have AVX2 and thus a reasonable
10630 /// instruction set for v32i8 shuffling..
10631 static SDValue lowerV32I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10632                                        const X86Subtarget *Subtarget,
10633                                        SelectionDAG &DAG) {
10634   SDLoc DL(Op);
10635   assert(V1.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10636   assert(V2.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10637   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10638   ArrayRef<int> Mask = SVOp->getMask();
10639   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10640   assert(Subtarget->hasAVX2() && "We can only lower v32i8 with AVX2!");
10641
10642   // Whenever we can lower this as a zext, that instruction is strictly faster
10643   // than any alternative. It also allows us to fold memory operands into the
10644   // shuffle in many cases.
10645   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v32i8, V1, V2,
10646                                                          Mask, Subtarget, DAG))
10647     return ZExt;
10648
10649   // Check for being able to broadcast a single element.
10650   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v32i8, V1,
10651                                                         Mask, Subtarget, DAG))
10652     return Broadcast;
10653
10654   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v32i8, V1, V2, Mask,
10655                                                 Subtarget, DAG))
10656     return Blend;
10657
10658   // Use dedicated unpack instructions for masks that match their pattern.
10659   if (SDValue V =
10660           lowerVectorShuffleWithUNPCK(DL, MVT::v32i8, Mask, V1, V2, DAG))
10661     return V;
10662
10663   // Try to use shift instructions.
10664   if (SDValue Shift =
10665           lowerVectorShuffleAsShift(DL, MVT::v32i8, V1, V2, Mask, DAG))
10666     return Shift;
10667
10668   // Try to use byte rotation instructions.
10669   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10670           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
10671     return Rotate;
10672
10673   if (isSingleInputShuffleMask(Mask)) {
10674     // There are no generalized cross-lane shuffle operations available on i8
10675     // element types.
10676     if (is128BitLaneCrossingShuffleMask(MVT::v32i8, Mask))
10677       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v32i8, V1, V2,
10678                                                      Mask, DAG);
10679
10680     SDValue PSHUFBMask[32];
10681     for (int i = 0; i < 32; ++i)
10682       PSHUFBMask[i] =
10683           Mask[i] < 0
10684               ? DAG.getUNDEF(MVT::i8)
10685               : DAG.getConstant(Mask[i] < 16 ? Mask[i] : Mask[i] - 16, DL,
10686                                 MVT::i8);
10687
10688     return DAG.getNode(
10689         X86ISD::PSHUFB, DL, MVT::v32i8, V1,
10690         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask));
10691   }
10692
10693   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10694   // shuffle.
10695   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10696           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
10697     return Result;
10698
10699   // Otherwise fall back on generic lowering.
10700   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v32i8, V1, V2, Mask, DAG);
10701 }
10702
10703 /// \brief High-level routine to lower various 256-bit x86 vector shuffles.
10704 ///
10705 /// This routine either breaks down the specific type of a 256-bit x86 vector
10706 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
10707 /// together based on the available instructions.
10708 static SDValue lower256BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10709                                         MVT VT, const X86Subtarget *Subtarget,
10710                                         SelectionDAG &DAG) {
10711   SDLoc DL(Op);
10712   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10713   ArrayRef<int> Mask = SVOp->getMask();
10714
10715   // If we have a single input to the zero element, insert that into V1 if we
10716   // can do so cheaply.
10717   int NumElts = VT.getVectorNumElements();
10718   int NumV2Elements = std::count_if(Mask.begin(), Mask.end(), [NumElts](int M) {
10719     return M >= NumElts;
10720   });
10721
10722   if (NumV2Elements == 1 && Mask[0] >= NumElts)
10723     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
10724                               DL, VT, V1, V2, Mask, Subtarget, DAG))
10725       return Insertion;
10726
10727   // There is a really nice hard cut-over between AVX1 and AVX2 that means we
10728   // can check for those subtargets here and avoid much of the subtarget
10729   // querying in the per-vector-type lowering routines. With AVX1 we have
10730   // essentially *zero* ability to manipulate a 256-bit vector with integer
10731   // types. Since we'll use floating point types there eventually, just
10732   // immediately cast everything to a float and operate entirely in that domain.
10733   if (VT.isInteger() && !Subtarget->hasAVX2()) {
10734     int ElementBits = VT.getScalarSizeInBits();
10735     if (ElementBits < 32)
10736       // No floating point type available, decompose into 128-bit vectors.
10737       return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10738
10739     MVT FpVT = MVT::getVectorVT(MVT::getFloatingPointVT(ElementBits),
10740                                 VT.getVectorNumElements());
10741     V1 = DAG.getBitcast(FpVT, V1);
10742     V2 = DAG.getBitcast(FpVT, V2);
10743     return DAG.getBitcast(VT, DAG.getVectorShuffle(FpVT, DL, V1, V2, Mask));
10744   }
10745
10746   switch (VT.SimpleTy) {
10747   case MVT::v4f64:
10748     return lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10749   case MVT::v4i64:
10750     return lowerV4I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10751   case MVT::v8f32:
10752     return lowerV8F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10753   case MVT::v8i32:
10754     return lowerV8I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10755   case MVT::v16i16:
10756     return lowerV16I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10757   case MVT::v32i8:
10758     return lowerV32I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10759
10760   default:
10761     llvm_unreachable("Not a valid 256-bit x86 vector type!");
10762   }
10763 }
10764
10765 /// \brief Try to lower a vector shuffle as a 128-bit shuffles.
10766 static SDValue lowerV4X128VectorShuffle(SDLoc DL, MVT VT,
10767                                         ArrayRef<int> Mask,
10768                                         SDValue V1, SDValue V2,
10769                                         SelectionDAG &DAG) {
10770   assert(VT.getScalarSizeInBits() == 64 &&
10771          "Unexpected element type size for 128bit shuffle.");
10772
10773   // To handle 256 bit vector requires VLX and most probably
10774   // function lowerV2X128VectorShuffle() is better solution.
10775   assert(VT.is512BitVector() && "Unexpected vector size for 128bit shuffle.");
10776
10777   SmallVector<int, 4> WidenedMask;
10778   if (!canWidenShuffleElements(Mask, WidenedMask))
10779     return SDValue();
10780
10781   // Form a 128-bit permutation.
10782   // Convert the 64-bit shuffle mask selection values into 128-bit selection
10783   // bits defined by a vshuf64x2 instruction's immediate control byte.
10784   unsigned PermMask = 0, Imm = 0;
10785   unsigned ControlBitsNum = WidenedMask.size() / 2;
10786
10787   for (int i = 0, Size = WidenedMask.size(); i < Size; ++i) {
10788     if (WidenedMask[i] == SM_SentinelZero)
10789       return SDValue();
10790
10791     // Use first element in place of undef mask.
10792     Imm = (WidenedMask[i] == SM_SentinelUndef) ? 0 : WidenedMask[i];
10793     PermMask |= (Imm % WidenedMask.size()) << (i * ControlBitsNum);
10794   }
10795
10796   return DAG.getNode(X86ISD::SHUF128, DL, VT, V1, V2,
10797                      DAG.getConstant(PermMask, DL, MVT::i8));
10798 }
10799
10800 static SDValue lowerVectorShuffleWithPERMV(SDLoc DL, MVT VT,
10801                                            ArrayRef<int> Mask, SDValue V1,
10802                                            SDValue V2, SelectionDAG &DAG) {
10803
10804   assert(VT.getScalarSizeInBits() >= 16 && "Unexpected data type for PERMV");
10805
10806   MVT MaskEltVT = MVT::getIntegerVT(VT.getScalarSizeInBits());
10807   MVT MaskVecVT = MVT::getVectorVT(MaskEltVT, VT.getVectorNumElements());
10808
10809   SDValue MaskNode = getConstVector(Mask, MaskVecVT, DAG, DL, true);
10810   if (isSingleInputShuffleMask(Mask))
10811     return DAG.getNode(X86ISD::VPERMV, DL, VT, MaskNode, V1);
10812
10813   return DAG.getNode(X86ISD::VPERMV3, DL, VT, V1, MaskNode, V2);
10814 }
10815
10816 /// \brief Handle lowering of 8-lane 64-bit floating point shuffles.
10817 static SDValue lowerV8F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10818                                        const X86Subtarget *Subtarget,
10819                                        SelectionDAG &DAG) {
10820   SDLoc DL(Op);
10821   assert(V1.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10822   assert(V2.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10823   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10824   ArrayRef<int> Mask = SVOp->getMask();
10825   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10826
10827   if (SDValue Shuf128 =
10828           lowerV4X128VectorShuffle(DL, MVT::v8f64, Mask, V1, V2, DAG))
10829     return Shuf128;
10830
10831   if (SDValue Unpck =
10832           lowerVectorShuffleWithUNPCK(DL, MVT::v8f64, Mask, V1, V2, DAG))
10833     return Unpck;
10834
10835   return lowerVectorShuffleWithPERMV(DL, MVT::v8f64, Mask, V1, V2, DAG);
10836 }
10837
10838 /// \brief Handle lowering of 16-lane 32-bit floating point shuffles.
10839 static SDValue lowerV16F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10840                                         const X86Subtarget *Subtarget,
10841                                         SelectionDAG &DAG) {
10842   SDLoc DL(Op);
10843   assert(V1.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10844   assert(V2.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10845   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10846   ArrayRef<int> Mask = SVOp->getMask();
10847   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10848
10849   if (SDValue Unpck =
10850           lowerVectorShuffleWithUNPCK(DL, MVT::v16f32, Mask, V1, V2, DAG))
10851     return Unpck;
10852
10853   return lowerVectorShuffleWithPERMV(DL, MVT::v16f32, Mask, V1, V2, DAG);
10854 }
10855
10856 /// \brief Handle lowering of 8-lane 64-bit integer shuffles.
10857 static SDValue lowerV8I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10858                                        const X86Subtarget *Subtarget,
10859                                        SelectionDAG &DAG) {
10860   SDLoc DL(Op);
10861   assert(V1.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10862   assert(V2.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10863   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10864   ArrayRef<int> Mask = SVOp->getMask();
10865   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10866
10867   if (SDValue Shuf128 =
10868           lowerV4X128VectorShuffle(DL, MVT::v8i64, Mask, V1, V2, DAG))
10869     return Shuf128;
10870
10871   if (SDValue Unpck =
10872           lowerVectorShuffleWithUNPCK(DL, MVT::v8i64, Mask, V1, V2, DAG))
10873     return Unpck;
10874
10875   return lowerVectorShuffleWithPERMV(DL, MVT::v8i64, Mask, V1, V2, DAG);
10876 }
10877
10878 /// \brief Handle lowering of 16-lane 32-bit integer shuffles.
10879 static SDValue lowerV16I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10880                                         const X86Subtarget *Subtarget,
10881                                         SelectionDAG &DAG) {
10882   SDLoc DL(Op);
10883   assert(V1.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10884   assert(V2.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10885   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10886   ArrayRef<int> Mask = SVOp->getMask();
10887   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10888
10889   if (SDValue Unpck =
10890           lowerVectorShuffleWithUNPCK(DL, MVT::v16i32, Mask, V1, V2, DAG))
10891     return Unpck;
10892
10893   return lowerVectorShuffleWithPERMV(DL, MVT::v16i32, Mask, V1, V2, DAG);
10894 }
10895
10896 /// \brief Handle lowering of 32-lane 16-bit integer shuffles.
10897 static SDValue lowerV32I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10898                                         const X86Subtarget *Subtarget,
10899                                         SelectionDAG &DAG) {
10900   SDLoc DL(Op);
10901   assert(V1.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10902   assert(V2.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10903   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10904   ArrayRef<int> Mask = SVOp->getMask();
10905   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10906   assert(Subtarget->hasBWI() && "We can only lower v32i16 with AVX-512-BWI!");
10907
10908   return lowerVectorShuffleWithPERMV(DL, MVT::v32i16, Mask, V1, V2, DAG);
10909 }
10910
10911 /// \brief Handle lowering of 64-lane 8-bit integer shuffles.
10912 static SDValue lowerV64I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10913                                        const X86Subtarget *Subtarget,
10914                                        SelectionDAG &DAG) {
10915   SDLoc DL(Op);
10916   assert(V1.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10917   assert(V2.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10918   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10919   ArrayRef<int> Mask = SVOp->getMask();
10920   assert(Mask.size() == 64 && "Unexpected mask size for v64 shuffle!");
10921   assert(Subtarget->hasBWI() && "We can only lower v64i8 with AVX-512-BWI!");
10922
10923   // FIXME: Implement direct support for this type!
10924   return splitAndLowerVectorShuffle(DL, MVT::v64i8, V1, V2, Mask, DAG);
10925 }
10926
10927 /// \brief High-level routine to lower various 512-bit x86 vector shuffles.
10928 ///
10929 /// This routine either breaks down the specific type of a 512-bit x86 vector
10930 /// shuffle or splits it into two 256-bit shuffles and fuses the results back
10931 /// together based on the available instructions.
10932 static SDValue lower512BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10933                                         MVT VT, const X86Subtarget *Subtarget,
10934                                         SelectionDAG &DAG) {
10935   SDLoc DL(Op);
10936   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10937   ArrayRef<int> Mask = SVOp->getMask();
10938   assert(Subtarget->hasAVX512() &&
10939          "Cannot lower 512-bit vectors w/ basic ISA!");
10940
10941   // Check for being able to broadcast a single element.
10942   if (SDValue Broadcast =
10943           lowerVectorShuffleAsBroadcast(DL, VT, V1, Mask, Subtarget, DAG))
10944     return Broadcast;
10945
10946   // Dispatch to each element type for lowering. If we don't have supprot for
10947   // specific element type shuffles at 512 bits, immediately split them and
10948   // lower them. Each lowering routine of a given type is allowed to assume that
10949   // the requisite ISA extensions for that element type are available.
10950   switch (VT.SimpleTy) {
10951   case MVT::v8f64:
10952     return lowerV8F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10953   case MVT::v16f32:
10954     return lowerV16F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10955   case MVT::v8i64:
10956     return lowerV8I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10957   case MVT::v16i32:
10958     return lowerV16I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10959   case MVT::v32i16:
10960     if (Subtarget->hasBWI())
10961       return lowerV32I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10962     break;
10963   case MVT::v64i8:
10964     if (Subtarget->hasBWI())
10965       return lowerV64I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10966     break;
10967
10968   default:
10969     llvm_unreachable("Not a valid 512-bit x86 vector type!");
10970   }
10971
10972   // Otherwise fall back on splitting.
10973   return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10974 }
10975
10976 // Lower vXi1 vector shuffles.
10977 // There is no a dedicated instruction on AVX-512 that shuffles the masks.
10978 // The only way to shuffle bits is to sign-extend the mask vector to SIMD
10979 // vector, shuffle and then truncate it back.
10980 static SDValue lower1BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10981                                       MVT VT, const X86Subtarget *Subtarget,
10982                                       SelectionDAG &DAG) {
10983   SDLoc DL(Op);
10984   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10985   ArrayRef<int> Mask = SVOp->getMask();
10986   assert(Subtarget->hasAVX512() &&
10987          "Cannot lower 512-bit vectors w/o basic ISA!");
10988   MVT ExtVT;
10989   switch (VT.SimpleTy) {
10990   default:
10991     llvm_unreachable("Expected a vector of i1 elements");
10992   case MVT::v2i1:
10993     ExtVT = MVT::v2i64;
10994     break;
10995   case MVT::v4i1:
10996     ExtVT = MVT::v4i32;
10997     break;
10998   case MVT::v8i1:
10999     ExtVT = MVT::v8i64; // Take 512-bit type, more shuffles on KNL
11000     break;
11001   case MVT::v16i1:
11002     ExtVT = MVT::v16i32;
11003     break;
11004   case MVT::v32i1:
11005     ExtVT = MVT::v32i16;
11006     break;
11007   case MVT::v64i1:
11008     ExtVT = MVT::v64i8;
11009     break;
11010   }
11011
11012   if (ISD::isBuildVectorAllZeros(V1.getNode()))
11013     V1 = getZeroVector(ExtVT, Subtarget, DAG, DL);
11014   else if (ISD::isBuildVectorAllOnes(V1.getNode()))
11015     V1 = getOnesVector(ExtVT, Subtarget, DAG, DL);
11016   else
11017     V1 = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, V1);
11018
11019   if (V2.isUndef())
11020     V2 = DAG.getUNDEF(ExtVT);
11021   else if (ISD::isBuildVectorAllZeros(V2.getNode()))
11022     V2 = getZeroVector(ExtVT, Subtarget, DAG, DL);
11023   else if (ISD::isBuildVectorAllOnes(V2.getNode()))
11024     V2 = getOnesVector(ExtVT, Subtarget, DAG, DL);
11025   else
11026     V2 = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, V2);
11027   return DAG.getNode(ISD::TRUNCATE, DL, VT,
11028                      DAG.getVectorShuffle(ExtVT, DL, V1, V2, Mask));
11029 }
11030 /// \brief Top-level lowering for x86 vector shuffles.
11031 ///
11032 /// This handles decomposition, canonicalization, and lowering of all x86
11033 /// vector shuffles. Most of the specific lowering strategies are encapsulated
11034 /// above in helper routines. The canonicalization attempts to widen shuffles
11035 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
11036 /// s.t. only one of the two inputs needs to be tested, etc.
11037 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
11038                                   SelectionDAG &DAG) {
11039   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11040   ArrayRef<int> Mask = SVOp->getMask();
11041   SDValue V1 = Op.getOperand(0);
11042   SDValue V2 = Op.getOperand(1);
11043   MVT VT = Op.getSimpleValueType();
11044   int NumElements = VT.getVectorNumElements();
11045   SDLoc dl(Op);
11046   bool Is1BitVector = (VT.getVectorElementType() == MVT::i1);
11047
11048   assert((VT.getSizeInBits() != 64 || Is1BitVector) &&
11049          "Can't lower MMX shuffles");
11050
11051   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
11052   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
11053   if (V1IsUndef && V2IsUndef)
11054     return DAG.getUNDEF(VT);
11055
11056   // When we create a shuffle node we put the UNDEF node to second operand,
11057   // but in some cases the first operand may be transformed to UNDEF.
11058   // In this case we should just commute the node.
11059   if (V1IsUndef)
11060     return DAG.getCommutedVectorShuffle(*SVOp);
11061
11062   // Check for non-undef masks pointing at an undef vector and make the masks
11063   // undef as well. This makes it easier to match the shuffle based solely on
11064   // the mask.
11065   if (V2IsUndef)
11066     for (int M : Mask)
11067       if (M >= NumElements) {
11068         SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
11069         for (int &M : NewMask)
11070           if (M >= NumElements)
11071             M = -1;
11072         return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
11073       }
11074
11075   // We actually see shuffles that are entirely re-arrangements of a set of
11076   // zero inputs. This mostly happens while decomposing complex shuffles into
11077   // simple ones. Directly lower these as a buildvector of zeros.
11078   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
11079   if (Zeroable.all())
11080     return getZeroVector(VT, Subtarget, DAG, dl);
11081
11082   // Try to collapse shuffles into using a vector type with fewer elements but
11083   // wider element types. We cap this to not form integers or floating point
11084   // elements wider than 64 bits, but it might be interesting to form i128
11085   // integers to handle flipping the low and high halves of AVX 256-bit vectors.
11086   SmallVector<int, 16> WidenedMask;
11087   if (VT.getScalarSizeInBits() < 64 && !Is1BitVector &&
11088       canWidenShuffleElements(Mask, WidenedMask)) {
11089     MVT NewEltVT = VT.isFloatingPoint()
11090                        ? MVT::getFloatingPointVT(VT.getScalarSizeInBits() * 2)
11091                        : MVT::getIntegerVT(VT.getScalarSizeInBits() * 2);
11092     MVT NewVT = MVT::getVectorVT(NewEltVT, VT.getVectorNumElements() / 2);
11093     // Make sure that the new vector type is legal. For example, v2f64 isn't
11094     // legal on SSE1.
11095     if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
11096       V1 = DAG.getBitcast(NewVT, V1);
11097       V2 = DAG.getBitcast(NewVT, V2);
11098       return DAG.getBitcast(
11099           VT, DAG.getVectorShuffle(NewVT, dl, V1, V2, WidenedMask));
11100     }
11101   }
11102
11103   int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
11104   for (int M : SVOp->getMask())
11105     if (M < 0)
11106       ++NumUndefElements;
11107     else if (M < NumElements)
11108       ++NumV1Elements;
11109     else
11110       ++NumV2Elements;
11111
11112   // Commute the shuffle as needed such that more elements come from V1 than
11113   // V2. This allows us to match the shuffle pattern strictly on how many
11114   // elements come from V1 without handling the symmetric cases.
11115   if (NumV2Elements > NumV1Elements)
11116     return DAG.getCommutedVectorShuffle(*SVOp);
11117
11118   // When the number of V1 and V2 elements are the same, try to minimize the
11119   // number of uses of V2 in the low half of the vector. When that is tied,
11120   // ensure that the sum of indices for V1 is equal to or lower than the sum
11121   // indices for V2. When those are equal, try to ensure that the number of odd
11122   // indices for V1 is lower than the number of odd indices for V2.
11123   if (NumV1Elements == NumV2Elements) {
11124     int LowV1Elements = 0, LowV2Elements = 0;
11125     for (int M : SVOp->getMask().slice(0, NumElements / 2))
11126       if (M >= NumElements)
11127         ++LowV2Elements;
11128       else if (M >= 0)
11129         ++LowV1Elements;
11130     if (LowV2Elements > LowV1Elements) {
11131       return DAG.getCommutedVectorShuffle(*SVOp);
11132     } else if (LowV2Elements == LowV1Elements) {
11133       int SumV1Indices = 0, SumV2Indices = 0;
11134       for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
11135         if (SVOp->getMask()[i] >= NumElements)
11136           SumV2Indices += i;
11137         else if (SVOp->getMask()[i] >= 0)
11138           SumV1Indices += i;
11139       if (SumV2Indices < SumV1Indices) {
11140         return DAG.getCommutedVectorShuffle(*SVOp);
11141       } else if (SumV2Indices == SumV1Indices) {
11142         int NumV1OddIndices = 0, NumV2OddIndices = 0;
11143         for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
11144           if (SVOp->getMask()[i] >= NumElements)
11145             NumV2OddIndices += i % 2;
11146           else if (SVOp->getMask()[i] >= 0)
11147             NumV1OddIndices += i % 2;
11148         if (NumV2OddIndices < NumV1OddIndices)
11149           return DAG.getCommutedVectorShuffle(*SVOp);
11150       }
11151     }
11152   }
11153
11154   // For each vector width, delegate to a specialized lowering routine.
11155   if (VT.is128BitVector())
11156     return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
11157
11158   if (VT.is256BitVector())
11159     return lower256BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
11160
11161   if (VT.is512BitVector())
11162     return lower512BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
11163
11164   if (Is1BitVector)
11165     return lower1BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
11166   llvm_unreachable("Unimplemented!");
11167 }
11168
11169 // This function assumes its argument is a BUILD_VECTOR of constants or
11170 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
11171 // true.
11172 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
11173                                     unsigned &MaskValue) {
11174   MaskValue = 0;
11175   unsigned NumElems = BuildVector->getNumOperands();
11176   
11177   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
11178   // We don't handle the >2 lanes case right now.
11179   unsigned NumLanes = (NumElems - 1) / 8 + 1;
11180   if (NumLanes > 2)
11181     return false;
11182
11183   unsigned NumElemsInLane = NumElems / NumLanes;
11184
11185   // Blend for v16i16 should be symmetric for the both lanes.
11186   for (unsigned i = 0; i < NumElemsInLane; ++i) {
11187     SDValue EltCond = BuildVector->getOperand(i);
11188     SDValue SndLaneEltCond =
11189         (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
11190
11191     int Lane1Cond = -1, Lane2Cond = -1;
11192     if (isa<ConstantSDNode>(EltCond))
11193       Lane1Cond = !isZero(EltCond);
11194     if (isa<ConstantSDNode>(SndLaneEltCond))
11195       Lane2Cond = !isZero(SndLaneEltCond);
11196
11197     unsigned LaneMask = 0;
11198     if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
11199       // Lane1Cond != 0, means we want the first argument.
11200       // Lane1Cond == 0, means we want the second argument.
11201       // The encoding of this argument is 0 for the first argument, 1
11202       // for the second. Therefore, invert the condition.
11203       LaneMask = !Lane1Cond << i;
11204     else if (Lane1Cond < 0)
11205       LaneMask = !Lane2Cond << i;
11206     else
11207       return false;
11208
11209     MaskValue |= LaneMask;
11210     if (NumLanes == 2)
11211       MaskValue |= LaneMask << NumElemsInLane;
11212   }
11213   return true;
11214 }
11215
11216 /// \brief Try to lower a VSELECT instruction to a vector shuffle.
11217 static SDValue lowerVSELECTtoVectorShuffle(SDValue Op,
11218                                            const X86Subtarget *Subtarget,
11219                                            SelectionDAG &DAG) {
11220   SDValue Cond = Op.getOperand(0);
11221   SDValue LHS = Op.getOperand(1);
11222   SDValue RHS = Op.getOperand(2);
11223   SDLoc dl(Op);
11224   MVT VT = Op.getSimpleValueType();
11225
11226   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
11227     return SDValue();
11228   auto *CondBV = cast<BuildVectorSDNode>(Cond);
11229
11230   // Only non-legal VSELECTs reach this lowering, convert those into generic
11231   // shuffles and re-use the shuffle lowering path for blends.
11232   SmallVector<int, 32> Mask;
11233   for (int i = 0, Size = VT.getVectorNumElements(); i < Size; ++i) {
11234     SDValue CondElt = CondBV->getOperand(i);
11235     Mask.push_back(
11236         isa<ConstantSDNode>(CondElt) ? i + (isZero(CondElt) ? Size : 0) : -1);
11237   }
11238   return DAG.getVectorShuffle(VT, dl, LHS, RHS, Mask);
11239 }
11240
11241 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
11242   // A vselect where all conditions and data are constants can be optimized into
11243   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
11244   if (ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(0).getNode()) &&
11245       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(1).getNode()) &&
11246       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(2).getNode()))
11247     return SDValue();
11248
11249   // Try to lower this to a blend-style vector shuffle. This can handle all
11250   // constant condition cases.
11251   if (SDValue BlendOp = lowerVSELECTtoVectorShuffle(Op, Subtarget, DAG))
11252     return BlendOp;
11253
11254   // Variable blends are only legal from SSE4.1 onward.
11255   if (!Subtarget->hasSSE41())
11256     return SDValue();
11257
11258   // Only some types will be legal on some subtargets. If we can emit a legal
11259   // VSELECT-matching blend, return Op, and but if we need to expand, return
11260   // a null value.
11261   switch (Op.getSimpleValueType().SimpleTy) {
11262   default:
11263     // Most of the vector types have blends past SSE4.1.
11264     return Op;
11265
11266   case MVT::v32i8:
11267     // The byte blends for AVX vectors were introduced only in AVX2.
11268     if (Subtarget->hasAVX2())
11269       return Op;
11270
11271     return SDValue();
11272
11273   case MVT::v8i16:
11274   case MVT::v16i16:
11275     // AVX-512 BWI and VLX features support VSELECT with i16 elements.
11276     if (Subtarget->hasBWI() && Subtarget->hasVLX())
11277       return Op;
11278
11279     // FIXME: We should custom lower this by fixing the condition and using i8
11280     // blends.
11281     return SDValue();
11282   }
11283 }
11284
11285 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
11286   MVT VT = Op.getSimpleValueType();
11287   SDLoc dl(Op);
11288
11289   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
11290     return SDValue();
11291
11292   if (VT.getSizeInBits() == 8) {
11293     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
11294                                   Op.getOperand(0), Op.getOperand(1));
11295     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
11296                                   DAG.getValueType(VT));
11297     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
11298   }
11299
11300   if (VT.getSizeInBits() == 16) {
11301     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11302     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
11303     if (Idx == 0)
11304       return DAG.getNode(
11305           ISD::TRUNCATE, dl, MVT::i16,
11306           DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
11307                       DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
11308                       Op.getOperand(1)));
11309     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
11310                                   Op.getOperand(0), Op.getOperand(1));
11311     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
11312                                   DAG.getValueType(VT));
11313     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
11314   }
11315
11316   if (VT == MVT::f32) {
11317     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
11318     // the result back to FR32 register. It's only worth matching if the
11319     // result has a single use which is a store or a bitcast to i32.  And in
11320     // the case of a store, it's not worth it if the index is a constant 0,
11321     // because a MOVSSmr can be used instead, which is smaller and faster.
11322     if (!Op.hasOneUse())
11323       return SDValue();
11324     SDNode *User = *Op.getNode()->use_begin();
11325     if ((User->getOpcode() != ISD::STORE ||
11326          (isa<ConstantSDNode>(Op.getOperand(1)) &&
11327           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
11328         (User->getOpcode() != ISD::BITCAST ||
11329          User->getValueType(0) != MVT::i32))
11330       return SDValue();
11331     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
11332                                   DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
11333                                   Op.getOperand(1));
11334     return DAG.getBitcast(MVT::f32, Extract);
11335   }
11336
11337   if (VT == MVT::i32 || VT == MVT::i64) {
11338     // ExtractPS/pextrq works with constant index.
11339     if (isa<ConstantSDNode>(Op.getOperand(1)))
11340       return Op;
11341   }
11342   return SDValue();
11343 }
11344
11345 /// Extract one bit from mask vector, like v16i1 or v8i1.
11346 /// AVX-512 feature.
11347 SDValue
11348 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
11349   SDValue Vec = Op.getOperand(0);
11350   SDLoc dl(Vec);
11351   MVT VecVT = Vec.getSimpleValueType();
11352   SDValue Idx = Op.getOperand(1);
11353   MVT EltVT = Op.getSimpleValueType();
11354
11355   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
11356   assert((VecVT.getVectorNumElements() <= 16 || Subtarget->hasBWI()) &&
11357          "Unexpected vector type in ExtractBitFromMaskVector");
11358
11359   // variable index can't be handled in mask registers,
11360   // extend vector to VR512
11361   if (!isa<ConstantSDNode>(Idx)) {
11362     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
11363     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
11364     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
11365                               ExtVT.getVectorElementType(), Ext, Idx);
11366     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
11367   }
11368
11369   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11370   const TargetRegisterClass* rc = getRegClassFor(VecVT);
11371   if (!Subtarget->hasDQI() && (VecVT.getVectorNumElements() <= 8))
11372     rc = getRegClassFor(MVT::v16i1);
11373   unsigned MaxSift = rc->getSize()*8 - 1;
11374   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
11375                     DAG.getConstant(MaxSift - IdxVal, dl, MVT::i8));
11376   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
11377                     DAG.getConstant(MaxSift, dl, MVT::i8));
11378   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
11379                        DAG.getIntPtrConstant(0, dl));
11380 }
11381
11382 SDValue
11383 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
11384                                            SelectionDAG &DAG) const {
11385   SDLoc dl(Op);
11386   SDValue Vec = Op.getOperand(0);
11387   MVT VecVT = Vec.getSimpleValueType();
11388   SDValue Idx = Op.getOperand(1);
11389
11390   if (Op.getSimpleValueType() == MVT::i1)
11391     return ExtractBitFromMaskVector(Op, DAG);
11392
11393   if (!isa<ConstantSDNode>(Idx)) {
11394     if (VecVT.is512BitVector() ||
11395         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
11396          VecVT.getVectorElementType().getSizeInBits() == 32)) {
11397
11398       MVT MaskEltVT =
11399         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
11400       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
11401                                     MaskEltVT.getSizeInBits());
11402
11403       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
11404       auto PtrVT = getPointerTy(DAG.getDataLayout());
11405       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
11406                                  getZeroVector(MaskVT, Subtarget, DAG, dl), Idx,
11407                                  DAG.getConstant(0, dl, PtrVT));
11408       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
11409       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Perm,
11410                          DAG.getConstant(0, dl, PtrVT));
11411     }
11412     return SDValue();
11413   }
11414
11415   // If this is a 256-bit vector result, first extract the 128-bit vector and
11416   // then extract the element from the 128-bit vector.
11417   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
11418
11419     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11420     // Get the 128-bit vector.
11421     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
11422     MVT EltVT = VecVT.getVectorElementType();
11423
11424     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
11425     assert(isPowerOf2_32(ElemsPerChunk) && "Elements per chunk not power of 2");
11426
11427     // Find IdxVal modulo ElemsPerChunk. Since ElemsPerChunk is a power of 2
11428     // this can be done with a mask.
11429     IdxVal &= ElemsPerChunk - 1;
11430     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
11431                        DAG.getConstant(IdxVal, dl, MVT::i32));
11432   }
11433
11434   assert(VecVT.is128BitVector() && "Unexpected vector length");
11435
11436   if (Subtarget->hasSSE41())
11437     if (SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG))
11438       return Res;
11439
11440   MVT VT = Op.getSimpleValueType();
11441   // TODO: handle v16i8.
11442   if (VT.getSizeInBits() == 16) {
11443     SDValue Vec = Op.getOperand(0);
11444     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11445     if (Idx == 0)
11446       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
11447                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
11448                                      DAG.getBitcast(MVT::v4i32, Vec),
11449                                      Op.getOperand(1)));
11450     // Transform it so it match pextrw which produces a 32-bit result.
11451     MVT EltVT = MVT::i32;
11452     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
11453                                   Op.getOperand(0), Op.getOperand(1));
11454     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
11455                                   DAG.getValueType(VT));
11456     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
11457   }
11458
11459   if (VT.getSizeInBits() == 32) {
11460     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11461     if (Idx == 0)
11462       return Op;
11463
11464     // SHUFPS the element to the lowest double word, then movss.
11465     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
11466     MVT VVT = Op.getOperand(0).getSimpleValueType();
11467     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
11468                                        DAG.getUNDEF(VVT), Mask);
11469     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
11470                        DAG.getIntPtrConstant(0, dl));
11471   }
11472
11473   if (VT.getSizeInBits() == 64) {
11474     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
11475     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
11476     //        to match extract_elt for f64.
11477     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11478     if (Idx == 0)
11479       return Op;
11480
11481     // UNPCKHPD the element to the lowest double word, then movsd.
11482     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
11483     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
11484     int Mask[2] = { 1, -1 };
11485     MVT VVT = Op.getOperand(0).getSimpleValueType();
11486     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
11487                                        DAG.getUNDEF(VVT), Mask);
11488     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
11489                        DAG.getIntPtrConstant(0, dl));
11490   }
11491
11492   return SDValue();
11493 }
11494
11495 /// Insert one bit to mask vector, like v16i1 or v8i1.
11496 /// AVX-512 feature.
11497 SDValue
11498 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
11499   SDLoc dl(Op);
11500   SDValue Vec = Op.getOperand(0);
11501   SDValue Elt = Op.getOperand(1);
11502   SDValue Idx = Op.getOperand(2);
11503   MVT VecVT = Vec.getSimpleValueType();
11504
11505   if (!isa<ConstantSDNode>(Idx)) {
11506     // Non constant index. Extend source and destination,
11507     // insert element and then truncate the result.
11508     MVT ExtVecVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
11509     MVT ExtEltVT = (VecVT == MVT::v8i1 ?  MVT::i64 : MVT::i32);
11510     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
11511       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
11512       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
11513     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
11514   }
11515
11516   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11517   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
11518   if (IdxVal)
11519     EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
11520                            DAG.getConstant(IdxVal, dl, MVT::i8));
11521   if (Vec.getOpcode() == ISD::UNDEF)
11522     return EltInVec;
11523   return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
11524 }
11525
11526 SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
11527                                                   SelectionDAG &DAG) const {
11528   MVT VT = Op.getSimpleValueType();
11529   MVT EltVT = VT.getVectorElementType();
11530
11531   if (EltVT == MVT::i1)
11532     return InsertBitToMaskVector(Op, DAG);
11533
11534   SDLoc dl(Op);
11535   SDValue N0 = Op.getOperand(0);
11536   SDValue N1 = Op.getOperand(1);
11537   SDValue N2 = Op.getOperand(2);
11538   if (!isa<ConstantSDNode>(N2))
11539     return SDValue();
11540   auto *N2C = cast<ConstantSDNode>(N2);
11541   unsigned IdxVal = N2C->getZExtValue();
11542
11543   // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
11544   // into that, and then insert the subvector back into the result.
11545   if (VT.is256BitVector() || VT.is512BitVector()) {
11546     // With a 256-bit vector, we can insert into the zero element efficiently
11547     // using a blend if we have AVX or AVX2 and the right data type.
11548     if (VT.is256BitVector() && IdxVal == 0) {
11549       // TODO: It is worthwhile to cast integer to floating point and back
11550       // and incur a domain crossing penalty if that's what we'll end up
11551       // doing anyway after extracting to a 128-bit vector.
11552       if ((Subtarget->hasAVX() && (EltVT == MVT::f64 || EltVT == MVT::f32)) ||
11553           (Subtarget->hasAVX2() && EltVT == MVT::i32)) {
11554         SDValue N1Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, N1);
11555         N2 = DAG.getIntPtrConstant(1, dl);
11556         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1Vec, N2);
11557       }
11558     }
11559
11560     // Get the desired 128-bit vector chunk.
11561     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
11562
11563     // Insert the element into the desired chunk.
11564     unsigned NumEltsIn128 = 128 / EltVT.getSizeInBits();
11565     assert(isPowerOf2_32(NumEltsIn128));
11566     // Since NumEltsIn128 is a power of 2 we can use mask instead of modulo.
11567     unsigned IdxIn128 = IdxVal & (NumEltsIn128 - 1);
11568
11569     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
11570                     DAG.getConstant(IdxIn128, dl, MVT::i32));
11571
11572     // Insert the changed part back into the bigger vector
11573     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
11574   }
11575   assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
11576
11577   if (Subtarget->hasSSE41()) {
11578     if (EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) {
11579       unsigned Opc;
11580       if (VT == MVT::v8i16) {
11581         Opc = X86ISD::PINSRW;
11582       } else {
11583         assert(VT == MVT::v16i8);
11584         Opc = X86ISD::PINSRB;
11585       }
11586
11587       // Transform it so it match pinsr{b,w} which expects a GR32 as its second
11588       // argument.
11589       if (N1.getValueType() != MVT::i32)
11590         N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11591       if (N2.getValueType() != MVT::i32)
11592         N2 = DAG.getIntPtrConstant(IdxVal, dl);
11593       return DAG.getNode(Opc, dl, VT, N0, N1, N2);
11594     }
11595
11596     if (EltVT == MVT::f32) {
11597       // Bits [7:6] of the constant are the source select. This will always be
11598       //   zero here. The DAG Combiner may combine an extract_elt index into
11599       //   these bits. For example (insert (extract, 3), 2) could be matched by
11600       //   putting the '3' into bits [7:6] of X86ISD::INSERTPS.
11601       // Bits [5:4] of the constant are the destination select. This is the
11602       //   value of the incoming immediate.
11603       // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
11604       //   combine either bitwise AND or insert of float 0.0 to set these bits.
11605
11606       bool MinSize = DAG.getMachineFunction().getFunction()->optForMinSize();
11607       if (IdxVal == 0 && (!MinSize || !MayFoldLoad(N1))) {
11608         // If this is an insertion of 32-bits into the low 32-bits of
11609         // a vector, we prefer to generate a blend with immediate rather
11610         // than an insertps. Blends are simpler operations in hardware and so
11611         // will always have equal or better performance than insertps.
11612         // But if optimizing for size and there's a load folding opportunity,
11613         // generate insertps because blendps does not have a 32-bit memory
11614         // operand form.
11615         N2 = DAG.getIntPtrConstant(1, dl);
11616         N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11617         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1, N2);
11618       }
11619       N2 = DAG.getIntPtrConstant(IdxVal << 4, dl);
11620       // Create this as a scalar to vector..
11621       N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11622       return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
11623     }
11624
11625     if (EltVT == MVT::i32 || EltVT == MVT::i64) {
11626       // PINSR* works with constant index.
11627       return Op;
11628     }
11629   }
11630
11631   if (EltVT == MVT::i8)
11632     return SDValue();
11633
11634   if (EltVT.getSizeInBits() == 16) {
11635     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
11636     // as its second argument.
11637     if (N1.getValueType() != MVT::i32)
11638       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11639     if (N2.getValueType() != MVT::i32)
11640       N2 = DAG.getIntPtrConstant(IdxVal, dl);
11641     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
11642   }
11643   return SDValue();
11644 }
11645
11646 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
11647   SDLoc dl(Op);
11648   MVT OpVT = Op.getSimpleValueType();
11649
11650   // If this is a 256-bit vector result, first insert into a 128-bit
11651   // vector and then insert into the 256-bit vector.
11652   if (!OpVT.is128BitVector()) {
11653     // Insert into a 128-bit vector.
11654     unsigned SizeFactor = OpVT.getSizeInBits()/128;
11655     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
11656                                  OpVT.getVectorNumElements() / SizeFactor);
11657
11658     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
11659
11660     // Insert the 128-bit vector.
11661     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
11662   }
11663
11664   if (OpVT == MVT::v1i64 &&
11665       Op.getOperand(0).getValueType() == MVT::i64)
11666     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
11667
11668   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
11669   assert(OpVT.is128BitVector() && "Expected an SSE type!");
11670   return DAG.getBitcast(
11671       OpVT, DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, AnyExt));
11672 }
11673
11674 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
11675 // a simple subregister reference or explicit instructions to grab
11676 // upper bits of a vector.
11677 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
11678                                       SelectionDAG &DAG) {
11679   SDLoc dl(Op);
11680   SDValue In =  Op.getOperand(0);
11681   SDValue Idx = Op.getOperand(1);
11682   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11683   MVT ResVT   = Op.getSimpleValueType();
11684   MVT InVT    = In.getSimpleValueType();
11685
11686   if (Subtarget->hasFp256()) {
11687     if (ResVT.is128BitVector() &&
11688         (InVT.is256BitVector() || InVT.is512BitVector()) &&
11689         isa<ConstantSDNode>(Idx)) {
11690       return Extract128BitVector(In, IdxVal, DAG, dl);
11691     }
11692     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
11693         isa<ConstantSDNode>(Idx)) {
11694       return Extract256BitVector(In, IdxVal, DAG, dl);
11695     }
11696   }
11697   return SDValue();
11698 }
11699
11700 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
11701 // simple superregister reference or explicit instructions to insert
11702 // the upper bits of a vector.
11703 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
11704                                      SelectionDAG &DAG) {
11705   if (!Subtarget->hasAVX())
11706     return SDValue();
11707
11708   SDLoc dl(Op);
11709   SDValue Vec = Op.getOperand(0);
11710   SDValue SubVec = Op.getOperand(1);
11711   SDValue Idx = Op.getOperand(2);
11712
11713   if (!isa<ConstantSDNode>(Idx))
11714     return SDValue();
11715
11716   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11717   MVT OpVT = Op.getSimpleValueType();
11718   MVT SubVecVT = SubVec.getSimpleValueType();
11719
11720   // Fold two 16-byte subvector loads into one 32-byte load:
11721   // (insert_subvector (insert_subvector undef, (load addr), 0),
11722   //                   (load addr + 16), Elts/2)
11723   // --> load32 addr
11724   if ((IdxVal == OpVT.getVectorNumElements() / 2) &&
11725       Vec.getOpcode() == ISD::INSERT_SUBVECTOR &&
11726       OpVT.is256BitVector() && SubVecVT.is128BitVector()) {
11727     auto *Idx2 = dyn_cast<ConstantSDNode>(Vec.getOperand(2));
11728     if (Idx2 && Idx2->getZExtValue() == 0) {
11729       SDValue SubVec2 = Vec.getOperand(1);
11730       // If needed, look through a bitcast to get to the load.
11731       if (SubVec2.getNode() && SubVec2.getOpcode() == ISD::BITCAST)
11732         SubVec2 = SubVec2.getOperand(0);
11733
11734       if (auto *FirstLd = dyn_cast<LoadSDNode>(SubVec2)) {
11735         bool Fast;
11736         unsigned Alignment = FirstLd->getAlignment();
11737         unsigned AS = FirstLd->getAddressSpace();
11738         const X86TargetLowering *TLI = Subtarget->getTargetLowering();
11739         if (TLI->allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(),
11740                                     OpVT, AS, Alignment, &Fast) && Fast) {
11741           SDValue Ops[] = { SubVec2, SubVec };
11742           if (SDValue Ld = EltsFromConsecutiveLoads(OpVT, Ops, dl, DAG, false))
11743             return Ld;
11744         }
11745       }
11746     }
11747   }
11748
11749   if ((OpVT.is256BitVector() || OpVT.is512BitVector()) &&
11750       SubVecVT.is128BitVector())
11751     return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
11752
11753   if (OpVT.is512BitVector() && SubVecVT.is256BitVector())
11754     return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
11755
11756   if (OpVT.getVectorElementType() == MVT::i1) {
11757     if (IdxVal == 0  && Vec.getOpcode() == ISD::UNDEF) // the operation is legal
11758       return Op;
11759     SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
11760     SDValue Undef = DAG.getUNDEF(OpVT);
11761     unsigned NumElems = OpVT.getVectorNumElements();
11762     SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
11763
11764     if (IdxVal == OpVT.getVectorNumElements() / 2) {
11765       // Zero upper bits of the Vec
11766       Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
11767       Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
11768
11769       SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
11770                                  SubVec, ZeroIdx);
11771       Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
11772       return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
11773     }
11774     if (IdxVal == 0) {
11775       SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
11776                                  SubVec, ZeroIdx);
11777       // Zero upper bits of the Vec2
11778       Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
11779       Vec2 = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec2, ShiftBits);
11780       // Zero lower bits of the Vec
11781       Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
11782       Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
11783       // Merge them together
11784       return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
11785     }
11786   }
11787   return SDValue();
11788 }
11789
11790 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
11791 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
11792 // one of the above mentioned nodes. It has to be wrapped because otherwise
11793 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
11794 // be used to form addressing mode. These wrapped nodes will be selected
11795 // into MOV32ri.
11796 SDValue
11797 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
11798   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
11799
11800   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11801   // global base reg.
11802   unsigned char OpFlag = 0;
11803   unsigned WrapperKind = X86ISD::Wrapper;
11804   CodeModel::Model M = DAG.getTarget().getCodeModel();
11805
11806   if (Subtarget->isPICStyleRIPRel() &&
11807       (M == CodeModel::Small || M == CodeModel::Kernel))
11808     WrapperKind = X86ISD::WrapperRIP;
11809   else if (Subtarget->isPICStyleGOT())
11810     OpFlag = X86II::MO_GOTOFF;
11811   else if (Subtarget->isPICStyleStubPIC())
11812     OpFlag = X86II::MO_PIC_BASE_OFFSET;
11813
11814   auto PtrVT = getPointerTy(DAG.getDataLayout());
11815   SDValue Result = DAG.getTargetConstantPool(
11816       CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(), OpFlag);
11817   SDLoc DL(CP);
11818   Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11819   // With PIC, the address is actually $g + Offset.
11820   if (OpFlag) {
11821     Result =
11822         DAG.getNode(ISD::ADD, DL, PtrVT,
11823                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11824   }
11825
11826   return Result;
11827 }
11828
11829 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
11830   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
11831
11832   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11833   // global base reg.
11834   unsigned char OpFlag = 0;
11835   unsigned WrapperKind = X86ISD::Wrapper;
11836   CodeModel::Model M = DAG.getTarget().getCodeModel();
11837
11838   if (Subtarget->isPICStyleRIPRel() &&
11839       (M == CodeModel::Small || M == CodeModel::Kernel))
11840     WrapperKind = X86ISD::WrapperRIP;
11841   else if (Subtarget->isPICStyleGOT())
11842     OpFlag = X86II::MO_GOTOFF;
11843   else if (Subtarget->isPICStyleStubPIC())
11844     OpFlag = X86II::MO_PIC_BASE_OFFSET;
11845
11846   auto PtrVT = getPointerTy(DAG.getDataLayout());
11847   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, OpFlag);
11848   SDLoc DL(JT);
11849   Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11850
11851   // With PIC, the address is actually $g + Offset.
11852   if (OpFlag)
11853     Result =
11854         DAG.getNode(ISD::ADD, DL, PtrVT,
11855                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11856
11857   return Result;
11858 }
11859
11860 SDValue
11861 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
11862   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
11863
11864   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11865   // global base reg.
11866   unsigned char OpFlag = 0;
11867   unsigned WrapperKind = X86ISD::Wrapper;
11868   CodeModel::Model M = DAG.getTarget().getCodeModel();
11869
11870   if (Subtarget->isPICStyleRIPRel() &&
11871       (M == CodeModel::Small || M == CodeModel::Kernel)) {
11872     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
11873       OpFlag = X86II::MO_GOTPCREL;
11874     WrapperKind = X86ISD::WrapperRIP;
11875   } else if (Subtarget->isPICStyleGOT()) {
11876     OpFlag = X86II::MO_GOT;
11877   } else if (Subtarget->isPICStyleStubPIC()) {
11878     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
11879   } else if (Subtarget->isPICStyleStubNoDynamic()) {
11880     OpFlag = X86II::MO_DARWIN_NONLAZY;
11881   }
11882
11883   auto PtrVT = getPointerTy(DAG.getDataLayout());
11884   SDValue Result = DAG.getTargetExternalSymbol(Sym, PtrVT, OpFlag);
11885
11886   SDLoc DL(Op);
11887   Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11888
11889   // With PIC, the address is actually $g + Offset.
11890   if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
11891       !Subtarget->is64Bit()) {
11892     Result =
11893         DAG.getNode(ISD::ADD, DL, PtrVT,
11894                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11895   }
11896
11897   // For symbols that require a load from a stub to get the address, emit the
11898   // load.
11899   if (isGlobalStubReference(OpFlag))
11900     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
11901                          MachinePointerInfo::getGOT(DAG.getMachineFunction()),
11902                          false, false, false, 0);
11903
11904   return Result;
11905 }
11906
11907 SDValue
11908 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
11909   // Create the TargetBlockAddressAddress node.
11910   unsigned char OpFlags =
11911     Subtarget->ClassifyBlockAddressReference();
11912   CodeModel::Model M = DAG.getTarget().getCodeModel();
11913   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
11914   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
11915   SDLoc dl(Op);
11916   auto PtrVT = getPointerTy(DAG.getDataLayout());
11917   SDValue Result = DAG.getTargetBlockAddress(BA, PtrVT, Offset, OpFlags);
11918
11919   if (Subtarget->isPICStyleRIPRel() &&
11920       (M == CodeModel::Small || M == CodeModel::Kernel))
11921     Result = DAG.getNode(X86ISD::WrapperRIP, dl, PtrVT, Result);
11922   else
11923     Result = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, Result);
11924
11925   // With PIC, the address is actually $g + Offset.
11926   if (isGlobalRelativeToPICBase(OpFlags)) {
11927     Result = DAG.getNode(ISD::ADD, dl, PtrVT,
11928                          DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
11929   }
11930
11931   return Result;
11932 }
11933
11934 SDValue
11935 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
11936                                       int64_t Offset, SelectionDAG &DAG) const {
11937   // Create the TargetGlobalAddress node, folding in the constant
11938   // offset if it is legal.
11939   unsigned char OpFlags =
11940       Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
11941   CodeModel::Model M = DAG.getTarget().getCodeModel();
11942   auto PtrVT = getPointerTy(DAG.getDataLayout());
11943   SDValue Result;
11944   if (OpFlags == X86II::MO_NO_FLAG &&
11945       X86::isOffsetSuitableForCodeModel(Offset, M)) {
11946     // A direct static reference to a global.
11947     Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, Offset);
11948     Offset = 0;
11949   } else {
11950     Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, OpFlags);
11951   }
11952
11953   if (Subtarget->isPICStyleRIPRel() &&
11954       (M == CodeModel::Small || M == CodeModel::Kernel))
11955     Result = DAG.getNode(X86ISD::WrapperRIP, dl, PtrVT, Result);
11956   else
11957     Result = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, Result);
11958
11959   // With PIC, the address is actually $g + Offset.
11960   if (isGlobalRelativeToPICBase(OpFlags)) {
11961     Result = DAG.getNode(ISD::ADD, dl, PtrVT,
11962                          DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
11963   }
11964
11965   // For globals that require a load from a stub to get the address, emit the
11966   // load.
11967   if (isGlobalStubReference(OpFlags))
11968     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
11969                          MachinePointerInfo::getGOT(DAG.getMachineFunction()),
11970                          false, false, false, 0);
11971
11972   // If there was a non-zero offset that we didn't fold, create an explicit
11973   // addition for it.
11974   if (Offset != 0)
11975     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result,
11976                          DAG.getConstant(Offset, dl, PtrVT));
11977
11978   return Result;
11979 }
11980
11981 SDValue
11982 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
11983   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
11984   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
11985   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
11986 }
11987
11988 static SDValue
11989 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
11990            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
11991            unsigned char OperandFlags, bool LocalDynamic = false) {
11992   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11993   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11994   SDLoc dl(GA);
11995   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11996                                            GA->getValueType(0),
11997                                            GA->getOffset(),
11998                                            OperandFlags);
11999
12000   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
12001                                            : X86ISD::TLSADDR;
12002
12003   if (InFlag) {
12004     SDValue Ops[] = { Chain,  TGA, *InFlag };
12005     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
12006   } else {
12007     SDValue Ops[]  = { Chain, TGA };
12008     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
12009   }
12010
12011   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
12012   MFI->setAdjustsStack(true);
12013   MFI->setHasCalls(true);
12014
12015   SDValue Flag = Chain.getValue(1);
12016   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
12017 }
12018
12019 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
12020 static SDValue
12021 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
12022                                 const EVT PtrVT) {
12023   SDValue InFlag;
12024   SDLoc dl(GA);  // ? function entry point might be better
12025   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
12026                                    DAG.getNode(X86ISD::GlobalBaseReg,
12027                                                SDLoc(), PtrVT), InFlag);
12028   InFlag = Chain.getValue(1);
12029
12030   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
12031 }
12032
12033 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
12034 static SDValue
12035 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
12036                                 const EVT PtrVT) {
12037   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
12038                     X86::RAX, X86II::MO_TLSGD);
12039 }
12040
12041 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
12042                                            SelectionDAG &DAG,
12043                                            const EVT PtrVT,
12044                                            bool is64Bit) {
12045   SDLoc dl(GA);
12046
12047   // Get the start address of the TLS block for this module.
12048   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
12049       .getInfo<X86MachineFunctionInfo>();
12050   MFI->incNumLocalDynamicTLSAccesses();
12051
12052   SDValue Base;
12053   if (is64Bit) {
12054     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
12055                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
12056   } else {
12057     SDValue InFlag;
12058     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
12059         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
12060     InFlag = Chain.getValue(1);
12061     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
12062                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
12063   }
12064
12065   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
12066   // of Base.
12067
12068   // Build x@dtpoff.
12069   unsigned char OperandFlags = X86II::MO_DTPOFF;
12070   unsigned WrapperKind = X86ISD::Wrapper;
12071   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
12072                                            GA->getValueType(0),
12073                                            GA->getOffset(), OperandFlags);
12074   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
12075
12076   // Add x@dtpoff with the base.
12077   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
12078 }
12079
12080 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
12081 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
12082                                    const EVT PtrVT, TLSModel::Model model,
12083                                    bool is64Bit, bool isPIC) {
12084   SDLoc dl(GA);
12085
12086   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
12087   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
12088                                                          is64Bit ? 257 : 256));
12089
12090   SDValue ThreadPointer =
12091       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0, dl),
12092                   MachinePointerInfo(Ptr), false, false, false, 0);
12093
12094   unsigned char OperandFlags = 0;
12095   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
12096   // initialexec.
12097   unsigned WrapperKind = X86ISD::Wrapper;
12098   if (model == TLSModel::LocalExec) {
12099     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
12100   } else if (model == TLSModel::InitialExec) {
12101     if (is64Bit) {
12102       OperandFlags = X86II::MO_GOTTPOFF;
12103       WrapperKind = X86ISD::WrapperRIP;
12104     } else {
12105       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
12106     }
12107   } else {
12108     llvm_unreachable("Unexpected model");
12109   }
12110
12111   // emit "addl x@ntpoff,%eax" (local exec)
12112   // or "addl x@indntpoff,%eax" (initial exec)
12113   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
12114   SDValue TGA =
12115       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
12116                                  GA->getOffset(), OperandFlags);
12117   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
12118
12119   if (model == TLSModel::InitialExec) {
12120     if (isPIC && !is64Bit) {
12121       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
12122                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
12123                            Offset);
12124     }
12125
12126     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
12127                          MachinePointerInfo::getGOT(DAG.getMachineFunction()),
12128                          false, false, false, 0);
12129   }
12130
12131   // The address of the thread local variable is the add of the thread
12132   // pointer with the offset of the variable.
12133   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
12134 }
12135
12136 SDValue
12137 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
12138
12139   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
12140   const GlobalValue *GV = GA->getGlobal();
12141   auto PtrVT = getPointerTy(DAG.getDataLayout());
12142
12143   if (Subtarget->isTargetELF()) {
12144     if (DAG.getTarget().Options.EmulatedTLS)
12145       return LowerToTLSEmulatedModel(GA, DAG);
12146     TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
12147     switch (model) {
12148       case TLSModel::GeneralDynamic:
12149         if (Subtarget->is64Bit())
12150           return LowerToTLSGeneralDynamicModel64(GA, DAG, PtrVT);
12151         return LowerToTLSGeneralDynamicModel32(GA, DAG, PtrVT);
12152       case TLSModel::LocalDynamic:
12153         return LowerToTLSLocalDynamicModel(GA, DAG, PtrVT,
12154                                            Subtarget->is64Bit());
12155       case TLSModel::InitialExec:
12156       case TLSModel::LocalExec:
12157         return LowerToTLSExecModel(GA, DAG, PtrVT, model, Subtarget->is64Bit(),
12158                                    DAG.getTarget().getRelocationModel() ==
12159                                        Reloc::PIC_);
12160     }
12161     llvm_unreachable("Unknown TLS model.");
12162   }
12163
12164   if (Subtarget->isTargetDarwin()) {
12165     // Darwin only has one model of TLS.  Lower to that.
12166     unsigned char OpFlag = 0;
12167     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
12168                            X86ISD::WrapperRIP : X86ISD::Wrapper;
12169
12170     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
12171     // global base reg.
12172     bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
12173                  !Subtarget->is64Bit();
12174     if (PIC32)
12175       OpFlag = X86II::MO_TLVP_PIC_BASE;
12176     else
12177       OpFlag = X86II::MO_TLVP;
12178     SDLoc DL(Op);
12179     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
12180                                                 GA->getValueType(0),
12181                                                 GA->getOffset(), OpFlag);
12182     SDValue Offset = DAG.getNode(WrapperKind, DL, PtrVT, Result);
12183
12184     // With PIC32, the address is actually $g + Offset.
12185     if (PIC32)
12186       Offset = DAG.getNode(ISD::ADD, DL, PtrVT,
12187                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
12188                            Offset);
12189
12190     // Lowering the machine isd will make sure everything is in the right
12191     // location.
12192     SDValue Chain = DAG.getEntryNode();
12193     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
12194     SDValue Args[] = { Chain, Offset };
12195     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
12196
12197     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
12198     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12199     MFI->setAdjustsStack(true);
12200
12201     // And our return value (tls address) is in the standard call return value
12202     // location.
12203     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
12204     return DAG.getCopyFromReg(Chain, DL, Reg, PtrVT, Chain.getValue(1));
12205   }
12206
12207   if (Subtarget->isTargetKnownWindowsMSVC() ||
12208       Subtarget->isTargetWindowsGNU()) {
12209     // Just use the implicit TLS architecture
12210     // Need to generate someting similar to:
12211     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
12212     //                                  ; from TEB
12213     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
12214     //   mov     rcx, qword [rdx+rcx*8]
12215     //   mov     eax, .tls$:tlsvar
12216     //   [rax+rcx] contains the address
12217     // Windows 64bit: gs:0x58
12218     // Windows 32bit: fs:__tls_array
12219
12220     SDLoc dl(GA);
12221     SDValue Chain = DAG.getEntryNode();
12222
12223     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
12224     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
12225     // use its literal value of 0x2C.
12226     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
12227                                         ? Type::getInt8PtrTy(*DAG.getContext(),
12228                                                              256)
12229                                         : Type::getInt32PtrTy(*DAG.getContext(),
12230                                                               257));
12231
12232     SDValue TlsArray = Subtarget->is64Bit()
12233                            ? DAG.getIntPtrConstant(0x58, dl)
12234                            : (Subtarget->isTargetWindowsGNU()
12235                                   ? DAG.getIntPtrConstant(0x2C, dl)
12236                                   : DAG.getExternalSymbol("_tls_array", PtrVT));
12237
12238     SDValue ThreadPointer =
12239         DAG.getLoad(PtrVT, dl, Chain, TlsArray, MachinePointerInfo(Ptr), false,
12240                     false, false, 0);
12241
12242     SDValue res;
12243     if (GV->getThreadLocalMode() == GlobalVariable::LocalExecTLSModel) {
12244       res = ThreadPointer;
12245     } else {
12246       // Load the _tls_index variable
12247       SDValue IDX = DAG.getExternalSymbol("_tls_index", PtrVT);
12248       if (Subtarget->is64Bit())
12249         IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, PtrVT, Chain, IDX,
12250                              MachinePointerInfo(), MVT::i32, false, false,
12251                              false, 0);
12252       else
12253         IDX = DAG.getLoad(PtrVT, dl, Chain, IDX, MachinePointerInfo(), false,
12254                           false, false, 0);
12255
12256       auto &DL = DAG.getDataLayout();
12257       SDValue Scale =
12258           DAG.getConstant(Log2_64_Ceil(DL.getPointerSize()), dl, PtrVT);
12259       IDX = DAG.getNode(ISD::SHL, dl, PtrVT, IDX, Scale);
12260
12261       res = DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, IDX);
12262     }
12263
12264     res = DAG.getLoad(PtrVT, dl, Chain, res, MachinePointerInfo(), false, false,
12265                       false, 0);
12266
12267     // Get the offset of start of .tls section
12268     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
12269                                              GA->getValueType(0),
12270                                              GA->getOffset(), X86II::MO_SECREL);
12271     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, TGA);
12272
12273     // The address of the thread local variable is the add of the thread
12274     // pointer with the offset of the variable.
12275     return DAG.getNode(ISD::ADD, dl, PtrVT, res, Offset);
12276   }
12277
12278   llvm_unreachable("TLS not implemented for this target.");
12279 }
12280
12281 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
12282 /// and take a 2 x i32 value to shift plus a shift amount.
12283 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
12284   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
12285   MVT VT = Op.getSimpleValueType();
12286   unsigned VTBits = VT.getSizeInBits();
12287   SDLoc dl(Op);
12288   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
12289   SDValue ShOpLo = Op.getOperand(0);
12290   SDValue ShOpHi = Op.getOperand(1);
12291   SDValue ShAmt  = Op.getOperand(2);
12292   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
12293   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
12294   // during isel.
12295   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
12296                                   DAG.getConstant(VTBits - 1, dl, MVT::i8));
12297   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
12298                                      DAG.getConstant(VTBits - 1, dl, MVT::i8))
12299                        : DAG.getConstant(0, dl, VT);
12300
12301   SDValue Tmp2, Tmp3;
12302   if (Op.getOpcode() == ISD::SHL_PARTS) {
12303     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
12304     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
12305   } else {
12306     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
12307     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
12308   }
12309
12310   // If the shift amount is larger or equal than the width of a part we can't
12311   // rely on the results of shld/shrd. Insert a test and select the appropriate
12312   // values for large shift amounts.
12313   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
12314                                 DAG.getConstant(VTBits, dl, MVT::i8));
12315   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
12316                              AndNode, DAG.getConstant(0, dl, MVT::i8));
12317
12318   SDValue Hi, Lo;
12319   SDValue CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
12320   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
12321   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
12322
12323   if (Op.getOpcode() == ISD::SHL_PARTS) {
12324     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
12325     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
12326   } else {
12327     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
12328     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
12329   }
12330
12331   SDValue Ops[2] = { Lo, Hi };
12332   return DAG.getMergeValues(Ops, dl);
12333 }
12334
12335 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
12336                                            SelectionDAG &DAG) const {
12337   SDValue Src = Op.getOperand(0);
12338   MVT SrcVT = Src.getSimpleValueType();
12339   MVT VT = Op.getSimpleValueType();
12340   SDLoc dl(Op);
12341
12342   if (SrcVT.isVector()) {
12343     if (SrcVT == MVT::v2i32 && VT == MVT::v2f64) {
12344       return DAG.getNode(X86ISD::CVTDQ2PD, dl, VT,
12345                          DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i32, Src,
12346                          DAG.getUNDEF(SrcVT)));
12347     }
12348     if (SrcVT.getVectorElementType() == MVT::i1) {
12349       MVT IntegerVT = MVT::getVectorVT(MVT::i32, SrcVT.getVectorNumElements());
12350       return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
12351                          DAG.getNode(ISD::SIGN_EXTEND, dl, IntegerVT, Src));
12352     }
12353     return SDValue();
12354   }
12355
12356   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
12357          "Unknown SINT_TO_FP to lower!");
12358
12359   // These are really Legal; return the operand so the caller accepts it as
12360   // Legal.
12361   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
12362     return Op;
12363   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
12364       Subtarget->is64Bit()) {
12365     return Op;
12366   }
12367
12368   unsigned Size = SrcVT.getSizeInBits()/8;
12369   MachineFunction &MF = DAG.getMachineFunction();
12370   auto PtrVT = getPointerTy(MF.getDataLayout());
12371   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
12372   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12373   SDValue Chain = DAG.getStore(
12374       DAG.getEntryNode(), dl, Op.getOperand(0), StackSlot,
12375       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI), false,
12376       false, 0);
12377   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
12378 }
12379
12380 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
12381                                      SDValue StackSlot,
12382                                      SelectionDAG &DAG) const {
12383   // Build the FILD
12384   SDLoc DL(Op);
12385   SDVTList Tys;
12386   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
12387   if (useSSE)
12388     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
12389   else
12390     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
12391
12392   unsigned ByteSize = SrcVT.getSizeInBits()/8;
12393
12394   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
12395   MachineMemOperand *MMO;
12396   if (FI) {
12397     int SSFI = FI->getIndex();
12398     MMO = DAG.getMachineFunction().getMachineMemOperand(
12399         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12400         MachineMemOperand::MOLoad, ByteSize, ByteSize);
12401   } else {
12402     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
12403     StackSlot = StackSlot.getOperand(1);
12404   }
12405   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
12406   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
12407                                            X86ISD::FILD, DL,
12408                                            Tys, Ops, SrcVT, MMO);
12409
12410   if (useSSE) {
12411     Chain = Result.getValue(1);
12412     SDValue InFlag = Result.getValue(2);
12413
12414     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
12415     // shouldn't be necessary except that RFP cannot be live across
12416     // multiple blocks. When stackifier is fixed, they can be uncoupled.
12417     MachineFunction &MF = DAG.getMachineFunction();
12418     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
12419     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
12420     auto PtrVT = getPointerTy(MF.getDataLayout());
12421     SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12422     Tys = DAG.getVTList(MVT::Other);
12423     SDValue Ops[] = {
12424       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
12425     };
12426     MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
12427         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12428         MachineMemOperand::MOStore, SSFISize, SSFISize);
12429
12430     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
12431                                     Ops, Op.getValueType(), MMO);
12432     Result = DAG.getLoad(
12433         Op.getValueType(), DL, Chain, StackSlot,
12434         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12435         false, false, false, 0);
12436   }
12437
12438   return Result;
12439 }
12440
12441 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
12442 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
12443                                                SelectionDAG &DAG) const {
12444   // This algorithm is not obvious. Here it is what we're trying to output:
12445   /*
12446      movq       %rax,  %xmm0
12447      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
12448      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
12449      #ifdef __SSE3__
12450        haddpd   %xmm0, %xmm0
12451      #else
12452        pshufd   $0x4e, %xmm0, %xmm1
12453        addpd    %xmm1, %xmm0
12454      #endif
12455   */
12456
12457   SDLoc dl(Op);
12458   LLVMContext *Context = DAG.getContext();
12459
12460   // Build some magic constants.
12461   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
12462   Constant *C0 = ConstantDataVector::get(*Context, CV0);
12463   auto PtrVT = getPointerTy(DAG.getDataLayout());
12464   SDValue CPIdx0 = DAG.getConstantPool(C0, PtrVT, 16);
12465
12466   SmallVector<Constant*,2> CV1;
12467   CV1.push_back(
12468     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
12469                                       APInt(64, 0x4330000000000000ULL))));
12470   CV1.push_back(
12471     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
12472                                       APInt(64, 0x4530000000000000ULL))));
12473   Constant *C1 = ConstantVector::get(CV1);
12474   SDValue CPIdx1 = DAG.getConstantPool(C1, PtrVT, 16);
12475
12476   // Load the 64-bit value into an XMM register.
12477   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
12478                             Op.getOperand(0));
12479   SDValue CLod0 =
12480       DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
12481                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12482                   false, false, false, 16);
12483   SDValue Unpck1 =
12484       getUnpackl(DAG, dl, MVT::v4i32, DAG.getBitcast(MVT::v4i32, XR1), CLod0);
12485
12486   SDValue CLod1 =
12487       DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
12488                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12489                   false, false, false, 16);
12490   SDValue XR2F = DAG.getBitcast(MVT::v2f64, Unpck1);
12491   // TODO: Are there any fast-math-flags to propagate here?
12492   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
12493   SDValue Result;
12494
12495   if (Subtarget->hasSSE3()) {
12496     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
12497     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
12498   } else {
12499     SDValue S2F = DAG.getBitcast(MVT::v4i32, Sub);
12500     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
12501                                            S2F, 0x4E, DAG);
12502     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
12503                          DAG.getBitcast(MVT::v2f64, Shuffle), Sub);
12504   }
12505
12506   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
12507                      DAG.getIntPtrConstant(0, dl));
12508 }
12509
12510 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
12511 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
12512                                                SelectionDAG &DAG) const {
12513   SDLoc dl(Op);
12514   // FP constant to bias correct the final result.
12515   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
12516                                    MVT::f64);
12517
12518   // Load the 32-bit value into an XMM register.
12519   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
12520                              Op.getOperand(0));
12521
12522   // Zero out the upper parts of the register.
12523   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
12524
12525   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
12526                      DAG.getBitcast(MVT::v2f64, Load),
12527                      DAG.getIntPtrConstant(0, dl));
12528
12529   // Or the load with the bias.
12530   SDValue Or = DAG.getNode(
12531       ISD::OR, dl, MVT::v2i64,
12532       DAG.getBitcast(MVT::v2i64,
12533                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Load)),
12534       DAG.getBitcast(MVT::v2i64,
12535                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Bias)));
12536   Or =
12537       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
12538                   DAG.getBitcast(MVT::v2f64, Or), DAG.getIntPtrConstant(0, dl));
12539
12540   // Subtract the bias.
12541   // TODO: Are there any fast-math-flags to propagate here?
12542   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
12543
12544   // Handle final rounding.
12545   MVT DestVT = Op.getSimpleValueType();
12546
12547   if (DestVT.bitsLT(MVT::f64))
12548     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
12549                        DAG.getIntPtrConstant(0, dl));
12550   if (DestVT.bitsGT(MVT::f64))
12551     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
12552
12553   // Handle final rounding.
12554   return Sub;
12555 }
12556
12557 static SDValue lowerUINT_TO_FP_vXi32(SDValue Op, SelectionDAG &DAG,
12558                                      const X86Subtarget &Subtarget) {
12559   // The algorithm is the following:
12560   // #ifdef __SSE4_1__
12561   //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
12562   //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
12563   //                                 (uint4) 0x53000000, 0xaa);
12564   // #else
12565   //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
12566   //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
12567   // #endif
12568   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
12569   //     return (float4) lo + fhi;
12570
12571   // We shouldn't use it when unsafe-fp-math is enabled though: we might later
12572   // reassociate the two FADDs, and if we do that, the algorithm fails
12573   // spectacularly (PR24512).
12574   // FIXME: If we ever have some kind of Machine FMF, this should be marked
12575   // as non-fast and always be enabled. Why isn't SDAG FMF enough? Because
12576   // there's also the MachineCombiner reassociations happening on Machine IR.
12577   if (DAG.getTarget().Options.UnsafeFPMath)
12578     return SDValue();
12579
12580   SDLoc DL(Op);
12581   SDValue V = Op->getOperand(0);
12582   MVT VecIntVT = V.getSimpleValueType();
12583   bool Is128 = VecIntVT == MVT::v4i32;
12584   MVT VecFloatVT = Is128 ? MVT::v4f32 : MVT::v8f32;
12585   // If we convert to something else than the supported type, e.g., to v4f64,
12586   // abort early.
12587   if (VecFloatVT != Op->getSimpleValueType(0))
12588     return SDValue();
12589
12590   unsigned NumElts = VecIntVT.getVectorNumElements();
12591   assert((VecIntVT == MVT::v4i32 || VecIntVT == MVT::v8i32) &&
12592          "Unsupported custom type");
12593   assert(NumElts <= 8 && "The size of the constant array must be fixed");
12594
12595   // In the #idef/#else code, we have in common:
12596   // - The vector of constants:
12597   // -- 0x4b000000
12598   // -- 0x53000000
12599   // - A shift:
12600   // -- v >> 16
12601
12602   // Create the splat vector for 0x4b000000.
12603   SDValue CstLow = DAG.getConstant(0x4b000000, DL, MVT::i32);
12604   SDValue CstLowArray[] = {CstLow, CstLow, CstLow, CstLow,
12605                            CstLow, CstLow, CstLow, CstLow};
12606   SDValue VecCstLow = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12607                                   makeArrayRef(&CstLowArray[0], NumElts));
12608   // Create the splat vector for 0x53000000.
12609   SDValue CstHigh = DAG.getConstant(0x53000000, DL, MVT::i32);
12610   SDValue CstHighArray[] = {CstHigh, CstHigh, CstHigh, CstHigh,
12611                             CstHigh, CstHigh, CstHigh, CstHigh};
12612   SDValue VecCstHigh = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12613                                    makeArrayRef(&CstHighArray[0], NumElts));
12614
12615   // Create the right shift.
12616   SDValue CstShift = DAG.getConstant(16, DL, MVT::i32);
12617   SDValue CstShiftArray[] = {CstShift, CstShift, CstShift, CstShift,
12618                              CstShift, CstShift, CstShift, CstShift};
12619   SDValue VecCstShift = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12620                                     makeArrayRef(&CstShiftArray[0], NumElts));
12621   SDValue HighShift = DAG.getNode(ISD::SRL, DL, VecIntVT, V, VecCstShift);
12622
12623   SDValue Low, High;
12624   if (Subtarget.hasSSE41()) {
12625     MVT VecI16VT = Is128 ? MVT::v8i16 : MVT::v16i16;
12626     //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
12627     SDValue VecCstLowBitcast = DAG.getBitcast(VecI16VT, VecCstLow);
12628     SDValue VecBitcast = DAG.getBitcast(VecI16VT, V);
12629     // Low will be bitcasted right away, so do not bother bitcasting back to its
12630     // original type.
12631     Low = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecBitcast,
12632                       VecCstLowBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
12633     //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
12634     //                                 (uint4) 0x53000000, 0xaa);
12635     SDValue VecCstHighBitcast = DAG.getBitcast(VecI16VT, VecCstHigh);
12636     SDValue VecShiftBitcast = DAG.getBitcast(VecI16VT, HighShift);
12637     // High will be bitcasted right away, so do not bother bitcasting back to
12638     // its original type.
12639     High = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecShiftBitcast,
12640                        VecCstHighBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
12641   } else {
12642     SDValue CstMask = DAG.getConstant(0xffff, DL, MVT::i32);
12643     SDValue VecCstMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT, CstMask,
12644                                      CstMask, CstMask, CstMask);
12645     //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
12646     SDValue LowAnd = DAG.getNode(ISD::AND, DL, VecIntVT, V, VecCstMask);
12647     Low = DAG.getNode(ISD::OR, DL, VecIntVT, LowAnd, VecCstLow);
12648
12649     //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
12650     High = DAG.getNode(ISD::OR, DL, VecIntVT, HighShift, VecCstHigh);
12651   }
12652
12653   // Create the vector constant for -(0x1.0p39f + 0x1.0p23f).
12654   SDValue CstFAdd = DAG.getConstantFP(
12655       APFloat(APFloat::IEEEsingle, APInt(32, 0xD3000080)), DL, MVT::f32);
12656   SDValue CstFAddArray[] = {CstFAdd, CstFAdd, CstFAdd, CstFAdd,
12657                             CstFAdd, CstFAdd, CstFAdd, CstFAdd};
12658   SDValue VecCstFAdd = DAG.getNode(ISD::BUILD_VECTOR, DL, VecFloatVT,
12659                                    makeArrayRef(&CstFAddArray[0], NumElts));
12660
12661   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
12662   SDValue HighBitcast = DAG.getBitcast(VecFloatVT, High);
12663   // TODO: Are there any fast-math-flags to propagate here?
12664   SDValue FHigh =
12665       DAG.getNode(ISD::FADD, DL, VecFloatVT, HighBitcast, VecCstFAdd);
12666   //     return (float4) lo + fhi;
12667   SDValue LowBitcast = DAG.getBitcast(VecFloatVT, Low);
12668   return DAG.getNode(ISD::FADD, DL, VecFloatVT, LowBitcast, FHigh);
12669 }
12670
12671 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
12672                                                SelectionDAG &DAG) const {
12673   SDValue N0 = Op.getOperand(0);
12674   MVT SVT = N0.getSimpleValueType();
12675   SDLoc dl(Op);
12676
12677   switch (SVT.SimpleTy) {
12678   default:
12679     llvm_unreachable("Custom UINT_TO_FP is not supported!");
12680   case MVT::v4i8:
12681   case MVT::v4i16:
12682   case MVT::v8i8:
12683   case MVT::v8i16: {
12684     MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
12685     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
12686                        DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
12687   }
12688   case MVT::v4i32:
12689   case MVT::v8i32:
12690     return lowerUINT_TO_FP_vXi32(Op, DAG, *Subtarget);
12691   case MVT::v16i8:
12692   case MVT::v16i16:
12693     assert(Subtarget->hasAVX512());
12694     return DAG.getNode(ISD::UINT_TO_FP, dl, Op.getValueType(),
12695                        DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v16i32, N0));
12696   }
12697 }
12698
12699 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
12700                                            SelectionDAG &DAG) const {
12701   SDValue N0 = Op.getOperand(0);
12702   SDLoc dl(Op);
12703   auto PtrVT = getPointerTy(DAG.getDataLayout());
12704
12705   if (Op.getSimpleValueType().isVector())
12706     return lowerUINT_TO_FP_vec(Op, DAG);
12707
12708   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
12709   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
12710   // the optimization here.
12711   if (DAG.SignBitIsZero(N0))
12712     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
12713
12714   MVT SrcVT = N0.getSimpleValueType();
12715   MVT DstVT = Op.getSimpleValueType();
12716
12717   if (Subtarget->hasAVX512() && isScalarFPTypeInSSEReg(DstVT) &&
12718       (SrcVT == MVT::i32 || (SrcVT == MVT::i64 && Subtarget->is64Bit()))) {
12719     // Conversions from unsigned i32 to f32/f64 are legal,
12720     // using VCVTUSI2SS/SD.  Same for i64 in 64-bit mode.
12721     return Op;
12722   }
12723
12724   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
12725     return LowerUINT_TO_FP_i64(Op, DAG);
12726   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
12727     return LowerUINT_TO_FP_i32(Op, DAG);
12728   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
12729     return SDValue();
12730
12731   // Make a 64-bit buffer, and use it to build an FILD.
12732   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
12733   if (SrcVT == MVT::i32) {
12734     SDValue WordOff = DAG.getConstant(4, dl, PtrVT);
12735     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, WordOff);
12736     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
12737                                   StackSlot, MachinePointerInfo(),
12738                                   false, false, 0);
12739     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, dl, MVT::i32),
12740                                   OffsetSlot, MachinePointerInfo(),
12741                                   false, false, 0);
12742     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
12743     return Fild;
12744   }
12745
12746   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
12747   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
12748                                StackSlot, MachinePointerInfo(),
12749                                false, false, 0);
12750   // For i64 source, we need to add the appropriate power of 2 if the input
12751   // was negative.  This is the same as the optimization in
12752   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
12753   // we must be careful to do the computation in x87 extended precision, not
12754   // in SSE. (The generic code can't know it's OK to do this, or how to.)
12755   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
12756   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
12757       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12758       MachineMemOperand::MOLoad, 8, 8);
12759
12760   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
12761   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
12762   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
12763                                          MVT::i64, MMO);
12764
12765   APInt FF(32, 0x5F800000ULL);
12766
12767   // Check whether the sign bit is set.
12768   SDValue SignSet = DAG.getSetCC(
12769       dl, getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64),
12770       Op.getOperand(0), DAG.getConstant(0, dl, MVT::i64), ISD::SETLT);
12771
12772   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
12773   SDValue FudgePtr = DAG.getConstantPool(
12774       ConstantInt::get(*DAG.getContext(), FF.zext(64)), PtrVT);
12775
12776   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
12777   SDValue Zero = DAG.getIntPtrConstant(0, dl);
12778   SDValue Four = DAG.getIntPtrConstant(4, dl);
12779   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
12780                                Zero, Four);
12781   FudgePtr = DAG.getNode(ISD::ADD, dl, PtrVT, FudgePtr, Offset);
12782
12783   // Load the value out, extending it from f32 to f80.
12784   // FIXME: Avoid the extend by constructing the right constant pool?
12785   SDValue Fudge = DAG.getExtLoad(
12786       ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(), FudgePtr,
12787       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), MVT::f32,
12788       false, false, false, 4);
12789   // Extend everything to 80 bits to force it to be done on x87.
12790   // TODO: Are there any fast-math-flags to propagate here?
12791   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
12792   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add,
12793                      DAG.getIntPtrConstant(0, dl));
12794 }
12795
12796 // If the given FP_TO_SINT (IsSigned) or FP_TO_UINT (!IsSigned) operation
12797 // is legal, or has an fp128 or f16 source (which needs to be promoted to f32),
12798 // just return an <SDValue(), SDValue()> pair.
12799 // Otherwise it is assumed to be a conversion from one of f32, f64 or f80
12800 // to i16, i32 or i64, and we lower it to a legal sequence.
12801 // If lowered to the final integer result we return a <result, SDValue()> pair.
12802 // Otherwise we lower it to a sequence ending with a FIST, return a
12803 // <FIST, StackSlot> pair, and the caller is responsible for loading
12804 // the final integer result from StackSlot.
12805 std::pair<SDValue,SDValue>
12806 X86TargetLowering::FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
12807                                    bool IsSigned, bool IsReplace) const {
12808   SDLoc DL(Op);
12809
12810   EVT DstTy = Op.getValueType();
12811   EVT TheVT = Op.getOperand(0).getValueType();
12812   auto PtrVT = getPointerTy(DAG.getDataLayout());
12813
12814   if (TheVT != MVT::f32 && TheVT != MVT::f64 && TheVT != MVT::f80) {
12815     // f16 must be promoted before using the lowering in this routine.
12816     // fp128 does not use this lowering.
12817     return std::make_pair(SDValue(), SDValue());
12818   }
12819
12820   // If using FIST to compute an unsigned i64, we'll need some fixup
12821   // to handle values above the maximum signed i64.  A FIST is always
12822   // used for the 32-bit subtarget, but also for f80 on a 64-bit target.
12823   bool UnsignedFixup = !IsSigned &&
12824                        DstTy == MVT::i64 &&
12825                        (!Subtarget->is64Bit() ||
12826                         !isScalarFPTypeInSSEReg(TheVT));
12827
12828   if (!IsSigned && DstTy != MVT::i64 && !Subtarget->hasAVX512()) {
12829     // Replace the fp-to-uint32 operation with an fp-to-sint64 FIST.
12830     // The low 32 bits of the fist result will have the correct uint32 result.
12831     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
12832     DstTy = MVT::i64;
12833   }
12834
12835   assert(DstTy.getSimpleVT() <= MVT::i64 &&
12836          DstTy.getSimpleVT() >= MVT::i16 &&
12837          "Unknown FP_TO_INT to lower!");
12838
12839   // These are really Legal.
12840   if (DstTy == MVT::i32 &&
12841       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
12842     return std::make_pair(SDValue(), SDValue());
12843   if (Subtarget->is64Bit() &&
12844       DstTy == MVT::i64 &&
12845       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
12846     return std::make_pair(SDValue(), SDValue());
12847
12848   // We lower FP->int64 into FISTP64 followed by a load from a temporary
12849   // stack slot.
12850   MachineFunction &MF = DAG.getMachineFunction();
12851   unsigned MemSize = DstTy.getSizeInBits()/8;
12852   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
12853   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12854
12855   unsigned Opc;
12856   switch (DstTy.getSimpleVT().SimpleTy) {
12857   default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
12858   case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
12859   case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
12860   case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
12861   }
12862
12863   SDValue Chain = DAG.getEntryNode();
12864   SDValue Value = Op.getOperand(0);
12865   SDValue Adjust; // 0x0 or 0x80000000, for result sign bit adjustment.
12866
12867   if (UnsignedFixup) {
12868     //
12869     // Conversion to unsigned i64 is implemented with a select,
12870     // depending on whether the source value fits in the range
12871     // of a signed i64.  Let Thresh be the FP equivalent of
12872     // 0x8000000000000000ULL.
12873     //
12874     //  Adjust i32 = (Value < Thresh) ? 0 : 0x80000000;
12875     //  FistSrc    = (Value < Thresh) ? Value : (Value - Thresh);
12876     //  Fist-to-mem64 FistSrc
12877     //  Add 0 or 0x800...0ULL to the 64-bit result, which is equivalent
12878     //  to XOR'ing the high 32 bits with Adjust.
12879     //
12880     // Being a power of 2, Thresh is exactly representable in all FP formats.
12881     // For X87 we'd like to use the smallest FP type for this constant, but
12882     // for DAG type consistency we have to match the FP operand type.
12883
12884     APFloat Thresh(APFloat::IEEEsingle, APInt(32, 0x5f000000));
12885     LLVM_ATTRIBUTE_UNUSED APFloat::opStatus Status = APFloat::opOK;
12886     bool LosesInfo = false;
12887     if (TheVT == MVT::f64)
12888       // The rounding mode is irrelevant as the conversion should be exact.
12889       Status = Thresh.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
12890                               &LosesInfo);
12891     else if (TheVT == MVT::f80)
12892       Status = Thresh.convert(APFloat::x87DoubleExtended,
12893                               APFloat::rmNearestTiesToEven, &LosesInfo);
12894
12895     assert(Status == APFloat::opOK && !LosesInfo &&
12896            "FP conversion should have been exact");
12897
12898     SDValue ThreshVal = DAG.getConstantFP(Thresh, DL, TheVT);
12899
12900     SDValue Cmp = DAG.getSetCC(DL,
12901                                getSetCCResultType(DAG.getDataLayout(),
12902                                                   *DAG.getContext(), TheVT),
12903                                Value, ThreshVal, ISD::SETLT);
12904     Adjust = DAG.getSelect(DL, MVT::i32, Cmp,
12905                            DAG.getConstant(0, DL, MVT::i32),
12906                            DAG.getConstant(0x80000000, DL, MVT::i32));
12907     SDValue Sub = DAG.getNode(ISD::FSUB, DL, TheVT, Value, ThreshVal);
12908     Cmp = DAG.getSetCC(DL, getSetCCResultType(DAG.getDataLayout(),
12909                                               *DAG.getContext(), TheVT),
12910                        Value, ThreshVal, ISD::SETLT);
12911     Value = DAG.getSelect(DL, TheVT, Cmp, Value, Sub);
12912   }
12913
12914   // FIXME This causes a redundant load/store if the SSE-class value is already
12915   // in memory, such as if it is on the callstack.
12916   if (isScalarFPTypeInSSEReg(TheVT)) {
12917     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
12918     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
12919                          MachinePointerInfo::getFixedStack(MF, SSFI), false,
12920                          false, 0);
12921     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
12922     SDValue Ops[] = {
12923       Chain, StackSlot, DAG.getValueType(TheVT)
12924     };
12925
12926     MachineMemOperand *MMO =
12927         MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
12928                                 MachineMemOperand::MOLoad, MemSize, MemSize);
12929     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
12930     Chain = Value.getValue(1);
12931     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
12932     StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12933   }
12934
12935   MachineMemOperand *MMO =
12936       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
12937                               MachineMemOperand::MOStore, MemSize, MemSize);
12938
12939   if (UnsignedFixup) {
12940
12941     // Insert the FIST, load its result as two i32's,
12942     // and XOR the high i32 with Adjust.
12943
12944     SDValue FistOps[] = { Chain, Value, StackSlot };
12945     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
12946                                            FistOps, DstTy, MMO);
12947
12948     SDValue Low32 = DAG.getLoad(MVT::i32, DL, FIST, StackSlot,
12949                                 MachinePointerInfo(),
12950                                 false, false, false, 0);
12951     SDValue HighAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackSlot,
12952                                    DAG.getConstant(4, DL, PtrVT));
12953
12954     SDValue High32 = DAG.getLoad(MVT::i32, DL, FIST, HighAddr,
12955                                  MachinePointerInfo(),
12956                                  false, false, false, 0);
12957     High32 = DAG.getNode(ISD::XOR, DL, MVT::i32, High32, Adjust);
12958
12959     if (Subtarget->is64Bit()) {
12960       // Join High32 and Low32 into a 64-bit result.
12961       // (High32 << 32) | Low32
12962       Low32 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Low32);
12963       High32 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, High32);
12964       High32 = DAG.getNode(ISD::SHL, DL, MVT::i64, High32,
12965                            DAG.getConstant(32, DL, MVT::i8));
12966       SDValue Result = DAG.getNode(ISD::OR, DL, MVT::i64, High32, Low32);
12967       return std::make_pair(Result, SDValue());
12968     }
12969
12970     SDValue ResultOps[] = { Low32, High32 };
12971
12972     SDValue pair = IsReplace
12973       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, ResultOps)
12974       : DAG.getMergeValues(ResultOps, DL);
12975     return std::make_pair(pair, SDValue());
12976   } else {
12977     // Build the FP_TO_INT*_IN_MEM
12978     SDValue Ops[] = { Chain, Value, StackSlot };
12979     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
12980                                            Ops, DstTy, MMO);
12981     return std::make_pair(FIST, StackSlot);
12982   }
12983 }
12984
12985 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
12986                               const X86Subtarget *Subtarget) {
12987   MVT VT = Op->getSimpleValueType(0);
12988   SDValue In = Op->getOperand(0);
12989   MVT InVT = In.getSimpleValueType();
12990   SDLoc dl(Op);
12991
12992   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
12993     return DAG.getNode(ISD::ZERO_EXTEND, dl, VT, In);
12994
12995   // Optimize vectors in AVX mode:
12996   //
12997   //   v8i16 -> v8i32
12998   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
12999   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
13000   //   Concat upper and lower parts.
13001   //
13002   //   v4i32 -> v4i64
13003   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
13004   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
13005   //   Concat upper and lower parts.
13006   //
13007
13008   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
13009       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
13010       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
13011     return SDValue();
13012
13013   if (Subtarget->hasInt256())
13014     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
13015
13016   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
13017   SDValue Undef = DAG.getUNDEF(InVT);
13018   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
13019   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
13020   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
13021
13022   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
13023                              VT.getVectorNumElements()/2);
13024
13025   OpLo = DAG.getBitcast(HVT, OpLo);
13026   OpHi = DAG.getBitcast(HVT, OpHi);
13027
13028   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
13029 }
13030
13031 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
13032                   const X86Subtarget *Subtarget, SelectionDAG &DAG) {
13033   MVT VT = Op->getSimpleValueType(0);
13034   SDValue In = Op->getOperand(0);
13035   MVT InVT = In.getSimpleValueType();
13036   SDLoc DL(Op);
13037   unsigned int NumElts = VT.getVectorNumElements();
13038   if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
13039     return SDValue();
13040
13041   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
13042     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
13043
13044   assert(InVT.getVectorElementType() == MVT::i1);
13045   MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
13046   SDValue One =
13047    DAG.getConstant(APInt(ExtVT.getScalarSizeInBits(), 1), DL, ExtVT);
13048   SDValue Zero =
13049    DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), DL, ExtVT);
13050
13051   SDValue V = DAG.getNode(ISD::VSELECT, DL, ExtVT, In, One, Zero);
13052   if (VT.is512BitVector())
13053     return V;
13054   return DAG.getNode(X86ISD::VTRUNC, DL, VT, V);
13055 }
13056
13057 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
13058                                SelectionDAG &DAG) {
13059   if (Subtarget->hasFp256())
13060     if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
13061       return Res;
13062
13063   return SDValue();
13064 }
13065
13066 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
13067                                 SelectionDAG &DAG) {
13068   SDLoc DL(Op);
13069   MVT VT = Op.getSimpleValueType();
13070   SDValue In = Op.getOperand(0);
13071   MVT SVT = In.getSimpleValueType();
13072
13073   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
13074     return LowerZERO_EXTEND_AVX512(Op, Subtarget, DAG);
13075
13076   if (Subtarget->hasFp256())
13077     if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
13078       return Res;
13079
13080   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
13081          VT.getVectorNumElements() != SVT.getVectorNumElements());
13082   return SDValue();
13083 }
13084
13085 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
13086   SDLoc DL(Op);
13087   MVT VT = Op.getSimpleValueType();
13088   SDValue In = Op.getOperand(0);
13089   MVT InVT = In.getSimpleValueType();
13090
13091   if (VT == MVT::i1) {
13092     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
13093            "Invalid scalar TRUNCATE operation");
13094     if (InVT.getSizeInBits() >= 32)
13095       return SDValue();
13096     In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
13097     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
13098   }
13099   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
13100          "Invalid TRUNCATE operation");
13101
13102   // move vector to mask - truncate solution for SKX
13103   if (VT.getVectorElementType() == MVT::i1) {
13104     if (InVT.is512BitVector() && InVT.getScalarSizeInBits() <= 16 &&
13105         Subtarget->hasBWI())
13106       return Op; // legal, will go to VPMOVB2M, VPMOVW2M
13107     if ((InVT.is256BitVector() || InVT.is128BitVector())
13108         && InVT.getScalarSizeInBits() <= 16 &&
13109         Subtarget->hasBWI() && Subtarget->hasVLX())
13110       return Op; // legal, will go to VPMOVB2M, VPMOVW2M
13111     if (InVT.is512BitVector() && InVT.getScalarSizeInBits() >= 32 &&
13112         Subtarget->hasDQI())
13113       return Op; // legal, will go to VPMOVD2M, VPMOVQ2M
13114     if ((InVT.is256BitVector() || InVT.is128BitVector())
13115         && InVT.getScalarSizeInBits() >= 32 &&
13116         Subtarget->hasDQI() && Subtarget->hasVLX())
13117       return Op; // legal, will go to VPMOVB2M, VPMOVQ2M
13118   }
13119
13120   if (VT.getVectorElementType() == MVT::i1) {
13121     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
13122     unsigned NumElts = InVT.getVectorNumElements();
13123     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
13124     if (InVT.getSizeInBits() < 512) {
13125       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
13126       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
13127       InVT = ExtVT;
13128     }
13129
13130     SDValue OneV =
13131      DAG.getConstant(APInt::getSignBit(InVT.getScalarSizeInBits()), DL, InVT);
13132     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
13133     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
13134   }
13135
13136   // vpmovqb/w/d, vpmovdb/w, vpmovwb
13137   if (Subtarget->hasAVX512()) {
13138     // word to byte only under BWI
13139     if (InVT == MVT::v16i16 && !Subtarget->hasBWI()) // v16i16 -> v16i8
13140       return DAG.getNode(X86ISD::VTRUNC, DL, VT,
13141                          DAG.getNode(X86ISD::VSEXT, DL, MVT::v16i32, In));
13142     return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
13143   }
13144   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
13145     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
13146     if (Subtarget->hasInt256()) {
13147       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
13148       In = DAG.getBitcast(MVT::v8i32, In);
13149       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
13150                                 ShufMask);
13151       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
13152                          DAG.getIntPtrConstant(0, DL));
13153     }
13154
13155     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
13156                                DAG.getIntPtrConstant(0, DL));
13157     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
13158                                DAG.getIntPtrConstant(2, DL));
13159     OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
13160     OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
13161     static const int ShufMask[] = {0, 2, 4, 6};
13162     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
13163   }
13164
13165   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
13166     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
13167     if (Subtarget->hasInt256()) {
13168       In = DAG.getBitcast(MVT::v32i8, In);
13169
13170       SmallVector<SDValue,32> pshufbMask;
13171       for (unsigned i = 0; i < 2; ++i) {
13172         pshufbMask.push_back(DAG.getConstant(0x0, DL, MVT::i8));
13173         pshufbMask.push_back(DAG.getConstant(0x1, DL, MVT::i8));
13174         pshufbMask.push_back(DAG.getConstant(0x4, DL, MVT::i8));
13175         pshufbMask.push_back(DAG.getConstant(0x5, DL, MVT::i8));
13176         pshufbMask.push_back(DAG.getConstant(0x8, DL, MVT::i8));
13177         pshufbMask.push_back(DAG.getConstant(0x9, DL, MVT::i8));
13178         pshufbMask.push_back(DAG.getConstant(0xc, DL, MVT::i8));
13179         pshufbMask.push_back(DAG.getConstant(0xd, DL, MVT::i8));
13180         for (unsigned j = 0; j < 8; ++j)
13181           pshufbMask.push_back(DAG.getConstant(0x80, DL, MVT::i8));
13182       }
13183       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
13184       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
13185       In = DAG.getBitcast(MVT::v4i64, In);
13186
13187       static const int ShufMask[] = {0,  2,  -1,  -1};
13188       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
13189                                 &ShufMask[0]);
13190       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
13191                        DAG.getIntPtrConstant(0, DL));
13192       return DAG.getBitcast(VT, In);
13193     }
13194
13195     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
13196                                DAG.getIntPtrConstant(0, DL));
13197
13198     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
13199                                DAG.getIntPtrConstant(4, DL));
13200
13201     OpLo = DAG.getBitcast(MVT::v16i8, OpLo);
13202     OpHi = DAG.getBitcast(MVT::v16i8, OpHi);
13203
13204     // The PSHUFB mask:
13205     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
13206                                    -1, -1, -1, -1, -1, -1, -1, -1};
13207
13208     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
13209     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
13210     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
13211
13212     OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
13213     OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
13214
13215     // The MOVLHPS Mask:
13216     static const int ShufMask2[] = {0, 1, 4, 5};
13217     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
13218     return DAG.getBitcast(MVT::v8i16, res);
13219   }
13220
13221   // Handle truncation of V256 to V128 using shuffles.
13222   if (!VT.is128BitVector() || !InVT.is256BitVector())
13223     return SDValue();
13224
13225   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
13226
13227   unsigned NumElems = VT.getVectorNumElements();
13228   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
13229
13230   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
13231   // Prepare truncation shuffle mask
13232   for (unsigned i = 0; i != NumElems; ++i)
13233     MaskVec[i] = i * 2;
13234   SDValue V = DAG.getVectorShuffle(NVT, DL, DAG.getBitcast(NVT, In),
13235                                    DAG.getUNDEF(NVT), &MaskVec[0]);
13236   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
13237                      DAG.getIntPtrConstant(0, DL));
13238 }
13239
13240 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
13241                                            SelectionDAG &DAG) const {
13242   assert(!Op.getSimpleValueType().isVector());
13243
13244   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
13245     /*IsSigned=*/ true, /*IsReplace=*/ false);
13246   SDValue FIST = Vals.first, StackSlot = Vals.second;
13247   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
13248   if (!FIST.getNode())
13249     return Op;
13250
13251   if (StackSlot.getNode())
13252     // Load the result.
13253     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
13254                        FIST, StackSlot, MachinePointerInfo(),
13255                        false, false, false, 0);
13256
13257   // The node is the result.
13258   return FIST;
13259 }
13260
13261 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
13262                                            SelectionDAG &DAG) const {
13263   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
13264     /*IsSigned=*/ false, /*IsReplace=*/ false);
13265   SDValue FIST = Vals.first, StackSlot = Vals.second;
13266   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
13267   if (!FIST.getNode())
13268     return Op;
13269
13270   if (StackSlot.getNode())
13271     // Load the result.
13272     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
13273                        FIST, StackSlot, MachinePointerInfo(),
13274                        false, false, false, 0);
13275
13276   // The node is the result.
13277   return FIST;
13278 }
13279
13280 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
13281   SDLoc DL(Op);
13282   MVT VT = Op.getSimpleValueType();
13283   SDValue In = Op.getOperand(0);
13284   MVT SVT = In.getSimpleValueType();
13285
13286   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
13287
13288   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
13289                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
13290                                  In, DAG.getUNDEF(SVT)));
13291 }
13292
13293 /// The only differences between FABS and FNEG are the mask and the logic op.
13294 /// FNEG also has a folding opportunity for FNEG(FABS(x)).
13295 static SDValue LowerFABSorFNEG(SDValue Op, SelectionDAG &DAG) {
13296   assert((Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) &&
13297          "Wrong opcode for lowering FABS or FNEG.");
13298
13299   bool IsFABS = (Op.getOpcode() == ISD::FABS);
13300
13301   // If this is a FABS and it has an FNEG user, bail out to fold the combination
13302   // into an FNABS. We'll lower the FABS after that if it is still in use.
13303   if (IsFABS)
13304     for (SDNode *User : Op->uses())
13305       if (User->getOpcode() == ISD::FNEG)
13306         return Op;
13307
13308   SDLoc dl(Op);
13309   MVT VT = Op.getSimpleValueType();
13310
13311   // FIXME: Use function attribute "OptimizeForSize" and/or CodeGenOpt::Level to
13312   // decide if we should generate a 16-byte constant mask when we only need 4 or
13313   // 8 bytes for the scalar case.
13314
13315   MVT LogicVT;
13316   MVT EltVT;
13317   unsigned NumElts;
13318
13319   if (VT.isVector()) {
13320     LogicVT = VT;
13321     EltVT = VT.getVectorElementType();
13322     NumElts = VT.getVectorNumElements();
13323   } else {
13324     // There are no scalar bitwise logical SSE/AVX instructions, so we
13325     // generate a 16-byte vector constant and logic op even for the scalar case.
13326     // Using a 16-byte mask allows folding the load of the mask with
13327     // the logic op, so it can save (~4 bytes) on code size.
13328     LogicVT = (VT == MVT::f64) ? MVT::v2f64 : MVT::v4f32;
13329     EltVT = VT;
13330     NumElts = (VT == MVT::f64) ? 2 : 4;
13331   }
13332
13333   unsigned EltBits = EltVT.getSizeInBits();
13334   LLVMContext *Context = DAG.getContext();
13335   // For FABS, mask is 0x7f...; for FNEG, mask is 0x80...
13336   APInt MaskElt =
13337     IsFABS ? APInt::getSignedMaxValue(EltBits) : APInt::getSignBit(EltBits);
13338   Constant *C = ConstantInt::get(*Context, MaskElt);
13339   C = ConstantVector::getSplat(NumElts, C);
13340   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13341   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
13342   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
13343   SDValue Mask =
13344       DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
13345                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13346                   false, false, false, Alignment);
13347
13348   SDValue Op0 = Op.getOperand(0);
13349   bool IsFNABS = !IsFABS && (Op0.getOpcode() == ISD::FABS);
13350   unsigned LogicOp =
13351     IsFABS ? X86ISD::FAND : IsFNABS ? X86ISD::FOR : X86ISD::FXOR;
13352   SDValue Operand = IsFNABS ? Op0.getOperand(0) : Op0;
13353
13354   if (VT.isVector())
13355     return DAG.getNode(LogicOp, dl, LogicVT, Operand, Mask);
13356
13357   // For the scalar case extend to a 128-bit vector, perform the logic op,
13358   // and extract the scalar result back out.
13359   Operand = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Operand);
13360   SDValue LogicNode = DAG.getNode(LogicOp, dl, LogicVT, Operand, Mask);
13361   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, LogicNode,
13362                      DAG.getIntPtrConstant(0, dl));
13363 }
13364
13365 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
13366   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13367   LLVMContext *Context = DAG.getContext();
13368   SDValue Op0 = Op.getOperand(0);
13369   SDValue Op1 = Op.getOperand(1);
13370   SDLoc dl(Op);
13371   MVT VT = Op.getSimpleValueType();
13372   MVT SrcVT = Op1.getSimpleValueType();
13373
13374   // If second operand is smaller, extend it first.
13375   if (SrcVT.bitsLT(VT)) {
13376     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
13377     SrcVT = VT;
13378   }
13379   // And if it is bigger, shrink it first.
13380   if (SrcVT.bitsGT(VT)) {
13381     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1, dl));
13382     SrcVT = VT;
13383   }
13384
13385   // At this point the operands and the result should have the same
13386   // type, and that won't be f80 since that is not custom lowered.
13387
13388   const fltSemantics &Sem =
13389       VT == MVT::f64 ? APFloat::IEEEdouble : APFloat::IEEEsingle;
13390   const unsigned SizeInBits = VT.getSizeInBits();
13391
13392   SmallVector<Constant *, 4> CV(
13393       VT == MVT::f64 ? 2 : 4,
13394       ConstantFP::get(*Context, APFloat(Sem, APInt(SizeInBits, 0))));
13395
13396   // First, clear all bits but the sign bit from the second operand (sign).
13397   CV[0] = ConstantFP::get(*Context,
13398                           APFloat(Sem, APInt::getHighBitsSet(SizeInBits, 1)));
13399   Constant *C = ConstantVector::get(CV);
13400   auto PtrVT = TLI.getPointerTy(DAG.getDataLayout());
13401   SDValue CPIdx = DAG.getConstantPool(C, PtrVT, 16);
13402
13403   // Perform all logic operations as 16-byte vectors because there are no
13404   // scalar FP logic instructions in SSE. This allows load folding of the
13405   // constants into the logic instructions.
13406   MVT LogicVT = (VT == MVT::f64) ? MVT::v2f64 : MVT::v4f32;
13407   SDValue Mask1 =
13408       DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
13409                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13410                   false, false, false, 16);
13411   Op1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Op1);
13412   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, LogicVT, Op1, Mask1);
13413
13414   // Next, clear the sign bit from the first operand (magnitude).
13415   // If it's a constant, we can clear it here.
13416   if (ConstantFPSDNode *Op0CN = dyn_cast<ConstantFPSDNode>(Op0)) {
13417     APFloat APF = Op0CN->getValueAPF();
13418     // If the magnitude is a positive zero, the sign bit alone is enough.
13419     if (APF.isPosZero())
13420       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SrcVT, SignBit,
13421                          DAG.getIntPtrConstant(0, dl));
13422     APF.clearSign();
13423     CV[0] = ConstantFP::get(*Context, APF);
13424   } else {
13425     CV[0] = ConstantFP::get(
13426         *Context,
13427         APFloat(Sem, APInt::getLowBitsSet(SizeInBits, SizeInBits - 1)));
13428   }
13429   C = ConstantVector::get(CV);
13430   CPIdx = DAG.getConstantPool(C, PtrVT, 16);
13431   SDValue Val =
13432       DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
13433                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13434                   false, false, false, 16);
13435   // If the magnitude operand wasn't a constant, we need to AND out the sign.
13436   if (!isa<ConstantFPSDNode>(Op0)) {
13437     Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Op0);
13438     Val = DAG.getNode(X86ISD::FAND, dl, LogicVT, Op0, Val);
13439   }
13440   // OR the magnitude value with the sign bit.
13441   Val = DAG.getNode(X86ISD::FOR, dl, LogicVT, Val, SignBit);
13442   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SrcVT, Val,
13443                      DAG.getIntPtrConstant(0, dl));
13444 }
13445
13446 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
13447   SDValue N0 = Op.getOperand(0);
13448   SDLoc dl(Op);
13449   MVT VT = Op.getSimpleValueType();
13450
13451   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
13452   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
13453                                   DAG.getConstant(1, dl, VT));
13454   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, dl, VT));
13455 }
13456
13457 // Check whether an OR'd tree is PTEST-able.
13458 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
13459                                       SelectionDAG &DAG) {
13460   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
13461
13462   if (!Subtarget->hasSSE41())
13463     return SDValue();
13464
13465   if (!Op->hasOneUse())
13466     return SDValue();
13467
13468   SDNode *N = Op.getNode();
13469   SDLoc DL(N);
13470
13471   SmallVector<SDValue, 8> Opnds;
13472   DenseMap<SDValue, unsigned> VecInMap;
13473   SmallVector<SDValue, 8> VecIns;
13474   EVT VT = MVT::Other;
13475
13476   // Recognize a special case where a vector is casted into wide integer to
13477   // test all 0s.
13478   Opnds.push_back(N->getOperand(0));
13479   Opnds.push_back(N->getOperand(1));
13480
13481   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
13482     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
13483     // BFS traverse all OR'd operands.
13484     if (I->getOpcode() == ISD::OR) {
13485       Opnds.push_back(I->getOperand(0));
13486       Opnds.push_back(I->getOperand(1));
13487       // Re-evaluate the number of nodes to be traversed.
13488       e += 2; // 2 more nodes (LHS and RHS) are pushed.
13489       continue;
13490     }
13491
13492     // Quit if a non-EXTRACT_VECTOR_ELT
13493     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13494       return SDValue();
13495
13496     // Quit if without a constant index.
13497     SDValue Idx = I->getOperand(1);
13498     if (!isa<ConstantSDNode>(Idx))
13499       return SDValue();
13500
13501     SDValue ExtractedFromVec = I->getOperand(0);
13502     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
13503     if (M == VecInMap.end()) {
13504       VT = ExtractedFromVec.getValueType();
13505       // Quit if not 128/256-bit vector.
13506       if (!VT.is128BitVector() && !VT.is256BitVector())
13507         return SDValue();
13508       // Quit if not the same type.
13509       if (VecInMap.begin() != VecInMap.end() &&
13510           VT != VecInMap.begin()->first.getValueType())
13511         return SDValue();
13512       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
13513       VecIns.push_back(ExtractedFromVec);
13514     }
13515     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
13516   }
13517
13518   assert((VT.is128BitVector() || VT.is256BitVector()) &&
13519          "Not extracted from 128-/256-bit vector.");
13520
13521   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
13522
13523   for (DenseMap<SDValue, unsigned>::const_iterator
13524         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
13525     // Quit if not all elements are used.
13526     if (I->second != FullMask)
13527       return SDValue();
13528   }
13529
13530   MVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
13531
13532   // Cast all vectors into TestVT for PTEST.
13533   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
13534     VecIns[i] = DAG.getBitcast(TestVT, VecIns[i]);
13535
13536   // If more than one full vectors are evaluated, OR them first before PTEST.
13537   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
13538     // Each iteration will OR 2 nodes and append the result until there is only
13539     // 1 node left, i.e. the final OR'd value of all vectors.
13540     SDValue LHS = VecIns[Slot];
13541     SDValue RHS = VecIns[Slot + 1];
13542     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
13543   }
13544
13545   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
13546                      VecIns.back(), VecIns.back());
13547 }
13548
13549 /// \brief return true if \c Op has a use that doesn't just read flags.
13550 static bool hasNonFlagsUse(SDValue Op) {
13551   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
13552        ++UI) {
13553     SDNode *User = *UI;
13554     unsigned UOpNo = UI.getOperandNo();
13555     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
13556       // Look pass truncate.
13557       UOpNo = User->use_begin().getOperandNo();
13558       User = *User->use_begin();
13559     }
13560
13561     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
13562         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
13563       return true;
13564   }
13565   return false;
13566 }
13567
13568 /// Emit nodes that will be selected as "test Op0,Op0", or something
13569 /// equivalent.
13570 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
13571                                     SelectionDAG &DAG) const {
13572   if (Op.getValueType() == MVT::i1) {
13573     SDValue ExtOp = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i8, Op);
13574     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, ExtOp,
13575                        DAG.getConstant(0, dl, MVT::i8));
13576   }
13577   // CF and OF aren't always set the way we want. Determine which
13578   // of these we need.
13579   bool NeedCF = false;
13580   bool NeedOF = false;
13581   switch (X86CC) {
13582   default: break;
13583   case X86::COND_A: case X86::COND_AE:
13584   case X86::COND_B: case X86::COND_BE:
13585     NeedCF = true;
13586     break;
13587   case X86::COND_G: case X86::COND_GE:
13588   case X86::COND_L: case X86::COND_LE:
13589   case X86::COND_O: case X86::COND_NO: {
13590     // Check if we really need to set the
13591     // Overflow flag. If NoSignedWrap is present
13592     // that is not actually needed.
13593     switch (Op->getOpcode()) {
13594     case ISD::ADD:
13595     case ISD::SUB:
13596     case ISD::MUL:
13597     case ISD::SHL: {
13598       const auto *BinNode = cast<BinaryWithFlagsSDNode>(Op.getNode());
13599       if (BinNode->Flags.hasNoSignedWrap())
13600         break;
13601     }
13602     default:
13603       NeedOF = true;
13604       break;
13605     }
13606     break;
13607   }
13608   }
13609   // See if we can use the EFLAGS value from the operand instead of
13610   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
13611   // we prove that the arithmetic won't overflow, we can't use OF or CF.
13612   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
13613     // Emit a CMP with 0, which is the TEST pattern.
13614     //if (Op.getValueType() == MVT::i1)
13615     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
13616     //                     DAG.getConstant(0, MVT::i1));
13617     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
13618                        DAG.getConstant(0, dl, Op.getValueType()));
13619   }
13620   unsigned Opcode = 0;
13621   unsigned NumOperands = 0;
13622
13623   // Truncate operations may prevent the merge of the SETCC instruction
13624   // and the arithmetic instruction before it. Attempt to truncate the operands
13625   // of the arithmetic instruction and use a reduced bit-width instruction.
13626   bool NeedTruncation = false;
13627   SDValue ArithOp = Op;
13628   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
13629     SDValue Arith = Op->getOperand(0);
13630     // Both the trunc and the arithmetic op need to have one user each.
13631     if (Arith->hasOneUse())
13632       switch (Arith.getOpcode()) {
13633         default: break;
13634         case ISD::ADD:
13635         case ISD::SUB:
13636         case ISD::AND:
13637         case ISD::OR:
13638         case ISD::XOR: {
13639           NeedTruncation = true;
13640           ArithOp = Arith;
13641         }
13642       }
13643   }
13644
13645   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
13646   // which may be the result of a CAST.  We use the variable 'Op', which is the
13647   // non-casted variable when we check for possible users.
13648   switch (ArithOp.getOpcode()) {
13649   case ISD::ADD:
13650     // Due to an isel shortcoming, be conservative if this add is likely to be
13651     // selected as part of a load-modify-store instruction. When the root node
13652     // in a match is a store, isel doesn't know how to remap non-chain non-flag
13653     // uses of other nodes in the match, such as the ADD in this case. This
13654     // leads to the ADD being left around and reselected, with the result being
13655     // two adds in the output.  Alas, even if none our users are stores, that
13656     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
13657     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
13658     // climbing the DAG back to the root, and it doesn't seem to be worth the
13659     // effort.
13660     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
13661          UE = Op.getNode()->use_end(); UI != UE; ++UI)
13662       if (UI->getOpcode() != ISD::CopyToReg &&
13663           UI->getOpcode() != ISD::SETCC &&
13664           UI->getOpcode() != ISD::STORE)
13665         goto default_case;
13666
13667     if (ConstantSDNode *C =
13668         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
13669       // An add of one will be selected as an INC.
13670       if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
13671         Opcode = X86ISD::INC;
13672         NumOperands = 1;
13673         break;
13674       }
13675
13676       // An add of negative one (subtract of one) will be selected as a DEC.
13677       if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
13678         Opcode = X86ISD::DEC;
13679         NumOperands = 1;
13680         break;
13681       }
13682     }
13683
13684     // Otherwise use a regular EFLAGS-setting add.
13685     Opcode = X86ISD::ADD;
13686     NumOperands = 2;
13687     break;
13688   case ISD::SHL:
13689   case ISD::SRL:
13690     // If we have a constant logical shift that's only used in a comparison
13691     // against zero turn it into an equivalent AND. This allows turning it into
13692     // a TEST instruction later.
13693     if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
13694         isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
13695       EVT VT = Op.getValueType();
13696       unsigned BitWidth = VT.getSizeInBits();
13697       unsigned ShAmt = Op->getConstantOperandVal(1);
13698       if (ShAmt >= BitWidth) // Avoid undefined shifts.
13699         break;
13700       APInt Mask = ArithOp.getOpcode() == ISD::SRL
13701                        ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
13702                        : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
13703       if (!Mask.isSignedIntN(32)) // Avoid large immediates.
13704         break;
13705       SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
13706                                 DAG.getConstant(Mask, dl, VT));
13707       DAG.ReplaceAllUsesWith(Op, New);
13708       Op = New;
13709     }
13710     break;
13711
13712   case ISD::AND:
13713     // If the primary and result isn't used, don't bother using X86ISD::AND,
13714     // because a TEST instruction will be better.
13715     if (!hasNonFlagsUse(Op))
13716       break;
13717     // FALL THROUGH
13718   case ISD::SUB:
13719   case ISD::OR:
13720   case ISD::XOR:
13721     // Due to the ISEL shortcoming noted above, be conservative if this op is
13722     // likely to be selected as part of a load-modify-store instruction.
13723     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
13724            UE = Op.getNode()->use_end(); UI != UE; ++UI)
13725       if (UI->getOpcode() == ISD::STORE)
13726         goto default_case;
13727
13728     // Otherwise use a regular EFLAGS-setting instruction.
13729     switch (ArithOp.getOpcode()) {
13730     default: llvm_unreachable("unexpected operator!");
13731     case ISD::SUB: Opcode = X86ISD::SUB; break;
13732     case ISD::XOR: Opcode = X86ISD::XOR; break;
13733     case ISD::AND: Opcode = X86ISD::AND; break;
13734     case ISD::OR: {
13735       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
13736         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
13737         if (EFLAGS.getNode())
13738           return EFLAGS;
13739       }
13740       Opcode = X86ISD::OR;
13741       break;
13742     }
13743     }
13744
13745     NumOperands = 2;
13746     break;
13747   case X86ISD::ADD:
13748   case X86ISD::SUB:
13749   case X86ISD::INC:
13750   case X86ISD::DEC:
13751   case X86ISD::OR:
13752   case X86ISD::XOR:
13753   case X86ISD::AND:
13754     return SDValue(Op.getNode(), 1);
13755   default:
13756   default_case:
13757     break;
13758   }
13759
13760   // If we found that truncation is beneficial, perform the truncation and
13761   // update 'Op'.
13762   if (NeedTruncation) {
13763     EVT VT = Op.getValueType();
13764     SDValue WideVal = Op->getOperand(0);
13765     EVT WideVT = WideVal.getValueType();
13766     unsigned ConvertedOp = 0;
13767     // Use a target machine opcode to prevent further DAGCombine
13768     // optimizations that may separate the arithmetic operations
13769     // from the setcc node.
13770     switch (WideVal.getOpcode()) {
13771       default: break;
13772       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
13773       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
13774       case ISD::AND: ConvertedOp = X86ISD::AND; break;
13775       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
13776       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
13777     }
13778
13779     if (ConvertedOp) {
13780       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13781       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
13782         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
13783         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
13784         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
13785       }
13786     }
13787   }
13788
13789   if (Opcode == 0)
13790     // Emit a CMP with 0, which is the TEST pattern.
13791     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
13792                        DAG.getConstant(0, dl, Op.getValueType()));
13793
13794   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
13795   SmallVector<SDValue, 4> Ops(Op->op_begin(), Op->op_begin() + NumOperands);
13796
13797   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
13798   DAG.ReplaceAllUsesWith(Op, New);
13799   return SDValue(New.getNode(), 1);
13800 }
13801
13802 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
13803 /// equivalent.
13804 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
13805                                    SDLoc dl, SelectionDAG &DAG) const {
13806   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
13807     if (C->getAPIntValue() == 0)
13808       return EmitTest(Op0, X86CC, dl, DAG);
13809
13810      assert(Op0.getValueType() != MVT::i1 &&
13811             "Unexpected comparison operation for MVT::i1 operands");
13812   }
13813
13814   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
13815        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
13816     // Do the comparison at i32 if it's smaller, besides the Atom case.
13817     // This avoids subregister aliasing issues. Keep the smaller reference
13818     // if we're optimizing for size, however, as that'll allow better folding
13819     // of memory operations.
13820     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
13821         !DAG.getMachineFunction().getFunction()->optForMinSize() &&
13822         !Subtarget->isAtom()) {
13823       unsigned ExtendOp =
13824           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
13825       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
13826       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
13827     }
13828     // Use SUB instead of CMP to enable CSE between SUB and CMP.
13829     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
13830     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
13831                               Op0, Op1);
13832     return SDValue(Sub.getNode(), 1);
13833   }
13834   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
13835 }
13836
13837 /// Convert a comparison if required by the subtarget.
13838 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
13839                                                  SelectionDAG &DAG) const {
13840   // If the subtarget does not support the FUCOMI instruction, floating-point
13841   // comparisons have to be converted.
13842   if (Subtarget->hasCMov() ||
13843       Cmp.getOpcode() != X86ISD::CMP ||
13844       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
13845       !Cmp.getOperand(1).getValueType().isFloatingPoint())
13846     return Cmp;
13847
13848   // The instruction selector will select an FUCOM instruction instead of
13849   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
13850   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
13851   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
13852   SDLoc dl(Cmp);
13853   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
13854   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
13855   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
13856                             DAG.getConstant(8, dl, MVT::i8));
13857   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
13858   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
13859 }
13860
13861 /// The minimum architected relative accuracy is 2^-12. We need one
13862 /// Newton-Raphson step to have a good float result (24 bits of precision).
13863 SDValue X86TargetLowering::getRsqrtEstimate(SDValue Op,
13864                                             DAGCombinerInfo &DCI,
13865                                             unsigned &RefinementSteps,
13866                                             bool &UseOneConstNR) const {
13867   EVT VT = Op.getValueType();
13868   const char *RecipOp;
13869
13870   // SSE1 has rsqrtss and rsqrtps. AVX adds a 256-bit variant for rsqrtps.
13871   // TODO: Add support for AVX512 (v16f32).
13872   // It is likely not profitable to do this for f64 because a double-precision
13873   // rsqrt estimate with refinement on x86 prior to FMA requires at least 16
13874   // instructions: convert to single, rsqrtss, convert back to double, refine
13875   // (3 steps = at least 13 insts). If an 'rsqrtsd' variant was added to the ISA
13876   // along with FMA, this could be a throughput win.
13877   if (VT == MVT::f32 && Subtarget->hasSSE1())
13878     RecipOp = "sqrtf";
13879   else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
13880            (VT == MVT::v8f32 && Subtarget->hasAVX()))
13881     RecipOp = "vec-sqrtf";
13882   else
13883     return SDValue();
13884
13885   TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
13886   if (!Recips.isEnabled(RecipOp))
13887     return SDValue();
13888
13889   RefinementSteps = Recips.getRefinementSteps(RecipOp);
13890   UseOneConstNR = false;
13891   return DCI.DAG.getNode(X86ISD::FRSQRT, SDLoc(Op), VT, Op);
13892 }
13893
13894 /// The minimum architected relative accuracy is 2^-12. We need one
13895 /// Newton-Raphson step to have a good float result (24 bits of precision).
13896 SDValue X86TargetLowering::getRecipEstimate(SDValue Op,
13897                                             DAGCombinerInfo &DCI,
13898                                             unsigned &RefinementSteps) const {
13899   EVT VT = Op.getValueType();
13900   const char *RecipOp;
13901
13902   // SSE1 has rcpss and rcpps. AVX adds a 256-bit variant for rcpps.
13903   // TODO: Add support for AVX512 (v16f32).
13904   // It is likely not profitable to do this for f64 because a double-precision
13905   // reciprocal estimate with refinement on x86 prior to FMA requires
13906   // 15 instructions: convert to single, rcpss, convert back to double, refine
13907   // (3 steps = 12 insts). If an 'rcpsd' variant was added to the ISA
13908   // along with FMA, this could be a throughput win.
13909   if (VT == MVT::f32 && Subtarget->hasSSE1())
13910     RecipOp = "divf";
13911   else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
13912            (VT == MVT::v8f32 && Subtarget->hasAVX()))
13913     RecipOp = "vec-divf";
13914   else
13915     return SDValue();
13916
13917   TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
13918   if (!Recips.isEnabled(RecipOp))
13919     return SDValue();
13920
13921   RefinementSteps = Recips.getRefinementSteps(RecipOp);
13922   return DCI.DAG.getNode(X86ISD::FRCP, SDLoc(Op), VT, Op);
13923 }
13924
13925 /// If we have at least two divisions that use the same divisor, convert to
13926 /// multplication by a reciprocal. This may need to be adjusted for a given
13927 /// CPU if a division's cost is not at least twice the cost of a multiplication.
13928 /// This is because we still need one division to calculate the reciprocal and
13929 /// then we need two multiplies by that reciprocal as replacements for the
13930 /// original divisions.
13931 unsigned X86TargetLowering::combineRepeatedFPDivisors() const {
13932   return 2;
13933 }
13934
13935 static bool isAllOnes(SDValue V) {
13936   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
13937   return C && C->isAllOnesValue();
13938 }
13939
13940 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
13941 /// if it's possible.
13942 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
13943                                      SDLoc dl, SelectionDAG &DAG) const {
13944   SDValue Op0 = And.getOperand(0);
13945   SDValue Op1 = And.getOperand(1);
13946   if (Op0.getOpcode() == ISD::TRUNCATE)
13947     Op0 = Op0.getOperand(0);
13948   if (Op1.getOpcode() == ISD::TRUNCATE)
13949     Op1 = Op1.getOperand(0);
13950
13951   SDValue LHS, RHS;
13952   if (Op1.getOpcode() == ISD::SHL)
13953     std::swap(Op0, Op1);
13954   if (Op0.getOpcode() == ISD::SHL) {
13955     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
13956       if (And00C->getZExtValue() == 1) {
13957         // If we looked past a truncate, check that it's only truncating away
13958         // known zeros.
13959         unsigned BitWidth = Op0.getValueSizeInBits();
13960         unsigned AndBitWidth = And.getValueSizeInBits();
13961         if (BitWidth > AndBitWidth) {
13962           APInt Zeros, Ones;
13963           DAG.computeKnownBits(Op0, Zeros, Ones);
13964           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
13965             return SDValue();
13966         }
13967         LHS = Op1;
13968         RHS = Op0.getOperand(1);
13969       }
13970   } else if (Op1.getOpcode() == ISD::Constant) {
13971     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
13972     uint64_t AndRHSVal = AndRHS->getZExtValue();
13973     SDValue AndLHS = Op0;
13974
13975     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
13976       LHS = AndLHS.getOperand(0);
13977       RHS = AndLHS.getOperand(1);
13978     }
13979
13980     // Use BT if the immediate can't be encoded in a TEST instruction.
13981     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
13982       LHS = AndLHS;
13983       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), dl, LHS.getValueType());
13984     }
13985   }
13986
13987   if (LHS.getNode()) {
13988     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
13989     // instruction.  Since the shift amount is in-range-or-undefined, we know
13990     // that doing a bittest on the i32 value is ok.  We extend to i32 because
13991     // the encoding for the i16 version is larger than the i32 version.
13992     // Also promote i16 to i32 for performance / code size reason.
13993     if (LHS.getValueType() == MVT::i8 ||
13994         LHS.getValueType() == MVT::i16)
13995       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
13996
13997     // If the operand types disagree, extend the shift amount to match.  Since
13998     // BT ignores high bits (like shifts) we can use anyextend.
13999     if (LHS.getValueType() != RHS.getValueType())
14000       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
14001
14002     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
14003     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
14004     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14005                        DAG.getConstant(Cond, dl, MVT::i8), BT);
14006   }
14007
14008   return SDValue();
14009 }
14010
14011 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
14012 /// mask CMPs.
14013 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
14014                               SDValue &Op1) {
14015   unsigned SSECC;
14016   bool Swap = false;
14017
14018   // SSE Condition code mapping:
14019   //  0 - EQ
14020   //  1 - LT
14021   //  2 - LE
14022   //  3 - UNORD
14023   //  4 - NEQ
14024   //  5 - NLT
14025   //  6 - NLE
14026   //  7 - ORD
14027   switch (SetCCOpcode) {
14028   default: llvm_unreachable("Unexpected SETCC condition");
14029   case ISD::SETOEQ:
14030   case ISD::SETEQ:  SSECC = 0; break;
14031   case ISD::SETOGT:
14032   case ISD::SETGT:  Swap = true; // Fallthrough
14033   case ISD::SETLT:
14034   case ISD::SETOLT: SSECC = 1; break;
14035   case ISD::SETOGE:
14036   case ISD::SETGE:  Swap = true; // Fallthrough
14037   case ISD::SETLE:
14038   case ISD::SETOLE: SSECC = 2; break;
14039   case ISD::SETUO:  SSECC = 3; break;
14040   case ISD::SETUNE:
14041   case ISD::SETNE:  SSECC = 4; break;
14042   case ISD::SETULE: Swap = true; // Fallthrough
14043   case ISD::SETUGE: SSECC = 5; break;
14044   case ISD::SETULT: Swap = true; // Fallthrough
14045   case ISD::SETUGT: SSECC = 6; break;
14046   case ISD::SETO:   SSECC = 7; break;
14047   case ISD::SETUEQ:
14048   case ISD::SETONE: SSECC = 8; break;
14049   }
14050   if (Swap)
14051     std::swap(Op0, Op1);
14052
14053   return SSECC;
14054 }
14055
14056 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
14057 // ones, and then concatenate the result back.
14058 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
14059   MVT VT = Op.getSimpleValueType();
14060
14061   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
14062          "Unsupported value type for operation");
14063
14064   unsigned NumElems = VT.getVectorNumElements();
14065   SDLoc dl(Op);
14066   SDValue CC = Op.getOperand(2);
14067
14068   // Extract the LHS vectors
14069   SDValue LHS = Op.getOperand(0);
14070   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
14071   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
14072
14073   // Extract the RHS vectors
14074   SDValue RHS = Op.getOperand(1);
14075   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
14076   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
14077
14078   // Issue the operation on the smaller types and concatenate the result back
14079   MVT EltVT = VT.getVectorElementType();
14080   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
14081   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
14082                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
14083                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
14084 }
14085
14086 static SDValue LowerBoolVSETCC_AVX512(SDValue Op, SelectionDAG &DAG) {
14087   SDValue Op0 = Op.getOperand(0);
14088   SDValue Op1 = Op.getOperand(1);
14089   SDValue CC = Op.getOperand(2);
14090   MVT VT = Op.getSimpleValueType();
14091   SDLoc dl(Op);
14092
14093   assert(Op0.getSimpleValueType().getVectorElementType() == MVT::i1 &&
14094          "Unexpected type for boolean compare operation");
14095   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
14096   SDValue NotOp0 = DAG.getNode(ISD::XOR, dl, VT, Op0,
14097                                DAG.getConstant(-1, dl, VT));
14098   SDValue NotOp1 = DAG.getNode(ISD::XOR, dl, VT, Op1,
14099                                DAG.getConstant(-1, dl, VT));
14100   switch (SetCCOpcode) {
14101   default: llvm_unreachable("Unexpected SETCC condition");
14102   case ISD::SETEQ:
14103     // (x == y) -> ~(x ^ y)
14104     return DAG.getNode(ISD::XOR, dl, VT,
14105                        DAG.getNode(ISD::XOR, dl, VT, Op0, Op1),
14106                        DAG.getConstant(-1, dl, VT));
14107   case ISD::SETNE:
14108     // (x != y) -> (x ^ y)
14109     return DAG.getNode(ISD::XOR, dl, VT, Op0, Op1);
14110   case ISD::SETUGT:
14111   case ISD::SETGT:
14112     // (x > y) -> (x & ~y)
14113     return DAG.getNode(ISD::AND, dl, VT, Op0, NotOp1);
14114   case ISD::SETULT:
14115   case ISD::SETLT:
14116     // (x < y) -> (~x & y)
14117     return DAG.getNode(ISD::AND, dl, VT, NotOp0, Op1);
14118   case ISD::SETULE:
14119   case ISD::SETLE:
14120     // (x <= y) -> (~x | y)
14121     return DAG.getNode(ISD::OR, dl, VT, NotOp0, Op1);
14122   case ISD::SETUGE:
14123   case ISD::SETGE:
14124     // (x >=y) -> (x | ~y)
14125     return DAG.getNode(ISD::OR, dl, VT, Op0, NotOp1);
14126   }
14127 }
14128
14129 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
14130                                      const X86Subtarget *Subtarget) {
14131   SDValue Op0 = Op.getOperand(0);
14132   SDValue Op1 = Op.getOperand(1);
14133   SDValue CC = Op.getOperand(2);
14134   MVT VT = Op.getSimpleValueType();
14135   SDLoc dl(Op);
14136
14137   assert(Op0.getSimpleValueType().getVectorElementType().getSizeInBits() >= 8 &&
14138          Op.getSimpleValueType().getVectorElementType() == MVT::i1 &&
14139          "Cannot set masked compare for this operation");
14140
14141   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
14142   unsigned  Opc = 0;
14143   bool Unsigned = false;
14144   bool Swap = false;
14145   unsigned SSECC;
14146   switch (SetCCOpcode) {
14147   default: llvm_unreachable("Unexpected SETCC condition");
14148   case ISD::SETNE:  SSECC = 4; break;
14149   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
14150   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
14151   case ISD::SETLT:  Swap = true; //fall-through
14152   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
14153   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
14154   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
14155   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
14156   case ISD::SETULE: Unsigned = true; //fall-through
14157   case ISD::SETLE:  SSECC = 2; break;
14158   }
14159
14160   if (Swap)
14161     std::swap(Op0, Op1);
14162   if (Opc)
14163     return DAG.getNode(Opc, dl, VT, Op0, Op1);
14164   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
14165   return DAG.getNode(Opc, dl, VT, Op0, Op1,
14166                      DAG.getConstant(SSECC, dl, MVT::i8));
14167 }
14168
14169 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
14170 /// operand \p Op1.  If non-trivial (for example because it's not constant)
14171 /// return an empty value.
14172 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
14173 {
14174   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
14175   if (!BV)
14176     return SDValue();
14177
14178   MVT VT = Op1.getSimpleValueType();
14179   MVT EVT = VT.getVectorElementType();
14180   unsigned n = VT.getVectorNumElements();
14181   SmallVector<SDValue, 8> ULTOp1;
14182
14183   for (unsigned i = 0; i < n; ++i) {
14184     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
14185     if (!Elt || Elt->isOpaque() || Elt->getSimpleValueType(0) != EVT)
14186       return SDValue();
14187
14188     // Avoid underflow.
14189     APInt Val = Elt->getAPIntValue();
14190     if (Val == 0)
14191       return SDValue();
14192
14193     ULTOp1.push_back(DAG.getConstant(Val - 1, dl, EVT));
14194   }
14195
14196   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
14197 }
14198
14199 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
14200                            SelectionDAG &DAG) {
14201   SDValue Op0 = Op.getOperand(0);
14202   SDValue Op1 = Op.getOperand(1);
14203   SDValue CC = Op.getOperand(2);
14204   MVT VT = Op.getSimpleValueType();
14205   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
14206   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
14207   SDLoc dl(Op);
14208
14209   if (isFP) {
14210 #ifndef NDEBUG
14211     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
14212     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
14213 #endif
14214
14215     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
14216     unsigned Opc = X86ISD::CMPP;
14217     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
14218       assert(VT.getVectorNumElements() <= 16);
14219       Opc = X86ISD::CMPM;
14220     }
14221     // In the two special cases we can't handle, emit two comparisons.
14222     if (SSECC == 8) {
14223       unsigned CC0, CC1;
14224       unsigned CombineOpc;
14225       if (SetCCOpcode == ISD::SETUEQ) {
14226         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
14227       } else {
14228         assert(SetCCOpcode == ISD::SETONE);
14229         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
14230       }
14231
14232       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
14233                                  DAG.getConstant(CC0, dl, MVT::i8));
14234       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
14235                                  DAG.getConstant(CC1, dl, MVT::i8));
14236       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
14237     }
14238     // Handle all other FP comparisons here.
14239     return DAG.getNode(Opc, dl, VT, Op0, Op1,
14240                        DAG.getConstant(SSECC, dl, MVT::i8));
14241   }
14242
14243   MVT VTOp0 = Op0.getSimpleValueType();
14244   assert(VTOp0 == Op1.getSimpleValueType() &&
14245          "Expected operands with same type!");
14246   assert(VT.getVectorNumElements() == VTOp0.getVectorNumElements() &&
14247          "Invalid number of packed elements for source and destination!");
14248
14249   if (VT.is128BitVector() && VTOp0.is256BitVector()) {
14250     // On non-AVX512 targets, a vector of MVT::i1 is promoted by the type
14251     // legalizer to a wider vector type.  In the case of 'vsetcc' nodes, the
14252     // legalizer firstly checks if the first operand in input to the setcc has
14253     // a legal type. If so, then it promotes the return type to that same type.
14254     // Otherwise, the return type is promoted to the 'next legal type' which,
14255     // for a vector of MVT::i1 is always a 128-bit integer vector type.
14256     //
14257     // We reach this code only if the following two conditions are met:
14258     // 1. Both return type and operand type have been promoted to wider types
14259     //    by the type legalizer.
14260     // 2. The original operand type has been promoted to a 256-bit vector.
14261     //
14262     // Note that condition 2. only applies for AVX targets.
14263     SDValue NewOp = DAG.getSetCC(dl, VTOp0, Op0, Op1, SetCCOpcode);
14264     return DAG.getZExtOrTrunc(NewOp, dl, VT);
14265   }
14266
14267   // The non-AVX512 code below works under the assumption that source and
14268   // destination types are the same.
14269   assert((Subtarget->hasAVX512() || (VT == VTOp0)) &&
14270          "Value types for source and destination must be the same!");
14271
14272   // Break 256-bit integer vector compare into smaller ones.
14273   if (VT.is256BitVector() && !Subtarget->hasInt256())
14274     return Lower256IntVSETCC(Op, DAG);
14275
14276   MVT OpVT = Op1.getSimpleValueType();
14277   if (OpVT.getVectorElementType() == MVT::i1)
14278     return LowerBoolVSETCC_AVX512(Op, DAG);
14279
14280   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
14281   if (Subtarget->hasAVX512()) {
14282     if (Op1.getSimpleValueType().is512BitVector() ||
14283         (Subtarget->hasBWI() && Subtarget->hasVLX()) ||
14284         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
14285       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
14286
14287     // In AVX-512 architecture setcc returns mask with i1 elements,
14288     // But there is no compare instruction for i8 and i16 elements in KNL.
14289     // We are not talking about 512-bit operands in this case, these
14290     // types are illegal.
14291     if (MaskResult &&
14292         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
14293          OpVT.getVectorElementType().getSizeInBits() >= 8))
14294       return DAG.getNode(ISD::TRUNCATE, dl, VT,
14295                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
14296   }
14297
14298   // Lower using XOP integer comparisons.
14299   if ((VT == MVT::v16i8 || VT == MVT::v8i16 ||
14300        VT == MVT::v4i32 || VT == MVT::v2i64) && Subtarget->hasXOP()) {
14301     // Translate compare code to XOP PCOM compare mode.
14302     unsigned CmpMode = 0;
14303     switch (SetCCOpcode) {
14304     default: llvm_unreachable("Unexpected SETCC condition");
14305     case ISD::SETULT:
14306     case ISD::SETLT: CmpMode = 0x00; break;
14307     case ISD::SETULE:
14308     case ISD::SETLE: CmpMode = 0x01; break;
14309     case ISD::SETUGT:
14310     case ISD::SETGT: CmpMode = 0x02; break;
14311     case ISD::SETUGE:
14312     case ISD::SETGE: CmpMode = 0x03; break;
14313     case ISD::SETEQ: CmpMode = 0x04; break;
14314     case ISD::SETNE: CmpMode = 0x05; break;
14315     }
14316
14317     // Are we comparing unsigned or signed integers?
14318     unsigned Opc = ISD::isUnsignedIntSetCC(SetCCOpcode)
14319       ? X86ISD::VPCOMU : X86ISD::VPCOM;
14320
14321     return DAG.getNode(Opc, dl, VT, Op0, Op1,
14322                        DAG.getConstant(CmpMode, dl, MVT::i8));
14323   }
14324
14325   // We are handling one of the integer comparisons here.  Since SSE only has
14326   // GT and EQ comparisons for integer, swapping operands and multiple
14327   // operations may be required for some comparisons.
14328   unsigned Opc;
14329   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
14330   bool Subus = false;
14331
14332   switch (SetCCOpcode) {
14333   default: llvm_unreachable("Unexpected SETCC condition");
14334   case ISD::SETNE:  Invert = true;
14335   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
14336   case ISD::SETLT:  Swap = true;
14337   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
14338   case ISD::SETGE:  Swap = true;
14339   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
14340                     Invert = true; break;
14341   case ISD::SETULT: Swap = true;
14342   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
14343                     FlipSigns = true; break;
14344   case ISD::SETUGE: Swap = true;
14345   case ISD::SETULE: Opc = X86ISD::PCMPGT;
14346                     FlipSigns = true; Invert = true; break;
14347   }
14348
14349   // Special case: Use min/max operations for SETULE/SETUGE
14350   MVT VET = VT.getVectorElementType();
14351   bool hasMinMax =
14352        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
14353     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
14354
14355   if (hasMinMax) {
14356     switch (SetCCOpcode) {
14357     default: break;
14358     case ISD::SETULE: Opc = ISD::UMIN; MinMax = true; break;
14359     case ISD::SETUGE: Opc = ISD::UMAX; MinMax = true; break;
14360     }
14361
14362     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
14363   }
14364
14365   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
14366   if (!MinMax && hasSubus) {
14367     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
14368     // Op0 u<= Op1:
14369     //   t = psubus Op0, Op1
14370     //   pcmpeq t, <0..0>
14371     switch (SetCCOpcode) {
14372     default: break;
14373     case ISD::SETULT: {
14374       // If the comparison is against a constant we can turn this into a
14375       // setule.  With psubus, setule does not require a swap.  This is
14376       // beneficial because the constant in the register is no longer
14377       // destructed as the destination so it can be hoisted out of a loop.
14378       // Only do this pre-AVX since vpcmp* is no longer destructive.
14379       if (Subtarget->hasAVX())
14380         break;
14381       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
14382       if (ULEOp1.getNode()) {
14383         Op1 = ULEOp1;
14384         Subus = true; Invert = false; Swap = false;
14385       }
14386       break;
14387     }
14388     // Psubus is better than flip-sign because it requires no inversion.
14389     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
14390     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
14391     }
14392
14393     if (Subus) {
14394       Opc = X86ISD::SUBUS;
14395       FlipSigns = false;
14396     }
14397   }
14398
14399   if (Swap)
14400     std::swap(Op0, Op1);
14401
14402   // Check that the operation in question is available (most are plain SSE2,
14403   // but PCMPGTQ and PCMPEQQ have different requirements).
14404   if (VT == MVT::v2i64) {
14405     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
14406       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
14407
14408       // First cast everything to the right type.
14409       Op0 = DAG.getBitcast(MVT::v4i32, Op0);
14410       Op1 = DAG.getBitcast(MVT::v4i32, Op1);
14411
14412       // Since SSE has no unsigned integer comparisons, we need to flip the sign
14413       // bits of the inputs before performing those operations. The lower
14414       // compare is always unsigned.
14415       SDValue SB;
14416       if (FlipSigns) {
14417         SB = DAG.getConstant(0x80000000U, dl, MVT::v4i32);
14418       } else {
14419         SDValue Sign = DAG.getConstant(0x80000000U, dl, MVT::i32);
14420         SDValue Zero = DAG.getConstant(0x00000000U, dl, MVT::i32);
14421         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
14422                          Sign, Zero, Sign, Zero);
14423       }
14424       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
14425       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
14426
14427       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
14428       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
14429       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
14430
14431       // Create masks for only the low parts/high parts of the 64 bit integers.
14432       static const int MaskHi[] = { 1, 1, 3, 3 };
14433       static const int MaskLo[] = { 0, 0, 2, 2 };
14434       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
14435       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
14436       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
14437
14438       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
14439       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
14440
14441       if (Invert)
14442         Result = DAG.getNOT(dl, Result, MVT::v4i32);
14443
14444       return DAG.getBitcast(VT, Result);
14445     }
14446
14447     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
14448       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
14449       // pcmpeqd + pshufd + pand.
14450       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
14451
14452       // First cast everything to the right type.
14453       Op0 = DAG.getBitcast(MVT::v4i32, Op0);
14454       Op1 = DAG.getBitcast(MVT::v4i32, Op1);
14455
14456       // Do the compare.
14457       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
14458
14459       // Make sure the lower and upper halves are both all-ones.
14460       static const int Mask[] = { 1, 0, 3, 2 };
14461       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
14462       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
14463
14464       if (Invert)
14465         Result = DAG.getNOT(dl, Result, MVT::v4i32);
14466
14467       return DAG.getBitcast(VT, Result);
14468     }
14469   }
14470
14471   // Since SSE has no unsigned integer comparisons, we need to flip the sign
14472   // bits of the inputs before performing those operations.
14473   if (FlipSigns) {
14474     MVT EltVT = VT.getVectorElementType();
14475     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), dl,
14476                                  VT);
14477     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
14478     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
14479   }
14480
14481   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
14482
14483   // If the logical-not of the result is required, perform that now.
14484   if (Invert)
14485     Result = DAG.getNOT(dl, Result, VT);
14486
14487   if (MinMax)
14488     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
14489
14490   if (Subus)
14491     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
14492                          getZeroVector(VT, Subtarget, DAG, dl));
14493
14494   return Result;
14495 }
14496
14497 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
14498
14499   MVT VT = Op.getSimpleValueType();
14500
14501   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
14502
14503   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
14504          && "SetCC type must be 8-bit or 1-bit integer");
14505   SDValue Op0 = Op.getOperand(0);
14506   SDValue Op1 = Op.getOperand(1);
14507   SDLoc dl(Op);
14508   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
14509
14510   // Optimize to BT if possible.
14511   // Lower (X & (1 << N)) == 0 to BT(X, N).
14512   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
14513   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
14514   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
14515       Op1.getOpcode() == ISD::Constant &&
14516       cast<ConstantSDNode>(Op1)->isNullValue() &&
14517       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14518     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
14519     if (NewSetCC.getNode()) {
14520       if (VT == MVT::i1)
14521         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewSetCC);
14522       return NewSetCC;
14523     }
14524   }
14525
14526   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
14527   // these.
14528   if (Op1.getOpcode() == ISD::Constant &&
14529       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
14530        cast<ConstantSDNode>(Op1)->isNullValue()) &&
14531       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14532
14533     // If the input is a setcc, then reuse the input setcc or use a new one with
14534     // the inverted condition.
14535     if (Op0.getOpcode() == X86ISD::SETCC) {
14536       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
14537       bool Invert = (CC == ISD::SETNE) ^
14538         cast<ConstantSDNode>(Op1)->isNullValue();
14539       if (!Invert)
14540         return Op0;
14541
14542       CCode = X86::GetOppositeBranchCondition(CCode);
14543       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14544                                   DAG.getConstant(CCode, dl, MVT::i8),
14545                                   Op0.getOperand(1));
14546       if (VT == MVT::i1)
14547         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
14548       return SetCC;
14549     }
14550   }
14551   if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
14552       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
14553       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14554
14555     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
14556     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, dl, MVT::i1), NewCC);
14557   }
14558
14559   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
14560   unsigned X86CC = TranslateX86CC(CC, dl, isFP, Op0, Op1, DAG);
14561   if (X86CC == X86::COND_INVALID)
14562     return SDValue();
14563
14564   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
14565   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
14566   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14567                               DAG.getConstant(X86CC, dl, MVT::i8), EFLAGS);
14568   if (VT == MVT::i1)
14569     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
14570   return SetCC;
14571 }
14572
14573 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
14574 static bool isX86LogicalCmp(SDValue Op) {
14575   unsigned Opc = Op.getNode()->getOpcode();
14576   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
14577       Opc == X86ISD::SAHF)
14578     return true;
14579   if (Op.getResNo() == 1 &&
14580       (Opc == X86ISD::ADD ||
14581        Opc == X86ISD::SUB ||
14582        Opc == X86ISD::ADC ||
14583        Opc == X86ISD::SBB ||
14584        Opc == X86ISD::SMUL ||
14585        Opc == X86ISD::UMUL ||
14586        Opc == X86ISD::INC ||
14587        Opc == X86ISD::DEC ||
14588        Opc == X86ISD::OR ||
14589        Opc == X86ISD::XOR ||
14590        Opc == X86ISD::AND))
14591     return true;
14592
14593   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
14594     return true;
14595
14596   return false;
14597 }
14598
14599 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
14600   if (V.getOpcode() != ISD::TRUNCATE)
14601     return false;
14602
14603   SDValue VOp0 = V.getOperand(0);
14604   unsigned InBits = VOp0.getValueSizeInBits();
14605   unsigned Bits = V.getValueSizeInBits();
14606   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
14607 }
14608
14609 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
14610   bool addTest = true;
14611   SDValue Cond  = Op.getOperand(0);
14612   SDValue Op1 = Op.getOperand(1);
14613   SDValue Op2 = Op.getOperand(2);
14614   SDLoc DL(Op);
14615   MVT VT = Op1.getSimpleValueType();
14616   SDValue CC;
14617
14618   // Lower FP selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
14619   // are available or VBLENDV if AVX is available.
14620   // Otherwise FP cmovs get lowered into a less efficient branch sequence later.
14621   if (Cond.getOpcode() == ISD::SETCC &&
14622       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
14623        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
14624       VT == Cond.getOperand(0).getSimpleValueType() && Cond->hasOneUse()) {
14625     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
14626     int SSECC = translateX86FSETCC(
14627         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
14628
14629     if (SSECC != 8) {
14630       if (Subtarget->hasAVX512()) {
14631         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
14632                                   DAG.getConstant(SSECC, DL, MVT::i8));
14633         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
14634       }
14635
14636       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
14637                                 DAG.getConstant(SSECC, DL, MVT::i8));
14638
14639       // If we have AVX, we can use a variable vector select (VBLENDV) instead
14640       // of 3 logic instructions for size savings and potentially speed.
14641       // Unfortunately, there is no scalar form of VBLENDV.
14642
14643       // If either operand is a constant, don't try this. We can expect to
14644       // optimize away at least one of the logic instructions later in that
14645       // case, so that sequence would be faster than a variable blend.
14646
14647       // BLENDV was introduced with SSE 4.1, but the 2 register form implicitly
14648       // uses XMM0 as the selection register. That may need just as many
14649       // instructions as the AND/ANDN/OR sequence due to register moves, so
14650       // don't bother.
14651
14652       if (Subtarget->hasAVX() &&
14653           !isa<ConstantFPSDNode>(Op1) && !isa<ConstantFPSDNode>(Op2)) {
14654
14655         // Convert to vectors, do a VSELECT, and convert back to scalar.
14656         // All of the conversions should be optimized away.
14657
14658         MVT VecVT = VT == MVT::f32 ? MVT::v4f32 : MVT::v2f64;
14659         SDValue VOp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op1);
14660         SDValue VOp2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op2);
14661         SDValue VCmp = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Cmp);
14662
14663         MVT VCmpVT = VT == MVT::f32 ? MVT::v4i32 : MVT::v2i64;
14664         VCmp = DAG.getBitcast(VCmpVT, VCmp);
14665
14666         SDValue VSel = DAG.getNode(ISD::VSELECT, DL, VecVT, VCmp, VOp1, VOp2);
14667
14668         return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
14669                            VSel, DAG.getIntPtrConstant(0, DL));
14670       }
14671       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
14672       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
14673       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
14674     }
14675   }
14676
14677   if (VT.isVector() && VT.getVectorElementType() == MVT::i1) {
14678     SDValue Op1Scalar;
14679     if (ISD::isBuildVectorOfConstantSDNodes(Op1.getNode()))
14680       Op1Scalar = ConvertI1VectorToInteger(Op1, DAG);
14681     else if (Op1.getOpcode() == ISD::BITCAST && Op1.getOperand(0))
14682       Op1Scalar = Op1.getOperand(0);
14683     SDValue Op2Scalar;
14684     if (ISD::isBuildVectorOfConstantSDNodes(Op2.getNode()))
14685       Op2Scalar = ConvertI1VectorToInteger(Op2, DAG);
14686     else if (Op2.getOpcode() == ISD::BITCAST && Op2.getOperand(0))
14687       Op2Scalar = Op2.getOperand(0);
14688     if (Op1Scalar.getNode() && Op2Scalar.getNode()) {
14689       SDValue newSelect = DAG.getNode(ISD::SELECT, DL,
14690                                       Op1Scalar.getValueType(),
14691                                       Cond, Op1Scalar, Op2Scalar);
14692       if (newSelect.getValueSizeInBits() == VT.getSizeInBits())
14693         return DAG.getBitcast(VT, newSelect);
14694       SDValue ExtVec = DAG.getBitcast(MVT::v8i1, newSelect);
14695       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, ExtVec,
14696                          DAG.getIntPtrConstant(0, DL));
14697     }
14698   }
14699
14700   if (VT == MVT::v4i1 || VT == MVT::v2i1) {
14701     SDValue zeroConst = DAG.getIntPtrConstant(0, DL);
14702     Op1 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
14703                       DAG.getUNDEF(MVT::v8i1), Op1, zeroConst);
14704     Op2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
14705                       DAG.getUNDEF(MVT::v8i1), Op2, zeroConst);
14706     SDValue newSelect = DAG.getNode(ISD::SELECT, DL, MVT::v8i1,
14707                                     Cond, Op1, Op2);
14708     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, newSelect, zeroConst);
14709   }
14710
14711   if (Cond.getOpcode() == ISD::SETCC) {
14712     SDValue NewCond = LowerSETCC(Cond, DAG);
14713     if (NewCond.getNode())
14714       Cond = NewCond;
14715   }
14716
14717   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
14718   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
14719   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
14720   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
14721   if (Cond.getOpcode() == X86ISD::SETCC &&
14722       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
14723       isZero(Cond.getOperand(1).getOperand(1))) {
14724     SDValue Cmp = Cond.getOperand(1);
14725
14726     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
14727
14728     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
14729         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
14730       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
14731
14732       SDValue CmpOp0 = Cmp.getOperand(0);
14733       // Apply further optimizations for special cases
14734       // (select (x != 0), -1, 0) -> neg & sbb
14735       // (select (x == 0), 0, -1) -> neg & sbb
14736       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
14737         if (YC->isNullValue() &&
14738             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
14739           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
14740           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
14741                                     DAG.getConstant(0, DL,
14742                                                     CmpOp0.getValueType()),
14743                                     CmpOp0);
14744           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14745                                     DAG.getConstant(X86::COND_B, DL, MVT::i8),
14746                                     SDValue(Neg.getNode(), 1));
14747           return Res;
14748         }
14749
14750       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
14751                         CmpOp0, DAG.getConstant(1, DL, CmpOp0.getValueType()));
14752       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14753
14754       SDValue Res =   // Res = 0 or -1.
14755         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14756                     DAG.getConstant(X86::COND_B, DL, MVT::i8), Cmp);
14757
14758       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
14759         Res = DAG.getNOT(DL, Res, Res.getValueType());
14760
14761       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
14762       if (!N2C || !N2C->isNullValue())
14763         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
14764       return Res;
14765     }
14766   }
14767
14768   // Look past (and (setcc_carry (cmp ...)), 1).
14769   if (Cond.getOpcode() == ISD::AND &&
14770       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
14771     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
14772     if (C && C->getAPIntValue() == 1)
14773       Cond = Cond.getOperand(0);
14774   }
14775
14776   // If condition flag is set by a X86ISD::CMP, then use it as the condition
14777   // setting operand in place of the X86ISD::SETCC.
14778   unsigned CondOpcode = Cond.getOpcode();
14779   if (CondOpcode == X86ISD::SETCC ||
14780       CondOpcode == X86ISD::SETCC_CARRY) {
14781     CC = Cond.getOperand(0);
14782
14783     SDValue Cmp = Cond.getOperand(1);
14784     unsigned Opc = Cmp.getOpcode();
14785     MVT VT = Op.getSimpleValueType();
14786
14787     bool IllegalFPCMov = false;
14788     if (VT.isFloatingPoint() && !VT.isVector() &&
14789         !isScalarFPTypeInSSEReg(VT))  // FPStack?
14790       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
14791
14792     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
14793         Opc == X86ISD::BT) { // FIXME
14794       Cond = Cmp;
14795       addTest = false;
14796     }
14797   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
14798              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
14799              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
14800               Cond.getOperand(0).getValueType() != MVT::i8)) {
14801     SDValue LHS = Cond.getOperand(0);
14802     SDValue RHS = Cond.getOperand(1);
14803     unsigned X86Opcode;
14804     unsigned X86Cond;
14805     SDVTList VTs;
14806     switch (CondOpcode) {
14807     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
14808     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
14809     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
14810     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
14811     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
14812     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
14813     default: llvm_unreachable("unexpected overflowing operator");
14814     }
14815     if (CondOpcode == ISD::UMULO)
14816       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
14817                           MVT::i32);
14818     else
14819       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14820
14821     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
14822
14823     if (CondOpcode == ISD::UMULO)
14824       Cond = X86Op.getValue(2);
14825     else
14826       Cond = X86Op.getValue(1);
14827
14828     CC = DAG.getConstant(X86Cond, DL, MVT::i8);
14829     addTest = false;
14830   }
14831
14832   if (addTest) {
14833     // Look past the truncate if the high bits are known zero.
14834     if (isTruncWithZeroHighBitsInput(Cond, DAG))
14835       Cond = Cond.getOperand(0);
14836
14837     // We know the result of AND is compared against zero. Try to match
14838     // it to BT.
14839     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
14840       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
14841       if (NewSetCC.getNode()) {
14842         CC = NewSetCC.getOperand(0);
14843         Cond = NewSetCC.getOperand(1);
14844         addTest = false;
14845       }
14846     }
14847   }
14848
14849   if (addTest) {
14850     CC = DAG.getConstant(X86::COND_NE, DL, MVT::i8);
14851     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
14852   }
14853
14854   // a <  b ? -1 :  0 -> RES = ~setcc_carry
14855   // a <  b ?  0 : -1 -> RES = setcc_carry
14856   // a >= b ? -1 :  0 -> RES = setcc_carry
14857   // a >= b ?  0 : -1 -> RES = ~setcc_carry
14858   if (Cond.getOpcode() == X86ISD::SUB) {
14859     Cond = ConvertCmpIfNecessary(Cond, DAG);
14860     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
14861
14862     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
14863         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
14864       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14865                                 DAG.getConstant(X86::COND_B, DL, MVT::i8),
14866                                 Cond);
14867       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
14868         return DAG.getNOT(DL, Res, Res.getValueType());
14869       return Res;
14870     }
14871   }
14872
14873   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
14874   // widen the cmov and push the truncate through. This avoids introducing a new
14875   // branch during isel and doesn't add any extensions.
14876   if (Op.getValueType() == MVT::i8 &&
14877       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
14878     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
14879     if (T1.getValueType() == T2.getValueType() &&
14880         // Blacklist CopyFromReg to avoid partial register stalls.
14881         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
14882       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
14883       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
14884       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
14885     }
14886   }
14887
14888   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
14889   // condition is true.
14890   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
14891   SDValue Ops[] = { Op2, Op1, CC, Cond };
14892   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
14893 }
14894
14895 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op,
14896                                        const X86Subtarget *Subtarget,
14897                                        SelectionDAG &DAG) {
14898   MVT VT = Op->getSimpleValueType(0);
14899   SDValue In = Op->getOperand(0);
14900   MVT InVT = In.getSimpleValueType();
14901   MVT VTElt = VT.getVectorElementType();
14902   MVT InVTElt = InVT.getVectorElementType();
14903   SDLoc dl(Op);
14904
14905   // SKX processor
14906   if ((InVTElt == MVT::i1) &&
14907       (((Subtarget->hasBWI() && Subtarget->hasVLX() &&
14908         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() <= 16)) ||
14909
14910        ((Subtarget->hasBWI() && VT.is512BitVector() &&
14911         VTElt.getSizeInBits() <= 16)) ||
14912
14913        ((Subtarget->hasDQI() && Subtarget->hasVLX() &&
14914         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() >= 32)) ||
14915
14916        ((Subtarget->hasDQI() && VT.is512BitVector() &&
14917         VTElt.getSizeInBits() >= 32))))
14918     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14919
14920   unsigned int NumElts = VT.getVectorNumElements();
14921
14922   if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
14923     return SDValue();
14924
14925   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1) {
14926     if (In.getOpcode() == X86ISD::VSEXT || In.getOpcode() == X86ISD::VZEXT)
14927       return DAG.getNode(In.getOpcode(), dl, VT, In.getOperand(0));
14928     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14929   }
14930
14931   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
14932   MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
14933   SDValue NegOne =
14934    DAG.getConstant(APInt::getAllOnesValue(ExtVT.getScalarSizeInBits()), dl,
14935                    ExtVT);
14936   SDValue Zero =
14937    DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), dl, ExtVT);
14938
14939   SDValue V = DAG.getNode(ISD::VSELECT, dl, ExtVT, In, NegOne, Zero);
14940   if (VT.is512BitVector())
14941     return V;
14942   return DAG.getNode(X86ISD::VTRUNC, dl, VT, V);
14943 }
14944
14945 static SDValue LowerSIGN_EXTEND_VECTOR_INREG(SDValue Op,
14946                                              const X86Subtarget *Subtarget,
14947                                              SelectionDAG &DAG) {
14948   SDValue In = Op->getOperand(0);
14949   MVT VT = Op->getSimpleValueType(0);
14950   MVT InVT = In.getSimpleValueType();
14951   assert(VT.getSizeInBits() == InVT.getSizeInBits());
14952
14953   MVT InSVT = InVT.getVectorElementType();
14954   assert(VT.getVectorElementType().getSizeInBits() > InSVT.getSizeInBits());
14955
14956   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
14957     return SDValue();
14958   if (InSVT != MVT::i32 && InSVT != MVT::i16 && InSVT != MVT::i8)
14959     return SDValue();
14960
14961   SDLoc dl(Op);
14962
14963   // SSE41 targets can use the pmovsx* instructions directly.
14964   if (Subtarget->hasSSE41())
14965     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14966
14967   // pre-SSE41 targets unpack lower lanes and then sign-extend using SRAI.
14968   SDValue Curr = In;
14969   MVT CurrVT = InVT;
14970
14971   // As SRAI is only available on i16/i32 types, we expand only up to i32
14972   // and handle i64 separately.
14973   while (CurrVT != VT && CurrVT.getVectorElementType() != MVT::i32) {
14974     Curr = DAG.getNode(X86ISD::UNPCKL, dl, CurrVT, DAG.getUNDEF(CurrVT), Curr);
14975     MVT CurrSVT = MVT::getIntegerVT(CurrVT.getScalarSizeInBits() * 2);
14976     CurrVT = MVT::getVectorVT(CurrSVT, CurrVT.getVectorNumElements() / 2);
14977     Curr = DAG.getBitcast(CurrVT, Curr);
14978   }
14979
14980   SDValue SignExt = Curr;
14981   if (CurrVT != InVT) {
14982     unsigned SignExtShift =
14983         CurrVT.getVectorElementType().getSizeInBits() - InSVT.getSizeInBits();
14984     SignExt = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
14985                           DAG.getConstant(SignExtShift, dl, MVT::i8));
14986   }
14987
14988   if (CurrVT == VT)
14989     return SignExt;
14990
14991   if (VT == MVT::v2i64 && CurrVT == MVT::v4i32) {
14992     SDValue Sign = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
14993                                DAG.getConstant(31, dl, MVT::i8));
14994     SDValue Ext = DAG.getVectorShuffle(CurrVT, dl, SignExt, Sign, {0, 4, 1, 5});
14995     return DAG.getBitcast(VT, Ext);
14996   }
14997
14998   return SDValue();
14999 }
15000
15001 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
15002                                 SelectionDAG &DAG) {
15003   MVT VT = Op->getSimpleValueType(0);
15004   SDValue In = Op->getOperand(0);
15005   MVT InVT = In.getSimpleValueType();
15006   SDLoc dl(Op);
15007
15008   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
15009     return LowerSIGN_EXTEND_AVX512(Op, Subtarget, DAG);
15010
15011   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
15012       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
15013       (VT != MVT::v16i16 || InVT != MVT::v16i8))
15014     return SDValue();
15015
15016   if (Subtarget->hasInt256())
15017     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
15018
15019   // Optimize vectors in AVX mode
15020   // Sign extend  v8i16 to v8i32 and
15021   //              v4i32 to v4i64
15022   //
15023   // Divide input vector into two parts
15024   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
15025   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
15026   // concat the vectors to original VT
15027
15028   unsigned NumElems = InVT.getVectorNumElements();
15029   SDValue Undef = DAG.getUNDEF(InVT);
15030
15031   SmallVector<int,8> ShufMask1(NumElems, -1);
15032   for (unsigned i = 0; i != NumElems/2; ++i)
15033     ShufMask1[i] = i;
15034
15035   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
15036
15037   SmallVector<int,8> ShufMask2(NumElems, -1);
15038   for (unsigned i = 0; i != NumElems/2; ++i)
15039     ShufMask2[i] = i + NumElems/2;
15040
15041   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
15042
15043   MVT HalfVT = MVT::getVectorVT(VT.getVectorElementType(),
15044                                 VT.getVectorNumElements()/2);
15045
15046   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
15047   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
15048
15049   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
15050 }
15051
15052 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
15053 // may emit an illegal shuffle but the expansion is still better than scalar
15054 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
15055 // we'll emit a shuffle and a arithmetic shift.
15056 // FIXME: Is the expansion actually better than scalar code? It doesn't seem so.
15057 // TODO: It is possible to support ZExt by zeroing the undef values during
15058 // the shuffle phase or after the shuffle.
15059 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
15060                                  SelectionDAG &DAG) {
15061   MVT RegVT = Op.getSimpleValueType();
15062   assert(RegVT.isVector() && "We only custom lower vector sext loads.");
15063   assert(RegVT.isInteger() &&
15064          "We only custom lower integer vector sext loads.");
15065
15066   // Nothing useful we can do without SSE2 shuffles.
15067   assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
15068
15069   LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
15070   SDLoc dl(Ld);
15071   EVT MemVT = Ld->getMemoryVT();
15072   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15073   unsigned RegSz = RegVT.getSizeInBits();
15074
15075   ISD::LoadExtType Ext = Ld->getExtensionType();
15076
15077   assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
15078          && "Only anyext and sext are currently implemented.");
15079   assert(MemVT != RegVT && "Cannot extend to the same type");
15080   assert(MemVT.isVector() && "Must load a vector from memory");
15081
15082   unsigned NumElems = RegVT.getVectorNumElements();
15083   unsigned MemSz = MemVT.getSizeInBits();
15084   assert(RegSz > MemSz && "Register size must be greater than the mem size");
15085
15086   if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
15087     // The only way in which we have a legal 256-bit vector result but not the
15088     // integer 256-bit operations needed to directly lower a sextload is if we
15089     // have AVX1 but not AVX2. In that case, we can always emit a sextload to
15090     // a 128-bit vector and a normal sign_extend to 256-bits that should get
15091     // correctly legalized. We do this late to allow the canonical form of
15092     // sextload to persist throughout the rest of the DAG combiner -- it wants
15093     // to fold together any extensions it can, and so will fuse a sign_extend
15094     // of an sextload into a sextload targeting a wider value.
15095     SDValue Load;
15096     if (MemSz == 128) {
15097       // Just switch this to a normal load.
15098       assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
15099                                        "it must be a legal 128-bit vector "
15100                                        "type!");
15101       Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
15102                   Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
15103                   Ld->isInvariant(), Ld->getAlignment());
15104     } else {
15105       assert(MemSz < 128 &&
15106              "Can't extend a type wider than 128 bits to a 256 bit vector!");
15107       // Do an sext load to a 128-bit vector type. We want to use the same
15108       // number of elements, but elements half as wide. This will end up being
15109       // recursively lowered by this routine, but will succeed as we definitely
15110       // have all the necessary features if we're using AVX1.
15111       EVT HalfEltVT =
15112           EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
15113       EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
15114       Load =
15115           DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
15116                          Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
15117                          Ld->isNonTemporal(), Ld->isInvariant(),
15118                          Ld->getAlignment());
15119     }
15120
15121     // Replace chain users with the new chain.
15122     assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
15123     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
15124
15125     // Finally, do a normal sign-extend to the desired register.
15126     return DAG.getSExtOrTrunc(Load, dl, RegVT);
15127   }
15128
15129   // All sizes must be a power of two.
15130   assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
15131          "Non-power-of-two elements are not custom lowered!");
15132
15133   // Attempt to load the original value using scalar loads.
15134   // Find the largest scalar type that divides the total loaded size.
15135   MVT SclrLoadTy = MVT::i8;
15136   for (MVT Tp : MVT::integer_valuetypes()) {
15137     if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
15138       SclrLoadTy = Tp;
15139     }
15140   }
15141
15142   // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
15143   if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
15144       (64 <= MemSz))
15145     SclrLoadTy = MVT::f64;
15146
15147   // Calculate the number of scalar loads that we need to perform
15148   // in order to load our vector from memory.
15149   unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
15150
15151   assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
15152          "Can only lower sext loads with a single scalar load!");
15153
15154   unsigned loadRegZize = RegSz;
15155   if (Ext == ISD::SEXTLOAD && RegSz >= 256)
15156     loadRegZize = 128;
15157
15158   // Represent our vector as a sequence of elements which are the
15159   // largest scalar that we can load.
15160   EVT LoadUnitVecVT = EVT::getVectorVT(
15161       *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
15162
15163   // Represent the data using the same element type that is stored in
15164   // memory. In practice, we ''widen'' MemVT.
15165   EVT WideVecVT =
15166       EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
15167                        loadRegZize / MemVT.getScalarSizeInBits());
15168
15169   assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
15170          "Invalid vector type");
15171
15172   // We can't shuffle using an illegal type.
15173   assert(TLI.isTypeLegal(WideVecVT) &&
15174          "We only lower types that form legal widened vector types");
15175
15176   SmallVector<SDValue, 8> Chains;
15177   SDValue Ptr = Ld->getBasePtr();
15178   SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, dl,
15179                                       TLI.getPointerTy(DAG.getDataLayout()));
15180   SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
15181
15182   for (unsigned i = 0; i < NumLoads; ++i) {
15183     // Perform a single load.
15184     SDValue ScalarLoad =
15185         DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
15186                     Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
15187                     Ld->getAlignment());
15188     Chains.push_back(ScalarLoad.getValue(1));
15189     // Create the first element type using SCALAR_TO_VECTOR in order to avoid
15190     // another round of DAGCombining.
15191     if (i == 0)
15192       Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
15193     else
15194       Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
15195                         ScalarLoad, DAG.getIntPtrConstant(i, dl));
15196
15197     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
15198   }
15199
15200   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
15201
15202   // Bitcast the loaded value to a vector of the original element type, in
15203   // the size of the target vector type.
15204   SDValue SlicedVec = DAG.getBitcast(WideVecVT, Res);
15205   unsigned SizeRatio = RegSz / MemSz;
15206
15207   if (Ext == ISD::SEXTLOAD) {
15208     // If we have SSE4.1, we can directly emit a VSEXT node.
15209     if (Subtarget->hasSSE41()) {
15210       SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
15211       DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
15212       return Sext;
15213     }
15214
15215     // Otherwise we'll use SIGN_EXTEND_VECTOR_INREG to sign extend the lowest
15216     // lanes.
15217     assert(TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND_VECTOR_INREG, RegVT) &&
15218            "We can't implement a sext load without SIGN_EXTEND_VECTOR_INREG!");
15219
15220     SDValue Shuff = DAG.getSignExtendVectorInReg(SlicedVec, dl, RegVT);
15221     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
15222     return Shuff;
15223   }
15224
15225   // Redistribute the loaded elements into the different locations.
15226   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
15227   for (unsigned i = 0; i != NumElems; ++i)
15228     ShuffleVec[i * SizeRatio] = i;
15229
15230   SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
15231                                        DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
15232
15233   // Bitcast to the requested type.
15234   Shuff = DAG.getBitcast(RegVT, Shuff);
15235   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
15236   return Shuff;
15237 }
15238
15239 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
15240 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
15241 // from the AND / OR.
15242 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
15243   Opc = Op.getOpcode();
15244   if (Opc != ISD::OR && Opc != ISD::AND)
15245     return false;
15246   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
15247           Op.getOperand(0).hasOneUse() &&
15248           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
15249           Op.getOperand(1).hasOneUse());
15250 }
15251
15252 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
15253 // 1 and that the SETCC node has a single use.
15254 static bool isXor1OfSetCC(SDValue Op) {
15255   if (Op.getOpcode() != ISD::XOR)
15256     return false;
15257   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
15258   if (N1C && N1C->getAPIntValue() == 1) {
15259     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
15260       Op.getOperand(0).hasOneUse();
15261   }
15262   return false;
15263 }
15264
15265 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
15266   bool addTest = true;
15267   SDValue Chain = Op.getOperand(0);
15268   SDValue Cond  = Op.getOperand(1);
15269   SDValue Dest  = Op.getOperand(2);
15270   SDLoc dl(Op);
15271   SDValue CC;
15272   bool Inverted = false;
15273
15274   if (Cond.getOpcode() == ISD::SETCC) {
15275     // Check for setcc([su]{add,sub,mul}o == 0).
15276     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
15277         isa<ConstantSDNode>(Cond.getOperand(1)) &&
15278         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
15279         Cond.getOperand(0).getResNo() == 1 &&
15280         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
15281          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
15282          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
15283          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
15284          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
15285          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
15286       Inverted = true;
15287       Cond = Cond.getOperand(0);
15288     } else {
15289       SDValue NewCond = LowerSETCC(Cond, DAG);
15290       if (NewCond.getNode())
15291         Cond = NewCond;
15292     }
15293   }
15294 #if 0
15295   // FIXME: LowerXALUO doesn't handle these!!
15296   else if (Cond.getOpcode() == X86ISD::ADD  ||
15297            Cond.getOpcode() == X86ISD::SUB  ||
15298            Cond.getOpcode() == X86ISD::SMUL ||
15299            Cond.getOpcode() == X86ISD::UMUL)
15300     Cond = LowerXALUO(Cond, DAG);
15301 #endif
15302
15303   // Look pass (and (setcc_carry (cmp ...)), 1).
15304   if (Cond.getOpcode() == ISD::AND &&
15305       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
15306     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
15307     if (C && C->getAPIntValue() == 1)
15308       Cond = Cond.getOperand(0);
15309   }
15310
15311   // If condition flag is set by a X86ISD::CMP, then use it as the condition
15312   // setting operand in place of the X86ISD::SETCC.
15313   unsigned CondOpcode = Cond.getOpcode();
15314   if (CondOpcode == X86ISD::SETCC ||
15315       CondOpcode == X86ISD::SETCC_CARRY) {
15316     CC = Cond.getOperand(0);
15317
15318     SDValue Cmp = Cond.getOperand(1);
15319     unsigned Opc = Cmp.getOpcode();
15320     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
15321     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
15322       Cond = Cmp;
15323       addTest = false;
15324     } else {
15325       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
15326       default: break;
15327       case X86::COND_O:
15328       case X86::COND_B:
15329         // These can only come from an arithmetic instruction with overflow,
15330         // e.g. SADDO, UADDO.
15331         Cond = Cond.getNode()->getOperand(1);
15332         addTest = false;
15333         break;
15334       }
15335     }
15336   }
15337   CondOpcode = Cond.getOpcode();
15338   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
15339       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
15340       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
15341        Cond.getOperand(0).getValueType() != MVT::i8)) {
15342     SDValue LHS = Cond.getOperand(0);
15343     SDValue RHS = Cond.getOperand(1);
15344     unsigned X86Opcode;
15345     unsigned X86Cond;
15346     SDVTList VTs;
15347     // Keep this in sync with LowerXALUO, otherwise we might create redundant
15348     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
15349     // X86ISD::INC).
15350     switch (CondOpcode) {
15351     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
15352     case ISD::SADDO:
15353       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
15354         if (C->isOne()) {
15355           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
15356           break;
15357         }
15358       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
15359     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
15360     case ISD::SSUBO:
15361       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
15362         if (C->isOne()) {
15363           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
15364           break;
15365         }
15366       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
15367     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
15368     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
15369     default: llvm_unreachable("unexpected overflowing operator");
15370     }
15371     if (Inverted)
15372       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
15373     if (CondOpcode == ISD::UMULO)
15374       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
15375                           MVT::i32);
15376     else
15377       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
15378
15379     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
15380
15381     if (CondOpcode == ISD::UMULO)
15382       Cond = X86Op.getValue(2);
15383     else
15384       Cond = X86Op.getValue(1);
15385
15386     CC = DAG.getConstant(X86Cond, dl, MVT::i8);
15387     addTest = false;
15388   } else {
15389     unsigned CondOpc;
15390     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
15391       SDValue Cmp = Cond.getOperand(0).getOperand(1);
15392       if (CondOpc == ISD::OR) {
15393         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
15394         // two branches instead of an explicit OR instruction with a
15395         // separate test.
15396         if (Cmp == Cond.getOperand(1).getOperand(1) &&
15397             isX86LogicalCmp(Cmp)) {
15398           CC = Cond.getOperand(0).getOperand(0);
15399           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15400                               Chain, Dest, CC, Cmp);
15401           CC = Cond.getOperand(1).getOperand(0);
15402           Cond = Cmp;
15403           addTest = false;
15404         }
15405       } else { // ISD::AND
15406         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
15407         // two branches instead of an explicit AND instruction with a
15408         // separate test. However, we only do this if this block doesn't
15409         // have a fall-through edge, because this requires an explicit
15410         // jmp when the condition is false.
15411         if (Cmp == Cond.getOperand(1).getOperand(1) &&
15412             isX86LogicalCmp(Cmp) &&
15413             Op.getNode()->hasOneUse()) {
15414           X86::CondCode CCode =
15415             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
15416           CCode = X86::GetOppositeBranchCondition(CCode);
15417           CC = DAG.getConstant(CCode, dl, MVT::i8);
15418           SDNode *User = *Op.getNode()->use_begin();
15419           // Look for an unconditional branch following this conditional branch.
15420           // We need this because we need to reverse the successors in order
15421           // to implement FCMP_OEQ.
15422           if (User->getOpcode() == ISD::BR) {
15423             SDValue FalseBB = User->getOperand(1);
15424             SDNode *NewBR =
15425               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
15426             assert(NewBR == User);
15427             (void)NewBR;
15428             Dest = FalseBB;
15429
15430             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15431                                 Chain, Dest, CC, Cmp);
15432             X86::CondCode CCode =
15433               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
15434             CCode = X86::GetOppositeBranchCondition(CCode);
15435             CC = DAG.getConstant(CCode, dl, MVT::i8);
15436             Cond = Cmp;
15437             addTest = false;
15438           }
15439         }
15440       }
15441     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
15442       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
15443       // It should be transformed during dag combiner except when the condition
15444       // is set by a arithmetics with overflow node.
15445       X86::CondCode CCode =
15446         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
15447       CCode = X86::GetOppositeBranchCondition(CCode);
15448       CC = DAG.getConstant(CCode, dl, MVT::i8);
15449       Cond = Cond.getOperand(0).getOperand(1);
15450       addTest = false;
15451     } else if (Cond.getOpcode() == ISD::SETCC &&
15452                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
15453       // For FCMP_OEQ, we can emit
15454       // two branches instead of an explicit AND instruction with a
15455       // separate test. However, we only do this if this block doesn't
15456       // have a fall-through edge, because this requires an explicit
15457       // jmp when the condition is false.
15458       if (Op.getNode()->hasOneUse()) {
15459         SDNode *User = *Op.getNode()->use_begin();
15460         // Look for an unconditional branch following this conditional branch.
15461         // We need this because we need to reverse the successors in order
15462         // to implement FCMP_OEQ.
15463         if (User->getOpcode() == ISD::BR) {
15464           SDValue FalseBB = User->getOperand(1);
15465           SDNode *NewBR =
15466             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
15467           assert(NewBR == User);
15468           (void)NewBR;
15469           Dest = FalseBB;
15470
15471           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
15472                                     Cond.getOperand(0), Cond.getOperand(1));
15473           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
15474           CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
15475           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15476                               Chain, Dest, CC, Cmp);
15477           CC = DAG.getConstant(X86::COND_P, dl, MVT::i8);
15478           Cond = Cmp;
15479           addTest = false;
15480         }
15481       }
15482     } else if (Cond.getOpcode() == ISD::SETCC &&
15483                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
15484       // For FCMP_UNE, we can emit
15485       // two branches instead of an explicit AND instruction with a
15486       // separate test. However, we only do this if this block doesn't
15487       // have a fall-through edge, because this requires an explicit
15488       // jmp when the condition is false.
15489       if (Op.getNode()->hasOneUse()) {
15490         SDNode *User = *Op.getNode()->use_begin();
15491         // Look for an unconditional branch following this conditional branch.
15492         // We need this because we need to reverse the successors in order
15493         // to implement FCMP_UNE.
15494         if (User->getOpcode() == ISD::BR) {
15495           SDValue FalseBB = User->getOperand(1);
15496           SDNode *NewBR =
15497             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
15498           assert(NewBR == User);
15499           (void)NewBR;
15500
15501           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
15502                                     Cond.getOperand(0), Cond.getOperand(1));
15503           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
15504           CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
15505           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15506                               Chain, Dest, CC, Cmp);
15507           CC = DAG.getConstant(X86::COND_NP, dl, MVT::i8);
15508           Cond = Cmp;
15509           addTest = false;
15510           Dest = FalseBB;
15511         }
15512       }
15513     }
15514   }
15515
15516   if (addTest) {
15517     // Look pass the truncate if the high bits are known zero.
15518     if (isTruncWithZeroHighBitsInput(Cond, DAG))
15519         Cond = Cond.getOperand(0);
15520
15521     // We know the result of AND is compared against zero. Try to match
15522     // it to BT.
15523     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
15524       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
15525       if (NewSetCC.getNode()) {
15526         CC = NewSetCC.getOperand(0);
15527         Cond = NewSetCC.getOperand(1);
15528         addTest = false;
15529       }
15530     }
15531   }
15532
15533   if (addTest) {
15534     X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
15535     CC = DAG.getConstant(X86Cond, dl, MVT::i8);
15536     Cond = EmitTest(Cond, X86Cond, dl, DAG);
15537   }
15538   Cond = ConvertCmpIfNecessary(Cond, DAG);
15539   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15540                      Chain, Dest, CC, Cond);
15541 }
15542
15543 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
15544 // Calls to _alloca are needed to probe the stack when allocating more than 4k
15545 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
15546 // that the guard pages used by the OS virtual memory manager are allocated in
15547 // correct sequence.
15548 SDValue
15549 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
15550                                            SelectionDAG &DAG) const {
15551   MachineFunction &MF = DAG.getMachineFunction();
15552   bool SplitStack = MF.shouldSplitStack();
15553   bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMachO()) ||
15554                SplitStack;
15555   SDLoc dl(Op);
15556
15557   if (!Lower) {
15558     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15559     SDNode* Node = Op.getNode();
15560
15561     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
15562     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
15563         " not tell us which reg is the stack pointer!");
15564     EVT VT = Node->getValueType(0);
15565     SDValue Tmp1 = SDValue(Node, 0);
15566     SDValue Tmp2 = SDValue(Node, 1);
15567     SDValue Tmp3 = Node->getOperand(2);
15568     SDValue Chain = Tmp1.getOperand(0);
15569
15570     // Chain the dynamic stack allocation so that it doesn't modify the stack
15571     // pointer when other instructions are using the stack.
15572     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, dl, true),
15573         SDLoc(Node));
15574
15575     SDValue Size = Tmp2.getOperand(1);
15576     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
15577     Chain = SP.getValue(1);
15578     unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
15579     const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
15580     unsigned StackAlign = TFI.getStackAlignment();
15581     Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
15582     if (Align > StackAlign)
15583       Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
15584           DAG.getConstant(-(uint64_t)Align, dl, VT));
15585     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
15586
15587     Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
15588         DAG.getIntPtrConstant(0, dl, true), SDValue(),
15589         SDLoc(Node));
15590
15591     SDValue Ops[2] = { Tmp1, Tmp2 };
15592     return DAG.getMergeValues(Ops, dl);
15593   }
15594
15595   // Get the inputs.
15596   SDValue Chain = Op.getOperand(0);
15597   SDValue Size  = Op.getOperand(1);
15598   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
15599   EVT VT = Op.getNode()->getValueType(0);
15600
15601   bool Is64Bit = Subtarget->is64Bit();
15602   MVT SPTy = getPointerTy(DAG.getDataLayout());
15603
15604   if (SplitStack) {
15605     MachineRegisterInfo &MRI = MF.getRegInfo();
15606
15607     if (Is64Bit) {
15608       // The 64 bit implementation of segmented stacks needs to clobber both r10
15609       // r11. This makes it impossible to use it along with nested parameters.
15610       const Function *F = MF.getFunction();
15611
15612       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
15613            I != E; ++I)
15614         if (I->hasNestAttr())
15615           report_fatal_error("Cannot use segmented stacks with functions that "
15616                              "have nested arguments.");
15617     }
15618
15619     const TargetRegisterClass *AddrRegClass = getRegClassFor(SPTy);
15620     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
15621     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
15622     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
15623                                 DAG.getRegister(Vreg, SPTy));
15624     SDValue Ops1[2] = { Value, Chain };
15625     return DAG.getMergeValues(Ops1, dl);
15626   } else {
15627     SDValue Flag;
15628     const unsigned Reg = (Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX);
15629
15630     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
15631     Flag = Chain.getValue(1);
15632     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
15633
15634     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
15635
15636     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15637     unsigned SPReg = RegInfo->getStackRegister();
15638     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
15639     Chain = SP.getValue(1);
15640
15641     if (Align) {
15642       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
15643                        DAG.getConstant(-(uint64_t)Align, dl, VT));
15644       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
15645     }
15646
15647     SDValue Ops1[2] = { SP, Chain };
15648     return DAG.getMergeValues(Ops1, dl);
15649   }
15650 }
15651
15652 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
15653   MachineFunction &MF = DAG.getMachineFunction();
15654   auto PtrVT = getPointerTy(MF.getDataLayout());
15655   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
15656
15657   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
15658   SDLoc DL(Op);
15659
15660   if (!Subtarget->is64Bit() ||
15661       Subtarget->isCallingConvWin64(MF.getFunction()->getCallingConv())) {
15662     // vastart just stores the address of the VarArgsFrameIndex slot into the
15663     // memory location argument.
15664     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
15665     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
15666                         MachinePointerInfo(SV), false, false, 0);
15667   }
15668
15669   // __va_list_tag:
15670   //   gp_offset         (0 - 6 * 8)
15671   //   fp_offset         (48 - 48 + 8 * 16)
15672   //   overflow_arg_area (point to parameters coming in memory).
15673   //   reg_save_area
15674   SmallVector<SDValue, 8> MemOps;
15675   SDValue FIN = Op.getOperand(1);
15676   // Store gp_offset
15677   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
15678                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
15679                                                DL, MVT::i32),
15680                                FIN, MachinePointerInfo(SV), false, false, 0);
15681   MemOps.push_back(Store);
15682
15683   // Store fp_offset
15684   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
15685   Store = DAG.getStore(Op.getOperand(0), DL,
15686                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(), DL,
15687                                        MVT::i32),
15688                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
15689   MemOps.push_back(Store);
15690
15691   // Store ptr to overflow_arg_area
15692   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
15693   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
15694   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
15695                        MachinePointerInfo(SV, 8),
15696                        false, false, 0);
15697   MemOps.push_back(Store);
15698
15699   // Store ptr to reg_save_area.
15700   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(
15701       Subtarget->isTarget64BitLP64() ? 8 : 4, DL));
15702   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), PtrVT);
15703   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN, MachinePointerInfo(
15704       SV, Subtarget->isTarget64BitLP64() ? 16 : 12), false, false, 0);
15705   MemOps.push_back(Store);
15706   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
15707 }
15708
15709 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
15710   assert(Subtarget->is64Bit() &&
15711          "LowerVAARG only handles 64-bit va_arg!");
15712   assert(Op.getNode()->getNumOperands() == 4);
15713
15714   MachineFunction &MF = DAG.getMachineFunction();
15715   if (Subtarget->isCallingConvWin64(MF.getFunction()->getCallingConv()))
15716     // The Win64 ABI uses char* instead of a structure.
15717     return DAG.expandVAArg(Op.getNode());
15718
15719   SDValue Chain = Op.getOperand(0);
15720   SDValue SrcPtr = Op.getOperand(1);
15721   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
15722   unsigned Align = Op.getConstantOperandVal(3);
15723   SDLoc dl(Op);
15724
15725   EVT ArgVT = Op.getNode()->getValueType(0);
15726   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
15727   uint32_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
15728   uint8_t ArgMode;
15729
15730   // Decide which area this value should be read from.
15731   // TODO: Implement the AMD64 ABI in its entirety. This simple
15732   // selection mechanism works only for the basic types.
15733   if (ArgVT == MVT::f80) {
15734     llvm_unreachable("va_arg for f80 not yet implemented");
15735   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
15736     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
15737   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
15738     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
15739   } else {
15740     llvm_unreachable("Unhandled argument type in LowerVAARG");
15741   }
15742
15743   if (ArgMode == 2) {
15744     // Sanity Check: Make sure using fp_offset makes sense.
15745     assert(!Subtarget->useSoftFloat() &&
15746            !(MF.getFunction()->hasFnAttribute(Attribute::NoImplicitFloat)) &&
15747            Subtarget->hasSSE1());
15748   }
15749
15750   // Insert VAARG_64 node into the DAG
15751   // VAARG_64 returns two values: Variable Argument Address, Chain
15752   SDValue InstOps[] = {Chain, SrcPtr, DAG.getConstant(ArgSize, dl, MVT::i32),
15753                        DAG.getConstant(ArgMode, dl, MVT::i8),
15754                        DAG.getConstant(Align, dl, MVT::i32)};
15755   SDVTList VTs = DAG.getVTList(getPointerTy(DAG.getDataLayout()), MVT::Other);
15756   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
15757                                           VTs, InstOps, MVT::i64,
15758                                           MachinePointerInfo(SV),
15759                                           /*Align=*/0,
15760                                           /*Volatile=*/false,
15761                                           /*ReadMem=*/true,
15762                                           /*WriteMem=*/true);
15763   Chain = VAARG.getValue(1);
15764
15765   // Load the next argument and return it
15766   return DAG.getLoad(ArgVT, dl,
15767                      Chain,
15768                      VAARG,
15769                      MachinePointerInfo(),
15770                      false, false, false, 0);
15771 }
15772
15773 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
15774                            SelectionDAG &DAG) {
15775   // X86-64 va_list is a struct { i32, i32, i8*, i8* }, except on Windows,
15776   // where a va_list is still an i8*.
15777   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
15778   if (Subtarget->isCallingConvWin64(
15779         DAG.getMachineFunction().getFunction()->getCallingConv()))
15780     // Probably a Win64 va_copy.
15781     return DAG.expandVACopy(Op.getNode());
15782
15783   SDValue Chain = Op.getOperand(0);
15784   SDValue DstPtr = Op.getOperand(1);
15785   SDValue SrcPtr = Op.getOperand(2);
15786   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
15787   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
15788   SDLoc DL(Op);
15789
15790   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
15791                        DAG.getIntPtrConstant(24, DL), 8, /*isVolatile*/false,
15792                        false, false,
15793                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
15794 }
15795
15796 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
15797 // amount is a constant. Takes immediate version of shift as input.
15798 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
15799                                           SDValue SrcOp, uint64_t ShiftAmt,
15800                                           SelectionDAG &DAG) {
15801   MVT ElementType = VT.getVectorElementType();
15802
15803   // Fold this packed shift into its first operand if ShiftAmt is 0.
15804   if (ShiftAmt == 0)
15805     return SrcOp;
15806
15807   // Check for ShiftAmt >= element width
15808   if (ShiftAmt >= ElementType.getSizeInBits()) {
15809     if (Opc == X86ISD::VSRAI)
15810       ShiftAmt = ElementType.getSizeInBits() - 1;
15811     else
15812       return DAG.getConstant(0, dl, VT);
15813   }
15814
15815   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
15816          && "Unknown target vector shift-by-constant node");
15817
15818   // Fold this packed vector shift into a build vector if SrcOp is a
15819   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
15820   if (VT == SrcOp.getSimpleValueType() &&
15821       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
15822     SmallVector<SDValue, 8> Elts;
15823     unsigned NumElts = SrcOp->getNumOperands();
15824     ConstantSDNode *ND;
15825
15826     switch(Opc) {
15827     default: llvm_unreachable(nullptr);
15828     case X86ISD::VSHLI:
15829       for (unsigned i=0; i!=NumElts; ++i) {
15830         SDValue CurrentOp = SrcOp->getOperand(i);
15831         if (CurrentOp->getOpcode() == ISD::UNDEF) {
15832           Elts.push_back(CurrentOp);
15833           continue;
15834         }
15835         ND = cast<ConstantSDNode>(CurrentOp);
15836         const APInt &C = ND->getAPIntValue();
15837         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), dl, ElementType));
15838       }
15839       break;
15840     case X86ISD::VSRLI:
15841       for (unsigned i=0; i!=NumElts; ++i) {
15842         SDValue CurrentOp = SrcOp->getOperand(i);
15843         if (CurrentOp->getOpcode() == ISD::UNDEF) {
15844           Elts.push_back(CurrentOp);
15845           continue;
15846         }
15847         ND = cast<ConstantSDNode>(CurrentOp);
15848         const APInt &C = ND->getAPIntValue();
15849         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), dl, ElementType));
15850       }
15851       break;
15852     case X86ISD::VSRAI:
15853       for (unsigned i=0; i!=NumElts; ++i) {
15854         SDValue CurrentOp = SrcOp->getOperand(i);
15855         if (CurrentOp->getOpcode() == ISD::UNDEF) {
15856           Elts.push_back(CurrentOp);
15857           continue;
15858         }
15859         ND = cast<ConstantSDNode>(CurrentOp);
15860         const APInt &C = ND->getAPIntValue();
15861         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), dl, ElementType));
15862       }
15863       break;
15864     }
15865
15866     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
15867   }
15868
15869   return DAG.getNode(Opc, dl, VT, SrcOp,
15870                      DAG.getConstant(ShiftAmt, dl, MVT::i8));
15871 }
15872
15873 // getTargetVShiftNode - Handle vector element shifts where the shift amount
15874 // may or may not be a constant. Takes immediate version of shift as input.
15875 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
15876                                    SDValue SrcOp, SDValue ShAmt,
15877                                    SelectionDAG &DAG) {
15878   MVT SVT = ShAmt.getSimpleValueType();
15879   assert((SVT == MVT::i32 || SVT == MVT::i64) && "Unexpected value type!");
15880
15881   // Catch shift-by-constant.
15882   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
15883     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
15884                                       CShAmt->getZExtValue(), DAG);
15885
15886   // Change opcode to non-immediate version
15887   switch (Opc) {
15888     default: llvm_unreachable("Unknown target vector shift node");
15889     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
15890     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
15891     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
15892   }
15893
15894   const X86Subtarget &Subtarget =
15895       static_cast<const X86Subtarget &>(DAG.getSubtarget());
15896   if (Subtarget.hasSSE41() && ShAmt.getOpcode() == ISD::ZERO_EXTEND &&
15897       ShAmt.getOperand(0).getSimpleValueType() == MVT::i16) {
15898     // Let the shuffle legalizer expand this shift amount node.
15899     SDValue Op0 = ShAmt.getOperand(0);
15900     Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(Op0), MVT::v8i16, Op0);
15901     ShAmt = getShuffleVectorZeroOrUndef(Op0, 0, true, &Subtarget, DAG);
15902   } else {
15903     // Need to build a vector containing shift amount.
15904     // SSE/AVX packed shifts only use the lower 64-bit of the shift count.
15905     SmallVector<SDValue, 4> ShOps;
15906     ShOps.push_back(ShAmt);
15907     if (SVT == MVT::i32) {
15908       ShOps.push_back(DAG.getConstant(0, dl, SVT));
15909       ShOps.push_back(DAG.getUNDEF(SVT));
15910     }
15911     ShOps.push_back(DAG.getUNDEF(SVT));
15912
15913     MVT BVT = SVT == MVT::i32 ? MVT::v4i32 : MVT::v2i64;
15914     ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, BVT, ShOps);
15915   }
15916
15917   // The return type has to be a 128-bit type with the same element
15918   // type as the input type.
15919   MVT EltVT = VT.getVectorElementType();
15920   MVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
15921
15922   ShAmt = DAG.getBitcast(ShVT, ShAmt);
15923   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
15924 }
15925
15926 /// \brief Return (and \p Op, \p Mask) for compare instructions or
15927 /// (vselect \p Mask, \p Op, \p PreservedSrc) for others along with the
15928 /// necessary casting or extending for \p Mask when lowering masking intrinsics
15929 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
15930                                     SDValue PreservedSrc,
15931                                     const X86Subtarget *Subtarget,
15932                                     SelectionDAG &DAG) {
15933     MVT VT = Op.getSimpleValueType();
15934     MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
15935     SDValue VMask;
15936     unsigned OpcodeSelect = ISD::VSELECT;
15937     SDLoc dl(Op);
15938
15939     if (isAllOnes(Mask))
15940       return Op;
15941
15942     if (MaskVT.bitsGT(Mask.getSimpleValueType())) {
15943       MVT newMaskVT = MVT::getIntegerVT(MaskVT.getSizeInBits());
15944       VMask = DAG.getBitcast(MaskVT,
15945                              DAG.getNode(ISD::ANY_EXTEND, dl, newMaskVT, Mask));
15946     } else {
15947       MVT BitcastVT = MVT::getVectorVT(MVT::i1,
15948                                        Mask.getSimpleValueType().getSizeInBits());
15949       // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
15950       // are extracted by EXTRACT_SUBVECTOR.
15951       VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15952                           DAG.getBitcast(BitcastVT, Mask),
15953                           DAG.getIntPtrConstant(0, dl));
15954     }
15955
15956     switch (Op.getOpcode()) {
15957     default: break;
15958     case X86ISD::PCMPEQM:
15959     case X86ISD::PCMPGTM:
15960     case X86ISD::CMPM:
15961     case X86ISD::CMPMU:
15962       return DAG.getNode(ISD::AND, dl, VT, Op, VMask);
15963     case X86ISD::VFPCLASS:
15964       return DAG.getNode(ISD::OR, dl, VT, Op, VMask);
15965     case X86ISD::VTRUNC:
15966     case X86ISD::VTRUNCS:
15967     case X86ISD::VTRUNCUS:
15968       // We can't use ISD::VSELECT here because it is not always "Legal"
15969       // for the destination type. For example vpmovqb require only AVX512
15970       // and vselect that can operate on byte element type require BWI
15971       OpcodeSelect = X86ISD::SELECT;
15972       break;
15973     }
15974     if (PreservedSrc.getOpcode() == ISD::UNDEF)
15975       PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
15976     return DAG.getNode(OpcodeSelect, dl, VT, VMask, Op, PreservedSrc);
15977 }
15978
15979 /// \brief Creates an SDNode for a predicated scalar operation.
15980 /// \returns (X86vselect \p Mask, \p Op, \p PreservedSrc).
15981 /// The mask is coming as MVT::i8 and it should be truncated
15982 /// to MVT::i1 while lowering masking intrinsics.
15983 /// The main difference between ScalarMaskingNode and VectorMaskingNode is using
15984 /// "X86select" instead of "vselect". We just can't create the "vselect" node
15985 /// for a scalar instruction.
15986 static SDValue getScalarMaskingNode(SDValue Op, SDValue Mask,
15987                                     SDValue PreservedSrc,
15988                                     const X86Subtarget *Subtarget,
15989                                     SelectionDAG &DAG) {
15990   if (isAllOnes(Mask))
15991     return Op;
15992
15993   MVT VT = Op.getSimpleValueType();
15994   SDLoc dl(Op);
15995   // The mask should be of type MVT::i1
15996   SDValue IMask = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Mask);
15997
15998   if (Op.getOpcode() == X86ISD::FSETCC)
15999     return DAG.getNode(ISD::AND, dl, VT, Op, IMask);
16000   if (Op.getOpcode() == X86ISD::VFPCLASS)
16001     return DAG.getNode(ISD::OR, dl, VT, Op, IMask);
16002
16003   if (PreservedSrc.getOpcode() == ISD::UNDEF)
16004     PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
16005   return DAG.getNode(X86ISD::SELECT, dl, VT, IMask, Op, PreservedSrc);
16006 }
16007
16008 static int getSEHRegistrationNodeSize(const Function *Fn) {
16009   if (!Fn->hasPersonalityFn())
16010     report_fatal_error(
16011         "querying registration node size for function without personality");
16012   // The RegNodeSize is 6 32-bit words for SEH and 4 for C++ EH. See
16013   // WinEHStatePass for the full struct definition.
16014   switch (classifyEHPersonality(Fn->getPersonalityFn())) {
16015   case EHPersonality::MSVC_X86SEH: return 24;
16016   case EHPersonality::MSVC_CXX: return 16;
16017   default: break;
16018   }
16019   report_fatal_error("can only recover FP for MSVC EH personality functions");
16020 }
16021
16022 /// When the 32-bit MSVC runtime transfers control to us, either to an outlined
16023 /// function or when returning to a parent frame after catching an exception, we
16024 /// recover the parent frame pointer by doing arithmetic on the incoming EBP.
16025 /// Here's the math:
16026 ///   RegNodeBase = EntryEBP - RegNodeSize
16027 ///   ParentFP = RegNodeBase - RegNodeFrameOffset
16028 /// Subtracting RegNodeSize takes us to the offset of the registration node, and
16029 /// subtracting the offset (negative on x86) takes us back to the parent FP.
16030 static SDValue recoverFramePointer(SelectionDAG &DAG, const Function *Fn,
16031                                    SDValue EntryEBP) {
16032   MachineFunction &MF = DAG.getMachineFunction();
16033   SDLoc dl;
16034
16035   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16036   MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
16037
16038   // It's possible that the parent function no longer has a personality function
16039   // if the exceptional code was optimized away, in which case we just return
16040   // the incoming EBP.
16041   if (!Fn->hasPersonalityFn())
16042     return EntryEBP;
16043
16044   int RegNodeSize = getSEHRegistrationNodeSize(Fn);
16045
16046   // Get an MCSymbol that will ultimately resolve to the frame offset of the EH
16047   // registration.
16048   MCSymbol *OffsetSym =
16049       MF.getMMI().getContext().getOrCreateParentFrameOffsetSymbol(
16050           GlobalValue::getRealLinkageName(Fn->getName()));
16051   SDValue OffsetSymVal = DAG.getMCSymbol(OffsetSym, PtrVT);
16052   SDValue RegNodeFrameOffset =
16053       DAG.getNode(ISD::LOCAL_RECOVER, dl, PtrVT, OffsetSymVal);
16054
16055   // RegNodeBase = EntryEBP - RegNodeSize
16056   // ParentFP = RegNodeBase - RegNodeFrameOffset
16057   SDValue RegNodeBase = DAG.getNode(ISD::SUB, dl, PtrVT, EntryEBP,
16058                                     DAG.getConstant(RegNodeSize, dl, PtrVT));
16059   return DAG.getNode(ISD::SUB, dl, PtrVT, RegNodeBase, RegNodeFrameOffset);
16060 }
16061
16062 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
16063                                        SelectionDAG &DAG) {
16064   SDLoc dl(Op);
16065   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16066   MVT VT = Op.getSimpleValueType();
16067   const IntrinsicData* IntrData = getIntrinsicWithoutChain(IntNo);
16068   if (IntrData) {
16069     switch(IntrData->Type) {
16070     case INTR_TYPE_1OP:
16071       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1));
16072     case INTR_TYPE_2OP:
16073       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
16074         Op.getOperand(2));
16075     case INTR_TYPE_2OP_IMM8:
16076       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
16077                          DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op.getOperand(2)));
16078     case INTR_TYPE_3OP:
16079       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
16080         Op.getOperand(2), Op.getOperand(3));
16081     case INTR_TYPE_4OP:
16082       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
16083         Op.getOperand(2), Op.getOperand(3), Op.getOperand(4));
16084     case INTR_TYPE_1OP_MASK_RM: {
16085       SDValue Src = Op.getOperand(1);
16086       SDValue PassThru = Op.getOperand(2);
16087       SDValue Mask = Op.getOperand(3);
16088       SDValue RoundingMode;
16089       // We allways add rounding mode to the Node.
16090       // If the rounding mode is not specified, we add the
16091       // "current direction" mode.
16092       if (Op.getNumOperands() == 4)
16093         RoundingMode =
16094           DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
16095       else
16096         RoundingMode = Op.getOperand(4);
16097       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16098       if (IntrWithRoundingModeOpcode != 0)
16099         if (cast<ConstantSDNode>(RoundingMode)->getZExtValue() !=
16100             X86::STATIC_ROUNDING::CUR_DIRECTION)
16101           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16102                                       dl, Op.getValueType(), Src, RoundingMode),
16103                                       Mask, PassThru, Subtarget, DAG);
16104       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src,
16105                                               RoundingMode),
16106                                   Mask, PassThru, Subtarget, DAG);
16107     }
16108     case INTR_TYPE_1OP_MASK: {
16109       SDValue Src = Op.getOperand(1);
16110       SDValue PassThru = Op.getOperand(2);
16111       SDValue Mask = Op.getOperand(3);
16112       // We add rounding mode to the Node when
16113       //   - RM Opcode is specified and
16114       //   - RM is not "current direction".
16115       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16116       if (IntrWithRoundingModeOpcode != 0) {
16117         SDValue Rnd = Op.getOperand(4);
16118         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
16119         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
16120           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16121                                       dl, Op.getValueType(),
16122                                       Src, Rnd),
16123                                       Mask, PassThru, Subtarget, DAG);
16124         }
16125       }
16126       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src),
16127                                   Mask, PassThru, Subtarget, DAG);
16128     }
16129     case INTR_TYPE_SCALAR_MASK: {
16130       SDValue Src1 = Op.getOperand(1);
16131       SDValue Src2 = Op.getOperand(2);
16132       SDValue passThru = Op.getOperand(3);
16133       SDValue Mask = Op.getOperand(4);
16134       return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2),
16135                                   Mask, passThru, Subtarget, DAG);
16136     }
16137     case INTR_TYPE_SCALAR_MASK_RM: {
16138       SDValue Src1 = Op.getOperand(1);
16139       SDValue Src2 = Op.getOperand(2);
16140       SDValue Src0 = Op.getOperand(3);
16141       SDValue Mask = Op.getOperand(4);
16142       // There are 2 kinds of intrinsics in this group:
16143       // (1) With suppress-all-exceptions (sae) or rounding mode- 6 operands
16144       // (2) With rounding mode and sae - 7 operands.
16145       if (Op.getNumOperands() == 6) {
16146         SDValue Sae  = Op.getOperand(5);
16147         unsigned Opc = IntrData->Opc1 ? IntrData->Opc1 : IntrData->Opc0;
16148         return getScalarMaskingNode(DAG.getNode(Opc, dl, VT, Src1, Src2,
16149                                                 Sae),
16150                                     Mask, Src0, Subtarget, DAG);
16151       }
16152       assert(Op.getNumOperands() == 7 && "Unexpected intrinsic form");
16153       SDValue RoundingMode  = Op.getOperand(5);
16154       SDValue Sae  = Op.getOperand(6);
16155       return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
16156                                               RoundingMode, Sae),
16157                                   Mask, Src0, Subtarget, DAG);
16158     }
16159     case INTR_TYPE_2OP_MASK:
16160     case INTR_TYPE_2OP_IMM8_MASK: {
16161       SDValue Src1 = Op.getOperand(1);
16162       SDValue Src2 = Op.getOperand(2);
16163       SDValue PassThru = Op.getOperand(3);
16164       SDValue Mask = Op.getOperand(4);
16165
16166       if (IntrData->Type == INTR_TYPE_2OP_IMM8_MASK)
16167         Src2 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Src2);
16168
16169       // We specify 2 possible opcodes for intrinsics with rounding modes.
16170       // First, we check if the intrinsic may have non-default rounding mode,
16171       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
16172       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16173       if (IntrWithRoundingModeOpcode != 0) {
16174         SDValue Rnd = Op.getOperand(5);
16175         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
16176         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
16177           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16178                                       dl, Op.getValueType(),
16179                                       Src1, Src2, Rnd),
16180                                       Mask, PassThru, Subtarget, DAG);
16181         }
16182       }
16183       // TODO: Intrinsics should have fast-math-flags to propagate.
16184       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,Src1,Src2),
16185                                   Mask, PassThru, Subtarget, DAG);
16186     }
16187     case INTR_TYPE_2OP_MASK_RM: {
16188       SDValue Src1 = Op.getOperand(1);
16189       SDValue Src2 = Op.getOperand(2);
16190       SDValue PassThru = Op.getOperand(3);
16191       SDValue Mask = Op.getOperand(4);
16192       // We specify 2 possible modes for intrinsics, with/without rounding
16193       // modes.
16194       // First, we check if the intrinsic have rounding mode (6 operands),
16195       // if not, we set rounding mode to "current".
16196       SDValue Rnd;
16197       if (Op.getNumOperands() == 6)
16198         Rnd = Op.getOperand(5);
16199       else
16200         Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
16201       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16202                                               Src1, Src2, Rnd),
16203                                   Mask, PassThru, Subtarget, DAG);
16204     }
16205     case INTR_TYPE_3OP_SCALAR_MASK_RM: {
16206       SDValue Src1 = Op.getOperand(1);
16207       SDValue Src2 = Op.getOperand(2);
16208       SDValue Src3 = Op.getOperand(3);
16209       SDValue PassThru = Op.getOperand(4);
16210       SDValue Mask = Op.getOperand(5);
16211       SDValue Sae  = Op.getOperand(6);
16212
16213       return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1,
16214                                               Src2, Src3, Sae),
16215                                   Mask, PassThru, Subtarget, DAG);
16216     }
16217     case INTR_TYPE_3OP_MASK_RM: {
16218       SDValue Src1 = Op.getOperand(1);
16219       SDValue Src2 = Op.getOperand(2);
16220       SDValue Imm = Op.getOperand(3);
16221       SDValue PassThru = Op.getOperand(4);
16222       SDValue Mask = Op.getOperand(5);
16223       // We specify 2 possible modes for intrinsics, with/without rounding
16224       // modes.
16225       // First, we check if the intrinsic have rounding mode (7 operands),
16226       // if not, we set rounding mode to "current".
16227       SDValue Rnd;
16228       if (Op.getNumOperands() == 7)
16229         Rnd = Op.getOperand(6);
16230       else
16231         Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
16232       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16233         Src1, Src2, Imm, Rnd),
16234         Mask, PassThru, Subtarget, DAG);
16235     }
16236     case INTR_TYPE_3OP_IMM8_MASK:
16237     case INTR_TYPE_3OP_MASK:
16238     case INSERT_SUBVEC: {
16239       SDValue Src1 = Op.getOperand(1);
16240       SDValue Src2 = Op.getOperand(2);
16241       SDValue Src3 = Op.getOperand(3);
16242       SDValue PassThru = Op.getOperand(4);
16243       SDValue Mask = Op.getOperand(5);
16244
16245       if (IntrData->Type == INTR_TYPE_3OP_IMM8_MASK)
16246         Src3 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Src3);
16247       else if (IntrData->Type == INSERT_SUBVEC) {
16248         // imm should be adapted to ISD::INSERT_SUBVECTOR behavior
16249         assert(isa<ConstantSDNode>(Src3) && "Expected a ConstantSDNode here!");
16250         unsigned Imm = cast<ConstantSDNode>(Src3)->getZExtValue();
16251         Imm *= Src2.getSimpleValueType().getVectorNumElements();
16252         Src3 = DAG.getTargetConstant(Imm, dl, MVT::i32);
16253       }
16254
16255       // We specify 2 possible opcodes for intrinsics with rounding modes.
16256       // First, we check if the intrinsic may have non-default rounding mode,
16257       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
16258       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16259       if (IntrWithRoundingModeOpcode != 0) {
16260         SDValue Rnd = Op.getOperand(6);
16261         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
16262         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
16263           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16264                                       dl, Op.getValueType(),
16265                                       Src1, Src2, Src3, Rnd),
16266                                       Mask, PassThru, Subtarget, DAG);
16267         }
16268       }
16269       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16270                                               Src1, Src2, Src3),
16271                                   Mask, PassThru, Subtarget, DAG);
16272     }
16273     case VPERM_3OP_MASKZ:
16274     case VPERM_3OP_MASK:
16275     case FMA_OP_MASK3:
16276     case FMA_OP_MASKZ:
16277     case FMA_OP_MASK: {
16278       SDValue Src1 = Op.getOperand(1);
16279       SDValue Src2 = Op.getOperand(2);
16280       SDValue Src3 = Op.getOperand(3);
16281       SDValue Mask = Op.getOperand(4);
16282       MVT VT = Op.getSimpleValueType();
16283       SDValue PassThru = SDValue();
16284
16285       // set PassThru element
16286       if (IntrData->Type == VPERM_3OP_MASKZ || IntrData->Type == FMA_OP_MASKZ)
16287         PassThru = getZeroVector(VT, Subtarget, DAG, dl);
16288       else if (IntrData->Type == FMA_OP_MASK3)
16289         PassThru = Src3;
16290       else
16291         PassThru = Src1;
16292
16293       // We specify 2 possible opcodes for intrinsics with rounding modes.
16294       // First, we check if the intrinsic may have non-default rounding mode,
16295       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
16296       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16297       if (IntrWithRoundingModeOpcode != 0) {
16298         SDValue Rnd = Op.getOperand(5);
16299         if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
16300             X86::STATIC_ROUNDING::CUR_DIRECTION)
16301           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16302                                                   dl, Op.getValueType(),
16303                                                   Src1, Src2, Src3, Rnd),
16304                                       Mask, PassThru, Subtarget, DAG);
16305       }
16306       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0,
16307                                               dl, Op.getValueType(),
16308                                               Src1, Src2, Src3),
16309                                   Mask, PassThru, Subtarget, DAG);
16310     }
16311     case TERLOG_OP_MASK:
16312     case TERLOG_OP_MASKZ: {
16313       SDValue Src1 = Op.getOperand(1);
16314       SDValue Src2 = Op.getOperand(2);
16315       SDValue Src3 = Op.getOperand(3);
16316       SDValue Src4 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op.getOperand(4));
16317       SDValue Mask = Op.getOperand(5);
16318       MVT VT = Op.getSimpleValueType();
16319       SDValue PassThru = Src1;
16320       // Set PassThru element.
16321       if (IntrData->Type == TERLOG_OP_MASKZ)
16322         PassThru = getZeroVector(VT, Subtarget, DAG, dl);
16323
16324       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16325                                               Src1, Src2, Src3, Src4),
16326                                   Mask, PassThru, Subtarget, DAG);
16327     }
16328     case FPCLASS: {
16329       // FPclass intrinsics with mask
16330        SDValue Src1 = Op.getOperand(1);
16331        MVT VT = Src1.getSimpleValueType();
16332        MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
16333        SDValue Imm = Op.getOperand(2);
16334        SDValue Mask = Op.getOperand(3);
16335        MVT BitcastVT = MVT::getVectorVT(MVT::i1,
16336                                      Mask.getSimpleValueType().getSizeInBits());
16337        SDValue FPclass = DAG.getNode(IntrData->Opc0, dl, MaskVT, Src1, Imm);
16338        SDValue FPclassMask = getVectorMaskingNode(FPclass, Mask,
16339                                                  DAG.getTargetConstant(0, dl, MaskVT),
16340                                                  Subtarget, DAG);
16341        SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
16342                                  DAG.getUNDEF(BitcastVT), FPclassMask,
16343                                  DAG.getIntPtrConstant(0, dl));
16344        return DAG.getBitcast(Op.getValueType(), Res);
16345     }
16346     case FPCLASSS: {
16347       SDValue Src1 = Op.getOperand(1);
16348       SDValue Imm = Op.getOperand(2);
16349       SDValue Mask = Op.getOperand(3);
16350       SDValue FPclass = DAG.getNode(IntrData->Opc0, dl, MVT::i1, Src1, Imm);
16351       SDValue FPclassMask = getScalarMaskingNode(FPclass, Mask,
16352         DAG.getTargetConstant(0, dl, MVT::i1), Subtarget, DAG);
16353       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i8, FPclassMask);
16354     }
16355     case CMP_MASK:
16356     case CMP_MASK_CC: {
16357       // Comparison intrinsics with masks.
16358       // Example of transformation:
16359       // (i8 (int_x86_avx512_mask_pcmpeq_q_128
16360       //             (v2i64 %a), (v2i64 %b), (i8 %mask))) ->
16361       // (i8 (bitcast
16362       //   (v8i1 (insert_subvector undef,
16363       //           (v2i1 (and (PCMPEQM %a, %b),
16364       //                      (extract_subvector
16365       //                         (v8i1 (bitcast %mask)), 0))), 0))))
16366       MVT VT = Op.getOperand(1).getSimpleValueType();
16367       MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
16368       SDValue Mask = Op.getOperand((IntrData->Type == CMP_MASK_CC) ? 4 : 3);
16369       MVT BitcastVT = MVT::getVectorVT(MVT::i1,
16370                                        Mask.getSimpleValueType().getSizeInBits());
16371       SDValue Cmp;
16372       if (IntrData->Type == CMP_MASK_CC) {
16373         SDValue CC = Op.getOperand(3);
16374         CC = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, CC);
16375         // We specify 2 possible opcodes for intrinsics with rounding modes.
16376         // First, we check if the intrinsic may have non-default rounding mode,
16377         // (IntrData->Opc1 != 0), then we check the rounding mode operand.
16378         if (IntrData->Opc1 != 0) {
16379           SDValue Rnd = Op.getOperand(5);
16380           if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
16381               X86::STATIC_ROUNDING::CUR_DIRECTION)
16382             Cmp = DAG.getNode(IntrData->Opc1, dl, MaskVT, Op.getOperand(1),
16383                               Op.getOperand(2), CC, Rnd);
16384         }
16385         //default rounding mode
16386         if(!Cmp.getNode())
16387             Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
16388                               Op.getOperand(2), CC);
16389
16390       } else {
16391         assert(IntrData->Type == CMP_MASK && "Unexpected intrinsic type!");
16392         Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
16393                           Op.getOperand(2));
16394       }
16395       SDValue CmpMask = getVectorMaskingNode(Cmp, Mask,
16396                                              DAG.getTargetConstant(0, dl,
16397                                                                    MaskVT),
16398                                              Subtarget, DAG);
16399       SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
16400                                 DAG.getUNDEF(BitcastVT), CmpMask,
16401                                 DAG.getIntPtrConstant(0, dl));
16402       return DAG.getBitcast(Op.getValueType(), Res);
16403     }
16404     case CMP_MASK_SCALAR_CC: {
16405       SDValue Src1 = Op.getOperand(1);
16406       SDValue Src2 = Op.getOperand(2);
16407       SDValue CC = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op.getOperand(3));
16408       SDValue Mask = Op.getOperand(4);
16409
16410       SDValue Cmp;
16411       if (IntrData->Opc1 != 0) {
16412         SDValue Rnd = Op.getOperand(5);
16413         if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
16414             X86::STATIC_ROUNDING::CUR_DIRECTION)
16415           Cmp = DAG.getNode(IntrData->Opc1, dl, MVT::i1, Src1, Src2, CC, Rnd);
16416       }
16417       //default rounding mode
16418       if(!Cmp.getNode())
16419         Cmp = DAG.getNode(IntrData->Opc0, dl, MVT::i1, Src1, Src2, CC);
16420
16421       SDValue CmpMask = getScalarMaskingNode(Cmp, Mask,
16422                                              DAG.getTargetConstant(0, dl,
16423                                                                    MVT::i1),
16424                                              Subtarget, DAG);
16425
16426       return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::i8,
16427                          DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i8, CmpMask),
16428                          DAG.getValueType(MVT::i1));
16429     }
16430     case COMI: { // Comparison intrinsics
16431       ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
16432       SDValue LHS = Op.getOperand(1);
16433       SDValue RHS = Op.getOperand(2);
16434       unsigned X86CC = TranslateX86CC(CC, dl, true, LHS, RHS, DAG);
16435       assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
16436       SDValue Cond = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
16437       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16438                                   DAG.getConstant(X86CC, dl, MVT::i8), Cond);
16439       return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16440     }
16441     case VSHIFT:
16442       return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
16443                                  Op.getOperand(1), Op.getOperand(2), DAG);
16444     case VSHIFT_MASK:
16445       return getVectorMaskingNode(getTargetVShiftNode(IntrData->Opc0, dl,
16446                                                       Op.getSimpleValueType(),
16447                                                       Op.getOperand(1),
16448                                                       Op.getOperand(2), DAG),
16449                                   Op.getOperand(4), Op.getOperand(3), Subtarget,
16450                                   DAG);
16451     case COMPRESS_EXPAND_IN_REG: {
16452       SDValue Mask = Op.getOperand(3);
16453       SDValue DataToCompress = Op.getOperand(1);
16454       SDValue PassThru = Op.getOperand(2);
16455       if (isAllOnes(Mask)) // return data as is
16456         return Op.getOperand(1);
16457
16458       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16459                                               DataToCompress),
16460                                   Mask, PassThru, Subtarget, DAG);
16461     }
16462     case BLEND: {
16463       SDValue Mask = Op.getOperand(3);
16464       MVT VT = Op.getSimpleValueType();
16465       MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
16466       MVT BitcastVT = MVT::getVectorVT(MVT::i1,
16467                                        Mask.getSimpleValueType().getSizeInBits());
16468       SDLoc dl(Op);
16469       SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16470                                   DAG.getBitcast(BitcastVT, Mask),
16471                                   DAG.getIntPtrConstant(0, dl));
16472       return DAG.getNode(IntrData->Opc0, dl, VT, VMask, Op.getOperand(1),
16473                          Op.getOperand(2));
16474     }
16475     default:
16476       break;
16477     }
16478   }
16479
16480   switch (IntNo) {
16481   default: return SDValue();    // Don't custom lower most intrinsics.
16482
16483   case Intrinsic::x86_avx2_permd:
16484   case Intrinsic::x86_avx2_permps:
16485     // Operands intentionally swapped. Mask is last operand to intrinsic,
16486     // but second operand for node/instruction.
16487     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
16488                        Op.getOperand(2), Op.getOperand(1));
16489
16490   // ptest and testp intrinsics. The intrinsic these come from are designed to
16491   // return an integer value, not just an instruction so lower it to the ptest
16492   // or testp pattern and a setcc for the result.
16493   case Intrinsic::x86_sse41_ptestz:
16494   case Intrinsic::x86_sse41_ptestc:
16495   case Intrinsic::x86_sse41_ptestnzc:
16496   case Intrinsic::x86_avx_ptestz_256:
16497   case Intrinsic::x86_avx_ptestc_256:
16498   case Intrinsic::x86_avx_ptestnzc_256:
16499   case Intrinsic::x86_avx_vtestz_ps:
16500   case Intrinsic::x86_avx_vtestc_ps:
16501   case Intrinsic::x86_avx_vtestnzc_ps:
16502   case Intrinsic::x86_avx_vtestz_pd:
16503   case Intrinsic::x86_avx_vtestc_pd:
16504   case Intrinsic::x86_avx_vtestnzc_pd:
16505   case Intrinsic::x86_avx_vtestz_ps_256:
16506   case Intrinsic::x86_avx_vtestc_ps_256:
16507   case Intrinsic::x86_avx_vtestnzc_ps_256:
16508   case Intrinsic::x86_avx_vtestz_pd_256:
16509   case Intrinsic::x86_avx_vtestc_pd_256:
16510   case Intrinsic::x86_avx_vtestnzc_pd_256: {
16511     bool IsTestPacked = false;
16512     unsigned X86CC;
16513     switch (IntNo) {
16514     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
16515     case Intrinsic::x86_avx_vtestz_ps:
16516     case Intrinsic::x86_avx_vtestz_pd:
16517     case Intrinsic::x86_avx_vtestz_ps_256:
16518     case Intrinsic::x86_avx_vtestz_pd_256:
16519       IsTestPacked = true; // Fallthrough
16520     case Intrinsic::x86_sse41_ptestz:
16521     case Intrinsic::x86_avx_ptestz_256:
16522       // ZF = 1
16523       X86CC = X86::COND_E;
16524       break;
16525     case Intrinsic::x86_avx_vtestc_ps:
16526     case Intrinsic::x86_avx_vtestc_pd:
16527     case Intrinsic::x86_avx_vtestc_ps_256:
16528     case Intrinsic::x86_avx_vtestc_pd_256:
16529       IsTestPacked = true; // Fallthrough
16530     case Intrinsic::x86_sse41_ptestc:
16531     case Intrinsic::x86_avx_ptestc_256:
16532       // CF = 1
16533       X86CC = X86::COND_B;
16534       break;
16535     case Intrinsic::x86_avx_vtestnzc_ps:
16536     case Intrinsic::x86_avx_vtestnzc_pd:
16537     case Intrinsic::x86_avx_vtestnzc_ps_256:
16538     case Intrinsic::x86_avx_vtestnzc_pd_256:
16539       IsTestPacked = true; // Fallthrough
16540     case Intrinsic::x86_sse41_ptestnzc:
16541     case Intrinsic::x86_avx_ptestnzc_256:
16542       // ZF and CF = 0
16543       X86CC = X86::COND_A;
16544       break;
16545     }
16546
16547     SDValue LHS = Op.getOperand(1);
16548     SDValue RHS = Op.getOperand(2);
16549     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
16550     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
16551     SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
16552     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
16553     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16554   }
16555   case Intrinsic::x86_avx512_kortestz_w:
16556   case Intrinsic::x86_avx512_kortestc_w: {
16557     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
16558     SDValue LHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(1));
16559     SDValue RHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(2));
16560     SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
16561     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
16562     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
16563     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16564   }
16565
16566   case Intrinsic::x86_sse42_pcmpistria128:
16567   case Intrinsic::x86_sse42_pcmpestria128:
16568   case Intrinsic::x86_sse42_pcmpistric128:
16569   case Intrinsic::x86_sse42_pcmpestric128:
16570   case Intrinsic::x86_sse42_pcmpistrio128:
16571   case Intrinsic::x86_sse42_pcmpestrio128:
16572   case Intrinsic::x86_sse42_pcmpistris128:
16573   case Intrinsic::x86_sse42_pcmpestris128:
16574   case Intrinsic::x86_sse42_pcmpistriz128:
16575   case Intrinsic::x86_sse42_pcmpestriz128: {
16576     unsigned Opcode;
16577     unsigned X86CC;
16578     switch (IntNo) {
16579     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
16580     case Intrinsic::x86_sse42_pcmpistria128:
16581       Opcode = X86ISD::PCMPISTRI;
16582       X86CC = X86::COND_A;
16583       break;
16584     case Intrinsic::x86_sse42_pcmpestria128:
16585       Opcode = X86ISD::PCMPESTRI;
16586       X86CC = X86::COND_A;
16587       break;
16588     case Intrinsic::x86_sse42_pcmpistric128:
16589       Opcode = X86ISD::PCMPISTRI;
16590       X86CC = X86::COND_B;
16591       break;
16592     case Intrinsic::x86_sse42_pcmpestric128:
16593       Opcode = X86ISD::PCMPESTRI;
16594       X86CC = X86::COND_B;
16595       break;
16596     case Intrinsic::x86_sse42_pcmpistrio128:
16597       Opcode = X86ISD::PCMPISTRI;
16598       X86CC = X86::COND_O;
16599       break;
16600     case Intrinsic::x86_sse42_pcmpestrio128:
16601       Opcode = X86ISD::PCMPESTRI;
16602       X86CC = X86::COND_O;
16603       break;
16604     case Intrinsic::x86_sse42_pcmpistris128:
16605       Opcode = X86ISD::PCMPISTRI;
16606       X86CC = X86::COND_S;
16607       break;
16608     case Intrinsic::x86_sse42_pcmpestris128:
16609       Opcode = X86ISD::PCMPESTRI;
16610       X86CC = X86::COND_S;
16611       break;
16612     case Intrinsic::x86_sse42_pcmpistriz128:
16613       Opcode = X86ISD::PCMPISTRI;
16614       X86CC = X86::COND_E;
16615       break;
16616     case Intrinsic::x86_sse42_pcmpestriz128:
16617       Opcode = X86ISD::PCMPESTRI;
16618       X86CC = X86::COND_E;
16619       break;
16620     }
16621     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
16622     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
16623     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
16624     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16625                                 DAG.getConstant(X86CC, dl, MVT::i8),
16626                                 SDValue(PCMP.getNode(), 1));
16627     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16628   }
16629
16630   case Intrinsic::x86_sse42_pcmpistri128:
16631   case Intrinsic::x86_sse42_pcmpestri128: {
16632     unsigned Opcode;
16633     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
16634       Opcode = X86ISD::PCMPISTRI;
16635     else
16636       Opcode = X86ISD::PCMPESTRI;
16637
16638     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
16639     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
16640     return DAG.getNode(Opcode, dl, VTs, NewOps);
16641   }
16642
16643   case Intrinsic::x86_seh_lsda: {
16644     // Compute the symbol for the LSDA. We know it'll get emitted later.
16645     MachineFunction &MF = DAG.getMachineFunction();
16646     SDValue Op1 = Op.getOperand(1);
16647     auto *Fn = cast<Function>(cast<GlobalAddressSDNode>(Op1)->getGlobal());
16648     MCSymbol *LSDASym = MF.getMMI().getContext().getOrCreateLSDASymbol(
16649         GlobalValue::getRealLinkageName(Fn->getName()));
16650
16651     // Generate a simple absolute symbol reference. This intrinsic is only
16652     // supported on 32-bit Windows, which isn't PIC.
16653     SDValue Result = DAG.getMCSymbol(LSDASym, VT);
16654     return DAG.getNode(X86ISD::Wrapper, dl, VT, Result);
16655   }
16656
16657   case Intrinsic::x86_seh_recoverfp: {
16658     SDValue FnOp = Op.getOperand(1);
16659     SDValue IncomingFPOp = Op.getOperand(2);
16660     GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(FnOp);
16661     auto *Fn = dyn_cast_or_null<Function>(GSD ? GSD->getGlobal() : nullptr);
16662     if (!Fn)
16663       report_fatal_error(
16664           "llvm.x86.seh.recoverfp must take a function as the first argument");
16665     return recoverFramePointer(DAG, Fn, IncomingFPOp);
16666   }
16667
16668   case Intrinsic::localaddress: {
16669     // Returns one of the stack, base, or frame pointer registers, depending on
16670     // which is used to reference local variables.
16671     MachineFunction &MF = DAG.getMachineFunction();
16672     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16673     unsigned Reg;
16674     if (RegInfo->hasBasePointer(MF))
16675       Reg = RegInfo->getBaseRegister();
16676     else // This function handles the SP or FP case.
16677       Reg = RegInfo->getPtrSizedFrameRegister(MF);
16678     return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
16679   }
16680   }
16681 }
16682
16683 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
16684                               SDValue Src, SDValue Mask, SDValue Base,
16685                               SDValue Index, SDValue ScaleOp, SDValue Chain,
16686                               const X86Subtarget * Subtarget) {
16687   SDLoc dl(Op);
16688   auto *C = cast<ConstantSDNode>(ScaleOp);
16689   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
16690   MVT MaskVT = MVT::getVectorVT(MVT::i1,
16691                              Index.getSimpleValueType().getVectorNumElements());
16692   SDValue MaskInReg;
16693   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
16694   if (MaskC)
16695     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
16696   else {
16697     MVT BitcastVT = MVT::getVectorVT(MVT::i1,
16698                                      Mask.getSimpleValueType().getSizeInBits());
16699
16700     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
16701     // are extracted by EXTRACT_SUBVECTOR.
16702     MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16703                             DAG.getBitcast(BitcastVT, Mask),
16704                             DAG.getIntPtrConstant(0, dl));
16705   }
16706   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
16707   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
16708   SDValue Segment = DAG.getRegister(0, MVT::i32);
16709   if (Src.getOpcode() == ISD::UNDEF)
16710     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
16711   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
16712   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
16713   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
16714   return DAG.getMergeValues(RetOps, dl);
16715 }
16716
16717 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
16718                                SDValue Src, SDValue Mask, SDValue Base,
16719                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
16720   SDLoc dl(Op);
16721   auto *C = cast<ConstantSDNode>(ScaleOp);
16722   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
16723   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
16724   SDValue Segment = DAG.getRegister(0, MVT::i32);
16725   MVT MaskVT = MVT::getVectorVT(MVT::i1,
16726                              Index.getSimpleValueType().getVectorNumElements());
16727   SDValue MaskInReg;
16728   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
16729   if (MaskC)
16730     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
16731   else {
16732     MVT BitcastVT = MVT::getVectorVT(MVT::i1,
16733                                      Mask.getSimpleValueType().getSizeInBits());
16734
16735     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
16736     // are extracted by EXTRACT_SUBVECTOR.
16737     MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16738                             DAG.getBitcast(BitcastVT, Mask),
16739                             DAG.getIntPtrConstant(0, dl));
16740   }
16741   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
16742   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
16743   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
16744   return SDValue(Res, 1);
16745 }
16746
16747 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
16748                                SDValue Mask, SDValue Base, SDValue Index,
16749                                SDValue ScaleOp, SDValue Chain) {
16750   SDLoc dl(Op);
16751   auto *C = cast<ConstantSDNode>(ScaleOp);
16752   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
16753   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
16754   SDValue Segment = DAG.getRegister(0, MVT::i32);
16755   MVT MaskVT =
16756     MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
16757   SDValue MaskInReg;
16758   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
16759   if (MaskC)
16760     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
16761   else
16762     MaskInReg = DAG.getBitcast(MaskVT, Mask);
16763   //SDVTList VTs = DAG.getVTList(MVT::Other);
16764   SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
16765   SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
16766   return SDValue(Res, 0);
16767 }
16768
16769 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
16770 // read performance monitor counters (x86_rdpmc).
16771 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
16772                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
16773                               SmallVectorImpl<SDValue> &Results) {
16774   assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
16775   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16776   SDValue LO, HI;
16777
16778   // The ECX register is used to select the index of the performance counter
16779   // to read.
16780   SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
16781                                    N->getOperand(2));
16782   SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
16783
16784   // Reads the content of a 64-bit performance counter and returns it in the
16785   // registers EDX:EAX.
16786   if (Subtarget->is64Bit()) {
16787     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
16788     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
16789                             LO.getValue(2));
16790   } else {
16791     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
16792     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
16793                             LO.getValue(2));
16794   }
16795   Chain = HI.getValue(1);
16796
16797   if (Subtarget->is64Bit()) {
16798     // The EAX register is loaded with the low-order 32 bits. The EDX register
16799     // is loaded with the supported high-order bits of the counter.
16800     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
16801                               DAG.getConstant(32, DL, MVT::i8));
16802     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
16803     Results.push_back(Chain);
16804     return;
16805   }
16806
16807   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
16808   SDValue Ops[] = { LO, HI };
16809   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
16810   Results.push_back(Pair);
16811   Results.push_back(Chain);
16812 }
16813
16814 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
16815 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
16816 // also used to custom lower READCYCLECOUNTER nodes.
16817 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
16818                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
16819                               SmallVectorImpl<SDValue> &Results) {
16820   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16821   SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
16822   SDValue LO, HI;
16823
16824   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
16825   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
16826   // and the EAX register is loaded with the low-order 32 bits.
16827   if (Subtarget->is64Bit()) {
16828     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
16829     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
16830                             LO.getValue(2));
16831   } else {
16832     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
16833     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
16834                             LO.getValue(2));
16835   }
16836   SDValue Chain = HI.getValue(1);
16837
16838   if (Opcode == X86ISD::RDTSCP_DAG) {
16839     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
16840
16841     // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
16842     // the ECX register. Add 'ecx' explicitly to the chain.
16843     SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
16844                                      HI.getValue(2));
16845     // Explicitly store the content of ECX at the location passed in input
16846     // to the 'rdtscp' intrinsic.
16847     Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
16848                          MachinePointerInfo(), false, false, 0);
16849   }
16850
16851   if (Subtarget->is64Bit()) {
16852     // The EDX register is loaded with the high-order 32 bits of the MSR, and
16853     // the EAX register is loaded with the low-order 32 bits.
16854     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
16855                               DAG.getConstant(32, DL, MVT::i8));
16856     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
16857     Results.push_back(Chain);
16858     return;
16859   }
16860
16861   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
16862   SDValue Ops[] = { LO, HI };
16863   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
16864   Results.push_back(Pair);
16865   Results.push_back(Chain);
16866 }
16867
16868 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
16869                                      SelectionDAG &DAG) {
16870   SmallVector<SDValue, 2> Results;
16871   SDLoc DL(Op);
16872   getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
16873                           Results);
16874   return DAG.getMergeValues(Results, DL);
16875 }
16876
16877 static SDValue LowerSEHRESTOREFRAME(SDValue Op, const X86Subtarget *Subtarget,
16878                                     SelectionDAG &DAG) {
16879   MachineFunction &MF = DAG.getMachineFunction();
16880   const Function *Fn = MF.getFunction();
16881   SDLoc dl(Op);
16882   SDValue Chain = Op.getOperand(0);
16883
16884   assert(Subtarget->getFrameLowering()->hasFP(MF) &&
16885          "using llvm.x86.seh.restoreframe requires a frame pointer");
16886
16887   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16888   MVT VT = TLI.getPointerTy(DAG.getDataLayout());
16889
16890   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16891   unsigned FrameReg =
16892       RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
16893   unsigned SPReg = RegInfo->getStackRegister();
16894   unsigned SlotSize = RegInfo->getSlotSize();
16895
16896   // Get incoming EBP.
16897   SDValue IncomingEBP =
16898       DAG.getCopyFromReg(Chain, dl, FrameReg, VT);
16899
16900   // SP is saved in the first field of every registration node, so load
16901   // [EBP-RegNodeSize] into SP.
16902   int RegNodeSize = getSEHRegistrationNodeSize(Fn);
16903   SDValue SPAddr = DAG.getNode(ISD::ADD, dl, VT, IncomingEBP,
16904                                DAG.getConstant(-RegNodeSize, dl, VT));
16905   SDValue NewSP =
16906       DAG.getLoad(VT, dl, Chain, SPAddr, MachinePointerInfo(), false, false,
16907                   false, VT.getScalarSizeInBits() / 8);
16908   Chain = DAG.getCopyToReg(Chain, dl, SPReg, NewSP);
16909
16910   if (!RegInfo->needsStackRealignment(MF)) {
16911     // Adjust EBP to point back to the original frame position.
16912     SDValue NewFP = recoverFramePointer(DAG, Fn, IncomingEBP);
16913     Chain = DAG.getCopyToReg(Chain, dl, FrameReg, NewFP);
16914   } else {
16915     assert(RegInfo->hasBasePointer(MF) &&
16916            "functions with Win32 EH must use frame or base pointer register");
16917
16918     // Reload the base pointer (ESI) with the adjusted incoming EBP.
16919     SDValue NewBP = recoverFramePointer(DAG, Fn, IncomingEBP);
16920     Chain = DAG.getCopyToReg(Chain, dl, RegInfo->getBaseRegister(), NewBP);
16921
16922     // Reload the spilled EBP value, now that the stack and base pointers are
16923     // set up.
16924     X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
16925     X86FI->setHasSEHFramePtrSave(true);
16926     int FI = MF.getFrameInfo()->CreateSpillStackObject(SlotSize, SlotSize);
16927     X86FI->setSEHFramePtrSaveIndex(FI);
16928     SDValue NewFP = DAG.getLoad(VT, dl, Chain, DAG.getFrameIndex(FI, VT),
16929                                 MachinePointerInfo(), false, false, false,
16930                                 VT.getScalarSizeInBits() / 8);
16931     Chain = DAG.getCopyToReg(NewFP, dl, FrameReg, NewFP);
16932   }
16933
16934   return Chain;
16935 }
16936
16937 /// \brief Lower intrinsics for TRUNCATE_TO_MEM case
16938 /// return truncate Store/MaskedStore Node
16939 static SDValue LowerINTRINSIC_TRUNCATE_TO_MEM(const SDValue & Op,
16940                                                SelectionDAG &DAG,
16941                                                MVT ElementType) {
16942   SDLoc dl(Op);
16943   SDValue Mask = Op.getOperand(4);
16944   SDValue DataToTruncate = Op.getOperand(3);
16945   SDValue Addr = Op.getOperand(2);
16946   SDValue Chain = Op.getOperand(0);
16947
16948   MVT VT  = DataToTruncate.getSimpleValueType();
16949   MVT SVT = MVT::getVectorVT(ElementType, VT.getVectorNumElements());
16950
16951   if (isAllOnes(Mask)) // return just a truncate store
16952     return DAG.getTruncStore(Chain, dl, DataToTruncate, Addr,
16953                              MachinePointerInfo(), SVT, false, false,
16954                              SVT.getScalarSizeInBits()/8);
16955
16956   MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
16957   MVT BitcastVT = MVT::getVectorVT(MVT::i1,
16958                                    Mask.getSimpleValueType().getSizeInBits());
16959   // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
16960   // are extracted by EXTRACT_SUBVECTOR.
16961   SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16962                               DAG.getBitcast(BitcastVT, Mask),
16963                               DAG.getIntPtrConstant(0, dl));
16964
16965   MachineMemOperand *MMO = DAG.getMachineFunction().
16966     getMachineMemOperand(MachinePointerInfo(),
16967                          MachineMemOperand::MOStore, SVT.getStoreSize(),
16968                          SVT.getScalarSizeInBits()/8);
16969
16970   return DAG.getMaskedStore(Chain, dl, DataToTruncate, Addr,
16971                             VMask, SVT, MMO, true);
16972 }
16973
16974 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
16975                                       SelectionDAG &DAG) {
16976   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
16977
16978   const IntrinsicData* IntrData = getIntrinsicWithChain(IntNo);
16979   if (!IntrData) {
16980     if (IntNo == llvm::Intrinsic::x86_seh_restoreframe)
16981       return LowerSEHRESTOREFRAME(Op, Subtarget, DAG);
16982     return SDValue();
16983   }
16984
16985   SDLoc dl(Op);
16986   switch(IntrData->Type) {
16987   default: llvm_unreachable("Unknown Intrinsic Type");
16988   case RDSEED:
16989   case RDRAND: {
16990     // Emit the node with the right value type.
16991     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
16992     SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
16993
16994     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
16995     // Otherwise return the value from Rand, which is always 0, casted to i32.
16996     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
16997                       DAG.getConstant(1, dl, Op->getValueType(1)),
16998                       DAG.getConstant(X86::COND_B, dl, MVT::i32),
16999                       SDValue(Result.getNode(), 1) };
17000     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
17001                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
17002                                   Ops);
17003
17004     // Return { result, isValid, chain }.
17005     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
17006                        SDValue(Result.getNode(), 2));
17007   }
17008   case GATHER: {
17009   //gather(v1, mask, index, base, scale);
17010     SDValue Chain = Op.getOperand(0);
17011     SDValue Src   = Op.getOperand(2);
17012     SDValue Base  = Op.getOperand(3);
17013     SDValue Index = Op.getOperand(4);
17014     SDValue Mask  = Op.getOperand(5);
17015     SDValue Scale = Op.getOperand(6);
17016     return getGatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale,
17017                          Chain, Subtarget);
17018   }
17019   case SCATTER: {
17020   //scatter(base, mask, index, v1, scale);
17021     SDValue Chain = Op.getOperand(0);
17022     SDValue Base  = Op.getOperand(2);
17023     SDValue Mask  = Op.getOperand(3);
17024     SDValue Index = Op.getOperand(4);
17025     SDValue Src   = Op.getOperand(5);
17026     SDValue Scale = Op.getOperand(6);
17027     return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index,
17028                           Scale, Chain);
17029   }
17030   case PREFETCH: {
17031     SDValue Hint = Op.getOperand(6);
17032     unsigned HintVal = cast<ConstantSDNode>(Hint)->getZExtValue();
17033     assert(HintVal < 2 && "Wrong prefetch hint in intrinsic: should be 0 or 1");
17034     unsigned Opcode = (HintVal ? IntrData->Opc1 : IntrData->Opc0);
17035     SDValue Chain = Op.getOperand(0);
17036     SDValue Mask  = Op.getOperand(2);
17037     SDValue Index = Op.getOperand(3);
17038     SDValue Base  = Op.getOperand(4);
17039     SDValue Scale = Op.getOperand(5);
17040     return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
17041   }
17042   // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
17043   case RDTSC: {
17044     SmallVector<SDValue, 2> Results;
17045     getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget,
17046                             Results);
17047     return DAG.getMergeValues(Results, dl);
17048   }
17049   // Read Performance Monitoring Counters.
17050   case RDPMC: {
17051     SmallVector<SDValue, 2> Results;
17052     getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
17053     return DAG.getMergeValues(Results, dl);
17054   }
17055   // XTEST intrinsics.
17056   case XTEST: {
17057     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
17058     SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
17059     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17060                                 DAG.getConstant(X86::COND_NE, dl, MVT::i8),
17061                                 InTrans);
17062     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
17063     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
17064                        Ret, SDValue(InTrans.getNode(), 1));
17065   }
17066   // ADC/ADCX/SBB
17067   case ADX: {
17068     SmallVector<SDValue, 2> Results;
17069     SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
17070     SDVTList VTs = DAG.getVTList(Op.getOperand(3)->getValueType(0), MVT::Other);
17071     SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(2),
17072                                 DAG.getConstant(-1, dl, MVT::i8));
17073     SDValue Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(3),
17074                               Op.getOperand(4), GenCF.getValue(1));
17075     SDValue Store = DAG.getStore(Op.getOperand(0), dl, Res.getValue(0),
17076                                  Op.getOperand(5), MachinePointerInfo(),
17077                                  false, false, 0);
17078     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17079                                 DAG.getConstant(X86::COND_B, dl, MVT::i8),
17080                                 Res.getValue(1));
17081     Results.push_back(SetCC);
17082     Results.push_back(Store);
17083     return DAG.getMergeValues(Results, dl);
17084   }
17085   case COMPRESS_TO_MEM: {
17086     SDLoc dl(Op);
17087     SDValue Mask = Op.getOperand(4);
17088     SDValue DataToCompress = Op.getOperand(3);
17089     SDValue Addr = Op.getOperand(2);
17090     SDValue Chain = Op.getOperand(0);
17091
17092     MVT VT = DataToCompress.getSimpleValueType();
17093     if (isAllOnes(Mask)) // return just a store
17094       return DAG.getStore(Chain, dl, DataToCompress, Addr,
17095                           MachinePointerInfo(), false, false,
17096                           VT.getScalarSizeInBits()/8);
17097
17098     SDValue Compressed =
17099       getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToCompress),
17100                            Mask, DAG.getUNDEF(VT), Subtarget, DAG);
17101     return DAG.getStore(Chain, dl, Compressed, Addr,
17102                         MachinePointerInfo(), false, false,
17103                         VT.getScalarSizeInBits()/8);
17104   }
17105   case TRUNCATE_TO_MEM_VI8:
17106     return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i8);
17107   case TRUNCATE_TO_MEM_VI16:
17108     return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i16);
17109   case TRUNCATE_TO_MEM_VI32:
17110     return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i32);
17111   case EXPAND_FROM_MEM: {
17112     SDLoc dl(Op);
17113     SDValue Mask = Op.getOperand(4);
17114     SDValue PassThru = Op.getOperand(3);
17115     SDValue Addr = Op.getOperand(2);
17116     SDValue Chain = Op.getOperand(0);
17117     MVT VT = Op.getSimpleValueType();
17118
17119     if (isAllOnes(Mask)) // return just a load
17120       return DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(), false, false,
17121                          false, VT.getScalarSizeInBits()/8);
17122
17123     SDValue DataToExpand = DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(),
17124                                        false, false, false,
17125                                        VT.getScalarSizeInBits()/8);
17126
17127     SDValue Results[] = {
17128       getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToExpand),
17129                            Mask, PassThru, Subtarget, DAG), Chain};
17130     return DAG.getMergeValues(Results, dl);
17131   }
17132   }
17133 }
17134
17135 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
17136                                            SelectionDAG &DAG) const {
17137   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
17138   MFI->setReturnAddressIsTaken(true);
17139
17140   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
17141     return SDValue();
17142
17143   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
17144   SDLoc dl(Op);
17145   EVT PtrVT = getPointerTy(DAG.getDataLayout());
17146
17147   if (Depth > 0) {
17148     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
17149     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17150     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), dl, PtrVT);
17151     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
17152                        DAG.getNode(ISD::ADD, dl, PtrVT,
17153                                    FrameAddr, Offset),
17154                        MachinePointerInfo(), false, false, false, 0);
17155   }
17156
17157   // Just load the return address.
17158   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
17159   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
17160                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
17161 }
17162
17163 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
17164   MachineFunction &MF = DAG.getMachineFunction();
17165   MachineFrameInfo *MFI = MF.getFrameInfo();
17166   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
17167   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17168   EVT VT = Op.getValueType();
17169
17170   MFI->setFrameAddressIsTaken(true);
17171
17172   if (MF.getTarget().getMCAsmInfo()->usesWindowsCFI()) {
17173     // Depth > 0 makes no sense on targets which use Windows unwind codes.  It
17174     // is not possible to crawl up the stack without looking at the unwind codes
17175     // simultaneously.
17176     int FrameAddrIndex = FuncInfo->getFAIndex();
17177     if (!FrameAddrIndex) {
17178       // Set up a frame object for the return address.
17179       unsigned SlotSize = RegInfo->getSlotSize();
17180       FrameAddrIndex = MF.getFrameInfo()->CreateFixedObject(
17181           SlotSize, /*Offset=*/0, /*IsImmutable=*/false);
17182       FuncInfo->setFAIndex(FrameAddrIndex);
17183     }
17184     return DAG.getFrameIndex(FrameAddrIndex, VT);
17185   }
17186
17187   unsigned FrameReg =
17188       RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
17189   SDLoc dl(Op);  // FIXME probably not meaningful
17190   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
17191   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
17192           (FrameReg == X86::EBP && VT == MVT::i32)) &&
17193          "Invalid Frame Register!");
17194   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
17195   while (Depth--)
17196     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
17197                             MachinePointerInfo(),
17198                             false, false, false, 0);
17199   return FrameAddr;
17200 }
17201
17202 // FIXME? Maybe this could be a TableGen attribute on some registers and
17203 // this table could be generated automatically from RegInfo.
17204 unsigned X86TargetLowering::getRegisterByName(const char* RegName, EVT VT,
17205                                               SelectionDAG &DAG) const {
17206   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
17207   const MachineFunction &MF = DAG.getMachineFunction();
17208
17209   unsigned Reg = StringSwitch<unsigned>(RegName)
17210                        .Case("esp", X86::ESP)
17211                        .Case("rsp", X86::RSP)
17212                        .Case("ebp", X86::EBP)
17213                        .Case("rbp", X86::RBP)
17214                        .Default(0);
17215
17216   if (Reg == X86::EBP || Reg == X86::RBP) {
17217     if (!TFI.hasFP(MF))
17218       report_fatal_error("register " + StringRef(RegName) +
17219                          " is allocatable: function has no frame pointer");
17220 #ifndef NDEBUG
17221     else {
17222       const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17223       unsigned FrameReg =
17224           RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
17225       assert((FrameReg == X86::EBP || FrameReg == X86::RBP) &&
17226              "Invalid Frame Register!");
17227     }
17228 #endif
17229   }
17230
17231   if (Reg)
17232     return Reg;
17233
17234   report_fatal_error("Invalid register name global variable");
17235 }
17236
17237 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
17238                                                      SelectionDAG &DAG) const {
17239   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17240   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize(), SDLoc(Op));
17241 }
17242
17243 unsigned X86TargetLowering::getExceptionPointerRegister(
17244     const Constant *PersonalityFn) const {
17245   if (classifyEHPersonality(PersonalityFn) == EHPersonality::CoreCLR)
17246     return Subtarget->isTarget64BitLP64() ? X86::RDX : X86::EDX;
17247
17248   return Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX;
17249 }
17250
17251 unsigned X86TargetLowering::getExceptionSelectorRegister(
17252     const Constant *PersonalityFn) const {
17253   // Funclet personalities don't use selectors (the runtime does the selection).
17254   assert(!isFuncletEHPersonality(classifyEHPersonality(PersonalityFn)));
17255   return Subtarget->isTarget64BitLP64() ? X86::RDX : X86::EDX;
17256 }
17257
17258 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
17259   SDValue Chain     = Op.getOperand(0);
17260   SDValue Offset    = Op.getOperand(1);
17261   SDValue Handler   = Op.getOperand(2);
17262   SDLoc dl      (Op);
17263
17264   EVT PtrVT = getPointerTy(DAG.getDataLayout());
17265   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17266   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
17267   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
17268           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
17269          "Invalid Frame Register!");
17270   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
17271   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
17272
17273   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
17274                                  DAG.getIntPtrConstant(RegInfo->getSlotSize(),
17275                                                        dl));
17276   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
17277   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
17278                        false, false, 0);
17279   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
17280
17281   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
17282                      DAG.getRegister(StoreAddrReg, PtrVT));
17283 }
17284
17285 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
17286                                                SelectionDAG &DAG) const {
17287   SDLoc DL(Op);
17288   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
17289                      DAG.getVTList(MVT::i32, MVT::Other),
17290                      Op.getOperand(0), Op.getOperand(1));
17291 }
17292
17293 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
17294                                                 SelectionDAG &DAG) const {
17295   SDLoc DL(Op);
17296   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
17297                      Op.getOperand(0), Op.getOperand(1));
17298 }
17299
17300 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
17301   return Op.getOperand(0);
17302 }
17303
17304 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
17305                                                 SelectionDAG &DAG) const {
17306   SDValue Root = Op.getOperand(0);
17307   SDValue Trmp = Op.getOperand(1); // trampoline
17308   SDValue FPtr = Op.getOperand(2); // nested function
17309   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
17310   SDLoc dl (Op);
17311
17312   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
17313   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
17314
17315   if (Subtarget->is64Bit()) {
17316     SDValue OutChains[6];
17317
17318     // Large code-model.
17319     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
17320     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
17321
17322     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
17323     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
17324
17325     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
17326
17327     // Load the pointer to the nested function into R11.
17328     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
17329     SDValue Addr = Trmp;
17330     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
17331                                 Addr, MachinePointerInfo(TrmpAddr),
17332                                 false, false, 0);
17333
17334     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17335                        DAG.getConstant(2, dl, MVT::i64));
17336     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
17337                                 MachinePointerInfo(TrmpAddr, 2),
17338                                 false, false, 2);
17339
17340     // Load the 'nest' parameter value into R10.
17341     // R10 is specified in X86CallingConv.td
17342     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
17343     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17344                        DAG.getConstant(10, dl, MVT::i64));
17345     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
17346                                 Addr, MachinePointerInfo(TrmpAddr, 10),
17347                                 false, false, 0);
17348
17349     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17350                        DAG.getConstant(12, dl, MVT::i64));
17351     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
17352                                 MachinePointerInfo(TrmpAddr, 12),
17353                                 false, false, 2);
17354
17355     // Jump to the nested function.
17356     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
17357     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17358                        DAG.getConstant(20, dl, MVT::i64));
17359     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
17360                                 Addr, MachinePointerInfo(TrmpAddr, 20),
17361                                 false, false, 0);
17362
17363     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
17364     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17365                        DAG.getConstant(22, dl, MVT::i64));
17366     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, dl, MVT::i8),
17367                                 Addr, MachinePointerInfo(TrmpAddr, 22),
17368                                 false, false, 0);
17369
17370     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
17371   } else {
17372     const Function *Func =
17373       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
17374     CallingConv::ID CC = Func->getCallingConv();
17375     unsigned NestReg;
17376
17377     switch (CC) {
17378     default:
17379       llvm_unreachable("Unsupported calling convention");
17380     case CallingConv::C:
17381     case CallingConv::X86_StdCall: {
17382       // Pass 'nest' parameter in ECX.
17383       // Must be kept in sync with X86CallingConv.td
17384       NestReg = X86::ECX;
17385
17386       // Check that ECX wasn't needed by an 'inreg' parameter.
17387       FunctionType *FTy = Func->getFunctionType();
17388       const AttributeSet &Attrs = Func->getAttributes();
17389
17390       if (!Attrs.isEmpty() && !Func->isVarArg()) {
17391         unsigned InRegCount = 0;
17392         unsigned Idx = 1;
17393
17394         for (FunctionType::param_iterator I = FTy->param_begin(),
17395              E = FTy->param_end(); I != E; ++I, ++Idx)
17396           if (Attrs.hasAttribute(Idx, Attribute::InReg)) {
17397             auto &DL = DAG.getDataLayout();
17398             // FIXME: should only count parameters that are lowered to integers.
17399             InRegCount += (DL.getTypeSizeInBits(*I) + 31) / 32;
17400           }
17401
17402         if (InRegCount > 2) {
17403           report_fatal_error("Nest register in use - reduce number of inreg"
17404                              " parameters!");
17405         }
17406       }
17407       break;
17408     }
17409     case CallingConv::X86_FastCall:
17410     case CallingConv::X86_ThisCall:
17411     case CallingConv::Fast:
17412       // Pass 'nest' parameter in EAX.
17413       // Must be kept in sync with X86CallingConv.td
17414       NestReg = X86::EAX;
17415       break;
17416     }
17417
17418     SDValue OutChains[4];
17419     SDValue Addr, Disp;
17420
17421     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17422                        DAG.getConstant(10, dl, MVT::i32));
17423     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
17424
17425     // This is storing the opcode for MOV32ri.
17426     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
17427     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
17428     OutChains[0] = DAG.getStore(Root, dl,
17429                                 DAG.getConstant(MOV32ri|N86Reg, dl, MVT::i8),
17430                                 Trmp, MachinePointerInfo(TrmpAddr),
17431                                 false, false, 0);
17432
17433     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17434                        DAG.getConstant(1, dl, MVT::i32));
17435     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
17436                                 MachinePointerInfo(TrmpAddr, 1),
17437                                 false, false, 1);
17438
17439     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
17440     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17441                        DAG.getConstant(5, dl, MVT::i32));
17442     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, dl, MVT::i8),
17443                                 Addr, MachinePointerInfo(TrmpAddr, 5),
17444                                 false, false, 1);
17445
17446     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17447                        DAG.getConstant(6, dl, MVT::i32));
17448     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
17449                                 MachinePointerInfo(TrmpAddr, 6),
17450                                 false, false, 1);
17451
17452     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
17453   }
17454 }
17455
17456 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
17457                                             SelectionDAG &DAG) const {
17458   /*
17459    The rounding mode is in bits 11:10 of FPSR, and has the following
17460    settings:
17461      00 Round to nearest
17462      01 Round to -inf
17463      10 Round to +inf
17464      11 Round to 0
17465
17466   FLT_ROUNDS, on the other hand, expects the following:
17467     -1 Undefined
17468      0 Round to 0
17469      1 Round to nearest
17470      2 Round to +inf
17471      3 Round to -inf
17472
17473   To perform the conversion, we do:
17474     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
17475   */
17476
17477   MachineFunction &MF = DAG.getMachineFunction();
17478   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
17479   unsigned StackAlignment = TFI.getStackAlignment();
17480   MVT VT = Op.getSimpleValueType();
17481   SDLoc DL(Op);
17482
17483   // Save FP Control Word to stack slot
17484   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
17485   SDValue StackSlot =
17486       DAG.getFrameIndex(SSFI, getPointerTy(DAG.getDataLayout()));
17487
17488   MachineMemOperand *MMO =
17489       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
17490                               MachineMemOperand::MOStore, 2, 2);
17491
17492   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
17493   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
17494                                           DAG.getVTList(MVT::Other),
17495                                           Ops, MVT::i16, MMO);
17496
17497   // Load FP Control Word from stack slot
17498   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
17499                             MachinePointerInfo(), false, false, false, 0);
17500
17501   // Transform as necessary
17502   SDValue CWD1 =
17503     DAG.getNode(ISD::SRL, DL, MVT::i16,
17504                 DAG.getNode(ISD::AND, DL, MVT::i16,
17505                             CWD, DAG.getConstant(0x800, DL, MVT::i16)),
17506                 DAG.getConstant(11, DL, MVT::i8));
17507   SDValue CWD2 =
17508     DAG.getNode(ISD::SRL, DL, MVT::i16,
17509                 DAG.getNode(ISD::AND, DL, MVT::i16,
17510                             CWD, DAG.getConstant(0x400, DL, MVT::i16)),
17511                 DAG.getConstant(9, DL, MVT::i8));
17512
17513   SDValue RetVal =
17514     DAG.getNode(ISD::AND, DL, MVT::i16,
17515                 DAG.getNode(ISD::ADD, DL, MVT::i16,
17516                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
17517                             DAG.getConstant(1, DL, MVT::i16)),
17518                 DAG.getConstant(3, DL, MVT::i16));
17519
17520   return DAG.getNode((VT.getSizeInBits() < 16 ?
17521                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
17522 }
17523
17524 /// \brief Lower a vector CTLZ using native supported vector CTLZ instruction.
17525 //
17526 // 1. i32/i64 128/256-bit vector (native support require VLX) are expended
17527 //    to 512-bit vector.
17528 // 2. i8/i16 vector implemented using dword LZCNT vector instruction
17529 //    ( sub(trunc(lzcnt(zext32(x)))) ). In case zext32(x) is illegal,
17530 //    split the vector, perform operation on it's Lo a Hi part and
17531 //    concatenate the results.
17532 static SDValue LowerVectorCTLZ_AVX512(SDValue Op, SelectionDAG &DAG) {
17533   SDLoc dl(Op);
17534   MVT VT = Op.getSimpleValueType();
17535   MVT EltVT = VT.getVectorElementType();
17536   unsigned NumElems = VT.getVectorNumElements();
17537
17538   if (EltVT == MVT::i64 || EltVT == MVT::i32) {
17539     // Extend to 512 bit vector.
17540     assert((VT.is256BitVector() || VT.is128BitVector()) &&
17541               "Unsupported value type for operation");
17542
17543     MVT NewVT = MVT::getVectorVT(EltVT, 512 / VT.getScalarSizeInBits());
17544     SDValue Vec512 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, NewVT,
17545                                  DAG.getUNDEF(NewVT),
17546                                  Op.getOperand(0),
17547                                  DAG.getIntPtrConstant(0, dl));
17548     SDValue CtlzNode = DAG.getNode(ISD::CTLZ, dl, NewVT, Vec512);
17549
17550     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, CtlzNode,
17551                        DAG.getIntPtrConstant(0, dl));
17552   }
17553
17554   assert((EltVT == MVT::i8 || EltVT == MVT::i16) &&
17555           "Unsupported element type");
17556
17557   if (16 < NumElems) {
17558     // Split vector, it's Lo and Hi parts will be handled in next iteration.
17559     SDValue Lo, Hi;
17560     std::tie(Lo, Hi) = DAG.SplitVector(Op.getOperand(0), dl);
17561     MVT OutVT = MVT::getVectorVT(EltVT, NumElems/2);
17562
17563     Lo = DAG.getNode(Op.getOpcode(), dl, OutVT, Lo);
17564     Hi = DAG.getNode(Op.getOpcode(), dl, OutVT, Hi);
17565
17566     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lo, Hi);
17567   }
17568
17569   MVT NewVT = MVT::getVectorVT(MVT::i32, NumElems);
17570
17571   assert((NewVT.is256BitVector() || NewVT.is512BitVector()) &&
17572           "Unsupported value type for operation");
17573
17574   // Use native supported vector instruction vplzcntd.
17575   Op = DAG.getNode(ISD::ZERO_EXTEND, dl, NewVT, Op.getOperand(0));
17576   SDValue CtlzNode = DAG.getNode(ISD::CTLZ, dl, NewVT, Op);
17577   SDValue TruncNode = DAG.getNode(ISD::TRUNCATE, dl, VT, CtlzNode);
17578   SDValue Delta = DAG.getConstant(32 - EltVT.getSizeInBits(), dl, VT);
17579
17580   return DAG.getNode(ISD::SUB, dl, VT, TruncNode, Delta);
17581 }
17582
17583 static SDValue LowerCTLZ(SDValue Op, const X86Subtarget *Subtarget,
17584                          SelectionDAG &DAG) {
17585   MVT VT = Op.getSimpleValueType();
17586   MVT OpVT = VT;
17587   unsigned NumBits = VT.getSizeInBits();
17588   SDLoc dl(Op);
17589
17590   if (VT.isVector() && Subtarget->hasAVX512())
17591     return LowerVectorCTLZ_AVX512(Op, DAG);
17592
17593   Op = Op.getOperand(0);
17594   if (VT == MVT::i8) {
17595     // Zero extend to i32 since there is not an i8 bsr.
17596     OpVT = MVT::i32;
17597     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
17598   }
17599
17600   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
17601   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
17602   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
17603
17604   // If src is zero (i.e. bsr sets ZF), returns NumBits.
17605   SDValue Ops[] = {
17606     Op,
17607     DAG.getConstant(NumBits + NumBits - 1, dl, OpVT),
17608     DAG.getConstant(X86::COND_E, dl, MVT::i8),
17609     Op.getValue(1)
17610   };
17611   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
17612
17613   // Finally xor with NumBits-1.
17614   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
17615                    DAG.getConstant(NumBits - 1, dl, OpVT));
17616
17617   if (VT == MVT::i8)
17618     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
17619   return Op;
17620 }
17621
17622 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, const X86Subtarget *Subtarget,
17623                                     SelectionDAG &DAG) {
17624   MVT VT = Op.getSimpleValueType();
17625   EVT OpVT = VT;
17626   unsigned NumBits = VT.getSizeInBits();
17627   SDLoc dl(Op);
17628
17629   if (VT.isVector() && Subtarget->hasAVX512())
17630     return LowerVectorCTLZ_AVX512(Op, DAG);
17631
17632   Op = Op.getOperand(0);
17633   if (VT == MVT::i8) {
17634     // Zero extend to i32 since there is not an i8 bsr.
17635     OpVT = MVT::i32;
17636     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
17637   }
17638
17639   // Issue a bsr (scan bits in reverse).
17640   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
17641   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
17642
17643   // And xor with NumBits-1.
17644   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
17645                    DAG.getConstant(NumBits - 1, dl, OpVT));
17646
17647   if (VT == MVT::i8)
17648     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
17649   return Op;
17650 }
17651
17652 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
17653   MVT VT = Op.getSimpleValueType();
17654   unsigned NumBits = VT.getScalarSizeInBits();
17655   SDLoc dl(Op);
17656
17657   if (VT.isVector()) {
17658     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17659
17660     SDValue N0 = Op.getOperand(0);
17661     SDValue Zero = DAG.getConstant(0, dl, VT);
17662
17663     // lsb(x) = (x & -x)
17664     SDValue LSB = DAG.getNode(ISD::AND, dl, VT, N0,
17665                               DAG.getNode(ISD::SUB, dl, VT, Zero, N0));
17666
17667     // cttz_undef(x) = (width - 1) - ctlz(lsb)
17668     if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF &&
17669         TLI.isOperationLegal(ISD::CTLZ, VT)) {
17670       SDValue WidthMinusOne = DAG.getConstant(NumBits - 1, dl, VT);
17671       return DAG.getNode(ISD::SUB, dl, VT, WidthMinusOne,
17672                          DAG.getNode(ISD::CTLZ, dl, VT, LSB));
17673     }
17674
17675     // cttz(x) = ctpop(lsb - 1)
17676     SDValue One = DAG.getConstant(1, dl, VT);
17677     return DAG.getNode(ISD::CTPOP, dl, VT,
17678                        DAG.getNode(ISD::SUB, dl, VT, LSB, One));
17679   }
17680
17681   assert(Op.getOpcode() == ISD::CTTZ &&
17682          "Only scalar CTTZ requires custom lowering");
17683
17684   // Issue a bsf (scan bits forward) which also sets EFLAGS.
17685   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
17686   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op.getOperand(0));
17687
17688   // If src is zero (i.e. bsf sets ZF), returns NumBits.
17689   SDValue Ops[] = {
17690     Op,
17691     DAG.getConstant(NumBits, dl, VT),
17692     DAG.getConstant(X86::COND_E, dl, MVT::i8),
17693     Op.getValue(1)
17694   };
17695   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
17696 }
17697
17698 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
17699 // ones, and then concatenate the result back.
17700 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
17701   MVT VT = Op.getSimpleValueType();
17702
17703   assert(VT.is256BitVector() && VT.isInteger() &&
17704          "Unsupported value type for operation");
17705
17706   unsigned NumElems = VT.getVectorNumElements();
17707   SDLoc dl(Op);
17708
17709   // Extract the LHS vectors
17710   SDValue LHS = Op.getOperand(0);
17711   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
17712   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
17713
17714   // Extract the RHS vectors
17715   SDValue RHS = Op.getOperand(1);
17716   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
17717   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
17718
17719   MVT EltVT = VT.getVectorElementType();
17720   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
17721
17722   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
17723                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
17724                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
17725 }
17726
17727 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
17728   if (Op.getValueType() == MVT::i1)
17729     return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
17730                        Op.getOperand(0), Op.getOperand(1));
17731   assert(Op.getSimpleValueType().is256BitVector() &&
17732          Op.getSimpleValueType().isInteger() &&
17733          "Only handle AVX 256-bit vector integer operation");
17734   return Lower256IntArith(Op, DAG);
17735 }
17736
17737 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
17738   if (Op.getValueType() == MVT::i1)
17739     return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
17740                        Op.getOperand(0), Op.getOperand(1));
17741   assert(Op.getSimpleValueType().is256BitVector() &&
17742          Op.getSimpleValueType().isInteger() &&
17743          "Only handle AVX 256-bit vector integer operation");
17744   return Lower256IntArith(Op, DAG);
17745 }
17746
17747 static SDValue LowerMINMAX(SDValue Op, SelectionDAG &DAG) {
17748   assert(Op.getSimpleValueType().is256BitVector() &&
17749          Op.getSimpleValueType().isInteger() &&
17750          "Only handle AVX 256-bit vector integer operation");
17751   return Lower256IntArith(Op, DAG);
17752 }
17753
17754 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
17755                         SelectionDAG &DAG) {
17756   SDLoc dl(Op);
17757   MVT VT = Op.getSimpleValueType();
17758
17759   if (VT == MVT::i1)
17760     return DAG.getNode(ISD::AND, dl, VT, Op.getOperand(0), Op.getOperand(1));
17761
17762   // Decompose 256-bit ops into smaller 128-bit ops.
17763   if (VT.is256BitVector() && !Subtarget->hasInt256())
17764     return Lower256IntArith(Op, DAG);
17765
17766   SDValue A = Op.getOperand(0);
17767   SDValue B = Op.getOperand(1);
17768
17769   // Lower v16i8/v32i8 mul as promotion to v8i16/v16i16 vector
17770   // pairs, multiply and truncate.
17771   if (VT == MVT::v16i8 || VT == MVT::v32i8) {
17772     if (Subtarget->hasInt256()) {
17773       if (VT == MVT::v32i8) {
17774         MVT SubVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() / 2);
17775         SDValue Lo = DAG.getIntPtrConstant(0, dl);
17776         SDValue Hi = DAG.getIntPtrConstant(VT.getVectorNumElements() / 2, dl);
17777         SDValue ALo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Lo);
17778         SDValue BLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Lo);
17779         SDValue AHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Hi);
17780         SDValue BHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Hi);
17781         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
17782                            DAG.getNode(ISD::MUL, dl, SubVT, ALo, BLo),
17783                            DAG.getNode(ISD::MUL, dl, SubVT, AHi, BHi));
17784       }
17785
17786       MVT ExVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements());
17787       return DAG.getNode(
17788           ISD::TRUNCATE, dl, VT,
17789           DAG.getNode(ISD::MUL, dl, ExVT,
17790                       DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, A),
17791                       DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, B)));
17792     }
17793
17794     assert(VT == MVT::v16i8 &&
17795            "Pre-AVX2 support only supports v16i8 multiplication");
17796     MVT ExVT = MVT::v8i16;
17797
17798     // Extract the lo parts and sign extend to i16
17799     SDValue ALo, BLo;
17800     if (Subtarget->hasSSE41()) {
17801       ALo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, A);
17802       BLo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, B);
17803     } else {
17804       const int ShufMask[] = {-1, 0, -1, 1, -1, 2, -1, 3,
17805                               -1, 4, -1, 5, -1, 6, -1, 7};
17806       ALo = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
17807       BLo = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
17808       ALo = DAG.getBitcast(ExVT, ALo);
17809       BLo = DAG.getBitcast(ExVT, BLo);
17810       ALo = DAG.getNode(ISD::SRA, dl, ExVT, ALo, DAG.getConstant(8, dl, ExVT));
17811       BLo = DAG.getNode(ISD::SRA, dl, ExVT, BLo, DAG.getConstant(8, dl, ExVT));
17812     }
17813
17814     // Extract the hi parts and sign extend to i16
17815     SDValue AHi, BHi;
17816     if (Subtarget->hasSSE41()) {
17817       const int ShufMask[] = {8,  9,  10, 11, 12, 13, 14, 15,
17818                               -1, -1, -1, -1, -1, -1, -1, -1};
17819       AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
17820       BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
17821       AHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, AHi);
17822       BHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, BHi);
17823     } else {
17824       const int ShufMask[] = {-1, 8,  -1, 9,  -1, 10, -1, 11,
17825                               -1, 12, -1, 13, -1, 14, -1, 15};
17826       AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
17827       BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
17828       AHi = DAG.getBitcast(ExVT, AHi);
17829       BHi = DAG.getBitcast(ExVT, BHi);
17830       AHi = DAG.getNode(ISD::SRA, dl, ExVT, AHi, DAG.getConstant(8, dl, ExVT));
17831       BHi = DAG.getNode(ISD::SRA, dl, ExVT, BHi, DAG.getConstant(8, dl, ExVT));
17832     }
17833
17834     // Multiply, mask the lower 8bits of the lo/hi results and pack
17835     SDValue RLo = DAG.getNode(ISD::MUL, dl, ExVT, ALo, BLo);
17836     SDValue RHi = DAG.getNode(ISD::MUL, dl, ExVT, AHi, BHi);
17837     RLo = DAG.getNode(ISD::AND, dl, ExVT, RLo, DAG.getConstant(255, dl, ExVT));
17838     RHi = DAG.getNode(ISD::AND, dl, ExVT, RHi, DAG.getConstant(255, dl, ExVT));
17839     return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
17840   }
17841
17842   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
17843   if (VT == MVT::v4i32) {
17844     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
17845            "Should not custom lower when pmuldq is available!");
17846
17847     // Extract the odd parts.
17848     static const int UnpackMask[] = { 1, -1, 3, -1 };
17849     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
17850     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
17851
17852     // Multiply the even parts.
17853     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
17854     // Now multiply odd parts.
17855     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
17856
17857     Evens = DAG.getBitcast(VT, Evens);
17858     Odds = DAG.getBitcast(VT, Odds);
17859
17860     // Merge the two vectors back together with a shuffle. This expands into 2
17861     // shuffles.
17862     static const int ShufMask[] = { 0, 4, 2, 6 };
17863     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
17864   }
17865
17866   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
17867          "Only know how to lower V2I64/V4I64/V8I64 multiply");
17868
17869   //  Ahi = psrlqi(a, 32);
17870   //  Bhi = psrlqi(b, 32);
17871   //
17872   //  AloBlo = pmuludq(a, b);
17873   //  AloBhi = pmuludq(a, Bhi);
17874   //  AhiBlo = pmuludq(Ahi, b);
17875
17876   //  AloBhi = psllqi(AloBhi, 32);
17877   //  AhiBlo = psllqi(AhiBlo, 32);
17878   //  return AloBlo + AloBhi + AhiBlo;
17879
17880   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
17881   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
17882
17883   SDValue AhiBlo = Ahi;
17884   SDValue AloBhi = Bhi;
17885   // Bit cast to 32-bit vectors for MULUDQ
17886   MVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
17887                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
17888   A = DAG.getBitcast(MulVT, A);
17889   B = DAG.getBitcast(MulVT, B);
17890   Ahi = DAG.getBitcast(MulVT, Ahi);
17891   Bhi = DAG.getBitcast(MulVT, Bhi);
17892
17893   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
17894   // After shifting right const values the result may be all-zero.
17895   if (!ISD::isBuildVectorAllZeros(Ahi.getNode())) {
17896     AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
17897     AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
17898   }
17899   if (!ISD::isBuildVectorAllZeros(Bhi.getNode())) {
17900     AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
17901     AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
17902   }
17903
17904   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
17905   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
17906 }
17907
17908 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
17909   assert(Subtarget->isTargetWin64() && "Unexpected target");
17910   EVT VT = Op.getValueType();
17911   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
17912          "Unexpected return type for lowering");
17913
17914   RTLIB::Libcall LC;
17915   bool isSigned;
17916   switch (Op->getOpcode()) {
17917   default: llvm_unreachable("Unexpected request for libcall!");
17918   case ISD::SDIV:      isSigned = true;  LC = RTLIB::SDIV_I128;    break;
17919   case ISD::UDIV:      isSigned = false; LC = RTLIB::UDIV_I128;    break;
17920   case ISD::SREM:      isSigned = true;  LC = RTLIB::SREM_I128;    break;
17921   case ISD::UREM:      isSigned = false; LC = RTLIB::UREM_I128;    break;
17922   case ISD::SDIVREM:   isSigned = true;  LC = RTLIB::SDIVREM_I128; break;
17923   case ISD::UDIVREM:   isSigned = false; LC = RTLIB::UDIVREM_I128; break;
17924   }
17925
17926   SDLoc dl(Op);
17927   SDValue InChain = DAG.getEntryNode();
17928
17929   TargetLowering::ArgListTy Args;
17930   TargetLowering::ArgListEntry Entry;
17931   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
17932     EVT ArgVT = Op->getOperand(i).getValueType();
17933     assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
17934            "Unexpected argument type for lowering");
17935     SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
17936     Entry.Node = StackPtr;
17937     InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
17938                            false, false, 16);
17939     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
17940     Entry.Ty = PointerType::get(ArgTy,0);
17941     Entry.isSExt = false;
17942     Entry.isZExt = false;
17943     Args.push_back(Entry);
17944   }
17945
17946   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
17947                                          getPointerTy(DAG.getDataLayout()));
17948
17949   TargetLowering::CallLoweringInfo CLI(DAG);
17950   CLI.setDebugLoc(dl).setChain(InChain)
17951     .setCallee(getLibcallCallingConv(LC),
17952                static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
17953                Callee, std::move(Args), 0)
17954     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
17955
17956   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
17957   return DAG.getBitcast(VT, CallInfo.first);
17958 }
17959
17960 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
17961                              SelectionDAG &DAG) {
17962   SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
17963   MVT VT = Op0.getSimpleValueType();
17964   SDLoc dl(Op);
17965
17966   assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
17967          (VT == MVT::v8i32 && Subtarget->hasInt256()));
17968
17969   // PMULxD operations multiply each even value (starting at 0) of LHS with
17970   // the related value of RHS and produce a widen result.
17971   // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
17972   // => <2 x i64> <ae|cg>
17973   //
17974   // In other word, to have all the results, we need to perform two PMULxD:
17975   // 1. one with the even values.
17976   // 2. one with the odd values.
17977   // To achieve #2, with need to place the odd values at an even position.
17978   //
17979   // Place the odd value at an even position (basically, shift all values 1
17980   // step to the left):
17981   const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
17982   // <a|b|c|d> => <b|undef|d|undef>
17983   SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
17984   // <e|f|g|h> => <f|undef|h|undef>
17985   SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
17986
17987   // Emit two multiplies, one for the lower 2 ints and one for the higher 2
17988   // ints.
17989   MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
17990   bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
17991   unsigned Opcode =
17992       (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
17993   // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
17994   // => <2 x i64> <ae|cg>
17995   SDValue Mul1 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
17996   // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
17997   // => <2 x i64> <bf|dh>
17998   SDValue Mul2 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
17999
18000   // Shuffle it back into the right order.
18001   SDValue Highs, Lows;
18002   if (VT == MVT::v8i32) {
18003     const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
18004     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
18005     const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
18006     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
18007   } else {
18008     const int HighMask[] = {1, 5, 3, 7};
18009     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
18010     const int LowMask[] = {0, 4, 2, 6};
18011     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
18012   }
18013
18014   // If we have a signed multiply but no PMULDQ fix up the high parts of a
18015   // unsigned multiply.
18016   if (IsSigned && !Subtarget->hasSSE41()) {
18017     SDValue ShAmt = DAG.getConstant(
18018         31, dl,
18019         DAG.getTargetLoweringInfo().getShiftAmountTy(VT, DAG.getDataLayout()));
18020     SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
18021                              DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
18022     SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
18023                              DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
18024
18025     SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
18026     Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
18027   }
18028
18029   // The first result of MUL_LOHI is actually the low value, followed by the
18030   // high value.
18031   SDValue Ops[] = {Lows, Highs};
18032   return DAG.getMergeValues(Ops, dl);
18033 }
18034
18035 // Return true if the required (according to Opcode) shift-imm form is natively
18036 // supported by the Subtarget
18037 static bool SupportedVectorShiftWithImm(MVT VT, const X86Subtarget *Subtarget,
18038                                         unsigned Opcode) {
18039   if (VT.getScalarSizeInBits() < 16)
18040     return false;
18041
18042   if (VT.is512BitVector() &&
18043       (VT.getScalarSizeInBits() > 16 || Subtarget->hasBWI()))
18044     return true;
18045
18046   bool LShift = VT.is128BitVector() ||
18047     (VT.is256BitVector() && Subtarget->hasInt256());
18048
18049   bool AShift = LShift && (Subtarget->hasVLX() ||
18050     (VT != MVT::v2i64 && VT != MVT::v4i64));
18051   return (Opcode == ISD::SRA) ? AShift : LShift;
18052 }
18053
18054 // The shift amount is a variable, but it is the same for all vector lanes.
18055 // These instructions are defined together with shift-immediate.
18056 static
18057 bool SupportedVectorShiftWithBaseAmnt(MVT VT, const X86Subtarget *Subtarget,
18058                                       unsigned Opcode) {
18059   return SupportedVectorShiftWithImm(VT, Subtarget, Opcode);
18060 }
18061
18062 // Return true if the required (according to Opcode) variable-shift form is
18063 // natively supported by the Subtarget
18064 static bool SupportedVectorVarShift(MVT VT, const X86Subtarget *Subtarget,
18065                                     unsigned Opcode) {
18066
18067   if (!Subtarget->hasInt256() || VT.getScalarSizeInBits() < 16)
18068     return false;
18069
18070   // vXi16 supported only on AVX-512, BWI
18071   if (VT.getScalarSizeInBits() == 16 && !Subtarget->hasBWI())
18072     return false;
18073
18074   if (VT.is512BitVector() || Subtarget->hasVLX())
18075     return true;
18076
18077   bool LShift = VT.is128BitVector() || VT.is256BitVector();
18078   bool AShift = LShift &&  VT != MVT::v2i64 && VT != MVT::v4i64;
18079   return (Opcode == ISD::SRA) ? AShift : LShift;
18080 }
18081
18082 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
18083                                          const X86Subtarget *Subtarget) {
18084   MVT VT = Op.getSimpleValueType();
18085   SDLoc dl(Op);
18086   SDValue R = Op.getOperand(0);
18087   SDValue Amt = Op.getOperand(1);
18088
18089   unsigned X86Opc = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
18090     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
18091
18092   auto ArithmeticShiftRight64 = [&](uint64_t ShiftAmt) {
18093     assert((VT == MVT::v2i64 || VT == MVT::v4i64) && "Unexpected SRA type");
18094     MVT ExVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() * 2);
18095     SDValue Ex = DAG.getBitcast(ExVT, R);
18096
18097     if (ShiftAmt >= 32) {
18098       // Splat sign to upper i32 dst, and SRA upper i32 src to lower i32.
18099       SDValue Upper =
18100           getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex, 31, DAG);
18101       SDValue Lower = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
18102                                                  ShiftAmt - 32, DAG);
18103       if (VT == MVT::v2i64)
18104         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {5, 1, 7, 3});
18105       if (VT == MVT::v4i64)
18106         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
18107                                   {9, 1, 11, 3, 13, 5, 15, 7});
18108     } else {
18109       // SRA upper i32, SHL whole i64 and select lower i32.
18110       SDValue Upper = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
18111                                                  ShiftAmt, DAG);
18112       SDValue Lower =
18113           getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt, DAG);
18114       Lower = DAG.getBitcast(ExVT, Lower);
18115       if (VT == MVT::v2i64)
18116         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {4, 1, 6, 3});
18117       if (VT == MVT::v4i64)
18118         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
18119                                   {8, 1, 10, 3, 12, 5, 14, 7});
18120     }
18121     return DAG.getBitcast(VT, Ex);
18122   };
18123
18124   // Optimize shl/srl/sra with constant shift amount.
18125   if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
18126     if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
18127       uint64_t ShiftAmt = ShiftConst->getZExtValue();
18128
18129       if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
18130         return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
18131
18132       // i64 SRA needs to be performed as partial shifts.
18133       if ((VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
18134           Op.getOpcode() == ISD::SRA && !Subtarget->hasXOP())
18135         return ArithmeticShiftRight64(ShiftAmt);
18136
18137       if (VT == MVT::v16i8 || (Subtarget->hasInt256() && VT == MVT::v32i8)) {
18138         unsigned NumElts = VT.getVectorNumElements();
18139         MVT ShiftVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
18140
18141         // Simple i8 add case
18142         if (Op.getOpcode() == ISD::SHL && ShiftAmt == 1)
18143           return DAG.getNode(ISD::ADD, dl, VT, R, R);
18144
18145         // ashr(R, 7)  === cmp_slt(R, 0)
18146         if (Op.getOpcode() == ISD::SRA && ShiftAmt == 7) {
18147           SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
18148           return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
18149         }
18150
18151         // XOP can shift v16i8 directly instead of as shift v8i16 + mask.
18152         if (VT == MVT::v16i8 && Subtarget->hasXOP())
18153           return SDValue();
18154
18155         if (Op.getOpcode() == ISD::SHL) {
18156           // Make a large shift.
18157           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ShiftVT,
18158                                                    R, ShiftAmt, DAG);
18159           SHL = DAG.getBitcast(VT, SHL);
18160           // Zero out the rightmost bits.
18161           SmallVector<SDValue, 32> V(
18162               NumElts, DAG.getConstant(uint8_t(-1U << ShiftAmt), dl, MVT::i8));
18163           return DAG.getNode(ISD::AND, dl, VT, SHL,
18164                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
18165         }
18166         if (Op.getOpcode() == ISD::SRL) {
18167           // Make a large shift.
18168           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ShiftVT,
18169                                                    R, ShiftAmt, DAG);
18170           SRL = DAG.getBitcast(VT, SRL);
18171           // Zero out the leftmost bits.
18172           SmallVector<SDValue, 32> V(
18173               NumElts, DAG.getConstant(uint8_t(-1U) >> ShiftAmt, dl, MVT::i8));
18174           return DAG.getNode(ISD::AND, dl, VT, SRL,
18175                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
18176         }
18177         if (Op.getOpcode() == ISD::SRA) {
18178           // ashr(R, Amt) === sub(xor(lshr(R, Amt), Mask), Mask)
18179           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
18180           SmallVector<SDValue, 32> V(NumElts,
18181                                      DAG.getConstant(128 >> ShiftAmt, dl,
18182                                                      MVT::i8));
18183           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
18184           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
18185           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
18186           return Res;
18187         }
18188         llvm_unreachable("Unknown shift opcode.");
18189       }
18190     }
18191   }
18192
18193   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
18194   if (!Subtarget->is64Bit() && !Subtarget->hasXOP() &&
18195       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64))) {
18196
18197     // Peek through any splat that was introduced for i64 shift vectorization.
18198     int SplatIndex = -1;
18199     if (ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt.getNode()))
18200       if (SVN->isSplat()) {
18201         SplatIndex = SVN->getSplatIndex();
18202         Amt = Amt.getOperand(0);
18203         assert(SplatIndex < (int)VT.getVectorNumElements() &&
18204                "Splat shuffle referencing second operand");
18205       }
18206
18207     if (Amt.getOpcode() != ISD::BITCAST ||
18208         Amt.getOperand(0).getOpcode() != ISD::BUILD_VECTOR)
18209       return SDValue();
18210
18211     Amt = Amt.getOperand(0);
18212     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
18213                      VT.getVectorNumElements();
18214     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
18215     uint64_t ShiftAmt = 0;
18216     unsigned BaseOp = (SplatIndex < 0 ? 0 : SplatIndex * Ratio);
18217     for (unsigned i = 0; i != Ratio; ++i) {
18218       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i + BaseOp));
18219       if (!C)
18220         return SDValue();
18221       // 6 == Log2(64)
18222       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
18223     }
18224
18225     // Check remaining shift amounts (if not a splat).
18226     if (SplatIndex < 0) {
18227       for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
18228         uint64_t ShAmt = 0;
18229         for (unsigned j = 0; j != Ratio; ++j) {
18230           ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
18231           if (!C)
18232             return SDValue();
18233           // 6 == Log2(64)
18234           ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
18235         }
18236         if (ShAmt != ShiftAmt)
18237           return SDValue();
18238       }
18239     }
18240
18241     if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
18242       return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
18243
18244     if (Op.getOpcode() == ISD::SRA)
18245       return ArithmeticShiftRight64(ShiftAmt);
18246   }
18247
18248   return SDValue();
18249 }
18250
18251 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
18252                                         const X86Subtarget* Subtarget) {
18253   MVT VT = Op.getSimpleValueType();
18254   SDLoc dl(Op);
18255   SDValue R = Op.getOperand(0);
18256   SDValue Amt = Op.getOperand(1);
18257
18258   unsigned X86OpcI = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
18259     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
18260
18261   unsigned X86OpcV = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHL :
18262     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRL : X86ISD::VSRA;
18263
18264   if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode())) {
18265     SDValue BaseShAmt;
18266     MVT EltVT = VT.getVectorElementType();
18267
18268     if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Amt)) {
18269       // Check if this build_vector node is doing a splat.
18270       // If so, then set BaseShAmt equal to the splat value.
18271       BaseShAmt = BV->getSplatValue();
18272       if (BaseShAmt && BaseShAmt.getOpcode() == ISD::UNDEF)
18273         BaseShAmt = SDValue();
18274     } else {
18275       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
18276         Amt = Amt.getOperand(0);
18277
18278       ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt);
18279       if (SVN && SVN->isSplat()) {
18280         unsigned SplatIdx = (unsigned)SVN->getSplatIndex();
18281         SDValue InVec = Amt.getOperand(0);
18282         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
18283           assert((SplatIdx < InVec.getSimpleValueType().getVectorNumElements()) &&
18284                  "Unexpected shuffle index found!");
18285           BaseShAmt = InVec.getOperand(SplatIdx);
18286         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
18287            if (ConstantSDNode *C =
18288                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
18289              if (C->getZExtValue() == SplatIdx)
18290                BaseShAmt = InVec.getOperand(1);
18291            }
18292         }
18293
18294         if (!BaseShAmt)
18295           // Avoid introducing an extract element from a shuffle.
18296           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InVec,
18297                                   DAG.getIntPtrConstant(SplatIdx, dl));
18298       }
18299     }
18300
18301     if (BaseShAmt.getNode()) {
18302       assert(EltVT.bitsLE(MVT::i64) && "Unexpected element type!");
18303       if (EltVT != MVT::i64 && EltVT.bitsGT(MVT::i32))
18304         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, BaseShAmt);
18305       else if (EltVT.bitsLT(MVT::i32))
18306         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
18307
18308       return getTargetVShiftNode(X86OpcI, dl, VT, R, BaseShAmt, DAG);
18309     }
18310   }
18311
18312   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
18313   if (!Subtarget->is64Bit() && VT == MVT::v2i64  &&
18314       Amt.getOpcode() == ISD::BITCAST &&
18315       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
18316     Amt = Amt.getOperand(0);
18317     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
18318                      VT.getVectorNumElements();
18319     std::vector<SDValue> Vals(Ratio);
18320     for (unsigned i = 0; i != Ratio; ++i)
18321       Vals[i] = Amt.getOperand(i);
18322     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
18323       for (unsigned j = 0; j != Ratio; ++j)
18324         if (Vals[j] != Amt.getOperand(i + j))
18325           return SDValue();
18326     }
18327
18328     if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode()))
18329       return DAG.getNode(X86OpcV, dl, VT, R, Op.getOperand(1));
18330   }
18331   return SDValue();
18332 }
18333
18334 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
18335                           SelectionDAG &DAG) {
18336   MVT VT = Op.getSimpleValueType();
18337   SDLoc dl(Op);
18338   SDValue R = Op.getOperand(0);
18339   SDValue Amt = Op.getOperand(1);
18340
18341   assert(VT.isVector() && "Custom lowering only for vector shifts!");
18342   assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
18343
18344   if (SDValue V = LowerScalarImmediateShift(Op, DAG, Subtarget))
18345     return V;
18346
18347   if (SDValue V = LowerScalarVariableShift(Op, DAG, Subtarget))
18348     return V;
18349
18350   if (SupportedVectorVarShift(VT, Subtarget, Op.getOpcode()))
18351     return Op;
18352
18353   // XOP has 128-bit variable logical/arithmetic shifts.
18354   // +ve/-ve Amt = shift left/right.
18355   if (Subtarget->hasXOP() &&
18356       (VT == MVT::v2i64 || VT == MVT::v4i32 ||
18357        VT == MVT::v8i16 || VT == MVT::v16i8)) {
18358     if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SRA) {
18359       SDValue Zero = getZeroVector(VT, Subtarget, DAG, dl);
18360       Amt = DAG.getNode(ISD::SUB, dl, VT, Zero, Amt);
18361     }
18362     if (Op.getOpcode() == ISD::SHL || Op.getOpcode() == ISD::SRL)
18363       return DAG.getNode(X86ISD::VPSHL, dl, VT, R, Amt);
18364     if (Op.getOpcode() == ISD::SRA)
18365       return DAG.getNode(X86ISD::VPSHA, dl, VT, R, Amt);
18366   }
18367
18368   // 2i64 vector logical shifts can efficiently avoid scalarization - do the
18369   // shifts per-lane and then shuffle the partial results back together.
18370   if (VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) {
18371     // Splat the shift amounts so the scalar shifts above will catch it.
18372     SDValue Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {0, 0});
18373     SDValue Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {1, 1});
18374     SDValue R0 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt0);
18375     SDValue R1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt1);
18376     return DAG.getVectorShuffle(VT, dl, R0, R1, {0, 3});
18377   }
18378
18379   // i64 vector arithmetic shift can be emulated with the transform:
18380   // M = lshr(SIGN_BIT, Amt)
18381   // ashr(R, Amt) === sub(xor(lshr(R, Amt), M), M)
18382   if ((VT == MVT::v2i64 || (VT == MVT::v4i64 && Subtarget->hasInt256())) &&
18383       Op.getOpcode() == ISD::SRA) {
18384     SDValue S = DAG.getConstant(APInt::getSignBit(64), dl, VT);
18385     SDValue M = DAG.getNode(ISD::SRL, dl, VT, S, Amt);
18386     R = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
18387     R = DAG.getNode(ISD::XOR, dl, VT, R, M);
18388     R = DAG.getNode(ISD::SUB, dl, VT, R, M);
18389     return R;
18390   }
18391
18392   // If possible, lower this packed shift into a vector multiply instead of
18393   // expanding it into a sequence of scalar shifts.
18394   // Do this only if the vector shift count is a constant build_vector.
18395   if (Op.getOpcode() == ISD::SHL &&
18396       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
18397        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
18398       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
18399     SmallVector<SDValue, 8> Elts;
18400     MVT SVT = VT.getVectorElementType();
18401     unsigned SVTBits = SVT.getSizeInBits();
18402     APInt One(SVTBits, 1);
18403     unsigned NumElems = VT.getVectorNumElements();
18404
18405     for (unsigned i=0; i !=NumElems; ++i) {
18406       SDValue Op = Amt->getOperand(i);
18407       if (Op->getOpcode() == ISD::UNDEF) {
18408         Elts.push_back(Op);
18409         continue;
18410       }
18411
18412       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
18413       APInt C(SVTBits, ND->getAPIntValue().getZExtValue());
18414       uint64_t ShAmt = C.getZExtValue();
18415       if (ShAmt >= SVTBits) {
18416         Elts.push_back(DAG.getUNDEF(SVT));
18417         continue;
18418       }
18419       Elts.push_back(DAG.getConstant(One.shl(ShAmt), dl, SVT));
18420     }
18421     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
18422     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
18423   }
18424
18425   // Lower SHL with variable shift amount.
18426   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
18427     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, dl, VT));
18428
18429     Op = DAG.getNode(ISD::ADD, dl, VT, Op,
18430                      DAG.getConstant(0x3f800000U, dl, VT));
18431     Op = DAG.getBitcast(MVT::v4f32, Op);
18432     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
18433     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
18434   }
18435
18436   // If possible, lower this shift as a sequence of two shifts by
18437   // constant plus a MOVSS/MOVSD instead of scalarizing it.
18438   // Example:
18439   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
18440   //
18441   // Could be rewritten as:
18442   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
18443   //
18444   // The advantage is that the two shifts from the example would be
18445   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
18446   // the vector shift into four scalar shifts plus four pairs of vector
18447   // insert/extract.
18448   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
18449       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
18450     unsigned TargetOpcode = X86ISD::MOVSS;
18451     bool CanBeSimplified;
18452     // The splat value for the first packed shift (the 'X' from the example).
18453     SDValue Amt1 = Amt->getOperand(0);
18454     // The splat value for the second packed shift (the 'Y' from the example).
18455     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
18456                                         Amt->getOperand(2);
18457
18458     // See if it is possible to replace this node with a sequence of
18459     // two shifts followed by a MOVSS/MOVSD
18460     if (VT == MVT::v4i32) {
18461       // Check if it is legal to use a MOVSS.
18462       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
18463                         Amt2 == Amt->getOperand(3);
18464       if (!CanBeSimplified) {
18465         // Otherwise, check if we can still simplify this node using a MOVSD.
18466         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
18467                           Amt->getOperand(2) == Amt->getOperand(3);
18468         TargetOpcode = X86ISD::MOVSD;
18469         Amt2 = Amt->getOperand(2);
18470       }
18471     } else {
18472       // Do similar checks for the case where the machine value type
18473       // is MVT::v8i16.
18474       CanBeSimplified = Amt1 == Amt->getOperand(1);
18475       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
18476         CanBeSimplified = Amt2 == Amt->getOperand(i);
18477
18478       if (!CanBeSimplified) {
18479         TargetOpcode = X86ISD::MOVSD;
18480         CanBeSimplified = true;
18481         Amt2 = Amt->getOperand(4);
18482         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
18483           CanBeSimplified = Amt1 == Amt->getOperand(i);
18484         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
18485           CanBeSimplified = Amt2 == Amt->getOperand(j);
18486       }
18487     }
18488
18489     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
18490         isa<ConstantSDNode>(Amt2)) {
18491       // Replace this node with two shifts followed by a MOVSS/MOVSD.
18492       MVT CastVT = MVT::v4i32;
18493       SDValue Splat1 =
18494         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), dl, VT);
18495       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
18496       SDValue Splat2 =
18497         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), dl, VT);
18498       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
18499       if (TargetOpcode == X86ISD::MOVSD)
18500         CastVT = MVT::v2i64;
18501       SDValue BitCast1 = DAG.getBitcast(CastVT, Shift1);
18502       SDValue BitCast2 = DAG.getBitcast(CastVT, Shift2);
18503       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
18504                                             BitCast1, DAG);
18505       return DAG.getBitcast(VT, Result);
18506     }
18507   }
18508
18509   // v4i32 Non Uniform Shifts.
18510   // If the shift amount is constant we can shift each lane using the SSE2
18511   // immediate shifts, else we need to zero-extend each lane to the lower i64
18512   // and shift using the SSE2 variable shifts.
18513   // The separate results can then be blended together.
18514   if (VT == MVT::v4i32) {
18515     unsigned Opc = Op.getOpcode();
18516     SDValue Amt0, Amt1, Amt2, Amt3;
18517     if (ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
18518       Amt0 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {0, 0, 0, 0});
18519       Amt1 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {1, 1, 1, 1});
18520       Amt2 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {2, 2, 2, 2});
18521       Amt3 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {3, 3, 3, 3});
18522     } else {
18523       // ISD::SHL is handled above but we include it here for completeness.
18524       switch (Opc) {
18525       default:
18526         llvm_unreachable("Unknown target vector shift node");
18527       case ISD::SHL:
18528         Opc = X86ISD::VSHL;
18529         break;
18530       case ISD::SRL:
18531         Opc = X86ISD::VSRL;
18532         break;
18533       case ISD::SRA:
18534         Opc = X86ISD::VSRA;
18535         break;
18536       }
18537       // The SSE2 shifts use the lower i64 as the same shift amount for
18538       // all lanes and the upper i64 is ignored. These shuffle masks
18539       // optimally zero-extend each lanes on SSE2/SSE41/AVX targets.
18540       SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
18541       Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Z, {0, 4, -1, -1});
18542       Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Z, {1, 5, -1, -1});
18543       Amt2 = DAG.getVectorShuffle(VT, dl, Amt, Z, {2, 6, -1, -1});
18544       Amt3 = DAG.getVectorShuffle(VT, dl, Amt, Z, {3, 7, -1, -1});
18545     }
18546
18547     SDValue R0 = DAG.getNode(Opc, dl, VT, R, Amt0);
18548     SDValue R1 = DAG.getNode(Opc, dl, VT, R, Amt1);
18549     SDValue R2 = DAG.getNode(Opc, dl, VT, R, Amt2);
18550     SDValue R3 = DAG.getNode(Opc, dl, VT, R, Amt3);
18551     SDValue R02 = DAG.getVectorShuffle(VT, dl, R0, R2, {0, -1, 6, -1});
18552     SDValue R13 = DAG.getVectorShuffle(VT, dl, R1, R3, {-1, 1, -1, 7});
18553     return DAG.getVectorShuffle(VT, dl, R02, R13, {0, 5, 2, 7});
18554   }
18555
18556   if (VT == MVT::v16i8 ||
18557       (VT == MVT::v32i8 && Subtarget->hasInt256() && !Subtarget->hasXOP())) {
18558     MVT ExtVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements() / 2);
18559     unsigned ShiftOpcode = Op->getOpcode();
18560
18561     auto SignBitSelect = [&](MVT SelVT, SDValue Sel, SDValue V0, SDValue V1) {
18562       // On SSE41 targets we make use of the fact that VSELECT lowers
18563       // to PBLENDVB which selects bytes based just on the sign bit.
18564       if (Subtarget->hasSSE41()) {
18565         V0 = DAG.getBitcast(VT, V0);
18566         V1 = DAG.getBitcast(VT, V1);
18567         Sel = DAG.getBitcast(VT, Sel);
18568         return DAG.getBitcast(SelVT,
18569                               DAG.getNode(ISD::VSELECT, dl, VT, Sel, V0, V1));
18570       }
18571       // On pre-SSE41 targets we test for the sign bit by comparing to
18572       // zero - a negative value will set all bits of the lanes to true
18573       // and VSELECT uses that in its OR(AND(V0,C),AND(V1,~C)) lowering.
18574       SDValue Z = getZeroVector(SelVT, Subtarget, DAG, dl);
18575       SDValue C = DAG.getNode(X86ISD::PCMPGT, dl, SelVT, Z, Sel);
18576       return DAG.getNode(ISD::VSELECT, dl, SelVT, C, V0, V1);
18577     };
18578
18579     // Turn 'a' into a mask suitable for VSELECT: a = a << 5;
18580     // We can safely do this using i16 shifts as we're only interested in
18581     // the 3 lower bits of each byte.
18582     Amt = DAG.getBitcast(ExtVT, Amt);
18583     Amt = DAG.getNode(ISD::SHL, dl, ExtVT, Amt, DAG.getConstant(5, dl, ExtVT));
18584     Amt = DAG.getBitcast(VT, Amt);
18585
18586     if (Op->getOpcode() == ISD::SHL || Op->getOpcode() == ISD::SRL) {
18587       // r = VSELECT(r, shift(r, 4), a);
18588       SDValue M =
18589           DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
18590       R = SignBitSelect(VT, Amt, M, R);
18591
18592       // a += a
18593       Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18594
18595       // r = VSELECT(r, shift(r, 2), a);
18596       M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
18597       R = SignBitSelect(VT, Amt, M, R);
18598
18599       // a += a
18600       Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18601
18602       // return VSELECT(r, shift(r, 1), a);
18603       M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
18604       R = SignBitSelect(VT, Amt, M, R);
18605       return R;
18606     }
18607
18608     if (Op->getOpcode() == ISD::SRA) {
18609       // For SRA we need to unpack each byte to the higher byte of a i16 vector
18610       // so we can correctly sign extend. We don't care what happens to the
18611       // lower byte.
18612       SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), Amt);
18613       SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), Amt);
18614       SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), R);
18615       SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), R);
18616       ALo = DAG.getBitcast(ExtVT, ALo);
18617       AHi = DAG.getBitcast(ExtVT, AHi);
18618       RLo = DAG.getBitcast(ExtVT, RLo);
18619       RHi = DAG.getBitcast(ExtVT, RHi);
18620
18621       // r = VSELECT(r, shift(r, 4), a);
18622       SDValue MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
18623                                 DAG.getConstant(4, dl, ExtVT));
18624       SDValue MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
18625                                 DAG.getConstant(4, dl, ExtVT));
18626       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
18627       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
18628
18629       // a += a
18630       ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
18631       AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
18632
18633       // r = VSELECT(r, shift(r, 2), a);
18634       MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
18635                         DAG.getConstant(2, dl, ExtVT));
18636       MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
18637                         DAG.getConstant(2, dl, ExtVT));
18638       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
18639       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
18640
18641       // a += a
18642       ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
18643       AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
18644
18645       // r = VSELECT(r, shift(r, 1), a);
18646       MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
18647                         DAG.getConstant(1, dl, ExtVT));
18648       MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
18649                         DAG.getConstant(1, dl, ExtVT));
18650       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
18651       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
18652
18653       // Logical shift the result back to the lower byte, leaving a zero upper
18654       // byte
18655       // meaning that we can safely pack with PACKUSWB.
18656       RLo =
18657           DAG.getNode(ISD::SRL, dl, ExtVT, RLo, DAG.getConstant(8, dl, ExtVT));
18658       RHi =
18659           DAG.getNode(ISD::SRL, dl, ExtVT, RHi, DAG.getConstant(8, dl, ExtVT));
18660       return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
18661     }
18662   }
18663
18664   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
18665   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
18666   // solution better.
18667   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
18668     MVT ExtVT = MVT::v8i32;
18669     unsigned ExtOpc =
18670         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
18671     R = DAG.getNode(ExtOpc, dl, ExtVT, R);
18672     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, ExtVT, Amt);
18673     return DAG.getNode(ISD::TRUNCATE, dl, VT,
18674                        DAG.getNode(Op.getOpcode(), dl, ExtVT, R, Amt));
18675   }
18676
18677   if (Subtarget->hasInt256() && !Subtarget->hasXOP() && VT == MVT::v16i16) {
18678     MVT ExtVT = MVT::v8i32;
18679     SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
18680     SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, Amt, Z);
18681     SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, Amt, Z);
18682     SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, R, R);
18683     SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, R, R);
18684     ALo = DAG.getBitcast(ExtVT, ALo);
18685     AHi = DAG.getBitcast(ExtVT, AHi);
18686     RLo = DAG.getBitcast(ExtVT, RLo);
18687     RHi = DAG.getBitcast(ExtVT, RHi);
18688     SDValue Lo = DAG.getNode(Op.getOpcode(), dl, ExtVT, RLo, ALo);
18689     SDValue Hi = DAG.getNode(Op.getOpcode(), dl, ExtVT, RHi, AHi);
18690     Lo = DAG.getNode(ISD::SRL, dl, ExtVT, Lo, DAG.getConstant(16, dl, ExtVT));
18691     Hi = DAG.getNode(ISD::SRL, dl, ExtVT, Hi, DAG.getConstant(16, dl, ExtVT));
18692     return DAG.getNode(X86ISD::PACKUS, dl, VT, Lo, Hi);
18693   }
18694
18695   if (VT == MVT::v8i16) {
18696     unsigned ShiftOpcode = Op->getOpcode();
18697
18698     auto SignBitSelect = [&](SDValue Sel, SDValue V0, SDValue V1) {
18699       // On SSE41 targets we make use of the fact that VSELECT lowers
18700       // to PBLENDVB which selects bytes based just on the sign bit.
18701       if (Subtarget->hasSSE41()) {
18702         MVT ExtVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() * 2);
18703         V0 = DAG.getBitcast(ExtVT, V0);
18704         V1 = DAG.getBitcast(ExtVT, V1);
18705         Sel = DAG.getBitcast(ExtVT, Sel);
18706         return DAG.getBitcast(
18707             VT, DAG.getNode(ISD::VSELECT, dl, ExtVT, Sel, V0, V1));
18708       }
18709       // On pre-SSE41 targets we splat the sign bit - a negative value will
18710       // set all bits of the lanes to true and VSELECT uses that in
18711       // its OR(AND(V0,C),AND(V1,~C)) lowering.
18712       SDValue C =
18713           DAG.getNode(ISD::SRA, dl, VT, Sel, DAG.getConstant(15, dl, VT));
18714       return DAG.getNode(ISD::VSELECT, dl, VT, C, V0, V1);
18715     };
18716
18717     // Turn 'a' into a mask suitable for VSELECT: a = a << 12;
18718     if (Subtarget->hasSSE41()) {
18719       // On SSE41 targets we need to replicate the shift mask in both
18720       // bytes for PBLENDVB.
18721       Amt = DAG.getNode(
18722           ISD::OR, dl, VT,
18723           DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(4, dl, VT)),
18724           DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT)));
18725     } else {
18726       Amt = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT));
18727     }
18728
18729     // r = VSELECT(r, shift(r, 8), a);
18730     SDValue M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(8, dl, VT));
18731     R = SignBitSelect(Amt, M, R);
18732
18733     // a += a
18734     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18735
18736     // r = VSELECT(r, shift(r, 4), a);
18737     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
18738     R = SignBitSelect(Amt, M, R);
18739
18740     // a += a
18741     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18742
18743     // r = VSELECT(r, shift(r, 2), a);
18744     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
18745     R = SignBitSelect(Amt, M, R);
18746
18747     // a += a
18748     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18749
18750     // return VSELECT(r, shift(r, 1), a);
18751     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
18752     R = SignBitSelect(Amt, M, R);
18753     return R;
18754   }
18755
18756   // Decompose 256-bit shifts into smaller 128-bit shifts.
18757   if (VT.is256BitVector()) {
18758     unsigned NumElems = VT.getVectorNumElements();
18759     MVT EltVT = VT.getVectorElementType();
18760     MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
18761
18762     // Extract the two vectors
18763     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
18764     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
18765
18766     // Recreate the shift amount vectors
18767     SDValue Amt1, Amt2;
18768     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
18769       // Constant shift amount
18770       SmallVector<SDValue, 8> Ops(Amt->op_begin(), Amt->op_begin() + NumElems);
18771       ArrayRef<SDValue> Amt1Csts = makeArrayRef(Ops).slice(0, NumElems / 2);
18772       ArrayRef<SDValue> Amt2Csts = makeArrayRef(Ops).slice(NumElems / 2);
18773
18774       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
18775       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
18776     } else {
18777       // Variable shift amount
18778       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
18779       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
18780     }
18781
18782     // Issue new vector shifts for the smaller types
18783     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
18784     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
18785
18786     // Concatenate the result back
18787     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
18788   }
18789
18790   return SDValue();
18791 }
18792
18793 static SDValue LowerRotate(SDValue Op, const X86Subtarget *Subtarget,
18794                            SelectionDAG &DAG) {
18795   MVT VT = Op.getSimpleValueType();
18796   SDLoc DL(Op);
18797   SDValue R = Op.getOperand(0);
18798   SDValue Amt = Op.getOperand(1);
18799
18800   assert(VT.isVector() && "Custom lowering only for vector rotates!");
18801   assert(Subtarget->hasXOP() && "XOP support required for vector rotates!");
18802   assert((Op.getOpcode() == ISD::ROTL) && "Only ROTL supported");
18803
18804   // XOP has 128-bit vector variable + immediate rotates.
18805   // +ve/-ve Amt = rotate left/right.
18806
18807   // Split 256-bit integers.
18808   if (VT.is256BitVector())
18809     return Lower256IntArith(Op, DAG);
18810
18811   assert(VT.is128BitVector() && "Only rotate 128-bit vectors!");
18812
18813   // Attempt to rotate by immediate.
18814   if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
18815     if (auto *RotateConst = BVAmt->getConstantSplatNode()) {
18816       uint64_t RotateAmt = RotateConst->getAPIntValue().getZExtValue();
18817       assert(RotateAmt < VT.getScalarSizeInBits() && "Rotation out of range");
18818       return DAG.getNode(X86ISD::VPROTI, DL, VT, R,
18819                          DAG.getConstant(RotateAmt, DL, MVT::i8));
18820     }
18821   }
18822
18823   // Use general rotate by variable (per-element).
18824   return DAG.getNode(X86ISD::VPROT, DL, VT, R, Amt);
18825 }
18826
18827 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
18828   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
18829   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
18830   // looks for this combo and may remove the "setcc" instruction if the "setcc"
18831   // has only one use.
18832   SDNode *N = Op.getNode();
18833   SDValue LHS = N->getOperand(0);
18834   SDValue RHS = N->getOperand(1);
18835   unsigned BaseOp = 0;
18836   unsigned Cond = 0;
18837   SDLoc DL(Op);
18838   switch (Op.getOpcode()) {
18839   default: llvm_unreachable("Unknown ovf instruction!");
18840   case ISD::SADDO:
18841     // A subtract of one will be selected as a INC. Note that INC doesn't
18842     // set CF, so we can't do this for UADDO.
18843     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
18844       if (C->isOne()) {
18845         BaseOp = X86ISD::INC;
18846         Cond = X86::COND_O;
18847         break;
18848       }
18849     BaseOp = X86ISD::ADD;
18850     Cond = X86::COND_O;
18851     break;
18852   case ISD::UADDO:
18853     BaseOp = X86ISD::ADD;
18854     Cond = X86::COND_B;
18855     break;
18856   case ISD::SSUBO:
18857     // A subtract of one will be selected as a DEC. Note that DEC doesn't
18858     // set CF, so we can't do this for USUBO.
18859     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
18860       if (C->isOne()) {
18861         BaseOp = X86ISD::DEC;
18862         Cond = X86::COND_O;
18863         break;
18864       }
18865     BaseOp = X86ISD::SUB;
18866     Cond = X86::COND_O;
18867     break;
18868   case ISD::USUBO:
18869     BaseOp = X86ISD::SUB;
18870     Cond = X86::COND_B;
18871     break;
18872   case ISD::SMULO:
18873     BaseOp = N->getValueType(0) == MVT::i8 ? X86ISD::SMUL8 : X86ISD::SMUL;
18874     Cond = X86::COND_O;
18875     break;
18876   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
18877     if (N->getValueType(0) == MVT::i8) {
18878       BaseOp = X86ISD::UMUL8;
18879       Cond = X86::COND_O;
18880       break;
18881     }
18882     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
18883                                  MVT::i32);
18884     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
18885
18886     SDValue SetCC =
18887       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18888                   DAG.getConstant(X86::COND_O, DL, MVT::i32),
18889                   SDValue(Sum.getNode(), 2));
18890
18891     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
18892   }
18893   }
18894
18895   // Also sets EFLAGS.
18896   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
18897   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
18898
18899   SDValue SetCC =
18900     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
18901                 DAG.getConstant(Cond, DL, MVT::i32),
18902                 SDValue(Sum.getNode(), 1));
18903
18904   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
18905 }
18906
18907 /// Returns true if the operand type is exactly twice the native width, and
18908 /// the corresponding cmpxchg8b or cmpxchg16b instruction is available.
18909 /// Used to know whether to use cmpxchg8/16b when expanding atomic operations
18910 /// (otherwise we leave them alone to become __sync_fetch_and_... calls).
18911 bool X86TargetLowering::needsCmpXchgNb(Type *MemType) const {
18912   unsigned OpWidth = MemType->getPrimitiveSizeInBits();
18913
18914   if (OpWidth == 64)
18915     return !Subtarget->is64Bit(); // FIXME this should be Subtarget.hasCmpxchg8b
18916   else if (OpWidth == 128)
18917     return Subtarget->hasCmpxchg16b();
18918   else
18919     return false;
18920 }
18921
18922 bool X86TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
18923   return needsCmpXchgNb(SI->getValueOperand()->getType());
18924 }
18925
18926 // Note: this turns large loads into lock cmpxchg8b/16b.
18927 // FIXME: On 32 bits x86, fild/movq might be faster than lock cmpxchg8b.
18928 TargetLowering::AtomicExpansionKind
18929 X86TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
18930   auto PTy = cast<PointerType>(LI->getPointerOperand()->getType());
18931   return needsCmpXchgNb(PTy->getElementType()) ? AtomicExpansionKind::CmpXChg
18932                                                : AtomicExpansionKind::None;
18933 }
18934
18935 TargetLowering::AtomicExpansionKind
18936 X86TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
18937   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
18938   Type *MemType = AI->getType();
18939
18940   // If the operand is too big, we must see if cmpxchg8/16b is available
18941   // and default to library calls otherwise.
18942   if (MemType->getPrimitiveSizeInBits() > NativeWidth) {
18943     return needsCmpXchgNb(MemType) ? AtomicExpansionKind::CmpXChg
18944                                    : AtomicExpansionKind::None;
18945   }
18946
18947   AtomicRMWInst::BinOp Op = AI->getOperation();
18948   switch (Op) {
18949   default:
18950     llvm_unreachable("Unknown atomic operation");
18951   case AtomicRMWInst::Xchg:
18952   case AtomicRMWInst::Add:
18953   case AtomicRMWInst::Sub:
18954     // It's better to use xadd, xsub or xchg for these in all cases.
18955     return AtomicExpansionKind::None;
18956   case AtomicRMWInst::Or:
18957   case AtomicRMWInst::And:
18958   case AtomicRMWInst::Xor:
18959     // If the atomicrmw's result isn't actually used, we can just add a "lock"
18960     // prefix to a normal instruction for these operations.
18961     return !AI->use_empty() ? AtomicExpansionKind::CmpXChg
18962                             : AtomicExpansionKind::None;
18963   case AtomicRMWInst::Nand:
18964   case AtomicRMWInst::Max:
18965   case AtomicRMWInst::Min:
18966   case AtomicRMWInst::UMax:
18967   case AtomicRMWInst::UMin:
18968     // These always require a non-trivial set of data operations on x86. We must
18969     // use a cmpxchg loop.
18970     return AtomicExpansionKind::CmpXChg;
18971   }
18972 }
18973
18974 static bool hasMFENCE(const X86Subtarget& Subtarget) {
18975   // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
18976   // no-sse2). There isn't any reason to disable it if the target processor
18977   // supports it.
18978   return Subtarget.hasSSE2() || Subtarget.is64Bit();
18979 }
18980
18981 LoadInst *
18982 X86TargetLowering::lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *AI) const {
18983   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
18984   Type *MemType = AI->getType();
18985   // Accesses larger than the native width are turned into cmpxchg/libcalls, so
18986   // there is no benefit in turning such RMWs into loads, and it is actually
18987   // harmful as it introduces a mfence.
18988   if (MemType->getPrimitiveSizeInBits() > NativeWidth)
18989     return nullptr;
18990
18991   auto Builder = IRBuilder<>(AI);
18992   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
18993   auto SynchScope = AI->getSynchScope();
18994   // We must restrict the ordering to avoid generating loads with Release or
18995   // ReleaseAcquire orderings.
18996   auto Order = AtomicCmpXchgInst::getStrongestFailureOrdering(AI->getOrdering());
18997   auto Ptr = AI->getPointerOperand();
18998
18999   // Before the load we need a fence. Here is an example lifted from
19000   // http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf showing why a fence
19001   // is required:
19002   // Thread 0:
19003   //   x.store(1, relaxed);
19004   //   r1 = y.fetch_add(0, release);
19005   // Thread 1:
19006   //   y.fetch_add(42, acquire);
19007   //   r2 = x.load(relaxed);
19008   // r1 = r2 = 0 is impossible, but becomes possible if the idempotent rmw is
19009   // lowered to just a load without a fence. A mfence flushes the store buffer,
19010   // making the optimization clearly correct.
19011   // FIXME: it is required if isAtLeastRelease(Order) but it is not clear
19012   // otherwise, we might be able to be more aggressive on relaxed idempotent
19013   // rmw. In practice, they do not look useful, so we don't try to be
19014   // especially clever.
19015   if (SynchScope == SingleThread)
19016     // FIXME: we could just insert an X86ISD::MEMBARRIER here, except we are at
19017     // the IR level, so we must wrap it in an intrinsic.
19018     return nullptr;
19019
19020   if (!hasMFENCE(*Subtarget))
19021     // FIXME: it might make sense to use a locked operation here but on a
19022     // different cache-line to prevent cache-line bouncing. In practice it
19023     // is probably a small win, and x86 processors without mfence are rare
19024     // enough that we do not bother.
19025     return nullptr;
19026
19027   Function *MFence =
19028       llvm::Intrinsic::getDeclaration(M, Intrinsic::x86_sse2_mfence);
19029   Builder.CreateCall(MFence, {});
19030
19031   // Finally we can emit the atomic load.
19032   LoadInst *Loaded = Builder.CreateAlignedLoad(Ptr,
19033           AI->getType()->getPrimitiveSizeInBits());
19034   Loaded->setAtomic(Order, SynchScope);
19035   AI->replaceAllUsesWith(Loaded);
19036   AI->eraseFromParent();
19037   return Loaded;
19038 }
19039
19040 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
19041                                  SelectionDAG &DAG) {
19042   SDLoc dl(Op);
19043   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
19044     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
19045   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
19046     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
19047
19048   // The only fence that needs an instruction is a sequentially-consistent
19049   // cross-thread fence.
19050   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
19051     if (hasMFENCE(*Subtarget))
19052       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
19053
19054     SDValue Chain = Op.getOperand(0);
19055     SDValue Zero = DAG.getConstant(0, dl, MVT::i32);
19056     SDValue Ops[] = {
19057       DAG.getRegister(X86::ESP, MVT::i32),     // Base
19058       DAG.getTargetConstant(1, dl, MVT::i8),   // Scale
19059       DAG.getRegister(0, MVT::i32),            // Index
19060       DAG.getTargetConstant(0, dl, MVT::i32),  // Disp
19061       DAG.getRegister(0, MVT::i32),            // Segment.
19062       Zero,
19063       Chain
19064     };
19065     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
19066     return SDValue(Res, 0);
19067   }
19068
19069   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
19070   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
19071 }
19072
19073 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
19074                              SelectionDAG &DAG) {
19075   MVT T = Op.getSimpleValueType();
19076   SDLoc DL(Op);
19077   unsigned Reg = 0;
19078   unsigned size = 0;
19079   switch(T.SimpleTy) {
19080   default: llvm_unreachable("Invalid value type!");
19081   case MVT::i8:  Reg = X86::AL;  size = 1; break;
19082   case MVT::i16: Reg = X86::AX;  size = 2; break;
19083   case MVT::i32: Reg = X86::EAX; size = 4; break;
19084   case MVT::i64:
19085     assert(Subtarget->is64Bit() && "Node not type legal!");
19086     Reg = X86::RAX; size = 8;
19087     break;
19088   }
19089   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
19090                                   Op.getOperand(2), SDValue());
19091   SDValue Ops[] = { cpIn.getValue(0),
19092                     Op.getOperand(1),
19093                     Op.getOperand(3),
19094                     DAG.getTargetConstant(size, DL, MVT::i8),
19095                     cpIn.getValue(1) };
19096   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
19097   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
19098   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
19099                                            Ops, T, MMO);
19100
19101   SDValue cpOut =
19102     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
19103   SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
19104                                       MVT::i32, cpOut.getValue(2));
19105   SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
19106                                 DAG.getConstant(X86::COND_E, DL, MVT::i8),
19107                                 EFLAGS);
19108
19109   DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
19110   DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
19111   DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
19112   return SDValue();
19113 }
19114
19115 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
19116                             SelectionDAG &DAG) {
19117   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
19118   MVT DstVT = Op.getSimpleValueType();
19119
19120   if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
19121     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
19122     if (DstVT != MVT::f64)
19123       // This conversion needs to be expanded.
19124       return SDValue();
19125
19126     SDValue InVec = Op->getOperand(0);
19127     SDLoc dl(Op);
19128     unsigned NumElts = SrcVT.getVectorNumElements();
19129     MVT SVT = SrcVT.getVectorElementType();
19130
19131     // Widen the vector in input in the case of MVT::v2i32.
19132     // Example: from MVT::v2i32 to MVT::v4i32.
19133     SmallVector<SDValue, 16> Elts;
19134     for (unsigned i = 0, e = NumElts; i != e; ++i)
19135       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
19136                                  DAG.getIntPtrConstant(i, dl)));
19137
19138     // Explicitly mark the extra elements as Undef.
19139     Elts.append(NumElts, DAG.getUNDEF(SVT));
19140
19141     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
19142     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
19143     SDValue ToV2F64 = DAG.getBitcast(MVT::v2f64, BV);
19144     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
19145                        DAG.getIntPtrConstant(0, dl));
19146   }
19147
19148   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
19149          Subtarget->hasMMX() && "Unexpected custom BITCAST");
19150   assert((DstVT == MVT::i64 ||
19151           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
19152          "Unexpected custom BITCAST");
19153   // i64 <=> MMX conversions are Legal.
19154   if (SrcVT==MVT::i64 && DstVT.isVector())
19155     return Op;
19156   if (DstVT==MVT::i64 && SrcVT.isVector())
19157     return Op;
19158   // MMX <=> MMX conversions are Legal.
19159   if (SrcVT.isVector() && DstVT.isVector())
19160     return Op;
19161   // All other conversions need to be expanded.
19162   return SDValue();
19163 }
19164
19165 /// Compute the horizontal sum of bytes in V for the elements of VT.
19166 ///
19167 /// Requires V to be a byte vector and VT to be an integer vector type with
19168 /// wider elements than V's type. The width of the elements of VT determines
19169 /// how many bytes of V are summed horizontally to produce each element of the
19170 /// result.
19171 static SDValue LowerHorizontalByteSum(SDValue V, MVT VT,
19172                                       const X86Subtarget *Subtarget,
19173                                       SelectionDAG &DAG) {
19174   SDLoc DL(V);
19175   MVT ByteVecVT = V.getSimpleValueType();
19176   MVT EltVT = VT.getVectorElementType();
19177   int NumElts = VT.getVectorNumElements();
19178   assert(ByteVecVT.getVectorElementType() == MVT::i8 &&
19179          "Expected value to have byte element type.");
19180   assert(EltVT != MVT::i8 &&
19181          "Horizontal byte sum only makes sense for wider elements!");
19182   unsigned VecSize = VT.getSizeInBits();
19183   assert(ByteVecVT.getSizeInBits() == VecSize && "Cannot change vector size!");
19184
19185   // PSADBW instruction horizontally add all bytes and leave the result in i64
19186   // chunks, thus directly computes the pop count for v2i64 and v4i64.
19187   if (EltVT == MVT::i64) {
19188     SDValue Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
19189     V = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT, V, Zeros);
19190     return DAG.getBitcast(VT, V);
19191   }
19192
19193   if (EltVT == MVT::i32) {
19194     // We unpack the low half and high half into i32s interleaved with zeros so
19195     // that we can use PSADBW to horizontally sum them. The most useful part of
19196     // this is that it lines up the results of two PSADBW instructions to be
19197     // two v2i64 vectors which concatenated are the 4 population counts. We can
19198     // then use PACKUSWB to shrink and concatenate them into a v4i32 again.
19199     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, DL);
19200     SDValue Low = DAG.getNode(X86ISD::UNPCKL, DL, VT, V, Zeros);
19201     SDValue High = DAG.getNode(X86ISD::UNPCKH, DL, VT, V, Zeros);
19202
19203     // Do the horizontal sums into two v2i64s.
19204     Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
19205     Low = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT,
19206                       DAG.getBitcast(ByteVecVT, Low), Zeros);
19207     High = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT,
19208                        DAG.getBitcast(ByteVecVT, High), Zeros);
19209
19210     // Merge them together.
19211     MVT ShortVecVT = MVT::getVectorVT(MVT::i16, VecSize / 16);
19212     V = DAG.getNode(X86ISD::PACKUS, DL, ByteVecVT,
19213                     DAG.getBitcast(ShortVecVT, Low),
19214                     DAG.getBitcast(ShortVecVT, High));
19215
19216     return DAG.getBitcast(VT, V);
19217   }
19218
19219   // The only element type left is i16.
19220   assert(EltVT == MVT::i16 && "Unknown how to handle type");
19221
19222   // To obtain pop count for each i16 element starting from the pop count for
19223   // i8 elements, shift the i16s left by 8, sum as i8s, and then shift as i16s
19224   // right by 8. It is important to shift as i16s as i8 vector shift isn't
19225   // directly supported.
19226   SmallVector<SDValue, 16> Shifters(NumElts, DAG.getConstant(8, DL, EltVT));
19227   SDValue Shifter = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters);
19228   SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, DAG.getBitcast(VT, V), Shifter);
19229   V = DAG.getNode(ISD::ADD, DL, ByteVecVT, DAG.getBitcast(ByteVecVT, Shl),
19230                   DAG.getBitcast(ByteVecVT, V));
19231   return DAG.getNode(ISD::SRL, DL, VT, DAG.getBitcast(VT, V), Shifter);
19232 }
19233
19234 static SDValue LowerVectorCTPOPInRegLUT(SDValue Op, SDLoc DL,
19235                                         const X86Subtarget *Subtarget,
19236                                         SelectionDAG &DAG) {
19237   MVT VT = Op.getSimpleValueType();
19238   MVT EltVT = VT.getVectorElementType();
19239   unsigned VecSize = VT.getSizeInBits();
19240
19241   // Implement a lookup table in register by using an algorithm based on:
19242   // http://wm.ite.pl/articles/sse-popcount.html
19243   //
19244   // The general idea is that every lower byte nibble in the input vector is an
19245   // index into a in-register pre-computed pop count table. We then split up the
19246   // input vector in two new ones: (1) a vector with only the shifted-right
19247   // higher nibbles for each byte and (2) a vector with the lower nibbles (and
19248   // masked out higher ones) for each byte. PSHUB is used separately with both
19249   // to index the in-register table. Next, both are added and the result is a
19250   // i8 vector where each element contains the pop count for input byte.
19251   //
19252   // To obtain the pop count for elements != i8, we follow up with the same
19253   // approach and use additional tricks as described below.
19254   //
19255   const int LUT[16] = {/* 0 */ 0, /* 1 */ 1, /* 2 */ 1, /* 3 */ 2,
19256                        /* 4 */ 1, /* 5 */ 2, /* 6 */ 2, /* 7 */ 3,
19257                        /* 8 */ 1, /* 9 */ 2, /* a */ 2, /* b */ 3,
19258                        /* c */ 2, /* d */ 3, /* e */ 3, /* f */ 4};
19259
19260   int NumByteElts = VecSize / 8;
19261   MVT ByteVecVT = MVT::getVectorVT(MVT::i8, NumByteElts);
19262   SDValue In = DAG.getBitcast(ByteVecVT, Op);
19263   SmallVector<SDValue, 16> LUTVec;
19264   for (int i = 0; i < NumByteElts; ++i)
19265     LUTVec.push_back(DAG.getConstant(LUT[i % 16], DL, MVT::i8));
19266   SDValue InRegLUT = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, LUTVec);
19267   SmallVector<SDValue, 16> Mask0F(NumByteElts,
19268                                   DAG.getConstant(0x0F, DL, MVT::i8));
19269   SDValue M0F = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Mask0F);
19270
19271   // High nibbles
19272   SmallVector<SDValue, 16> Four(NumByteElts, DAG.getConstant(4, DL, MVT::i8));
19273   SDValue FourV = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Four);
19274   SDValue HighNibbles = DAG.getNode(ISD::SRL, DL, ByteVecVT, In, FourV);
19275
19276   // Low nibbles
19277   SDValue LowNibbles = DAG.getNode(ISD::AND, DL, ByteVecVT, In, M0F);
19278
19279   // The input vector is used as the shuffle mask that index elements into the
19280   // LUT. After counting low and high nibbles, add the vector to obtain the
19281   // final pop count per i8 element.
19282   SDValue HighPopCnt =
19283       DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, HighNibbles);
19284   SDValue LowPopCnt =
19285       DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, LowNibbles);
19286   SDValue PopCnt = DAG.getNode(ISD::ADD, DL, ByteVecVT, HighPopCnt, LowPopCnt);
19287
19288   if (EltVT == MVT::i8)
19289     return PopCnt;
19290
19291   return LowerHorizontalByteSum(PopCnt, VT, Subtarget, DAG);
19292 }
19293
19294 static SDValue LowerVectorCTPOPBitmath(SDValue Op, SDLoc DL,
19295                                        const X86Subtarget *Subtarget,
19296                                        SelectionDAG &DAG) {
19297   MVT VT = Op.getSimpleValueType();
19298   assert(VT.is128BitVector() &&
19299          "Only 128-bit vector bitmath lowering supported.");
19300
19301   int VecSize = VT.getSizeInBits();
19302   MVT EltVT = VT.getVectorElementType();
19303   int Len = EltVT.getSizeInBits();
19304
19305   // This is the vectorized version of the "best" algorithm from
19306   // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
19307   // with a minor tweak to use a series of adds + shifts instead of vector
19308   // multiplications. Implemented for all integer vector types. We only use
19309   // this when we don't have SSSE3 which allows a LUT-based lowering that is
19310   // much faster, even faster than using native popcnt instructions.
19311
19312   auto GetShift = [&](unsigned OpCode, SDValue V, int Shifter) {
19313     MVT VT = V.getSimpleValueType();
19314     SmallVector<SDValue, 32> Shifters(
19315         VT.getVectorNumElements(),
19316         DAG.getConstant(Shifter, DL, VT.getVectorElementType()));
19317     return DAG.getNode(OpCode, DL, VT, V,
19318                        DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters));
19319   };
19320   auto GetMask = [&](SDValue V, APInt Mask) {
19321     MVT VT = V.getSimpleValueType();
19322     SmallVector<SDValue, 32> Masks(
19323         VT.getVectorNumElements(),
19324         DAG.getConstant(Mask, DL, VT.getVectorElementType()));
19325     return DAG.getNode(ISD::AND, DL, VT, V,
19326                        DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Masks));
19327   };
19328
19329   // We don't want to incur the implicit masks required to SRL vNi8 vectors on
19330   // x86, so set the SRL type to have elements at least i16 wide. This is
19331   // correct because all of our SRLs are followed immediately by a mask anyways
19332   // that handles any bits that sneak into the high bits of the byte elements.
19333   MVT SrlVT = Len > 8 ? VT : MVT::getVectorVT(MVT::i16, VecSize / 16);
19334
19335   SDValue V = Op;
19336
19337   // v = v - ((v >> 1) & 0x55555555...)
19338   SDValue Srl =
19339       DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 1));
19340   SDValue And = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x55)));
19341   V = DAG.getNode(ISD::SUB, DL, VT, V, And);
19342
19343   // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
19344   SDValue AndLHS = GetMask(V, APInt::getSplat(Len, APInt(8, 0x33)));
19345   Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 2));
19346   SDValue AndRHS = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x33)));
19347   V = DAG.getNode(ISD::ADD, DL, VT, AndLHS, AndRHS);
19348
19349   // v = (v + (v >> 4)) & 0x0F0F0F0F...
19350   Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 4));
19351   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, V, Srl);
19352   V = GetMask(Add, APInt::getSplat(Len, APInt(8, 0x0F)));
19353
19354   // At this point, V contains the byte-wise population count, and we are
19355   // merely doing a horizontal sum if necessary to get the wider element
19356   // counts.
19357   if (EltVT == MVT::i8)
19358     return V;
19359
19360   return LowerHorizontalByteSum(
19361       DAG.getBitcast(MVT::getVectorVT(MVT::i8, VecSize / 8), V), VT, Subtarget,
19362       DAG);
19363 }
19364
19365 static SDValue LowerVectorCTPOP(SDValue Op, const X86Subtarget *Subtarget,
19366                                 SelectionDAG &DAG) {
19367   MVT VT = Op.getSimpleValueType();
19368   // FIXME: Need to add AVX-512 support here!
19369   assert((VT.is256BitVector() || VT.is128BitVector()) &&
19370          "Unknown CTPOP type to handle");
19371   SDLoc DL(Op.getNode());
19372   SDValue Op0 = Op.getOperand(0);
19373
19374   if (!Subtarget->hasSSSE3()) {
19375     // We can't use the fast LUT approach, so fall back on vectorized bitmath.
19376     assert(VT.is128BitVector() && "Only 128-bit vectors supported in SSE!");
19377     return LowerVectorCTPOPBitmath(Op0, DL, Subtarget, DAG);
19378   }
19379
19380   if (VT.is256BitVector() && !Subtarget->hasInt256()) {
19381     unsigned NumElems = VT.getVectorNumElements();
19382
19383     // Extract each 128-bit vector, compute pop count and concat the result.
19384     SDValue LHS = Extract128BitVector(Op0, 0, DAG, DL);
19385     SDValue RHS = Extract128BitVector(Op0, NumElems/2, DAG, DL);
19386
19387     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT,
19388                        LowerVectorCTPOPInRegLUT(LHS, DL, Subtarget, DAG),
19389                        LowerVectorCTPOPInRegLUT(RHS, DL, Subtarget, DAG));
19390   }
19391
19392   return LowerVectorCTPOPInRegLUT(Op0, DL, Subtarget, DAG);
19393 }
19394
19395 static SDValue LowerCTPOP(SDValue Op, const X86Subtarget *Subtarget,
19396                           SelectionDAG &DAG) {
19397   assert(Op.getSimpleValueType().isVector() &&
19398          "We only do custom lowering for vector population count.");
19399   return LowerVectorCTPOP(Op, Subtarget, DAG);
19400 }
19401
19402 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
19403   SDNode *Node = Op.getNode();
19404   SDLoc dl(Node);
19405   EVT T = Node->getValueType(0);
19406   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
19407                               DAG.getConstant(0, dl, T), Node->getOperand(2));
19408   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
19409                        cast<AtomicSDNode>(Node)->getMemoryVT(),
19410                        Node->getOperand(0),
19411                        Node->getOperand(1), negOp,
19412                        cast<AtomicSDNode>(Node)->getMemOperand(),
19413                        cast<AtomicSDNode>(Node)->getOrdering(),
19414                        cast<AtomicSDNode>(Node)->getSynchScope());
19415 }
19416
19417 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
19418   SDNode *Node = Op.getNode();
19419   SDLoc dl(Node);
19420   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
19421
19422   // Convert seq_cst store -> xchg
19423   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
19424   // FIXME: On 32-bit, store -> fist or movq would be more efficient
19425   //        (The only way to get a 16-byte store is cmpxchg16b)
19426   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
19427   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
19428       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
19429     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
19430                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
19431                                  Node->getOperand(0),
19432                                  Node->getOperand(1), Node->getOperand(2),
19433                                  cast<AtomicSDNode>(Node)->getMemOperand(),
19434                                  cast<AtomicSDNode>(Node)->getOrdering(),
19435                                  cast<AtomicSDNode>(Node)->getSynchScope());
19436     return Swap.getValue(1);
19437   }
19438   // Other atomic stores have a simple pattern.
19439   return Op;
19440 }
19441
19442 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
19443   MVT VT = Op.getNode()->getSimpleValueType(0);
19444
19445   // Let legalize expand this if it isn't a legal type yet.
19446   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
19447     return SDValue();
19448
19449   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
19450
19451   unsigned Opc;
19452   bool ExtraOp = false;
19453   switch (Op.getOpcode()) {
19454   default: llvm_unreachable("Invalid code");
19455   case ISD::ADDC: Opc = X86ISD::ADD; break;
19456   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
19457   case ISD::SUBC: Opc = X86ISD::SUB; break;
19458   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
19459   }
19460
19461   if (!ExtraOp)
19462     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
19463                        Op.getOperand(1));
19464   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
19465                      Op.getOperand(1), Op.getOperand(2));
19466 }
19467
19468 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
19469                             SelectionDAG &DAG) {
19470   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
19471
19472   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
19473   // which returns the values as { float, float } (in XMM0) or
19474   // { double, double } (which is returned in XMM0, XMM1).
19475   SDLoc dl(Op);
19476   SDValue Arg = Op.getOperand(0);
19477   EVT ArgVT = Arg.getValueType();
19478   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
19479
19480   TargetLowering::ArgListTy Args;
19481   TargetLowering::ArgListEntry Entry;
19482
19483   Entry.Node = Arg;
19484   Entry.Ty = ArgTy;
19485   Entry.isSExt = false;
19486   Entry.isZExt = false;
19487   Args.push_back(Entry);
19488
19489   bool isF64 = ArgVT == MVT::f64;
19490   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
19491   // the small struct {f32, f32} is returned in (eax, edx). For f64,
19492   // the results are returned via SRet in memory.
19493   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
19494   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19495   SDValue Callee =
19496       DAG.getExternalSymbol(LibcallName, TLI.getPointerTy(DAG.getDataLayout()));
19497
19498   Type *RetTy = isF64
19499     ? (Type*)StructType::get(ArgTy, ArgTy, nullptr)
19500     : (Type*)VectorType::get(ArgTy, 4);
19501
19502   TargetLowering::CallLoweringInfo CLI(DAG);
19503   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
19504     .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
19505
19506   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
19507
19508   if (isF64)
19509     // Returned in xmm0 and xmm1.
19510     return CallResult.first;
19511
19512   // Returned in bits 0:31 and 32:64 xmm0.
19513   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
19514                                CallResult.first, DAG.getIntPtrConstant(0, dl));
19515   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
19516                                CallResult.first, DAG.getIntPtrConstant(1, dl));
19517   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
19518   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
19519 }
19520
19521 static SDValue LowerMSCATTER(SDValue Op, const X86Subtarget *Subtarget,
19522                              SelectionDAG &DAG) {
19523   assert(Subtarget->hasAVX512() &&
19524          "MGATHER/MSCATTER are supported on AVX-512 arch only");
19525
19526   MaskedScatterSDNode *N = cast<MaskedScatterSDNode>(Op.getNode());
19527   MVT VT = N->getValue().getSimpleValueType();
19528   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported scatter op");
19529   SDLoc dl(Op);
19530
19531   // X86 scatter kills mask register, so its type should be added to
19532   // the list of return values
19533   if (N->getNumValues() == 1) {
19534     SDValue Index = N->getIndex();
19535     if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
19536         !Index.getSimpleValueType().is512BitVector())
19537       Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
19538
19539     SDVTList VTs = DAG.getVTList(N->getMask().getValueType(), MVT::Other);
19540     SDValue Ops[] = { N->getOperand(0), N->getOperand(1),  N->getOperand(2),
19541                       N->getOperand(3), Index };
19542
19543     SDValue NewScatter = DAG.getMaskedScatter(VTs, VT, dl, Ops, N->getMemOperand());
19544     DAG.ReplaceAllUsesWith(Op, SDValue(NewScatter.getNode(), 1));
19545     return SDValue(NewScatter.getNode(), 0);
19546   }
19547   return Op;
19548 }
19549
19550 static SDValue LowerMGATHER(SDValue Op, const X86Subtarget *Subtarget,
19551                             SelectionDAG &DAG) {
19552   assert(Subtarget->hasAVX512() &&
19553          "MGATHER/MSCATTER are supported on AVX-512 arch only");
19554
19555   MaskedGatherSDNode *N = cast<MaskedGatherSDNode>(Op.getNode());
19556   MVT VT = Op.getSimpleValueType();
19557   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported gather op");
19558   SDLoc dl(Op);
19559
19560   SDValue Index = N->getIndex();
19561   if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
19562       !Index.getSimpleValueType().is512BitVector()) {
19563     Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
19564     SDValue Ops[] = { N->getOperand(0), N->getOperand(1),  N->getOperand(2),
19565                       N->getOperand(3), Index };
19566     DAG.UpdateNodeOperands(N, Ops);
19567   }
19568   return Op;
19569 }
19570
19571 SDValue X86TargetLowering::LowerGC_TRANSITION_START(SDValue Op,
19572                                                     SelectionDAG &DAG) const {
19573   // TODO: Eventually, the lowering of these nodes should be informed by or
19574   // deferred to the GC strategy for the function in which they appear. For
19575   // now, however, they must be lowered to something. Since they are logically
19576   // no-ops in the case of a null GC strategy (or a GC strategy which does not
19577   // require special handling for these nodes), lower them as literal NOOPs for
19578   // the time being.
19579   SmallVector<SDValue, 2> Ops;
19580
19581   Ops.push_back(Op.getOperand(0));
19582   if (Op->getGluedNode())
19583     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
19584
19585   SDLoc OpDL(Op);
19586   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
19587   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
19588
19589   return NOOP;
19590 }
19591
19592 SDValue X86TargetLowering::LowerGC_TRANSITION_END(SDValue Op,
19593                                                   SelectionDAG &DAG) const {
19594   // TODO: Eventually, the lowering of these nodes should be informed by or
19595   // deferred to the GC strategy for the function in which they appear. For
19596   // now, however, they must be lowered to something. Since they are logically
19597   // no-ops in the case of a null GC strategy (or a GC strategy which does not
19598   // require special handling for these nodes), lower them as literal NOOPs for
19599   // the time being.
19600   SmallVector<SDValue, 2> Ops;
19601
19602   Ops.push_back(Op.getOperand(0));
19603   if (Op->getGluedNode())
19604     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
19605
19606   SDLoc OpDL(Op);
19607   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
19608   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
19609
19610   return NOOP;
19611 }
19612
19613 /// LowerOperation - Provide custom lowering hooks for some operations.
19614 ///
19615 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
19616   switch (Op.getOpcode()) {
19617   default: llvm_unreachable("Should not custom lower this!");
19618   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
19619   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
19620     return LowerCMP_SWAP(Op, Subtarget, DAG);
19621   case ISD::CTPOP:              return LowerCTPOP(Op, Subtarget, DAG);
19622   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
19623   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
19624   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
19625   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, Subtarget, DAG);
19626   case ISD::VECTOR_SHUFFLE:     return lowerVectorShuffle(Op, Subtarget, DAG);
19627   case ISD::VSELECT:            return LowerVSELECT(Op, DAG);
19628   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
19629   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
19630   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
19631   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
19632   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
19633   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
19634   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
19635   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
19636   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
19637   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
19638   case ISD::SHL_PARTS:
19639   case ISD::SRA_PARTS:
19640   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
19641   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
19642   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
19643   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
19644   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
19645   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
19646   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
19647   case ISD::SIGN_EXTEND_VECTOR_INREG:
19648     return LowerSIGN_EXTEND_VECTOR_INREG(Op, Subtarget, DAG);
19649   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
19650   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
19651   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
19652   case ISD::LOAD:               return LowerExtendedLoad(Op, Subtarget, DAG);
19653   case ISD::FABS:
19654   case ISD::FNEG:               return LowerFABSorFNEG(Op, DAG);
19655   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
19656   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
19657   case ISD::SETCC:              return LowerSETCC(Op, DAG);
19658   case ISD::SELECT:             return LowerSELECT(Op, DAG);
19659   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
19660   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
19661   case ISD::VASTART:            return LowerVASTART(Op, DAG);
19662   case ISD::VAARG:              return LowerVAARG(Op, DAG);
19663   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
19664   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, Subtarget, DAG);
19665   case ISD::INTRINSIC_VOID:
19666   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
19667   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
19668   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
19669   case ISD::FRAME_TO_ARGS_OFFSET:
19670                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
19671   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
19672   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
19673   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
19674   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
19675   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
19676   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
19677   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
19678   case ISD::CTLZ:               return LowerCTLZ(Op, Subtarget, DAG);
19679   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, Subtarget, DAG);
19680   case ISD::CTTZ:
19681   case ISD::CTTZ_ZERO_UNDEF:    return LowerCTTZ(Op, DAG);
19682   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
19683   case ISD::UMUL_LOHI:
19684   case ISD::SMUL_LOHI:          return LowerMUL_LOHI(Op, Subtarget, DAG);
19685   case ISD::ROTL:               return LowerRotate(Op, Subtarget, DAG);
19686   case ISD::SRA:
19687   case ISD::SRL:
19688   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
19689   case ISD::SADDO:
19690   case ISD::UADDO:
19691   case ISD::SSUBO:
19692   case ISD::USUBO:
19693   case ISD::SMULO:
19694   case ISD::UMULO:              return LowerXALUO(Op, DAG);
19695   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
19696   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
19697   case ISD::ADDC:
19698   case ISD::ADDE:
19699   case ISD::SUBC:
19700   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
19701   case ISD::ADD:                return LowerADD(Op, DAG);
19702   case ISD::SUB:                return LowerSUB(Op, DAG);
19703   case ISD::SMAX:
19704   case ISD::SMIN:
19705   case ISD::UMAX:
19706   case ISD::UMIN:               return LowerMINMAX(Op, DAG);
19707   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
19708   case ISD::MGATHER:            return LowerMGATHER(Op, Subtarget, DAG);
19709   case ISD::MSCATTER:           return LowerMSCATTER(Op, Subtarget, DAG);
19710   case ISD::GC_TRANSITION_START:
19711                                 return LowerGC_TRANSITION_START(Op, DAG);
19712   case ISD::GC_TRANSITION_END:  return LowerGC_TRANSITION_END(Op, DAG);
19713   }
19714 }
19715
19716 /// ReplaceNodeResults - Replace a node with an illegal result type
19717 /// with a new node built out of custom code.
19718 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
19719                                            SmallVectorImpl<SDValue>&Results,
19720                                            SelectionDAG &DAG) const {
19721   SDLoc dl(N);
19722   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19723   switch (N->getOpcode()) {
19724   default:
19725     llvm_unreachable("Do not know how to custom type legalize this operation!");
19726   // We might have generated v2f32 FMIN/FMAX operations. Widen them to v4f32.
19727   case X86ISD::FMINC:
19728   case X86ISD::FMIN:
19729   case X86ISD::FMAXC:
19730   case X86ISD::FMAX: {
19731     EVT VT = N->getValueType(0);
19732     assert(VT == MVT::v2f32 && "Unexpected type (!= v2f32) on FMIN/FMAX.");
19733     SDValue UNDEF = DAG.getUNDEF(VT);
19734     SDValue LHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
19735                               N->getOperand(0), UNDEF);
19736     SDValue RHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
19737                               N->getOperand(1), UNDEF);
19738     Results.push_back(DAG.getNode(N->getOpcode(), dl, MVT::v4f32, LHS, RHS));
19739     return;
19740   }
19741   case ISD::SIGN_EXTEND_INREG:
19742   case ISD::ADDC:
19743   case ISD::ADDE:
19744   case ISD::SUBC:
19745   case ISD::SUBE:
19746     // We don't want to expand or promote these.
19747     return;
19748   case ISD::SDIV:
19749   case ISD::UDIV:
19750   case ISD::SREM:
19751   case ISD::UREM:
19752   case ISD::SDIVREM:
19753   case ISD::UDIVREM: {
19754     SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
19755     Results.push_back(V);
19756     return;
19757   }
19758   case ISD::FP_TO_SINT:
19759   case ISD::FP_TO_UINT: {
19760     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
19761
19762     std::pair<SDValue,SDValue> Vals =
19763         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
19764     SDValue FIST = Vals.first, StackSlot = Vals.second;
19765     if (FIST.getNode()) {
19766       EVT VT = N->getValueType(0);
19767       // Return a load from the stack slot.
19768       if (StackSlot.getNode())
19769         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
19770                                       MachinePointerInfo(),
19771                                       false, false, false, 0));
19772       else
19773         Results.push_back(FIST);
19774     }
19775     return;
19776   }
19777   case ISD::UINT_TO_FP: {
19778     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
19779     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
19780         N->getValueType(0) != MVT::v2f32)
19781       return;
19782     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
19783                                  N->getOperand(0));
19784     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
19785                                      MVT::f64);
19786     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
19787     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
19788                              DAG.getBitcast(MVT::v2i64, VBias));
19789     Or = DAG.getBitcast(MVT::v2f64, Or);
19790     // TODO: Are there any fast-math-flags to propagate here?
19791     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
19792     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
19793     return;
19794   }
19795   case ISD::FP_ROUND: {
19796     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
19797         return;
19798     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
19799     Results.push_back(V);
19800     return;
19801   }
19802   case ISD::FP_EXTEND: {
19803     // Right now, only MVT::v2f32 has OperationAction for FP_EXTEND.
19804     // No other ValueType for FP_EXTEND should reach this point.
19805     assert(N->getValueType(0) == MVT::v2f32 &&
19806            "Do not know how to legalize this Node");
19807     return;
19808   }
19809   case ISD::INTRINSIC_W_CHAIN: {
19810     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
19811     switch (IntNo) {
19812     default : llvm_unreachable("Do not know how to custom type "
19813                                "legalize this intrinsic operation!");
19814     case Intrinsic::x86_rdtsc:
19815       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
19816                                      Results);
19817     case Intrinsic::x86_rdtscp:
19818       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
19819                                      Results);
19820     case Intrinsic::x86_rdpmc:
19821       return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
19822     }
19823   }
19824   case ISD::READCYCLECOUNTER: {
19825     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
19826                                    Results);
19827   }
19828   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
19829     EVT T = N->getValueType(0);
19830     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
19831     bool Regs64bit = T == MVT::i128;
19832     MVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
19833     SDValue cpInL, cpInH;
19834     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
19835                         DAG.getConstant(0, dl, HalfT));
19836     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
19837                         DAG.getConstant(1, dl, HalfT));
19838     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
19839                              Regs64bit ? X86::RAX : X86::EAX,
19840                              cpInL, SDValue());
19841     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
19842                              Regs64bit ? X86::RDX : X86::EDX,
19843                              cpInH, cpInL.getValue(1));
19844     SDValue swapInL, swapInH;
19845     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
19846                           DAG.getConstant(0, dl, HalfT));
19847     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
19848                           DAG.getConstant(1, dl, HalfT));
19849     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
19850                                Regs64bit ? X86::RBX : X86::EBX,
19851                                swapInL, cpInH.getValue(1));
19852     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
19853                                Regs64bit ? X86::RCX : X86::ECX,
19854                                swapInH, swapInL.getValue(1));
19855     SDValue Ops[] = { swapInH.getValue(0),
19856                       N->getOperand(1),
19857                       swapInH.getValue(1) };
19858     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
19859     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
19860     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
19861                                   X86ISD::LCMPXCHG8_DAG;
19862     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
19863     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
19864                                         Regs64bit ? X86::RAX : X86::EAX,
19865                                         HalfT, Result.getValue(1));
19866     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
19867                                         Regs64bit ? X86::RDX : X86::EDX,
19868                                         HalfT, cpOutL.getValue(2));
19869     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
19870
19871     SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
19872                                         MVT::i32, cpOutH.getValue(2));
19873     SDValue Success =
19874         DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
19875                     DAG.getConstant(X86::COND_E, dl, MVT::i8), EFLAGS);
19876     Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
19877
19878     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
19879     Results.push_back(Success);
19880     Results.push_back(EFLAGS.getValue(1));
19881     return;
19882   }
19883   case ISD::ATOMIC_SWAP:
19884   case ISD::ATOMIC_LOAD_ADD:
19885   case ISD::ATOMIC_LOAD_SUB:
19886   case ISD::ATOMIC_LOAD_AND:
19887   case ISD::ATOMIC_LOAD_OR:
19888   case ISD::ATOMIC_LOAD_XOR:
19889   case ISD::ATOMIC_LOAD_NAND:
19890   case ISD::ATOMIC_LOAD_MIN:
19891   case ISD::ATOMIC_LOAD_MAX:
19892   case ISD::ATOMIC_LOAD_UMIN:
19893   case ISD::ATOMIC_LOAD_UMAX:
19894   case ISD::ATOMIC_LOAD: {
19895     // Delegate to generic TypeLegalization. Situations we can really handle
19896     // should have already been dealt with by AtomicExpandPass.cpp.
19897     break;
19898   }
19899   case ISD::BITCAST: {
19900     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
19901     EVT DstVT = N->getValueType(0);
19902     EVT SrcVT = N->getOperand(0)->getValueType(0);
19903
19904     if (SrcVT != MVT::f64 ||
19905         (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
19906       return;
19907
19908     unsigned NumElts = DstVT.getVectorNumElements();
19909     EVT SVT = DstVT.getVectorElementType();
19910     EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
19911     SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
19912                                    MVT::v2f64, N->getOperand(0));
19913     SDValue ToVecInt = DAG.getBitcast(WiderVT, Expanded);
19914
19915     if (ExperimentalVectorWideningLegalization) {
19916       // If we are legalizing vectors by widening, we already have the desired
19917       // legal vector type, just return it.
19918       Results.push_back(ToVecInt);
19919       return;
19920     }
19921
19922     SmallVector<SDValue, 8> Elts;
19923     for (unsigned i = 0, e = NumElts; i != e; ++i)
19924       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
19925                                    ToVecInt, DAG.getIntPtrConstant(i, dl)));
19926
19927     Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
19928   }
19929   }
19930 }
19931
19932 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
19933   switch ((X86ISD::NodeType)Opcode) {
19934   case X86ISD::FIRST_NUMBER:       break;
19935   case X86ISD::BSF:                return "X86ISD::BSF";
19936   case X86ISD::BSR:                return "X86ISD::BSR";
19937   case X86ISD::SHLD:               return "X86ISD::SHLD";
19938   case X86ISD::SHRD:               return "X86ISD::SHRD";
19939   case X86ISD::FAND:               return "X86ISD::FAND";
19940   case X86ISD::FANDN:              return "X86ISD::FANDN";
19941   case X86ISD::FOR:                return "X86ISD::FOR";
19942   case X86ISD::FXOR:               return "X86ISD::FXOR";
19943   case X86ISD::FILD:               return "X86ISD::FILD";
19944   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
19945   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
19946   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
19947   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
19948   case X86ISD::FLD:                return "X86ISD::FLD";
19949   case X86ISD::FST:                return "X86ISD::FST";
19950   case X86ISD::CALL:               return "X86ISD::CALL";
19951   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
19952   case X86ISD::RDTSCP_DAG:         return "X86ISD::RDTSCP_DAG";
19953   case X86ISD::RDPMC_DAG:          return "X86ISD::RDPMC_DAG";
19954   case X86ISD::BT:                 return "X86ISD::BT";
19955   case X86ISD::CMP:                return "X86ISD::CMP";
19956   case X86ISD::COMI:               return "X86ISD::COMI";
19957   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
19958   case X86ISD::CMPM:               return "X86ISD::CMPM";
19959   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
19960   case X86ISD::CMPM_RND:           return "X86ISD::CMPM_RND";
19961   case X86ISD::SETCC:              return "X86ISD::SETCC";
19962   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
19963   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
19964   case X86ISD::FGETSIGNx86:        return "X86ISD::FGETSIGNx86";
19965   case X86ISD::CMOV:               return "X86ISD::CMOV";
19966   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
19967   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
19968   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
19969   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
19970   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
19971   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
19972   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
19973   case X86ISD::MOVDQ2Q:            return "X86ISD::MOVDQ2Q";
19974   case X86ISD::MMX_MOVD2W:         return "X86ISD::MMX_MOVD2W";
19975   case X86ISD::MMX_MOVW2D:         return "X86ISD::MMX_MOVW2D";
19976   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
19977   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
19978   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
19979   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
19980   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
19981   case X86ISD::MMX_PINSRW:         return "X86ISD::MMX_PINSRW";
19982   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
19983   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
19984   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
19985   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
19986   case X86ISD::SHRUNKBLEND:        return "X86ISD::SHRUNKBLEND";
19987   case X86ISD::ADDUS:              return "X86ISD::ADDUS";
19988   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
19989   case X86ISD::HADD:               return "X86ISD::HADD";
19990   case X86ISD::HSUB:               return "X86ISD::HSUB";
19991   case X86ISD::FHADD:              return "X86ISD::FHADD";
19992   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
19993   case X86ISD::ABS:                return "X86ISD::ABS";
19994   case X86ISD::CONFLICT:           return "X86ISD::CONFLICT";
19995   case X86ISD::FMAX:               return "X86ISD::FMAX";
19996   case X86ISD::FMAX_RND:           return "X86ISD::FMAX_RND";
19997   case X86ISD::FMIN:               return "X86ISD::FMIN";
19998   case X86ISD::FMIN_RND:           return "X86ISD::FMIN_RND";
19999   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
20000   case X86ISD::FMINC:              return "X86ISD::FMINC";
20001   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
20002   case X86ISD::FRCP:               return "X86ISD::FRCP";
20003   case X86ISD::EXTRQI:             return "X86ISD::EXTRQI";
20004   case X86ISD::INSERTQI:           return "X86ISD::INSERTQI";
20005   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
20006   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
20007   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
20008   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
20009   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
20010   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
20011   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
20012   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
20013   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
20014   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
20015   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
20016   case X86ISD::LCMPXCHG16_DAG:     return "X86ISD::LCMPXCHG16_DAG";
20017   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
20018   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
20019   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
20020   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
20021   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
20022   case X86ISD::VTRUNCS:            return "X86ISD::VTRUNCS";
20023   case X86ISD::VTRUNCUS:           return "X86ISD::VTRUNCUS";
20024   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
20025   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
20026   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
20027   case X86ISD::CVTDQ2PD:           return "X86ISD::CVTDQ2PD";
20028   case X86ISD::CVTUDQ2PD:          return "X86ISD::CVTUDQ2PD";
20029   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
20030   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
20031   case X86ISD::VSHL:               return "X86ISD::VSHL";
20032   case X86ISD::VSRL:               return "X86ISD::VSRL";
20033   case X86ISD::VSRA:               return "X86ISD::VSRA";
20034   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
20035   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
20036   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
20037   case X86ISD::CMPP:               return "X86ISD::CMPP";
20038   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
20039   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
20040   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
20041   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
20042   case X86ISD::ADD:                return "X86ISD::ADD";
20043   case X86ISD::SUB:                return "X86ISD::SUB";
20044   case X86ISD::ADC:                return "X86ISD::ADC";
20045   case X86ISD::SBB:                return "X86ISD::SBB";
20046   case X86ISD::SMUL:               return "X86ISD::SMUL";
20047   case X86ISD::UMUL:               return "X86ISD::UMUL";
20048   case X86ISD::SMUL8:              return "X86ISD::SMUL8";
20049   case X86ISD::UMUL8:              return "X86ISD::UMUL8";
20050   case X86ISD::SDIVREM8_SEXT_HREG: return "X86ISD::SDIVREM8_SEXT_HREG";
20051   case X86ISD::UDIVREM8_ZEXT_HREG: return "X86ISD::UDIVREM8_ZEXT_HREG";
20052   case X86ISD::INC:                return "X86ISD::INC";
20053   case X86ISD::DEC:                return "X86ISD::DEC";
20054   case X86ISD::OR:                 return "X86ISD::OR";
20055   case X86ISD::XOR:                return "X86ISD::XOR";
20056   case X86ISD::AND:                return "X86ISD::AND";
20057   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
20058   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
20059   case X86ISD::PTEST:              return "X86ISD::PTEST";
20060   case X86ISD::TESTP:              return "X86ISD::TESTP";
20061   case X86ISD::TESTM:              return "X86ISD::TESTM";
20062   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
20063   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
20064   case X86ISD::KTEST:              return "X86ISD::KTEST";
20065   case X86ISD::PACKSS:             return "X86ISD::PACKSS";
20066   case X86ISD::PACKUS:             return "X86ISD::PACKUS";
20067   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
20068   case X86ISD::VALIGN:             return "X86ISD::VALIGN";
20069   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
20070   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
20071   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
20072   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
20073   case X86ISD::SHUF128:            return "X86ISD::SHUF128";
20074   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
20075   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
20076   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
20077   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
20078   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
20079   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
20080   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
20081   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
20082   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
20083   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
20084   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
20085   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
20086   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
20087   case X86ISD::SUBV_BROADCAST:     return "X86ISD::SUBV_BROADCAST";
20088   case X86ISD::VEXTRACT:           return "X86ISD::VEXTRACT";
20089   case X86ISD::VPERMILPV:          return "X86ISD::VPERMILPV";
20090   case X86ISD::VPERMILPI:          return "X86ISD::VPERMILPI";
20091   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
20092   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
20093   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
20094   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
20095   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
20096   case X86ISD::VPTERNLOG:          return "X86ISD::VPTERNLOG";
20097   case X86ISD::VFIXUPIMM:          return "X86ISD::VFIXUPIMM";
20098   case X86ISD::VRANGE:             return "X86ISD::VRANGE";
20099   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
20100   case X86ISD::PMULDQ:             return "X86ISD::PMULDQ";
20101   case X86ISD::PSADBW:             return "X86ISD::PSADBW";
20102   case X86ISD::DBPSADBW:           return "X86ISD::DBPSADBW";
20103   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
20104   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
20105   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
20106   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
20107   case X86ISD::MFENCE:             return "X86ISD::MFENCE";
20108   case X86ISD::SFENCE:             return "X86ISD::SFENCE";
20109   case X86ISD::LFENCE:             return "X86ISD::LFENCE";
20110   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
20111   case X86ISD::SAHF:               return "X86ISD::SAHF";
20112   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
20113   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
20114   case X86ISD::VPMADDUBSW:         return "X86ISD::VPMADDUBSW";
20115   case X86ISD::VPMADDWD:           return "X86ISD::VPMADDWD";
20116   case X86ISD::VPROT:              return "X86ISD::VPROT";
20117   case X86ISD::VPROTI:             return "X86ISD::VPROTI";
20118   case X86ISD::VPSHA:              return "X86ISD::VPSHA";
20119   case X86ISD::VPSHL:              return "X86ISD::VPSHL";
20120   case X86ISD::VPCOM:              return "X86ISD::VPCOM";
20121   case X86ISD::VPCOMU:             return "X86ISD::VPCOMU";
20122   case X86ISD::FMADD:              return "X86ISD::FMADD";
20123   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
20124   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
20125   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
20126   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
20127   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
20128   case X86ISD::FMADD_RND:          return "X86ISD::FMADD_RND";
20129   case X86ISD::FNMADD_RND:         return "X86ISD::FNMADD_RND";
20130   case X86ISD::FMSUB_RND:          return "X86ISD::FMSUB_RND";
20131   case X86ISD::FNMSUB_RND:         return "X86ISD::FNMSUB_RND";
20132   case X86ISD::FMADDSUB_RND:       return "X86ISD::FMADDSUB_RND";
20133   case X86ISD::FMSUBADD_RND:       return "X86ISD::FMSUBADD_RND";
20134   case X86ISD::VRNDSCALE:          return "X86ISD::VRNDSCALE";
20135   case X86ISD::VREDUCE:            return "X86ISD::VREDUCE";
20136   case X86ISD::VGETMANT:           return "X86ISD::VGETMANT";
20137   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
20138   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
20139   case X86ISD::XTEST:              return "X86ISD::XTEST";
20140   case X86ISD::COMPRESS:           return "X86ISD::COMPRESS";
20141   case X86ISD::EXPAND:             return "X86ISD::EXPAND";
20142   case X86ISD::SELECT:             return "X86ISD::SELECT";
20143   case X86ISD::ADDSUB:             return "X86ISD::ADDSUB";
20144   case X86ISD::RCP28:              return "X86ISD::RCP28";
20145   case X86ISD::EXP2:               return "X86ISD::EXP2";
20146   case X86ISD::RSQRT28:            return "X86ISD::RSQRT28";
20147   case X86ISD::FADD_RND:           return "X86ISD::FADD_RND";
20148   case X86ISD::FSUB_RND:           return "X86ISD::FSUB_RND";
20149   case X86ISD::FMUL_RND:           return "X86ISD::FMUL_RND";
20150   case X86ISD::FDIV_RND:           return "X86ISD::FDIV_RND";
20151   case X86ISD::FSQRT_RND:          return "X86ISD::FSQRT_RND";
20152   case X86ISD::FGETEXP_RND:        return "X86ISD::FGETEXP_RND";
20153   case X86ISD::SCALEF:             return "X86ISD::SCALEF";
20154   case X86ISD::ADDS:               return "X86ISD::ADDS";
20155   case X86ISD::SUBS:               return "X86ISD::SUBS";
20156   case X86ISD::AVG:                return "X86ISD::AVG";
20157   case X86ISD::MULHRS:             return "X86ISD::MULHRS";
20158   case X86ISD::SINT_TO_FP_RND:     return "X86ISD::SINT_TO_FP_RND";
20159   case X86ISD::UINT_TO_FP_RND:     return "X86ISD::UINT_TO_FP_RND";
20160   case X86ISD::FP_TO_SINT_RND:     return "X86ISD::FP_TO_SINT_RND";
20161   case X86ISD::FP_TO_UINT_RND:     return "X86ISD::FP_TO_UINT_RND";
20162   case X86ISD::VFPCLASS:           return "X86ISD::VFPCLASS";
20163   }
20164   return nullptr;
20165 }
20166
20167 // isLegalAddressingMode - Return true if the addressing mode represented
20168 // by AM is legal for this target, for a load/store of the specified type.
20169 bool X86TargetLowering::isLegalAddressingMode(const DataLayout &DL,
20170                                               const AddrMode &AM, Type *Ty,
20171                                               unsigned AS) const {
20172   // X86 supports extremely general addressing modes.
20173   CodeModel::Model M = getTargetMachine().getCodeModel();
20174   Reloc::Model R = getTargetMachine().getRelocationModel();
20175
20176   // X86 allows a sign-extended 32-bit immediate field as a displacement.
20177   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
20178     return false;
20179
20180   if (AM.BaseGV) {
20181     unsigned GVFlags =
20182       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
20183
20184     // If a reference to this global requires an extra load, we can't fold it.
20185     if (isGlobalStubReference(GVFlags))
20186       return false;
20187
20188     // If BaseGV requires a register for the PIC base, we cannot also have a
20189     // BaseReg specified.
20190     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
20191       return false;
20192
20193     // If lower 4G is not available, then we must use rip-relative addressing.
20194     if ((M != CodeModel::Small || R != Reloc::Static) &&
20195         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
20196       return false;
20197   }
20198
20199   switch (AM.Scale) {
20200   case 0:
20201   case 1:
20202   case 2:
20203   case 4:
20204   case 8:
20205     // These scales always work.
20206     break;
20207   case 3:
20208   case 5:
20209   case 9:
20210     // These scales are formed with basereg+scalereg.  Only accept if there is
20211     // no basereg yet.
20212     if (AM.HasBaseReg)
20213       return false;
20214     break;
20215   default:  // Other stuff never works.
20216     return false;
20217   }
20218
20219   return true;
20220 }
20221
20222 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
20223   unsigned Bits = Ty->getScalarSizeInBits();
20224
20225   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
20226   // particularly cheaper than those without.
20227   if (Bits == 8)
20228     return false;
20229
20230   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
20231   // variable shifts just as cheap as scalar ones.
20232   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
20233     return false;
20234
20235   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
20236   // fully general vector.
20237   return true;
20238 }
20239
20240 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
20241   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
20242     return false;
20243   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
20244   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
20245   return NumBits1 > NumBits2;
20246 }
20247
20248 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
20249   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
20250     return false;
20251
20252   if (!isTypeLegal(EVT::getEVT(Ty1)))
20253     return false;
20254
20255   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
20256
20257   // Assuming the caller doesn't have a zeroext or signext return parameter,
20258   // truncation all the way down to i1 is valid.
20259   return true;
20260 }
20261
20262 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
20263   return isInt<32>(Imm);
20264 }
20265
20266 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
20267   // Can also use sub to handle negated immediates.
20268   return isInt<32>(Imm);
20269 }
20270
20271 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
20272   if (!VT1.isInteger() || !VT2.isInteger())
20273     return false;
20274   unsigned NumBits1 = VT1.getSizeInBits();
20275   unsigned NumBits2 = VT2.getSizeInBits();
20276   return NumBits1 > NumBits2;
20277 }
20278
20279 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
20280   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
20281   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
20282 }
20283
20284 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
20285   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
20286   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
20287 }
20288
20289 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
20290   EVT VT1 = Val.getValueType();
20291   if (isZExtFree(VT1, VT2))
20292     return true;
20293
20294   if (Val.getOpcode() != ISD::LOAD)
20295     return false;
20296
20297   if (!VT1.isSimple() || !VT1.isInteger() ||
20298       !VT2.isSimple() || !VT2.isInteger())
20299     return false;
20300
20301   switch (VT1.getSimpleVT().SimpleTy) {
20302   default: break;
20303   case MVT::i8:
20304   case MVT::i16:
20305   case MVT::i32:
20306     // X86 has 8, 16, and 32-bit zero-extending loads.
20307     return true;
20308   }
20309
20310   return false;
20311 }
20312
20313 bool X86TargetLowering::isVectorLoadExtDesirable(SDValue) const { return true; }
20314
20315 bool
20316 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
20317   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4() || Subtarget->hasAVX512()))
20318     return false;
20319
20320   VT = VT.getScalarType();
20321
20322   if (!VT.isSimple())
20323     return false;
20324
20325   switch (VT.getSimpleVT().SimpleTy) {
20326   case MVT::f32:
20327   case MVT::f64:
20328     return true;
20329   default:
20330     break;
20331   }
20332
20333   return false;
20334 }
20335
20336 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
20337   // i16 instructions are longer (0x66 prefix) and potentially slower.
20338   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
20339 }
20340
20341 /// isShuffleMaskLegal - Targets can use this to indicate that they only
20342 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
20343 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
20344 /// are assumed to be legal.
20345 bool
20346 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
20347                                       EVT VT) const {
20348   if (!VT.isSimple())
20349     return false;
20350
20351   // Not for i1 vectors
20352   if (VT.getSimpleVT().getScalarType() == MVT::i1)
20353     return false;
20354
20355   // Very little shuffling can be done for 64-bit vectors right now.
20356   if (VT.getSimpleVT().getSizeInBits() == 64)
20357     return false;
20358
20359   // We only care that the types being shuffled are legal. The lowering can
20360   // handle any possible shuffle mask that results.
20361   return isTypeLegal(VT.getSimpleVT());
20362 }
20363
20364 bool
20365 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
20366                                           EVT VT) const {
20367   // Just delegate to the generic legality, clear masks aren't special.
20368   return isShuffleMaskLegal(Mask, VT);
20369 }
20370
20371 //===----------------------------------------------------------------------===//
20372 //                           X86 Scheduler Hooks
20373 //===----------------------------------------------------------------------===//
20374
20375 /// Utility function to emit xbegin specifying the start of an RTM region.
20376 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
20377                                      const TargetInstrInfo *TII) {
20378   DebugLoc DL = MI->getDebugLoc();
20379
20380   const BasicBlock *BB = MBB->getBasicBlock();
20381   MachineFunction::iterator I = ++MBB->getIterator();
20382
20383   // For the v = xbegin(), we generate
20384   //
20385   // thisMBB:
20386   //  xbegin sinkMBB
20387   //
20388   // mainMBB:
20389   //  eax = -1
20390   //
20391   // sinkMBB:
20392   //  v = eax
20393
20394   MachineBasicBlock *thisMBB = MBB;
20395   MachineFunction *MF = MBB->getParent();
20396   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
20397   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
20398   MF->insert(I, mainMBB);
20399   MF->insert(I, sinkMBB);
20400
20401   // Transfer the remainder of BB and its successor edges to sinkMBB.
20402   sinkMBB->splice(sinkMBB->begin(), MBB,
20403                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
20404   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
20405
20406   // thisMBB:
20407   //  xbegin sinkMBB
20408   //  # fallthrough to mainMBB
20409   //  # abortion to sinkMBB
20410   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
20411   thisMBB->addSuccessor(mainMBB);
20412   thisMBB->addSuccessor(sinkMBB);
20413
20414   // mainMBB:
20415   //  EAX = -1
20416   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
20417   mainMBB->addSuccessor(sinkMBB);
20418
20419   // sinkMBB:
20420   // EAX is live into the sinkMBB
20421   sinkMBB->addLiveIn(X86::EAX);
20422   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
20423           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
20424     .addReg(X86::EAX);
20425
20426   MI->eraseFromParent();
20427   return sinkMBB;
20428 }
20429
20430 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
20431 // or XMM0_V32I8 in AVX all of this code can be replaced with that
20432 // in the .td file.
20433 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
20434                                        const TargetInstrInfo *TII) {
20435   unsigned Opc;
20436   switch (MI->getOpcode()) {
20437   default: llvm_unreachable("illegal opcode!");
20438   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
20439   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
20440   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
20441   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
20442   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
20443   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
20444   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
20445   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
20446   }
20447
20448   DebugLoc dl = MI->getDebugLoc();
20449   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
20450
20451   unsigned NumArgs = MI->getNumOperands();
20452   for (unsigned i = 1; i < NumArgs; ++i) {
20453     MachineOperand &Op = MI->getOperand(i);
20454     if (!(Op.isReg() && Op.isImplicit()))
20455       MIB.addOperand(Op);
20456   }
20457   if (MI->hasOneMemOperand())
20458     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
20459
20460   BuildMI(*BB, MI, dl,
20461     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
20462     .addReg(X86::XMM0);
20463
20464   MI->eraseFromParent();
20465   return BB;
20466 }
20467
20468 // FIXME: Custom handling because TableGen doesn't support multiple implicit
20469 // defs in an instruction pattern
20470 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
20471                                        const TargetInstrInfo *TII) {
20472   unsigned Opc;
20473   switch (MI->getOpcode()) {
20474   default: llvm_unreachable("illegal opcode!");
20475   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
20476   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
20477   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
20478   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
20479   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
20480   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
20481   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
20482   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
20483   }
20484
20485   DebugLoc dl = MI->getDebugLoc();
20486   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
20487
20488   unsigned NumArgs = MI->getNumOperands(); // remove the results
20489   for (unsigned i = 1; i < NumArgs; ++i) {
20490     MachineOperand &Op = MI->getOperand(i);
20491     if (!(Op.isReg() && Op.isImplicit()))
20492       MIB.addOperand(Op);
20493   }
20494   if (MI->hasOneMemOperand())
20495     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
20496
20497   BuildMI(*BB, MI, dl,
20498     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
20499     .addReg(X86::ECX);
20500
20501   MI->eraseFromParent();
20502   return BB;
20503 }
20504
20505 static MachineBasicBlock *EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
20506                                       const X86Subtarget *Subtarget) {
20507   DebugLoc dl = MI->getDebugLoc();
20508   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20509   // Address into RAX/EAX, other two args into ECX, EDX.
20510   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
20511   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
20512   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
20513   for (int i = 0; i < X86::AddrNumOperands; ++i)
20514     MIB.addOperand(MI->getOperand(i));
20515
20516   unsigned ValOps = X86::AddrNumOperands;
20517   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
20518     .addReg(MI->getOperand(ValOps).getReg());
20519   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
20520     .addReg(MI->getOperand(ValOps+1).getReg());
20521
20522   // The instruction doesn't actually take any operands though.
20523   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
20524
20525   MI->eraseFromParent(); // The pseudo is gone now.
20526   return BB;
20527 }
20528
20529 MachineBasicBlock *
20530 X86TargetLowering::EmitVAARG64WithCustomInserter(MachineInstr *MI,
20531                                                  MachineBasicBlock *MBB) const {
20532   // Emit va_arg instruction on X86-64.
20533
20534   // Operands to this pseudo-instruction:
20535   // 0  ) Output        : destination address (reg)
20536   // 1-5) Input         : va_list address (addr, i64mem)
20537   // 6  ) ArgSize       : Size (in bytes) of vararg type
20538   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
20539   // 8  ) Align         : Alignment of type
20540   // 9  ) EFLAGS (implicit-def)
20541
20542   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
20543   static_assert(X86::AddrNumOperands == 5,
20544                 "VAARG_64 assumes 5 address operands");
20545
20546   unsigned DestReg = MI->getOperand(0).getReg();
20547   MachineOperand &Base = MI->getOperand(1);
20548   MachineOperand &Scale = MI->getOperand(2);
20549   MachineOperand &Index = MI->getOperand(3);
20550   MachineOperand &Disp = MI->getOperand(4);
20551   MachineOperand &Segment = MI->getOperand(5);
20552   unsigned ArgSize = MI->getOperand(6).getImm();
20553   unsigned ArgMode = MI->getOperand(7).getImm();
20554   unsigned Align = MI->getOperand(8).getImm();
20555
20556   // Memory Reference
20557   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
20558   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
20559   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
20560
20561   // Machine Information
20562   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20563   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
20564   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
20565   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
20566   DebugLoc DL = MI->getDebugLoc();
20567
20568   // struct va_list {
20569   //   i32   gp_offset
20570   //   i32   fp_offset
20571   //   i64   overflow_area (address)
20572   //   i64   reg_save_area (address)
20573   // }
20574   // sizeof(va_list) = 24
20575   // alignment(va_list) = 8
20576
20577   unsigned TotalNumIntRegs = 6;
20578   unsigned TotalNumXMMRegs = 8;
20579   bool UseGPOffset = (ArgMode == 1);
20580   bool UseFPOffset = (ArgMode == 2);
20581   unsigned MaxOffset = TotalNumIntRegs * 8 +
20582                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
20583
20584   /* Align ArgSize to a multiple of 8 */
20585   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
20586   bool NeedsAlign = (Align > 8);
20587
20588   MachineBasicBlock *thisMBB = MBB;
20589   MachineBasicBlock *overflowMBB;
20590   MachineBasicBlock *offsetMBB;
20591   MachineBasicBlock *endMBB;
20592
20593   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
20594   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
20595   unsigned OffsetReg = 0;
20596
20597   if (!UseGPOffset && !UseFPOffset) {
20598     // If we only pull from the overflow region, we don't create a branch.
20599     // We don't need to alter control flow.
20600     OffsetDestReg = 0; // unused
20601     OverflowDestReg = DestReg;
20602
20603     offsetMBB = nullptr;
20604     overflowMBB = thisMBB;
20605     endMBB = thisMBB;
20606   } else {
20607     // First emit code to check if gp_offset (or fp_offset) is below the bound.
20608     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
20609     // If not, pull from overflow_area. (branch to overflowMBB)
20610     //
20611     //       thisMBB
20612     //         |     .
20613     //         |        .
20614     //     offsetMBB   overflowMBB
20615     //         |        .
20616     //         |     .
20617     //        endMBB
20618
20619     // Registers for the PHI in endMBB
20620     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
20621     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
20622
20623     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
20624     MachineFunction *MF = MBB->getParent();
20625     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20626     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20627     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20628
20629     MachineFunction::iterator MBBIter = ++MBB->getIterator();
20630
20631     // Insert the new basic blocks
20632     MF->insert(MBBIter, offsetMBB);
20633     MF->insert(MBBIter, overflowMBB);
20634     MF->insert(MBBIter, endMBB);
20635
20636     // Transfer the remainder of MBB and its successor edges to endMBB.
20637     endMBB->splice(endMBB->begin(), thisMBB,
20638                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
20639     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
20640
20641     // Make offsetMBB and overflowMBB successors of thisMBB
20642     thisMBB->addSuccessor(offsetMBB);
20643     thisMBB->addSuccessor(overflowMBB);
20644
20645     // endMBB is a successor of both offsetMBB and overflowMBB
20646     offsetMBB->addSuccessor(endMBB);
20647     overflowMBB->addSuccessor(endMBB);
20648
20649     // Load the offset value into a register
20650     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
20651     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
20652       .addOperand(Base)
20653       .addOperand(Scale)
20654       .addOperand(Index)
20655       .addDisp(Disp, UseFPOffset ? 4 : 0)
20656       .addOperand(Segment)
20657       .setMemRefs(MMOBegin, MMOEnd);
20658
20659     // Check if there is enough room left to pull this argument.
20660     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
20661       .addReg(OffsetReg)
20662       .addImm(MaxOffset + 8 - ArgSizeA8);
20663
20664     // Branch to "overflowMBB" if offset >= max
20665     // Fall through to "offsetMBB" otherwise
20666     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
20667       .addMBB(overflowMBB);
20668   }
20669
20670   // In offsetMBB, emit code to use the reg_save_area.
20671   if (offsetMBB) {
20672     assert(OffsetReg != 0);
20673
20674     // Read the reg_save_area address.
20675     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
20676     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
20677       .addOperand(Base)
20678       .addOperand(Scale)
20679       .addOperand(Index)
20680       .addDisp(Disp, 16)
20681       .addOperand(Segment)
20682       .setMemRefs(MMOBegin, MMOEnd);
20683
20684     // Zero-extend the offset
20685     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
20686       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
20687         .addImm(0)
20688         .addReg(OffsetReg)
20689         .addImm(X86::sub_32bit);
20690
20691     // Add the offset to the reg_save_area to get the final address.
20692     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
20693       .addReg(OffsetReg64)
20694       .addReg(RegSaveReg);
20695
20696     // Compute the offset for the next argument
20697     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
20698     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
20699       .addReg(OffsetReg)
20700       .addImm(UseFPOffset ? 16 : 8);
20701
20702     // Store it back into the va_list.
20703     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
20704       .addOperand(Base)
20705       .addOperand(Scale)
20706       .addOperand(Index)
20707       .addDisp(Disp, UseFPOffset ? 4 : 0)
20708       .addOperand(Segment)
20709       .addReg(NextOffsetReg)
20710       .setMemRefs(MMOBegin, MMOEnd);
20711
20712     // Jump to endMBB
20713     BuildMI(offsetMBB, DL, TII->get(X86::JMP_1))
20714       .addMBB(endMBB);
20715   }
20716
20717   //
20718   // Emit code to use overflow area
20719   //
20720
20721   // Load the overflow_area address into a register.
20722   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
20723   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
20724     .addOperand(Base)
20725     .addOperand(Scale)
20726     .addOperand(Index)
20727     .addDisp(Disp, 8)
20728     .addOperand(Segment)
20729     .setMemRefs(MMOBegin, MMOEnd);
20730
20731   // If we need to align it, do so. Otherwise, just copy the address
20732   // to OverflowDestReg.
20733   if (NeedsAlign) {
20734     // Align the overflow address
20735     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
20736     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
20737
20738     // aligned_addr = (addr + (align-1)) & ~(align-1)
20739     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
20740       .addReg(OverflowAddrReg)
20741       .addImm(Align-1);
20742
20743     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
20744       .addReg(TmpReg)
20745       .addImm(~(uint64_t)(Align-1));
20746   } else {
20747     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
20748       .addReg(OverflowAddrReg);
20749   }
20750
20751   // Compute the next overflow address after this argument.
20752   // (the overflow address should be kept 8-byte aligned)
20753   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
20754   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
20755     .addReg(OverflowDestReg)
20756     .addImm(ArgSizeA8);
20757
20758   // Store the new overflow address.
20759   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
20760     .addOperand(Base)
20761     .addOperand(Scale)
20762     .addOperand(Index)
20763     .addDisp(Disp, 8)
20764     .addOperand(Segment)
20765     .addReg(NextAddrReg)
20766     .setMemRefs(MMOBegin, MMOEnd);
20767
20768   // If we branched, emit the PHI to the front of endMBB.
20769   if (offsetMBB) {
20770     BuildMI(*endMBB, endMBB->begin(), DL,
20771             TII->get(X86::PHI), DestReg)
20772       .addReg(OffsetDestReg).addMBB(offsetMBB)
20773       .addReg(OverflowDestReg).addMBB(overflowMBB);
20774   }
20775
20776   // Erase the pseudo instruction
20777   MI->eraseFromParent();
20778
20779   return endMBB;
20780 }
20781
20782 MachineBasicBlock *
20783 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
20784                                                  MachineInstr *MI,
20785                                                  MachineBasicBlock *MBB) const {
20786   // Emit code to save XMM registers to the stack. The ABI says that the
20787   // number of registers to save is given in %al, so it's theoretically
20788   // possible to do an indirect jump trick to avoid saving all of them,
20789   // however this code takes a simpler approach and just executes all
20790   // of the stores if %al is non-zero. It's less code, and it's probably
20791   // easier on the hardware branch predictor, and stores aren't all that
20792   // expensive anyway.
20793
20794   // Create the new basic blocks. One block contains all the XMM stores,
20795   // and one block is the final destination regardless of whether any
20796   // stores were performed.
20797   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
20798   MachineFunction *F = MBB->getParent();
20799   MachineFunction::iterator MBBIter = ++MBB->getIterator();
20800   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
20801   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
20802   F->insert(MBBIter, XMMSaveMBB);
20803   F->insert(MBBIter, EndMBB);
20804
20805   // Transfer the remainder of MBB and its successor edges to EndMBB.
20806   EndMBB->splice(EndMBB->begin(), MBB,
20807                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
20808   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
20809
20810   // The original block will now fall through to the XMM save block.
20811   MBB->addSuccessor(XMMSaveMBB);
20812   // The XMMSaveMBB will fall through to the end block.
20813   XMMSaveMBB->addSuccessor(EndMBB);
20814
20815   // Now add the instructions.
20816   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20817   DebugLoc DL = MI->getDebugLoc();
20818
20819   unsigned CountReg = MI->getOperand(0).getReg();
20820   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
20821   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
20822
20823   if (!Subtarget->isCallingConvWin64(F->getFunction()->getCallingConv())) {
20824     // If %al is 0, branch around the XMM save block.
20825     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
20826     BuildMI(MBB, DL, TII->get(X86::JE_1)).addMBB(EndMBB);
20827     MBB->addSuccessor(EndMBB);
20828   }
20829
20830   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
20831   // that was just emitted, but clearly shouldn't be "saved".
20832   assert((MI->getNumOperands() <= 3 ||
20833           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
20834           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
20835          && "Expected last argument to be EFLAGS");
20836   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
20837   // In the XMM save block, save all the XMM argument registers.
20838   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
20839     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
20840     MachineMemOperand *MMO = F->getMachineMemOperand(
20841         MachinePointerInfo::getFixedStack(*F, RegSaveFrameIndex, Offset),
20842         MachineMemOperand::MOStore,
20843         /*Size=*/16, /*Align=*/16);
20844     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
20845       .addFrameIndex(RegSaveFrameIndex)
20846       .addImm(/*Scale=*/1)
20847       .addReg(/*IndexReg=*/0)
20848       .addImm(/*Disp=*/Offset)
20849       .addReg(/*Segment=*/0)
20850       .addReg(MI->getOperand(i).getReg())
20851       .addMemOperand(MMO);
20852   }
20853
20854   MI->eraseFromParent();   // The pseudo instruction is gone now.
20855
20856   return EndMBB;
20857 }
20858
20859 // The EFLAGS operand of SelectItr might be missing a kill marker
20860 // because there were multiple uses of EFLAGS, and ISel didn't know
20861 // which to mark. Figure out whether SelectItr should have had a
20862 // kill marker, and set it if it should. Returns the correct kill
20863 // marker value.
20864 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
20865                                      MachineBasicBlock* BB,
20866                                      const TargetRegisterInfo* TRI) {
20867   // Scan forward through BB for a use/def of EFLAGS.
20868   MachineBasicBlock::iterator miI(std::next(SelectItr));
20869   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
20870     const MachineInstr& mi = *miI;
20871     if (mi.readsRegister(X86::EFLAGS))
20872       return false;
20873     if (mi.definesRegister(X86::EFLAGS))
20874       break; // Should have kill-flag - update below.
20875   }
20876
20877   // If we hit the end of the block, check whether EFLAGS is live into a
20878   // successor.
20879   if (miI == BB->end()) {
20880     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
20881                                           sEnd = BB->succ_end();
20882          sItr != sEnd; ++sItr) {
20883       MachineBasicBlock* succ = *sItr;
20884       if (succ->isLiveIn(X86::EFLAGS))
20885         return false;
20886     }
20887   }
20888
20889   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
20890   // out. SelectMI should have a kill flag on EFLAGS.
20891   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
20892   return true;
20893 }
20894
20895 // Return true if it is OK for this CMOV pseudo-opcode to be cascaded
20896 // together with other CMOV pseudo-opcodes into a single basic-block with
20897 // conditional jump around it.
20898 static bool isCMOVPseudo(MachineInstr *MI) {
20899   switch (MI->getOpcode()) {
20900   case X86::CMOV_FR32:
20901   case X86::CMOV_FR64:
20902   case X86::CMOV_GR8:
20903   case X86::CMOV_GR16:
20904   case X86::CMOV_GR32:
20905   case X86::CMOV_RFP32:
20906   case X86::CMOV_RFP64:
20907   case X86::CMOV_RFP80:
20908   case X86::CMOV_V2F64:
20909   case X86::CMOV_V2I64:
20910   case X86::CMOV_V4F32:
20911   case X86::CMOV_V4F64:
20912   case X86::CMOV_V4I64:
20913   case X86::CMOV_V16F32:
20914   case X86::CMOV_V8F32:
20915   case X86::CMOV_V8F64:
20916   case X86::CMOV_V8I64:
20917   case X86::CMOV_V8I1:
20918   case X86::CMOV_V16I1:
20919   case X86::CMOV_V32I1:
20920   case X86::CMOV_V64I1:
20921     return true;
20922
20923   default:
20924     return false;
20925   }
20926 }
20927
20928 MachineBasicBlock *
20929 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
20930                                      MachineBasicBlock *BB) const {
20931   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20932   DebugLoc DL = MI->getDebugLoc();
20933
20934   // To "insert" a SELECT_CC instruction, we actually have to insert the
20935   // diamond control-flow pattern.  The incoming instruction knows the
20936   // destination vreg to set, the condition code register to branch on, the
20937   // true/false values to select between, and a branch opcode to use.
20938   const BasicBlock *LLVM_BB = BB->getBasicBlock();
20939   MachineFunction::iterator It = ++BB->getIterator();
20940
20941   //  thisMBB:
20942   //  ...
20943   //   TrueVal = ...
20944   //   cmpTY ccX, r1, r2
20945   //   bCC copy1MBB
20946   //   fallthrough --> copy0MBB
20947   MachineBasicBlock *thisMBB = BB;
20948   MachineFunction *F = BB->getParent();
20949
20950   // This code lowers all pseudo-CMOV instructions. Generally it lowers these
20951   // as described above, by inserting a BB, and then making a PHI at the join
20952   // point to select the true and false operands of the CMOV in the PHI.
20953   //
20954   // The code also handles two different cases of multiple CMOV opcodes
20955   // in a row.
20956   //
20957   // Case 1:
20958   // In this case, there are multiple CMOVs in a row, all which are based on
20959   // the same condition setting (or the exact opposite condition setting).
20960   // In this case we can lower all the CMOVs using a single inserted BB, and
20961   // then make a number of PHIs at the join point to model the CMOVs. The only
20962   // trickiness here, is that in a case like:
20963   //
20964   // t2 = CMOV cond1 t1, f1
20965   // t3 = CMOV cond1 t2, f2
20966   //
20967   // when rewriting this into PHIs, we have to perform some renaming on the
20968   // temps since you cannot have a PHI operand refer to a PHI result earlier
20969   // in the same block.  The "simple" but wrong lowering would be:
20970   //
20971   // t2 = PHI t1(BB1), f1(BB2)
20972   // t3 = PHI t2(BB1), f2(BB2)
20973   //
20974   // but clearly t2 is not defined in BB1, so that is incorrect. The proper
20975   // renaming is to note that on the path through BB1, t2 is really just a
20976   // copy of t1, and do that renaming, properly generating:
20977   //
20978   // t2 = PHI t1(BB1), f1(BB2)
20979   // t3 = PHI t1(BB1), f2(BB2)
20980   //
20981   // Case 2, we lower cascaded CMOVs such as
20982   //
20983   //   (CMOV (CMOV F, T, cc1), T, cc2)
20984   //
20985   // to two successives branches.  For that, we look for another CMOV as the
20986   // following instruction.
20987   //
20988   // Without this, we would add a PHI between the two jumps, which ends up
20989   // creating a few copies all around. For instance, for
20990   //
20991   //    (sitofp (zext (fcmp une)))
20992   //
20993   // we would generate:
20994   //
20995   //         ucomiss %xmm1, %xmm0
20996   //         movss  <1.0f>, %xmm0
20997   //         movaps  %xmm0, %xmm1
20998   //         jne     .LBB5_2
20999   //         xorps   %xmm1, %xmm1
21000   // .LBB5_2:
21001   //         jp      .LBB5_4
21002   //         movaps  %xmm1, %xmm0
21003   // .LBB5_4:
21004   //         retq
21005   //
21006   // because this custom-inserter would have generated:
21007   //
21008   //   A
21009   //   | \
21010   //   |  B
21011   //   | /
21012   //   C
21013   //   | \
21014   //   |  D
21015   //   | /
21016   //   E
21017   //
21018   // A: X = ...; Y = ...
21019   // B: empty
21020   // C: Z = PHI [X, A], [Y, B]
21021   // D: empty
21022   // E: PHI [X, C], [Z, D]
21023   //
21024   // If we lower both CMOVs in a single step, we can instead generate:
21025   //
21026   //   A
21027   //   | \
21028   //   |  C
21029   //   | /|
21030   //   |/ |
21031   //   |  |
21032   //   |  D
21033   //   | /
21034   //   E
21035   //
21036   // A: X = ...; Y = ...
21037   // D: empty
21038   // E: PHI [X, A], [X, C], [Y, D]
21039   //
21040   // Which, in our sitofp/fcmp example, gives us something like:
21041   //
21042   //         ucomiss %xmm1, %xmm0
21043   //         movss  <1.0f>, %xmm0
21044   //         jne     .LBB5_4
21045   //         jp      .LBB5_4
21046   //         xorps   %xmm0, %xmm0
21047   // .LBB5_4:
21048   //         retq
21049   //
21050   MachineInstr *CascadedCMOV = nullptr;
21051   MachineInstr *LastCMOV = MI;
21052   X86::CondCode CC = X86::CondCode(MI->getOperand(3).getImm());
21053   X86::CondCode OppCC = X86::GetOppositeBranchCondition(CC);
21054   MachineBasicBlock::iterator NextMIIt =
21055       std::next(MachineBasicBlock::iterator(MI));
21056
21057   // Check for case 1, where there are multiple CMOVs with the same condition
21058   // first.  Of the two cases of multiple CMOV lowerings, case 1 reduces the
21059   // number of jumps the most.
21060
21061   if (isCMOVPseudo(MI)) {
21062     // See if we have a string of CMOVS with the same condition.
21063     while (NextMIIt != BB->end() &&
21064            isCMOVPseudo(NextMIIt) &&
21065            (NextMIIt->getOperand(3).getImm() == CC ||
21066             NextMIIt->getOperand(3).getImm() == OppCC)) {
21067       LastCMOV = &*NextMIIt;
21068       ++NextMIIt;
21069     }
21070   }
21071
21072   // This checks for case 2, but only do this if we didn't already find
21073   // case 1, as indicated by LastCMOV == MI.
21074   if (LastCMOV == MI &&
21075       NextMIIt != BB->end() && NextMIIt->getOpcode() == MI->getOpcode() &&
21076       NextMIIt->getOperand(2).getReg() == MI->getOperand(2).getReg() &&
21077       NextMIIt->getOperand(1).getReg() == MI->getOperand(0).getReg()) {
21078     CascadedCMOV = &*NextMIIt;
21079   }
21080
21081   MachineBasicBlock *jcc1MBB = nullptr;
21082
21083   // If we have a cascaded CMOV, we lower it to two successive branches to
21084   // the same block.  EFLAGS is used by both, so mark it as live in the second.
21085   if (CascadedCMOV) {
21086     jcc1MBB = F->CreateMachineBasicBlock(LLVM_BB);
21087     F->insert(It, jcc1MBB);
21088     jcc1MBB->addLiveIn(X86::EFLAGS);
21089   }
21090
21091   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
21092   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
21093   F->insert(It, copy0MBB);
21094   F->insert(It, sinkMBB);
21095
21096   // If the EFLAGS register isn't dead in the terminator, then claim that it's
21097   // live into the sink and copy blocks.
21098   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
21099
21100   MachineInstr *LastEFLAGSUser = CascadedCMOV ? CascadedCMOV : LastCMOV;
21101   if (!LastEFLAGSUser->killsRegister(X86::EFLAGS) &&
21102       !checkAndUpdateEFLAGSKill(LastEFLAGSUser, BB, TRI)) {
21103     copy0MBB->addLiveIn(X86::EFLAGS);
21104     sinkMBB->addLiveIn(X86::EFLAGS);
21105   }
21106
21107   // Transfer the remainder of BB and its successor edges to sinkMBB.
21108   sinkMBB->splice(sinkMBB->begin(), BB,
21109                   std::next(MachineBasicBlock::iterator(LastCMOV)), BB->end());
21110   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
21111
21112   // Add the true and fallthrough blocks as its successors.
21113   if (CascadedCMOV) {
21114     // The fallthrough block may be jcc1MBB, if we have a cascaded CMOV.
21115     BB->addSuccessor(jcc1MBB);
21116
21117     // In that case, jcc1MBB will itself fallthrough the copy0MBB, and
21118     // jump to the sinkMBB.
21119     jcc1MBB->addSuccessor(copy0MBB);
21120     jcc1MBB->addSuccessor(sinkMBB);
21121   } else {
21122     BB->addSuccessor(copy0MBB);
21123   }
21124
21125   // The true block target of the first (or only) branch is always sinkMBB.
21126   BB->addSuccessor(sinkMBB);
21127
21128   // Create the conditional branch instruction.
21129   unsigned Opc = X86::GetCondBranchFromCond(CC);
21130   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
21131
21132   if (CascadedCMOV) {
21133     unsigned Opc2 = X86::GetCondBranchFromCond(
21134         (X86::CondCode)CascadedCMOV->getOperand(3).getImm());
21135     BuildMI(jcc1MBB, DL, TII->get(Opc2)).addMBB(sinkMBB);
21136   }
21137
21138   //  copy0MBB:
21139   //   %FalseValue = ...
21140   //   # fallthrough to sinkMBB
21141   copy0MBB->addSuccessor(sinkMBB);
21142
21143   //  sinkMBB:
21144   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
21145   //  ...
21146   MachineBasicBlock::iterator MIItBegin = MachineBasicBlock::iterator(MI);
21147   MachineBasicBlock::iterator MIItEnd =
21148     std::next(MachineBasicBlock::iterator(LastCMOV));
21149   MachineBasicBlock::iterator SinkInsertionPoint = sinkMBB->begin();
21150   DenseMap<unsigned, std::pair<unsigned, unsigned>> RegRewriteTable;
21151   MachineInstrBuilder MIB;
21152
21153   // As we are creating the PHIs, we have to be careful if there is more than
21154   // one.  Later CMOVs may reference the results of earlier CMOVs, but later
21155   // PHIs have to reference the individual true/false inputs from earlier PHIs.
21156   // That also means that PHI construction must work forward from earlier to
21157   // later, and that the code must maintain a mapping from earlier PHI's
21158   // destination registers, and the registers that went into the PHI.
21159
21160   for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd; ++MIIt) {
21161     unsigned DestReg = MIIt->getOperand(0).getReg();
21162     unsigned Op1Reg = MIIt->getOperand(1).getReg();
21163     unsigned Op2Reg = MIIt->getOperand(2).getReg();
21164
21165     // If this CMOV we are generating is the opposite condition from
21166     // the jump we generated, then we have to swap the operands for the
21167     // PHI that is going to be generated.
21168     if (MIIt->getOperand(3).getImm() == OppCC)
21169         std::swap(Op1Reg, Op2Reg);
21170
21171     if (RegRewriteTable.find(Op1Reg) != RegRewriteTable.end())
21172       Op1Reg = RegRewriteTable[Op1Reg].first;
21173
21174     if (RegRewriteTable.find(Op2Reg) != RegRewriteTable.end())
21175       Op2Reg = RegRewriteTable[Op2Reg].second;
21176
21177     MIB = BuildMI(*sinkMBB, SinkInsertionPoint, DL,
21178                   TII->get(X86::PHI), DestReg)
21179           .addReg(Op1Reg).addMBB(copy0MBB)
21180           .addReg(Op2Reg).addMBB(thisMBB);
21181
21182     // Add this PHI to the rewrite table.
21183     RegRewriteTable[DestReg] = std::make_pair(Op1Reg, Op2Reg);
21184   }
21185
21186   // If we have a cascaded CMOV, the second Jcc provides the same incoming
21187   // value as the first Jcc (the True operand of the SELECT_CC/CMOV nodes).
21188   if (CascadedCMOV) {
21189     MIB.addReg(MI->getOperand(2).getReg()).addMBB(jcc1MBB);
21190     // Copy the PHI result to the register defined by the second CMOV.
21191     BuildMI(*sinkMBB, std::next(MachineBasicBlock::iterator(MIB.getInstr())),
21192             DL, TII->get(TargetOpcode::COPY),
21193             CascadedCMOV->getOperand(0).getReg())
21194         .addReg(MI->getOperand(0).getReg());
21195     CascadedCMOV->eraseFromParent();
21196   }
21197
21198   // Now remove the CMOV(s).
21199   for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd; )
21200     (MIIt++)->eraseFromParent();
21201
21202   return sinkMBB;
21203 }
21204
21205 MachineBasicBlock *
21206 X86TargetLowering::EmitLoweredAtomicFP(MachineInstr *MI,
21207                                        MachineBasicBlock *BB) const {
21208   // Combine the following atomic floating-point modification pattern:
21209   //   a.store(reg OP a.load(acquire), release)
21210   // Transform them into:
21211   //   OPss (%gpr), %xmm
21212   //   movss %xmm, (%gpr)
21213   // Or sd equivalent for 64-bit operations.
21214   unsigned MOp, FOp;
21215   switch (MI->getOpcode()) {
21216   default: llvm_unreachable("unexpected instr type for EmitLoweredAtomicFP");
21217   case X86::RELEASE_FADD32mr: MOp = X86::MOVSSmr; FOp = X86::ADDSSrm; break;
21218   case X86::RELEASE_FADD64mr: MOp = X86::MOVSDmr; FOp = X86::ADDSDrm; break;
21219   }
21220   const X86InstrInfo *TII = Subtarget->getInstrInfo();
21221   DebugLoc DL = MI->getDebugLoc();
21222   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
21223   MachineOperand MSrc = MI->getOperand(0);
21224   unsigned VSrc = MI->getOperand(5).getReg();
21225   const MachineOperand &Disp = MI->getOperand(3);
21226   MachineOperand ZeroDisp = MachineOperand::CreateImm(0);
21227   bool hasDisp = Disp.isGlobal() || Disp.isImm();
21228   if (hasDisp && MSrc.isReg())
21229     MSrc.setIsKill(false);
21230   MachineInstrBuilder MIM = BuildMI(*BB, MI, DL, TII->get(MOp))
21231                                 .addOperand(/*Base=*/MSrc)
21232                                 .addImm(/*Scale=*/1)
21233                                 .addReg(/*Index=*/0)
21234                                 .addDisp(hasDisp ? Disp : ZeroDisp, /*off=*/0)
21235                                 .addReg(0);
21236   MachineInstr *MIO = BuildMI(*BB, (MachineInstr *)MIM, DL, TII->get(FOp),
21237                               MRI.createVirtualRegister(MRI.getRegClass(VSrc)))
21238                           .addReg(VSrc)
21239                           .addOperand(/*Base=*/MSrc)
21240                           .addImm(/*Scale=*/1)
21241                           .addReg(/*Index=*/0)
21242                           .addDisp(hasDisp ? Disp : ZeroDisp, /*off=*/0)
21243                           .addReg(/*Segment=*/0);
21244   MIM.addReg(MIO->getOperand(0).getReg(), RegState::Kill);
21245   MI->eraseFromParent(); // The pseudo instruction is gone now.
21246   return BB;
21247 }
21248
21249 MachineBasicBlock *
21250 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI,
21251                                         MachineBasicBlock *BB) const {
21252   MachineFunction *MF = BB->getParent();
21253   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21254   DebugLoc DL = MI->getDebugLoc();
21255   const BasicBlock *LLVM_BB = BB->getBasicBlock();
21256
21257   assert(MF->shouldSplitStack());
21258
21259   const bool Is64Bit = Subtarget->is64Bit();
21260   const bool IsLP64 = Subtarget->isTarget64BitLP64();
21261
21262   const unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
21263   const unsigned TlsOffset = IsLP64 ? 0x70 : Is64Bit ? 0x40 : 0x30;
21264
21265   // BB:
21266   //  ... [Till the alloca]
21267   // If stacklet is not large enough, jump to mallocMBB
21268   //
21269   // bumpMBB:
21270   //  Allocate by subtracting from RSP
21271   //  Jump to continueMBB
21272   //
21273   // mallocMBB:
21274   //  Allocate by call to runtime
21275   //
21276   // continueMBB:
21277   //  ...
21278   //  [rest of original BB]
21279   //
21280
21281   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
21282   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
21283   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
21284
21285   MachineRegisterInfo &MRI = MF->getRegInfo();
21286   const TargetRegisterClass *AddrRegClass =
21287       getRegClassFor(getPointerTy(MF->getDataLayout()));
21288
21289   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
21290     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
21291     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
21292     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
21293     sizeVReg = MI->getOperand(1).getReg(),
21294     physSPReg = IsLP64 || Subtarget->isTargetNaCl64() ? X86::RSP : X86::ESP;
21295
21296   MachineFunction::iterator MBBIter = ++BB->getIterator();
21297
21298   MF->insert(MBBIter, bumpMBB);
21299   MF->insert(MBBIter, mallocMBB);
21300   MF->insert(MBBIter, continueMBB);
21301
21302   continueMBB->splice(continueMBB->begin(), BB,
21303                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
21304   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
21305
21306   // Add code to the main basic block to check if the stack limit has been hit,
21307   // and if so, jump to mallocMBB otherwise to bumpMBB.
21308   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
21309   BuildMI(BB, DL, TII->get(IsLP64 ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
21310     .addReg(tmpSPVReg).addReg(sizeVReg);
21311   BuildMI(BB, DL, TII->get(IsLP64 ? X86::CMP64mr:X86::CMP32mr))
21312     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
21313     .addReg(SPLimitVReg);
21314   BuildMI(BB, DL, TII->get(X86::JG_1)).addMBB(mallocMBB);
21315
21316   // bumpMBB simply decreases the stack pointer, since we know the current
21317   // stacklet has enough space.
21318   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
21319     .addReg(SPLimitVReg);
21320   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
21321     .addReg(SPLimitVReg);
21322   BuildMI(bumpMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
21323
21324   // Calls into a routine in libgcc to allocate more space from the heap.
21325   const uint32_t *RegMask =
21326       Subtarget->getRegisterInfo()->getCallPreservedMask(*MF, CallingConv::C);
21327   if (IsLP64) {
21328     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
21329       .addReg(sizeVReg);
21330     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
21331       .addExternalSymbol("__morestack_allocate_stack_space")
21332       .addRegMask(RegMask)
21333       .addReg(X86::RDI, RegState::Implicit)
21334       .addReg(X86::RAX, RegState::ImplicitDefine);
21335   } else if (Is64Bit) {
21336     BuildMI(mallocMBB, DL, TII->get(X86::MOV32rr), X86::EDI)
21337       .addReg(sizeVReg);
21338     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
21339       .addExternalSymbol("__morestack_allocate_stack_space")
21340       .addRegMask(RegMask)
21341       .addReg(X86::EDI, RegState::Implicit)
21342       .addReg(X86::EAX, RegState::ImplicitDefine);
21343   } else {
21344     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
21345       .addImm(12);
21346     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
21347     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
21348       .addExternalSymbol("__morestack_allocate_stack_space")
21349       .addRegMask(RegMask)
21350       .addReg(X86::EAX, RegState::ImplicitDefine);
21351   }
21352
21353   if (!Is64Bit)
21354     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
21355       .addImm(16);
21356
21357   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
21358     .addReg(IsLP64 ? X86::RAX : X86::EAX);
21359   BuildMI(mallocMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
21360
21361   // Set up the CFG correctly.
21362   BB->addSuccessor(bumpMBB);
21363   BB->addSuccessor(mallocMBB);
21364   mallocMBB->addSuccessor(continueMBB);
21365   bumpMBB->addSuccessor(continueMBB);
21366
21367   // Take care of the PHI nodes.
21368   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
21369           MI->getOperand(0).getReg())
21370     .addReg(mallocPtrVReg).addMBB(mallocMBB)
21371     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
21372
21373   // Delete the original pseudo instruction.
21374   MI->eraseFromParent();
21375
21376   // And we're done.
21377   return continueMBB;
21378 }
21379
21380 MachineBasicBlock *
21381 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
21382                                         MachineBasicBlock *BB) const {
21383   assert(!Subtarget->isTargetMachO());
21384   DebugLoc DL = MI->getDebugLoc();
21385   MachineInstr *ResumeMI = Subtarget->getFrameLowering()->emitStackProbe(
21386       *BB->getParent(), *BB, MI, DL, false);
21387   MachineBasicBlock *ResumeBB = ResumeMI->getParent();
21388   MI->eraseFromParent(); // The pseudo instruction is gone now.
21389   return ResumeBB;
21390 }
21391
21392 MachineBasicBlock *
21393 X86TargetLowering::EmitLoweredCatchRet(MachineInstr *MI,
21394                                        MachineBasicBlock *BB) const {
21395   MachineFunction *MF = BB->getParent();
21396   const Constant *PerFn = MF->getFunction()->getPersonalityFn();
21397   const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
21398   MachineBasicBlock *TargetMBB = MI->getOperand(0).getMBB();
21399   DebugLoc DL = MI->getDebugLoc();
21400
21401   assert(!isAsynchronousEHPersonality(classifyEHPersonality(PerFn)) &&
21402          "SEH does not use catchret!");
21403
21404   // Only 32-bit EH needs to worry about manually restoring stack pointers.
21405   if (!Subtarget->is32Bit())
21406     return BB;
21407
21408   // C++ EH creates a new target block to hold the restore code, and wires up
21409   // the new block to the return destination with a normal JMP_4.
21410   MachineBasicBlock *RestoreMBB =
21411       MF->CreateMachineBasicBlock(BB->getBasicBlock());
21412   assert(BB->succ_size() == 1);
21413   MF->insert(TargetMBB->getIterator(), RestoreMBB);
21414   RestoreMBB->transferSuccessorsAndUpdatePHIs(BB);
21415   BB->addSuccessor(RestoreMBB);
21416   MI->getOperand(0).setMBB(RestoreMBB);
21417
21418   auto RestoreMBBI = RestoreMBB->begin();
21419   BuildMI(*RestoreMBB, RestoreMBBI, DL, TII.get(X86::EH_RESTORE));
21420   BuildMI(*RestoreMBB, RestoreMBBI, DL, TII.get(X86::JMP_4)).addMBB(TargetMBB);
21421   return BB;
21422 }
21423
21424 MachineBasicBlock *
21425 X86TargetLowering::EmitLoweredCatchPad(MachineInstr *MI,
21426                                        MachineBasicBlock *BB) const {
21427   MachineFunction *MF = BB->getParent();
21428   const Constant *PerFn = MF->getFunction()->getPersonalityFn();
21429   bool IsSEH = isAsynchronousEHPersonality(classifyEHPersonality(PerFn));
21430   // Only 32-bit SEH requires special handling for catchpad.
21431   if (IsSEH && Subtarget->is32Bit()) {
21432     const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
21433     DebugLoc DL = MI->getDebugLoc();
21434     BuildMI(*BB, MI, DL, TII.get(X86::EH_RESTORE));
21435   }
21436   MI->eraseFromParent();
21437   return BB;
21438 }
21439
21440 MachineBasicBlock *
21441 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
21442                                       MachineBasicBlock *BB) const {
21443   // This is pretty easy.  We're taking the value that we received from
21444   // our load from the relocation, sticking it in either RDI (x86-64)
21445   // or EAX and doing an indirect call.  The return value will then
21446   // be in the normal return register.
21447   MachineFunction *F = BB->getParent();
21448   const X86InstrInfo *TII = Subtarget->getInstrInfo();
21449   DebugLoc DL = MI->getDebugLoc();
21450
21451   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
21452   assert(MI->getOperand(3).isGlobal() && "This should be a global");
21453
21454   // Get a register mask for the lowered call.
21455   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
21456   // proper register mask.
21457   const uint32_t *RegMask =
21458       Subtarget->getRegisterInfo()->getCallPreservedMask(*F, CallingConv::C);
21459   if (Subtarget->is64Bit()) {
21460     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
21461                                       TII->get(X86::MOV64rm), X86::RDI)
21462     .addReg(X86::RIP)
21463     .addImm(0).addReg(0)
21464     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
21465                       MI->getOperand(3).getTargetFlags())
21466     .addReg(0);
21467     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
21468     addDirectMem(MIB, X86::RDI);
21469     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
21470   } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
21471     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
21472                                       TII->get(X86::MOV32rm), X86::EAX)
21473     .addReg(0)
21474     .addImm(0).addReg(0)
21475     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
21476                       MI->getOperand(3).getTargetFlags())
21477     .addReg(0);
21478     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
21479     addDirectMem(MIB, X86::EAX);
21480     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
21481   } else {
21482     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
21483                                       TII->get(X86::MOV32rm), X86::EAX)
21484     .addReg(TII->getGlobalBaseReg(F))
21485     .addImm(0).addReg(0)
21486     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
21487                       MI->getOperand(3).getTargetFlags())
21488     .addReg(0);
21489     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
21490     addDirectMem(MIB, X86::EAX);
21491     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
21492   }
21493
21494   MI->eraseFromParent(); // The pseudo instruction is gone now.
21495   return BB;
21496 }
21497
21498 MachineBasicBlock *
21499 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
21500                                     MachineBasicBlock *MBB) const {
21501   DebugLoc DL = MI->getDebugLoc();
21502   MachineFunction *MF = MBB->getParent();
21503   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21504   MachineRegisterInfo &MRI = MF->getRegInfo();
21505
21506   const BasicBlock *BB = MBB->getBasicBlock();
21507   MachineFunction::iterator I = ++MBB->getIterator();
21508
21509   // Memory Reference
21510   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
21511   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
21512
21513   unsigned DstReg;
21514   unsigned MemOpndSlot = 0;
21515
21516   unsigned CurOp = 0;
21517
21518   DstReg = MI->getOperand(CurOp++).getReg();
21519   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
21520   assert(RC->hasType(MVT::i32) && "Invalid destination!");
21521   unsigned mainDstReg = MRI.createVirtualRegister(RC);
21522   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
21523
21524   MemOpndSlot = CurOp;
21525
21526   MVT PVT = getPointerTy(MF->getDataLayout());
21527   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
21528          "Invalid Pointer Size!");
21529
21530   // For v = setjmp(buf), we generate
21531   //
21532   // thisMBB:
21533   //  buf[LabelOffset] = restoreMBB <-- takes address of restoreMBB
21534   //  SjLjSetup restoreMBB
21535   //
21536   // mainMBB:
21537   //  v_main = 0
21538   //
21539   // sinkMBB:
21540   //  v = phi(main, restore)
21541   //
21542   // restoreMBB:
21543   //  if base pointer being used, load it from frame
21544   //  v_restore = 1
21545
21546   MachineBasicBlock *thisMBB = MBB;
21547   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
21548   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
21549   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
21550   MF->insert(I, mainMBB);
21551   MF->insert(I, sinkMBB);
21552   MF->push_back(restoreMBB);
21553   restoreMBB->setHasAddressTaken();
21554
21555   MachineInstrBuilder MIB;
21556
21557   // Transfer the remainder of BB and its successor edges to sinkMBB.
21558   sinkMBB->splice(sinkMBB->begin(), MBB,
21559                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
21560   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
21561
21562   // thisMBB:
21563   unsigned PtrStoreOpc = 0;
21564   unsigned LabelReg = 0;
21565   const int64_t LabelOffset = 1 * PVT.getStoreSize();
21566   Reloc::Model RM = MF->getTarget().getRelocationModel();
21567   bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
21568                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
21569
21570   // Prepare IP either in reg or imm.
21571   if (!UseImmLabel) {
21572     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
21573     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
21574     LabelReg = MRI.createVirtualRegister(PtrRC);
21575     if (Subtarget->is64Bit()) {
21576       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
21577               .addReg(X86::RIP)
21578               .addImm(0)
21579               .addReg(0)
21580               .addMBB(restoreMBB)
21581               .addReg(0);
21582     } else {
21583       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
21584       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
21585               .addReg(XII->getGlobalBaseReg(MF))
21586               .addImm(0)
21587               .addReg(0)
21588               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
21589               .addReg(0);
21590     }
21591   } else
21592     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
21593   // Store IP
21594   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
21595   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
21596     if (i == X86::AddrDisp)
21597       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
21598     else
21599       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
21600   }
21601   if (!UseImmLabel)
21602     MIB.addReg(LabelReg);
21603   else
21604     MIB.addMBB(restoreMBB);
21605   MIB.setMemRefs(MMOBegin, MMOEnd);
21606   // Setup
21607   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
21608           .addMBB(restoreMBB);
21609
21610   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
21611   MIB.addRegMask(RegInfo->getNoPreservedMask());
21612   thisMBB->addSuccessor(mainMBB);
21613   thisMBB->addSuccessor(restoreMBB);
21614
21615   // mainMBB:
21616   //  EAX = 0
21617   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
21618   mainMBB->addSuccessor(sinkMBB);
21619
21620   // sinkMBB:
21621   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
21622           TII->get(X86::PHI), DstReg)
21623     .addReg(mainDstReg).addMBB(mainMBB)
21624     .addReg(restoreDstReg).addMBB(restoreMBB);
21625
21626   // restoreMBB:
21627   if (RegInfo->hasBasePointer(*MF)) {
21628     const bool Uses64BitFramePtr =
21629         Subtarget->isTarget64BitLP64() || Subtarget->isTargetNaCl64();
21630     X86MachineFunctionInfo *X86FI = MF->getInfo<X86MachineFunctionInfo>();
21631     X86FI->setRestoreBasePointer(MF);
21632     unsigned FramePtr = RegInfo->getFrameRegister(*MF);
21633     unsigned BasePtr = RegInfo->getBaseRegister();
21634     unsigned Opm = Uses64BitFramePtr ? X86::MOV64rm : X86::MOV32rm;
21635     addRegOffset(BuildMI(restoreMBB, DL, TII->get(Opm), BasePtr),
21636                  FramePtr, true, X86FI->getRestoreBasePointerOffset())
21637       .setMIFlag(MachineInstr::FrameSetup);
21638   }
21639   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
21640   BuildMI(restoreMBB, DL, TII->get(X86::JMP_1)).addMBB(sinkMBB);
21641   restoreMBB->addSuccessor(sinkMBB);
21642
21643   MI->eraseFromParent();
21644   return sinkMBB;
21645 }
21646
21647 MachineBasicBlock *
21648 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
21649                                      MachineBasicBlock *MBB) const {
21650   DebugLoc DL = MI->getDebugLoc();
21651   MachineFunction *MF = MBB->getParent();
21652   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21653   MachineRegisterInfo &MRI = MF->getRegInfo();
21654
21655   // Memory Reference
21656   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
21657   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
21658
21659   MVT PVT = getPointerTy(MF->getDataLayout());
21660   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
21661          "Invalid Pointer Size!");
21662
21663   const TargetRegisterClass *RC =
21664     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
21665   unsigned Tmp = MRI.createVirtualRegister(RC);
21666   // Since FP is only updated here but NOT referenced, it's treated as GPR.
21667   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
21668   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
21669   unsigned SP = RegInfo->getStackRegister();
21670
21671   MachineInstrBuilder MIB;
21672
21673   const int64_t LabelOffset = 1 * PVT.getStoreSize();
21674   const int64_t SPOffset = 2 * PVT.getStoreSize();
21675
21676   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
21677   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
21678
21679   // Reload FP
21680   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
21681   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
21682     MIB.addOperand(MI->getOperand(i));
21683   MIB.setMemRefs(MMOBegin, MMOEnd);
21684   // Reload IP
21685   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
21686   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
21687     if (i == X86::AddrDisp)
21688       MIB.addDisp(MI->getOperand(i), LabelOffset);
21689     else
21690       MIB.addOperand(MI->getOperand(i));
21691   }
21692   MIB.setMemRefs(MMOBegin, MMOEnd);
21693   // Reload SP
21694   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
21695   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
21696     if (i == X86::AddrDisp)
21697       MIB.addDisp(MI->getOperand(i), SPOffset);
21698     else
21699       MIB.addOperand(MI->getOperand(i));
21700   }
21701   MIB.setMemRefs(MMOBegin, MMOEnd);
21702   // Jump
21703   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
21704
21705   MI->eraseFromParent();
21706   return MBB;
21707 }
21708
21709 // Replace 213-type (isel default) FMA3 instructions with 231-type for
21710 // accumulator loops. Writing back to the accumulator allows the coalescer
21711 // to remove extra copies in the loop.
21712 // FIXME: Do this on AVX512.  We don't support 231 variants yet (PR23937).
21713 MachineBasicBlock *
21714 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
21715                                  MachineBasicBlock *MBB) const {
21716   MachineOperand &AddendOp = MI->getOperand(3);
21717
21718   // Bail out early if the addend isn't a register - we can't switch these.
21719   if (!AddendOp.isReg())
21720     return MBB;
21721
21722   MachineFunction &MF = *MBB->getParent();
21723   MachineRegisterInfo &MRI = MF.getRegInfo();
21724
21725   // Check whether the addend is defined by a PHI:
21726   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
21727   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
21728   if (!AddendDef.isPHI())
21729     return MBB;
21730
21731   // Look for the following pattern:
21732   // loop:
21733   //   %addend = phi [%entry, 0], [%loop, %result]
21734   //   ...
21735   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
21736
21737   // Replace with:
21738   //   loop:
21739   //   %addend = phi [%entry, 0], [%loop, %result]
21740   //   ...
21741   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
21742
21743   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
21744     assert(AddendDef.getOperand(i).isReg());
21745     MachineOperand PHISrcOp = AddendDef.getOperand(i);
21746     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
21747     if (&PHISrcInst == MI) {
21748       // Found a matching instruction.
21749       unsigned NewFMAOpc = 0;
21750       switch (MI->getOpcode()) {
21751         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
21752         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
21753         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
21754         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
21755         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
21756         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
21757         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
21758         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
21759         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
21760         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
21761         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
21762         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
21763         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
21764         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
21765         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
21766         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
21767         case X86::VFMADDSUBPDr213r: NewFMAOpc = X86::VFMADDSUBPDr231r; break;
21768         case X86::VFMADDSUBPSr213r: NewFMAOpc = X86::VFMADDSUBPSr231r; break;
21769         case X86::VFMSUBADDPDr213r: NewFMAOpc = X86::VFMSUBADDPDr231r; break;
21770         case X86::VFMSUBADDPSr213r: NewFMAOpc = X86::VFMSUBADDPSr231r; break;
21771
21772         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
21773         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
21774         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
21775         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
21776         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
21777         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
21778         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
21779         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
21780         case X86::VFMADDSUBPDr213rY: NewFMAOpc = X86::VFMADDSUBPDr231rY; break;
21781         case X86::VFMADDSUBPSr213rY: NewFMAOpc = X86::VFMADDSUBPSr231rY; break;
21782         case X86::VFMSUBADDPDr213rY: NewFMAOpc = X86::VFMSUBADDPDr231rY; break;
21783         case X86::VFMSUBADDPSr213rY: NewFMAOpc = X86::VFMSUBADDPSr231rY; break;
21784         default: llvm_unreachable("Unrecognized FMA variant.");
21785       }
21786
21787       const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
21788       MachineInstrBuilder MIB =
21789         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
21790         .addOperand(MI->getOperand(0))
21791         .addOperand(MI->getOperand(3))
21792         .addOperand(MI->getOperand(2))
21793         .addOperand(MI->getOperand(1));
21794       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
21795       MI->eraseFromParent();
21796     }
21797   }
21798
21799   return MBB;
21800 }
21801
21802 MachineBasicBlock *
21803 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
21804                                                MachineBasicBlock *BB) const {
21805   switch (MI->getOpcode()) {
21806   default: llvm_unreachable("Unexpected instr type to insert");
21807   case X86::TAILJMPd64:
21808   case X86::TAILJMPr64:
21809   case X86::TAILJMPm64:
21810   case X86::TAILJMPd64_REX:
21811   case X86::TAILJMPr64_REX:
21812   case X86::TAILJMPm64_REX:
21813     llvm_unreachable("TAILJMP64 would not be touched here.");
21814   case X86::TCRETURNdi64:
21815   case X86::TCRETURNri64:
21816   case X86::TCRETURNmi64:
21817     return BB;
21818   case X86::WIN_ALLOCA:
21819     return EmitLoweredWinAlloca(MI, BB);
21820   case X86::CATCHRET:
21821     return EmitLoweredCatchRet(MI, BB);
21822   case X86::CATCHPAD:
21823     return EmitLoweredCatchPad(MI, BB);
21824   case X86::SEG_ALLOCA_32:
21825   case X86::SEG_ALLOCA_64:
21826     return EmitLoweredSegAlloca(MI, BB);
21827   case X86::TLSCall_32:
21828   case X86::TLSCall_64:
21829     return EmitLoweredTLSCall(MI, BB);
21830   case X86::CMOV_FR32:
21831   case X86::CMOV_FR64:
21832   case X86::CMOV_GR8:
21833   case X86::CMOV_GR16:
21834   case X86::CMOV_GR32:
21835   case X86::CMOV_RFP32:
21836   case X86::CMOV_RFP64:
21837   case X86::CMOV_RFP80:
21838   case X86::CMOV_V2F64:
21839   case X86::CMOV_V2I64:
21840   case X86::CMOV_V4F32:
21841   case X86::CMOV_V4F64:
21842   case X86::CMOV_V4I64:
21843   case X86::CMOV_V16F32:
21844   case X86::CMOV_V8F32:
21845   case X86::CMOV_V8F64:
21846   case X86::CMOV_V8I64:
21847   case X86::CMOV_V8I1:
21848   case X86::CMOV_V16I1:
21849   case X86::CMOV_V32I1:
21850   case X86::CMOV_V64I1:
21851     return EmitLoweredSelect(MI, BB);
21852
21853   case X86::RELEASE_FADD32mr:
21854   case X86::RELEASE_FADD64mr:
21855     return EmitLoweredAtomicFP(MI, BB);
21856
21857   case X86::FP32_TO_INT16_IN_MEM:
21858   case X86::FP32_TO_INT32_IN_MEM:
21859   case X86::FP32_TO_INT64_IN_MEM:
21860   case X86::FP64_TO_INT16_IN_MEM:
21861   case X86::FP64_TO_INT32_IN_MEM:
21862   case X86::FP64_TO_INT64_IN_MEM:
21863   case X86::FP80_TO_INT16_IN_MEM:
21864   case X86::FP80_TO_INT32_IN_MEM:
21865   case X86::FP80_TO_INT64_IN_MEM: {
21866     MachineFunction *F = BB->getParent();
21867     const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21868     DebugLoc DL = MI->getDebugLoc();
21869
21870     // Change the floating point control register to use "round towards zero"
21871     // mode when truncating to an integer value.
21872     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
21873     addFrameReference(BuildMI(*BB, MI, DL,
21874                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
21875
21876     // Load the old value of the high byte of the control word...
21877     unsigned OldCW =
21878       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
21879     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
21880                       CWFrameIdx);
21881
21882     // Set the high part to be round to zero...
21883     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
21884       .addImm(0xC7F);
21885
21886     // Reload the modified control word now...
21887     addFrameReference(BuildMI(*BB, MI, DL,
21888                               TII->get(X86::FLDCW16m)), CWFrameIdx);
21889
21890     // Restore the memory image of control word to original value
21891     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
21892       .addReg(OldCW);
21893
21894     // Get the X86 opcode to use.
21895     unsigned Opc;
21896     switch (MI->getOpcode()) {
21897     default: llvm_unreachable("illegal opcode!");
21898     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
21899     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
21900     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
21901     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
21902     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
21903     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
21904     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
21905     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
21906     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
21907     }
21908
21909     X86AddressMode AM;
21910     MachineOperand &Op = MI->getOperand(0);
21911     if (Op.isReg()) {
21912       AM.BaseType = X86AddressMode::RegBase;
21913       AM.Base.Reg = Op.getReg();
21914     } else {
21915       AM.BaseType = X86AddressMode::FrameIndexBase;
21916       AM.Base.FrameIndex = Op.getIndex();
21917     }
21918     Op = MI->getOperand(1);
21919     if (Op.isImm())
21920       AM.Scale = Op.getImm();
21921     Op = MI->getOperand(2);
21922     if (Op.isImm())
21923       AM.IndexReg = Op.getImm();
21924     Op = MI->getOperand(3);
21925     if (Op.isGlobal()) {
21926       AM.GV = Op.getGlobal();
21927     } else {
21928       AM.Disp = Op.getImm();
21929     }
21930     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
21931                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
21932
21933     // Reload the original control word now.
21934     addFrameReference(BuildMI(*BB, MI, DL,
21935                               TII->get(X86::FLDCW16m)), CWFrameIdx);
21936
21937     MI->eraseFromParent();   // The pseudo instruction is gone now.
21938     return BB;
21939   }
21940     // String/text processing lowering.
21941   case X86::PCMPISTRM128REG:
21942   case X86::VPCMPISTRM128REG:
21943   case X86::PCMPISTRM128MEM:
21944   case X86::VPCMPISTRM128MEM:
21945   case X86::PCMPESTRM128REG:
21946   case X86::VPCMPESTRM128REG:
21947   case X86::PCMPESTRM128MEM:
21948   case X86::VPCMPESTRM128MEM:
21949     assert(Subtarget->hasSSE42() &&
21950            "Target must have SSE4.2 or AVX features enabled");
21951     return EmitPCMPSTRM(MI, BB, Subtarget->getInstrInfo());
21952
21953   // String/text processing lowering.
21954   case X86::PCMPISTRIREG:
21955   case X86::VPCMPISTRIREG:
21956   case X86::PCMPISTRIMEM:
21957   case X86::VPCMPISTRIMEM:
21958   case X86::PCMPESTRIREG:
21959   case X86::VPCMPESTRIREG:
21960   case X86::PCMPESTRIMEM:
21961   case X86::VPCMPESTRIMEM:
21962     assert(Subtarget->hasSSE42() &&
21963            "Target must have SSE4.2 or AVX features enabled");
21964     return EmitPCMPSTRI(MI, BB, Subtarget->getInstrInfo());
21965
21966   // Thread synchronization.
21967   case X86::MONITOR:
21968     return EmitMonitor(MI, BB, Subtarget);
21969
21970   // xbegin
21971   case X86::XBEGIN:
21972     return EmitXBegin(MI, BB, Subtarget->getInstrInfo());
21973
21974   case X86::VASTART_SAVE_XMM_REGS:
21975     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
21976
21977   case X86::VAARG_64:
21978     return EmitVAARG64WithCustomInserter(MI, BB);
21979
21980   case X86::EH_SjLj_SetJmp32:
21981   case X86::EH_SjLj_SetJmp64:
21982     return emitEHSjLjSetJmp(MI, BB);
21983
21984   case X86::EH_SjLj_LongJmp32:
21985   case X86::EH_SjLj_LongJmp64:
21986     return emitEHSjLjLongJmp(MI, BB);
21987
21988   case TargetOpcode::STATEPOINT:
21989     // As an implementation detail, STATEPOINT shares the STACKMAP format at
21990     // this point in the process.  We diverge later.
21991     return emitPatchPoint(MI, BB);
21992
21993   case TargetOpcode::STACKMAP:
21994   case TargetOpcode::PATCHPOINT:
21995     return emitPatchPoint(MI, BB);
21996
21997   case X86::VFMADDPDr213r:
21998   case X86::VFMADDPSr213r:
21999   case X86::VFMADDSDr213r:
22000   case X86::VFMADDSSr213r:
22001   case X86::VFMSUBPDr213r:
22002   case X86::VFMSUBPSr213r:
22003   case X86::VFMSUBSDr213r:
22004   case X86::VFMSUBSSr213r:
22005   case X86::VFNMADDPDr213r:
22006   case X86::VFNMADDPSr213r:
22007   case X86::VFNMADDSDr213r:
22008   case X86::VFNMADDSSr213r:
22009   case X86::VFNMSUBPDr213r:
22010   case X86::VFNMSUBPSr213r:
22011   case X86::VFNMSUBSDr213r:
22012   case X86::VFNMSUBSSr213r:
22013   case X86::VFMADDSUBPDr213r:
22014   case X86::VFMADDSUBPSr213r:
22015   case X86::VFMSUBADDPDr213r:
22016   case X86::VFMSUBADDPSr213r:
22017   case X86::VFMADDPDr213rY:
22018   case X86::VFMADDPSr213rY:
22019   case X86::VFMSUBPDr213rY:
22020   case X86::VFMSUBPSr213rY:
22021   case X86::VFNMADDPDr213rY:
22022   case X86::VFNMADDPSr213rY:
22023   case X86::VFNMSUBPDr213rY:
22024   case X86::VFNMSUBPSr213rY:
22025   case X86::VFMADDSUBPDr213rY:
22026   case X86::VFMADDSUBPSr213rY:
22027   case X86::VFMSUBADDPDr213rY:
22028   case X86::VFMSUBADDPSr213rY:
22029     return emitFMA3Instr(MI, BB);
22030   }
22031 }
22032
22033 //===----------------------------------------------------------------------===//
22034 //                           X86 Optimization Hooks
22035 //===----------------------------------------------------------------------===//
22036
22037 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
22038                                                       APInt &KnownZero,
22039                                                       APInt &KnownOne,
22040                                                       const SelectionDAG &DAG,
22041                                                       unsigned Depth) const {
22042   unsigned BitWidth = KnownZero.getBitWidth();
22043   unsigned Opc = Op.getOpcode();
22044   assert((Opc >= ISD::BUILTIN_OP_END ||
22045           Opc == ISD::INTRINSIC_WO_CHAIN ||
22046           Opc == ISD::INTRINSIC_W_CHAIN ||
22047           Opc == ISD::INTRINSIC_VOID) &&
22048          "Should use MaskedValueIsZero if you don't know whether Op"
22049          " is a target node!");
22050
22051   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
22052   switch (Opc) {
22053   default: break;
22054   case X86ISD::ADD:
22055   case X86ISD::SUB:
22056   case X86ISD::ADC:
22057   case X86ISD::SBB:
22058   case X86ISD::SMUL:
22059   case X86ISD::UMUL:
22060   case X86ISD::INC:
22061   case X86ISD::DEC:
22062   case X86ISD::OR:
22063   case X86ISD::XOR:
22064   case X86ISD::AND:
22065     // These nodes' second result is a boolean.
22066     if (Op.getResNo() == 0)
22067       break;
22068     // Fallthrough
22069   case X86ISD::SETCC:
22070     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
22071     break;
22072   case ISD::INTRINSIC_WO_CHAIN: {
22073     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
22074     unsigned NumLoBits = 0;
22075     switch (IntId) {
22076     default: break;
22077     case Intrinsic::x86_sse_movmsk_ps:
22078     case Intrinsic::x86_avx_movmsk_ps_256:
22079     case Intrinsic::x86_sse2_movmsk_pd:
22080     case Intrinsic::x86_avx_movmsk_pd_256:
22081     case Intrinsic::x86_mmx_pmovmskb:
22082     case Intrinsic::x86_sse2_pmovmskb_128:
22083     case Intrinsic::x86_avx2_pmovmskb: {
22084       // High bits of movmskp{s|d}, pmovmskb are known zero.
22085       switch (IntId) {
22086         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
22087         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
22088         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
22089         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
22090         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
22091         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
22092         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
22093         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
22094       }
22095       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
22096       break;
22097     }
22098     }
22099     break;
22100   }
22101   }
22102 }
22103
22104 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
22105   SDValue Op,
22106   const SelectionDAG &,
22107   unsigned Depth) const {
22108   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
22109   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
22110     return Op.getValueType().getScalarSizeInBits();
22111
22112   // Fallback case.
22113   return 1;
22114 }
22115
22116 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
22117 /// node is a GlobalAddress + offset.
22118 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
22119                                        const GlobalValue* &GA,
22120                                        int64_t &Offset) const {
22121   if (N->getOpcode() == X86ISD::Wrapper) {
22122     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
22123       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
22124       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
22125       return true;
22126     }
22127   }
22128   return TargetLowering::isGAPlusOffset(N, GA, Offset);
22129 }
22130
22131 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
22132 /// same as extracting the high 128-bit part of 256-bit vector and then
22133 /// inserting the result into the low part of a new 256-bit vector
22134 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
22135   EVT VT = SVOp->getValueType(0);
22136   unsigned NumElems = VT.getVectorNumElements();
22137
22138   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
22139   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
22140     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
22141         SVOp->getMaskElt(j) >= 0)
22142       return false;
22143
22144   return true;
22145 }
22146
22147 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
22148 /// same as extracting the low 128-bit part of 256-bit vector and then
22149 /// inserting the result into the high part of a new 256-bit vector
22150 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
22151   EVT VT = SVOp->getValueType(0);
22152   unsigned NumElems = VT.getVectorNumElements();
22153
22154   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
22155   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
22156     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
22157         SVOp->getMaskElt(j) >= 0)
22158       return false;
22159
22160   return true;
22161 }
22162
22163 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
22164 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
22165                                         TargetLowering::DAGCombinerInfo &DCI,
22166                                         const X86Subtarget* Subtarget) {
22167   SDLoc dl(N);
22168   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
22169   SDValue V1 = SVOp->getOperand(0);
22170   SDValue V2 = SVOp->getOperand(1);
22171   EVT VT = SVOp->getValueType(0);
22172   unsigned NumElems = VT.getVectorNumElements();
22173
22174   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
22175       V2.getOpcode() == ISD::CONCAT_VECTORS) {
22176     //
22177     //                   0,0,0,...
22178     //                      |
22179     //    V      UNDEF    BUILD_VECTOR    UNDEF
22180     //     \      /           \           /
22181     //  CONCAT_VECTOR         CONCAT_VECTOR
22182     //         \                  /
22183     //          \                /
22184     //          RESULT: V + zero extended
22185     //
22186     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
22187         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
22188         V1.getOperand(1).getOpcode() != ISD::UNDEF)
22189       return SDValue();
22190
22191     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
22192       return SDValue();
22193
22194     // To match the shuffle mask, the first half of the mask should
22195     // be exactly the first vector, and all the rest a splat with the
22196     // first element of the second one.
22197     for (unsigned i = 0; i != NumElems/2; ++i)
22198       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
22199           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
22200         return SDValue();
22201
22202     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
22203     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
22204       if (Ld->hasNUsesOfValue(1, 0)) {
22205         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
22206         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
22207         SDValue ResNode =
22208           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
22209                                   Ld->getMemoryVT(),
22210                                   Ld->getPointerInfo(),
22211                                   Ld->getAlignment(),
22212                                   false/*isVolatile*/, true/*ReadMem*/,
22213                                   false/*WriteMem*/);
22214
22215         // Make sure the newly-created LOAD is in the same position as Ld in
22216         // terms of dependency. We create a TokenFactor for Ld and ResNode,
22217         // and update uses of Ld's output chain to use the TokenFactor.
22218         if (Ld->hasAnyUseOfValue(1)) {
22219           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
22220                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
22221           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
22222           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
22223                                  SDValue(ResNode.getNode(), 1));
22224         }
22225
22226         return DAG.getBitcast(VT, ResNode);
22227       }
22228     }
22229
22230     // Emit a zeroed vector and insert the desired subvector on its
22231     // first half.
22232     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
22233     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
22234     return DCI.CombineTo(N, InsV);
22235   }
22236
22237   //===--------------------------------------------------------------------===//
22238   // Combine some shuffles into subvector extracts and inserts:
22239   //
22240
22241   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
22242   if (isShuffleHigh128VectorInsertLow(SVOp)) {
22243     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
22244     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
22245     return DCI.CombineTo(N, InsV);
22246   }
22247
22248   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
22249   if (isShuffleLow128VectorInsertHigh(SVOp)) {
22250     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
22251     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
22252     return DCI.CombineTo(N, InsV);
22253   }
22254
22255   return SDValue();
22256 }
22257
22258 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
22259 /// possible.
22260 ///
22261 /// This is the leaf of the recursive combinine below. When we have found some
22262 /// chain of single-use x86 shuffle instructions and accumulated the combined
22263 /// shuffle mask represented by them, this will try to pattern match that mask
22264 /// into either a single instruction if there is a special purpose instruction
22265 /// for this operation, or into a PSHUFB instruction which is a fully general
22266 /// instruction but should only be used to replace chains over a certain depth.
22267 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
22268                                    int Depth, bool HasPSHUFB, SelectionDAG &DAG,
22269                                    TargetLowering::DAGCombinerInfo &DCI,
22270                                    const X86Subtarget *Subtarget) {
22271   assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
22272
22273   // Find the operand that enters the chain. Note that multiple uses are OK
22274   // here, we're not going to remove the operand we find.
22275   SDValue Input = Op.getOperand(0);
22276   while (Input.getOpcode() == ISD::BITCAST)
22277     Input = Input.getOperand(0);
22278
22279   MVT VT = Input.getSimpleValueType();
22280   MVT RootVT = Root.getSimpleValueType();
22281   SDLoc DL(Root);
22282
22283   if (Mask.size() == 1) {
22284     int Index = Mask[0];
22285     assert((Index >= 0 || Index == SM_SentinelUndef ||
22286             Index == SM_SentinelZero) &&
22287            "Invalid shuffle index found!");
22288
22289     // We may end up with an accumulated mask of size 1 as a result of
22290     // widening of shuffle operands (see function canWidenShuffleElements).
22291     // If the only shuffle index is equal to SM_SentinelZero then propagate
22292     // a zero vector. Otherwise, the combine shuffle mask is a no-op shuffle
22293     // mask, and therefore the entire chain of shuffles can be folded away.
22294     if (Index == SM_SentinelZero)
22295       DCI.CombineTo(Root.getNode(), getZeroVector(RootVT, Subtarget, DAG, DL));
22296     else
22297       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Input),
22298                     /*AddTo*/ true);
22299     return true;
22300   }
22301
22302   // Use the float domain if the operand type is a floating point type.
22303   bool FloatDomain = VT.isFloatingPoint();
22304
22305   // For floating point shuffles, we don't have free copies in the shuffle
22306   // instructions or the ability to load as part of the instruction, so
22307   // canonicalize their shuffles to UNPCK or MOV variants.
22308   //
22309   // Note that even with AVX we prefer the PSHUFD form of shuffle for integer
22310   // vectors because it can have a load folded into it that UNPCK cannot. This
22311   // doesn't preclude something switching to the shorter encoding post-RA.
22312   //
22313   // FIXME: Should teach these routines about AVX vector widths.
22314   if (FloatDomain && VT.is128BitVector()) {
22315     if (Mask.equals({0, 0}) || Mask.equals({1, 1})) {
22316       bool Lo = Mask.equals({0, 0});
22317       unsigned Shuffle;
22318       MVT ShuffleVT;
22319       // Check if we have SSE3 which will let us use MOVDDUP. That instruction
22320       // is no slower than UNPCKLPD but has the option to fold the input operand
22321       // into even an unaligned memory load.
22322       if (Lo && Subtarget->hasSSE3()) {
22323         Shuffle = X86ISD::MOVDDUP;
22324         ShuffleVT = MVT::v2f64;
22325       } else {
22326         // We have MOVLHPS and MOVHLPS throughout SSE and they encode smaller
22327         // than the UNPCK variants.
22328         Shuffle = Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS;
22329         ShuffleVT = MVT::v4f32;
22330       }
22331       if (Depth == 1 && Root->getOpcode() == Shuffle)
22332         return false; // Nothing to do!
22333       Op = DAG.getBitcast(ShuffleVT, Input);
22334       DCI.AddToWorklist(Op.getNode());
22335       if (Shuffle == X86ISD::MOVDDUP)
22336         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
22337       else
22338         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
22339       DCI.AddToWorklist(Op.getNode());
22340       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
22341                     /*AddTo*/ true);
22342       return true;
22343     }
22344     if (Subtarget->hasSSE3() &&
22345         (Mask.equals({0, 0, 2, 2}) || Mask.equals({1, 1, 3, 3}))) {
22346       bool Lo = Mask.equals({0, 0, 2, 2});
22347       unsigned Shuffle = Lo ? X86ISD::MOVSLDUP : X86ISD::MOVSHDUP;
22348       MVT ShuffleVT = MVT::v4f32;
22349       if (Depth == 1 && Root->getOpcode() == Shuffle)
22350         return false; // Nothing to do!
22351       Op = DAG.getBitcast(ShuffleVT, Input);
22352       DCI.AddToWorklist(Op.getNode());
22353       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
22354       DCI.AddToWorklist(Op.getNode());
22355       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
22356                     /*AddTo*/ true);
22357       return true;
22358     }
22359     if (Mask.equals({0, 0, 1, 1}) || Mask.equals({2, 2, 3, 3})) {
22360       bool Lo = Mask.equals({0, 0, 1, 1});
22361       unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
22362       MVT ShuffleVT = MVT::v4f32;
22363       if (Depth == 1 && Root->getOpcode() == Shuffle)
22364         return false; // Nothing to do!
22365       Op = DAG.getBitcast(ShuffleVT, Input);
22366       DCI.AddToWorklist(Op.getNode());
22367       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
22368       DCI.AddToWorklist(Op.getNode());
22369       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
22370                     /*AddTo*/ true);
22371       return true;
22372     }
22373   }
22374
22375   // We always canonicalize the 8 x i16 and 16 x i8 shuffles into their UNPCK
22376   // variants as none of these have single-instruction variants that are
22377   // superior to the UNPCK formulation.
22378   if (!FloatDomain && VT.is128BitVector() &&
22379       (Mask.equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
22380        Mask.equals({4, 4, 5, 5, 6, 6, 7, 7}) ||
22381        Mask.equals({0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7}) ||
22382        Mask.equals(
22383            {8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15}))) {
22384     bool Lo = Mask[0] == 0;
22385     unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
22386     if (Depth == 1 && Root->getOpcode() == Shuffle)
22387       return false; // Nothing to do!
22388     MVT ShuffleVT;
22389     switch (Mask.size()) {
22390     case 8:
22391       ShuffleVT = MVT::v8i16;
22392       break;
22393     case 16:
22394       ShuffleVT = MVT::v16i8;
22395       break;
22396     default:
22397       llvm_unreachable("Impossible mask size!");
22398     };
22399     Op = DAG.getBitcast(ShuffleVT, Input);
22400     DCI.AddToWorklist(Op.getNode());
22401     Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
22402     DCI.AddToWorklist(Op.getNode());
22403     DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
22404                   /*AddTo*/ true);
22405     return true;
22406   }
22407
22408   // Don't try to re-form single instruction chains under any circumstances now
22409   // that we've done encoding canonicalization for them.
22410   if (Depth < 2)
22411     return false;
22412
22413   // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
22414   // can replace them with a single PSHUFB instruction profitably. Intel's
22415   // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
22416   // in practice PSHUFB tends to be *very* fast so we're more aggressive.
22417   if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
22418     SmallVector<SDValue, 16> PSHUFBMask;
22419     int NumBytes = VT.getSizeInBits() / 8;
22420     int Ratio = NumBytes / Mask.size();
22421     for (int i = 0; i < NumBytes; ++i) {
22422       if (Mask[i / Ratio] == SM_SentinelUndef) {
22423         PSHUFBMask.push_back(DAG.getUNDEF(MVT::i8));
22424         continue;
22425       }
22426       int M = Mask[i / Ratio] != SM_SentinelZero
22427                   ? Ratio * Mask[i / Ratio] + i % Ratio
22428                   : 255;
22429       PSHUFBMask.push_back(DAG.getConstant(M, DL, MVT::i8));
22430     }
22431     MVT ByteVT = MVT::getVectorVT(MVT::i8, NumBytes);
22432     Op = DAG.getBitcast(ByteVT, Input);
22433     DCI.AddToWorklist(Op.getNode());
22434     SDValue PSHUFBMaskOp =
22435         DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVT, PSHUFBMask);
22436     DCI.AddToWorklist(PSHUFBMaskOp.getNode());
22437     Op = DAG.getNode(X86ISD::PSHUFB, DL, ByteVT, Op, PSHUFBMaskOp);
22438     DCI.AddToWorklist(Op.getNode());
22439     DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
22440                   /*AddTo*/ true);
22441     return true;
22442   }
22443
22444   // Failed to find any combines.
22445   return false;
22446 }
22447
22448 /// \brief Fully generic combining of x86 shuffle instructions.
22449 ///
22450 /// This should be the last combine run over the x86 shuffle instructions. Once
22451 /// they have been fully optimized, this will recursively consider all chains
22452 /// of single-use shuffle instructions, build a generic model of the cumulative
22453 /// shuffle operation, and check for simpler instructions which implement this
22454 /// operation. We use this primarily for two purposes:
22455 ///
22456 /// 1) Collapse generic shuffles to specialized single instructions when
22457 ///    equivalent. In most cases, this is just an encoding size win, but
22458 ///    sometimes we will collapse multiple generic shuffles into a single
22459 ///    special-purpose shuffle.
22460 /// 2) Look for sequences of shuffle instructions with 3 or more total
22461 ///    instructions, and replace them with the slightly more expensive SSSE3
22462 ///    PSHUFB instruction if available. We do this as the last combining step
22463 ///    to ensure we avoid using PSHUFB if we can implement the shuffle with
22464 ///    a suitable short sequence of other instructions. The PHUFB will either
22465 ///    use a register or have to read from memory and so is slightly (but only
22466 ///    slightly) more expensive than the other shuffle instructions.
22467 ///
22468 /// Because this is inherently a quadratic operation (for each shuffle in
22469 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
22470 /// This should never be an issue in practice as the shuffle lowering doesn't
22471 /// produce sequences of more than 8 instructions.
22472 ///
22473 /// FIXME: We will currently miss some cases where the redundant shuffling
22474 /// would simplify under the threshold for PSHUFB formation because of
22475 /// combine-ordering. To fix this, we should do the redundant instruction
22476 /// combining in this recursive walk.
22477 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
22478                                           ArrayRef<int> RootMask,
22479                                           int Depth, bool HasPSHUFB,
22480                                           SelectionDAG &DAG,
22481                                           TargetLowering::DAGCombinerInfo &DCI,
22482                                           const X86Subtarget *Subtarget) {
22483   // Bound the depth of our recursive combine because this is ultimately
22484   // quadratic in nature.
22485   if (Depth > 8)
22486     return false;
22487
22488   // Directly rip through bitcasts to find the underlying operand.
22489   while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
22490     Op = Op.getOperand(0);
22491
22492   MVT VT = Op.getSimpleValueType();
22493   if (!VT.isVector())
22494     return false; // Bail if we hit a non-vector.
22495
22496   assert(Root.getSimpleValueType().isVector() &&
22497          "Shuffles operate on vector types!");
22498   assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
22499          "Can only combine shuffles of the same vector register size.");
22500
22501   if (!isTargetShuffle(Op.getOpcode()))
22502     return false;
22503   SmallVector<int, 16> OpMask;
22504   bool IsUnary;
22505   bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, OpMask, IsUnary);
22506   // We only can combine unary shuffles which we can decode the mask for.
22507   if (!HaveMask || !IsUnary)
22508     return false;
22509
22510   assert(VT.getVectorNumElements() == OpMask.size() &&
22511          "Different mask size from vector size!");
22512   assert(((RootMask.size() > OpMask.size() &&
22513            RootMask.size() % OpMask.size() == 0) ||
22514           (OpMask.size() > RootMask.size() &&
22515            OpMask.size() % RootMask.size() == 0) ||
22516           OpMask.size() == RootMask.size()) &&
22517          "The smaller number of elements must divide the larger.");
22518   int RootRatio = std::max<int>(1, OpMask.size() / RootMask.size());
22519   int OpRatio = std::max<int>(1, RootMask.size() / OpMask.size());
22520   assert(((RootRatio == 1 && OpRatio == 1) ||
22521           (RootRatio == 1) != (OpRatio == 1)) &&
22522          "Must not have a ratio for both incoming and op masks!");
22523
22524   SmallVector<int, 16> Mask;
22525   Mask.reserve(std::max(OpMask.size(), RootMask.size()));
22526
22527   // Merge this shuffle operation's mask into our accumulated mask. Note that
22528   // this shuffle's mask will be the first applied to the input, followed by the
22529   // root mask to get us all the way to the root value arrangement. The reason
22530   // for this order is that we are recursing up the operation chain.
22531   for (int i = 0, e = std::max(OpMask.size(), RootMask.size()); i < e; ++i) {
22532     int RootIdx = i / RootRatio;
22533     if (RootMask[RootIdx] < 0) {
22534       // This is a zero or undef lane, we're done.
22535       Mask.push_back(RootMask[RootIdx]);
22536       continue;
22537     }
22538
22539     int RootMaskedIdx = RootMask[RootIdx] * RootRatio + i % RootRatio;
22540     int OpIdx = RootMaskedIdx / OpRatio;
22541     if (OpMask[OpIdx] < 0) {
22542       // The incoming lanes are zero or undef, it doesn't matter which ones we
22543       // are using.
22544       Mask.push_back(OpMask[OpIdx]);
22545       continue;
22546     }
22547
22548     // Ok, we have non-zero lanes, map them through.
22549     Mask.push_back(OpMask[OpIdx] * OpRatio +
22550                    RootMaskedIdx % OpRatio);
22551   }
22552
22553   // See if we can recurse into the operand to combine more things.
22554   switch (Op.getOpcode()) {
22555   case X86ISD::PSHUFB:
22556     HasPSHUFB = true;
22557   case X86ISD::PSHUFD:
22558   case X86ISD::PSHUFHW:
22559   case X86ISD::PSHUFLW:
22560     if (Op.getOperand(0).hasOneUse() &&
22561         combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
22562                                       HasPSHUFB, DAG, DCI, Subtarget))
22563       return true;
22564     break;
22565
22566   case X86ISD::UNPCKL:
22567   case X86ISD::UNPCKH:
22568     assert(Op.getOperand(0) == Op.getOperand(1) &&
22569            "We only combine unary shuffles!");
22570     // We can't check for single use, we have to check that this shuffle is the
22571     // only user.
22572     if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
22573         combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
22574                                       HasPSHUFB, DAG, DCI, Subtarget))
22575       return true;
22576     break;
22577   }
22578
22579   // Minor canonicalization of the accumulated shuffle mask to make it easier
22580   // to match below. All this does is detect masks with squential pairs of
22581   // elements, and shrink them to the half-width mask. It does this in a loop
22582   // so it will reduce the size of the mask to the minimal width mask which
22583   // performs an equivalent shuffle.
22584   SmallVector<int, 16> WidenedMask;
22585   while (Mask.size() > 1 && canWidenShuffleElements(Mask, WidenedMask)) {
22586     Mask = std::move(WidenedMask);
22587     WidenedMask.clear();
22588   }
22589
22590   return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
22591                                 Subtarget);
22592 }
22593
22594 /// \brief Get the PSHUF-style mask from PSHUF node.
22595 ///
22596 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
22597 /// PSHUF-style masks that can be reused with such instructions.
22598 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
22599   MVT VT = N.getSimpleValueType();
22600   SmallVector<int, 4> Mask;
22601   bool IsUnary;
22602   bool HaveMask = getTargetShuffleMask(N.getNode(), VT, Mask, IsUnary);
22603   (void)HaveMask;
22604   assert(HaveMask);
22605
22606   // If we have more than 128-bits, only the low 128-bits of shuffle mask
22607   // matter. Check that the upper masks are repeats and remove them.
22608   if (VT.getSizeInBits() > 128) {
22609     int LaneElts = 128 / VT.getScalarSizeInBits();
22610 #ifndef NDEBUG
22611     for (int i = 1, NumLanes = VT.getSizeInBits() / 128; i < NumLanes; ++i)
22612       for (int j = 0; j < LaneElts; ++j)
22613         assert(Mask[j] == Mask[i * LaneElts + j] - (LaneElts * i) &&
22614                "Mask doesn't repeat in high 128-bit lanes!");
22615 #endif
22616     Mask.resize(LaneElts);
22617   }
22618
22619   switch (N.getOpcode()) {
22620   case X86ISD::PSHUFD:
22621     return Mask;
22622   case X86ISD::PSHUFLW:
22623     Mask.resize(4);
22624     return Mask;
22625   case X86ISD::PSHUFHW:
22626     Mask.erase(Mask.begin(), Mask.begin() + 4);
22627     for (int &M : Mask)
22628       M -= 4;
22629     return Mask;
22630   default:
22631     llvm_unreachable("No valid shuffle instruction found!");
22632   }
22633 }
22634
22635 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
22636 ///
22637 /// We walk up the chain and look for a combinable shuffle, skipping over
22638 /// shuffles that we could hoist this shuffle's transformation past without
22639 /// altering anything.
22640 static SDValue
22641 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
22642                              SelectionDAG &DAG,
22643                              TargetLowering::DAGCombinerInfo &DCI) {
22644   assert(N.getOpcode() == X86ISD::PSHUFD &&
22645          "Called with something other than an x86 128-bit half shuffle!");
22646   SDLoc DL(N);
22647
22648   // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
22649   // of the shuffles in the chain so that we can form a fresh chain to replace
22650   // this one.
22651   SmallVector<SDValue, 8> Chain;
22652   SDValue V = N.getOperand(0);
22653   for (; V.hasOneUse(); V = V.getOperand(0)) {
22654     switch (V.getOpcode()) {
22655     default:
22656       return SDValue(); // Nothing combined!
22657
22658     case ISD::BITCAST:
22659       // Skip bitcasts as we always know the type for the target specific
22660       // instructions.
22661       continue;
22662
22663     case X86ISD::PSHUFD:
22664       // Found another dword shuffle.
22665       break;
22666
22667     case X86ISD::PSHUFLW:
22668       // Check that the low words (being shuffled) are the identity in the
22669       // dword shuffle, and the high words are self-contained.
22670       if (Mask[0] != 0 || Mask[1] != 1 ||
22671           !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
22672         return SDValue();
22673
22674       Chain.push_back(V);
22675       continue;
22676
22677     case X86ISD::PSHUFHW:
22678       // Check that the high words (being shuffled) are the identity in the
22679       // dword shuffle, and the low words are self-contained.
22680       if (Mask[2] != 2 || Mask[3] != 3 ||
22681           !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
22682         return SDValue();
22683
22684       Chain.push_back(V);
22685       continue;
22686
22687     case X86ISD::UNPCKL:
22688     case X86ISD::UNPCKH:
22689       // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
22690       // shuffle into a preceding word shuffle.
22691       if (V.getSimpleValueType().getVectorElementType() != MVT::i8 &&
22692           V.getSimpleValueType().getVectorElementType() != MVT::i16)
22693         return SDValue();
22694
22695       // Search for a half-shuffle which we can combine with.
22696       unsigned CombineOp =
22697           V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
22698       if (V.getOperand(0) != V.getOperand(1) ||
22699           !V->isOnlyUserOf(V.getOperand(0).getNode()))
22700         return SDValue();
22701       Chain.push_back(V);
22702       V = V.getOperand(0);
22703       do {
22704         switch (V.getOpcode()) {
22705         default:
22706           return SDValue(); // Nothing to combine.
22707
22708         case X86ISD::PSHUFLW:
22709         case X86ISD::PSHUFHW:
22710           if (V.getOpcode() == CombineOp)
22711             break;
22712
22713           Chain.push_back(V);
22714
22715           // Fallthrough!
22716         case ISD::BITCAST:
22717           V = V.getOperand(0);
22718           continue;
22719         }
22720         break;
22721       } while (V.hasOneUse());
22722       break;
22723     }
22724     // Break out of the loop if we break out of the switch.
22725     break;
22726   }
22727
22728   if (!V.hasOneUse())
22729     // We fell out of the loop without finding a viable combining instruction.
22730     return SDValue();
22731
22732   // Merge this node's mask and our incoming mask.
22733   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
22734   for (int &M : Mask)
22735     M = VMask[M];
22736   V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
22737                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
22738
22739   // Rebuild the chain around this new shuffle.
22740   while (!Chain.empty()) {
22741     SDValue W = Chain.pop_back_val();
22742
22743     if (V.getValueType() != W.getOperand(0).getValueType())
22744       V = DAG.getBitcast(W.getOperand(0).getValueType(), V);
22745
22746     switch (W.getOpcode()) {
22747     default:
22748       llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
22749
22750     case X86ISD::UNPCKL:
22751     case X86ISD::UNPCKH:
22752       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
22753       break;
22754
22755     case X86ISD::PSHUFD:
22756     case X86ISD::PSHUFLW:
22757     case X86ISD::PSHUFHW:
22758       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
22759       break;
22760     }
22761   }
22762   if (V.getValueType() != N.getValueType())
22763     V = DAG.getBitcast(N.getValueType(), V);
22764
22765   // Return the new chain to replace N.
22766   return V;
22767 }
22768
22769 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or
22770 /// pshufhw.
22771 ///
22772 /// We walk up the chain, skipping shuffles of the other half and looking
22773 /// through shuffles which switch halves trying to find a shuffle of the same
22774 /// pair of dwords.
22775 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
22776                                         SelectionDAG &DAG,
22777                                         TargetLowering::DAGCombinerInfo &DCI) {
22778   assert(
22779       (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
22780       "Called with something other than an x86 128-bit half shuffle!");
22781   SDLoc DL(N);
22782   unsigned CombineOpcode = N.getOpcode();
22783
22784   // Walk up a single-use chain looking for a combinable shuffle.
22785   SDValue V = N.getOperand(0);
22786   for (; V.hasOneUse(); V = V.getOperand(0)) {
22787     switch (V.getOpcode()) {
22788     default:
22789       return false; // Nothing combined!
22790
22791     case ISD::BITCAST:
22792       // Skip bitcasts as we always know the type for the target specific
22793       // instructions.
22794       continue;
22795
22796     case X86ISD::PSHUFLW:
22797     case X86ISD::PSHUFHW:
22798       if (V.getOpcode() == CombineOpcode)
22799         break;
22800
22801       // Other-half shuffles are no-ops.
22802       continue;
22803     }
22804     // Break out of the loop if we break out of the switch.
22805     break;
22806   }
22807
22808   if (!V.hasOneUse())
22809     // We fell out of the loop without finding a viable combining instruction.
22810     return false;
22811
22812   // Combine away the bottom node as its shuffle will be accumulated into
22813   // a preceding shuffle.
22814   DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
22815
22816   // Record the old value.
22817   SDValue Old = V;
22818
22819   // Merge this node's mask and our incoming mask (adjusted to account for all
22820   // the pshufd instructions encountered).
22821   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
22822   for (int &M : Mask)
22823     M = VMask[M];
22824   V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
22825                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
22826
22827   // Check that the shuffles didn't cancel each other out. If not, we need to
22828   // combine to the new one.
22829   if (Old != V)
22830     // Replace the combinable shuffle with the combined one, updating all users
22831     // so that we re-evaluate the chain here.
22832     DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
22833
22834   return true;
22835 }
22836
22837 /// \brief Try to combine x86 target specific shuffles.
22838 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
22839                                            TargetLowering::DAGCombinerInfo &DCI,
22840                                            const X86Subtarget *Subtarget) {
22841   SDLoc DL(N);
22842   MVT VT = N.getSimpleValueType();
22843   SmallVector<int, 4> Mask;
22844
22845   switch (N.getOpcode()) {
22846   case X86ISD::PSHUFD:
22847   case X86ISD::PSHUFLW:
22848   case X86ISD::PSHUFHW:
22849     Mask = getPSHUFShuffleMask(N);
22850     assert(Mask.size() == 4);
22851     break;
22852   default:
22853     return SDValue();
22854   }
22855
22856   // Nuke no-op shuffles that show up after combining.
22857   if (isNoopShuffleMask(Mask))
22858     return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
22859
22860   // Look for simplifications involving one or two shuffle instructions.
22861   SDValue V = N.getOperand(0);
22862   switch (N.getOpcode()) {
22863   default:
22864     break;
22865   case X86ISD::PSHUFLW:
22866   case X86ISD::PSHUFHW:
22867     assert(VT.getVectorElementType() == MVT::i16 && "Bad word shuffle type!");
22868
22869     if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
22870       return SDValue(); // We combined away this shuffle, so we're done.
22871
22872     // See if this reduces to a PSHUFD which is no more expensive and can
22873     // combine with more operations. Note that it has to at least flip the
22874     // dwords as otherwise it would have been removed as a no-op.
22875     if (makeArrayRef(Mask).equals({2, 3, 0, 1})) {
22876       int DMask[] = {0, 1, 2, 3};
22877       int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
22878       DMask[DOffset + 0] = DOffset + 1;
22879       DMask[DOffset + 1] = DOffset + 0;
22880       MVT DVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
22881       V = DAG.getBitcast(DVT, V);
22882       DCI.AddToWorklist(V.getNode());
22883       V = DAG.getNode(X86ISD::PSHUFD, DL, DVT, V,
22884                       getV4X86ShuffleImm8ForMask(DMask, DL, DAG));
22885       DCI.AddToWorklist(V.getNode());
22886       return DAG.getBitcast(VT, V);
22887     }
22888
22889     // Look for shuffle patterns which can be implemented as a single unpack.
22890     // FIXME: This doesn't handle the location of the PSHUFD generically, and
22891     // only works when we have a PSHUFD followed by two half-shuffles.
22892     if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
22893         (V.getOpcode() == X86ISD::PSHUFLW ||
22894          V.getOpcode() == X86ISD::PSHUFHW) &&
22895         V.getOpcode() != N.getOpcode() &&
22896         V.hasOneUse()) {
22897       SDValue D = V.getOperand(0);
22898       while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
22899         D = D.getOperand(0);
22900       if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
22901         SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
22902         SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
22903         int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
22904         int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
22905         int WordMask[8];
22906         for (int i = 0; i < 4; ++i) {
22907           WordMask[i + NOffset] = Mask[i] + NOffset;
22908           WordMask[i + VOffset] = VMask[i] + VOffset;
22909         }
22910         // Map the word mask through the DWord mask.
22911         int MappedMask[8];
22912         for (int i = 0; i < 8; ++i)
22913           MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
22914         if (makeArrayRef(MappedMask).equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
22915             makeArrayRef(MappedMask).equals({4, 4, 5, 5, 6, 6, 7, 7})) {
22916           // We can replace all three shuffles with an unpack.
22917           V = DAG.getBitcast(VT, D.getOperand(0));
22918           DCI.AddToWorklist(V.getNode());
22919           return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
22920                                                 : X86ISD::UNPCKH,
22921                              DL, VT, V, V);
22922         }
22923       }
22924     }
22925
22926     break;
22927
22928   case X86ISD::PSHUFD:
22929     if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG, DCI))
22930       return NewN;
22931
22932     break;
22933   }
22934
22935   return SDValue();
22936 }
22937
22938 /// \brief Try to combine a shuffle into a target-specific add-sub node.
22939 ///
22940 /// We combine this directly on the abstract vector shuffle nodes so it is
22941 /// easier to generically match. We also insert dummy vector shuffle nodes for
22942 /// the operands which explicitly discard the lanes which are unused by this
22943 /// operation to try to flow through the rest of the combiner the fact that
22944 /// they're unused.
22945 static SDValue combineShuffleToAddSub(SDNode *N, SelectionDAG &DAG) {
22946   SDLoc DL(N);
22947   EVT VT = N->getValueType(0);
22948
22949   // We only handle target-independent shuffles.
22950   // FIXME: It would be easy and harmless to use the target shuffle mask
22951   // extraction tool to support more.
22952   if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
22953     return SDValue();
22954
22955   auto *SVN = cast<ShuffleVectorSDNode>(N);
22956   ArrayRef<int> Mask = SVN->getMask();
22957   SDValue V1 = N->getOperand(0);
22958   SDValue V2 = N->getOperand(1);
22959
22960   // We require the first shuffle operand to be the SUB node, and the second to
22961   // be the ADD node.
22962   // FIXME: We should support the commuted patterns.
22963   if (V1->getOpcode() != ISD::FSUB || V2->getOpcode() != ISD::FADD)
22964     return SDValue();
22965
22966   // If there are other uses of these operations we can't fold them.
22967   if (!V1->hasOneUse() || !V2->hasOneUse())
22968     return SDValue();
22969
22970   // Ensure that both operations have the same operands. Note that we can
22971   // commute the FADD operands.
22972   SDValue LHS = V1->getOperand(0), RHS = V1->getOperand(1);
22973   if ((V2->getOperand(0) != LHS || V2->getOperand(1) != RHS) &&
22974       (V2->getOperand(0) != RHS || V2->getOperand(1) != LHS))
22975     return SDValue();
22976
22977   // We're looking for blends between FADD and FSUB nodes. We insist on these
22978   // nodes being lined up in a specific expected pattern.
22979   if (!(isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
22980         isShuffleEquivalent(V1, V2, Mask, {0, 5, 2, 7}) ||
22981         isShuffleEquivalent(V1, V2, Mask, {0, 9, 2, 11, 4, 13, 6, 15})))
22982     return SDValue();
22983
22984   // Only specific types are legal at this point, assert so we notice if and
22985   // when these change.
22986   assert((VT == MVT::v4f32 || VT == MVT::v2f64 || VT == MVT::v8f32 ||
22987           VT == MVT::v4f64) &&
22988          "Unknown vector type encountered!");
22989
22990   return DAG.getNode(X86ISD::ADDSUB, DL, VT, LHS, RHS);
22991 }
22992
22993 /// PerformShuffleCombine - Performs several different shuffle combines.
22994 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
22995                                      TargetLowering::DAGCombinerInfo &DCI,
22996                                      const X86Subtarget *Subtarget) {
22997   SDLoc dl(N);
22998   SDValue N0 = N->getOperand(0);
22999   SDValue N1 = N->getOperand(1);
23000   EVT VT = N->getValueType(0);
23001
23002   // Don't create instructions with illegal types after legalize types has run.
23003   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23004   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
23005     return SDValue();
23006
23007   // If we have legalized the vector types, look for blends of FADD and FSUB
23008   // nodes that we can fuse into an ADDSUB node.
23009   if (TLI.isTypeLegal(VT) && Subtarget->hasSSE3())
23010     if (SDValue AddSub = combineShuffleToAddSub(N, DAG))
23011       return AddSub;
23012
23013   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
23014   if (Subtarget->hasFp256() && VT.is256BitVector() &&
23015       N->getOpcode() == ISD::VECTOR_SHUFFLE)
23016     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
23017
23018   // During Type Legalization, when promoting illegal vector types,
23019   // the backend might introduce new shuffle dag nodes and bitcasts.
23020   //
23021   // This code performs the following transformation:
23022   // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
23023   //       (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
23024   //
23025   // We do this only if both the bitcast and the BINOP dag nodes have
23026   // one use. Also, perform this transformation only if the new binary
23027   // operation is legal. This is to avoid introducing dag nodes that
23028   // potentially need to be further expanded (or custom lowered) into a
23029   // less optimal sequence of dag nodes.
23030   if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
23031       N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
23032       N0.getOpcode() == ISD::BITCAST) {
23033     SDValue BC0 = N0.getOperand(0);
23034     EVT SVT = BC0.getValueType();
23035     unsigned Opcode = BC0.getOpcode();
23036     unsigned NumElts = VT.getVectorNumElements();
23037
23038     if (BC0.hasOneUse() && SVT.isVector() &&
23039         SVT.getVectorNumElements() * 2 == NumElts &&
23040         TLI.isOperationLegal(Opcode, VT)) {
23041       bool CanFold = false;
23042       switch (Opcode) {
23043       default : break;
23044       case ISD::ADD :
23045       case ISD::FADD :
23046       case ISD::SUB :
23047       case ISD::FSUB :
23048       case ISD::MUL :
23049       case ISD::FMUL :
23050         CanFold = true;
23051       }
23052
23053       unsigned SVTNumElts = SVT.getVectorNumElements();
23054       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
23055       for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
23056         CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
23057       for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
23058         CanFold = SVOp->getMaskElt(i) < 0;
23059
23060       if (CanFold) {
23061         SDValue BC00 = DAG.getBitcast(VT, BC0.getOperand(0));
23062         SDValue BC01 = DAG.getBitcast(VT, BC0.getOperand(1));
23063         SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
23064         return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
23065       }
23066     }
23067   }
23068
23069   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
23070   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
23071   // consecutive, non-overlapping, and in the right order.
23072   SmallVector<SDValue, 16> Elts;
23073   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
23074     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
23075
23076   if (SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true))
23077     return LD;
23078
23079   if (isTargetShuffle(N->getOpcode())) {
23080     SDValue Shuffle =
23081         PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
23082     if (Shuffle.getNode())
23083       return Shuffle;
23084
23085     // Try recursively combining arbitrary sequences of x86 shuffle
23086     // instructions into higher-order shuffles. We do this after combining
23087     // specific PSHUF instruction sequences into their minimal form so that we
23088     // can evaluate how many specialized shuffle instructions are involved in
23089     // a particular chain.
23090     SmallVector<int, 1> NonceMask; // Just a placeholder.
23091     NonceMask.push_back(0);
23092     if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
23093                                       /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
23094                                       DCI, Subtarget))
23095       return SDValue(); // This routine will use CombineTo to replace N.
23096   }
23097
23098   return SDValue();
23099 }
23100
23101 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
23102 /// specific shuffle of a load can be folded into a single element load.
23103 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
23104 /// shuffles have been custom lowered so we need to handle those here.
23105 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
23106                                          TargetLowering::DAGCombinerInfo &DCI) {
23107   if (DCI.isBeforeLegalizeOps())
23108     return SDValue();
23109
23110   SDValue InVec = N->getOperand(0);
23111   SDValue EltNo = N->getOperand(1);
23112
23113   if (!isa<ConstantSDNode>(EltNo))
23114     return SDValue();
23115
23116   EVT OriginalVT = InVec.getValueType();
23117
23118   if (InVec.getOpcode() == ISD::BITCAST) {
23119     // Don't duplicate a load with other uses.
23120     if (!InVec.hasOneUse())
23121       return SDValue();
23122     EVT BCVT = InVec.getOperand(0).getValueType();
23123     if (!BCVT.isVector() ||
23124         BCVT.getVectorNumElements() != OriginalVT.getVectorNumElements())
23125       return SDValue();
23126     InVec = InVec.getOperand(0);
23127   }
23128
23129   EVT CurrentVT = InVec.getValueType();
23130
23131   if (!isTargetShuffle(InVec.getOpcode()))
23132     return SDValue();
23133
23134   // Don't duplicate a load with other uses.
23135   if (!InVec.hasOneUse())
23136     return SDValue();
23137
23138   SmallVector<int, 16> ShuffleMask;
23139   bool UnaryShuffle;
23140   if (!getTargetShuffleMask(InVec.getNode(), CurrentVT.getSimpleVT(),
23141                             ShuffleMask, UnaryShuffle))
23142     return SDValue();
23143
23144   // Select the input vector, guarding against out of range extract vector.
23145   unsigned NumElems = CurrentVT.getVectorNumElements();
23146   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
23147   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
23148   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
23149                                          : InVec.getOperand(1);
23150
23151   // If inputs to shuffle are the same for both ops, then allow 2 uses
23152   unsigned AllowedUses = InVec.getNumOperands() > 1 &&
23153                          InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
23154
23155   if (LdNode.getOpcode() == ISD::BITCAST) {
23156     // Don't duplicate a load with other uses.
23157     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
23158       return SDValue();
23159
23160     AllowedUses = 1; // only allow 1 load use if we have a bitcast
23161     LdNode = LdNode.getOperand(0);
23162   }
23163
23164   if (!ISD::isNormalLoad(LdNode.getNode()))
23165     return SDValue();
23166
23167   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
23168
23169   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
23170     return SDValue();
23171
23172   EVT EltVT = N->getValueType(0);
23173   // If there's a bitcast before the shuffle, check if the load type and
23174   // alignment is valid.
23175   unsigned Align = LN0->getAlignment();
23176   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23177   unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
23178       EltVT.getTypeForEVT(*DAG.getContext()));
23179
23180   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, EltVT))
23181     return SDValue();
23182
23183   // All checks match so transform back to vector_shuffle so that DAG combiner
23184   // can finish the job
23185   SDLoc dl(N);
23186
23187   // Create shuffle node taking into account the case that its a unary shuffle
23188   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(CurrentVT)
23189                                    : InVec.getOperand(1);
23190   Shuffle = DAG.getVectorShuffle(CurrentVT, dl,
23191                                  InVec.getOperand(0), Shuffle,
23192                                  &ShuffleMask[0]);
23193   Shuffle = DAG.getBitcast(OriginalVT, Shuffle);
23194   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
23195                      EltNo);
23196 }
23197
23198 static SDValue PerformBITCASTCombine(SDNode *N, SelectionDAG &DAG,
23199                                      const X86Subtarget *Subtarget) {
23200   SDValue N0 = N->getOperand(0);
23201   EVT VT = N->getValueType(0);
23202
23203   // Detect bitcasts between i32 to x86mmx low word. Since MMX types are
23204   // special and don't usually play with other vector types, it's better to
23205   // handle them early to be sure we emit efficient code by avoiding
23206   // store-load conversions.
23207   if (VT == MVT::x86mmx && N0.getOpcode() == ISD::BUILD_VECTOR &&
23208       N0.getValueType() == MVT::v2i32 &&
23209       isa<ConstantSDNode>(N0.getOperand(1))) {
23210     SDValue N00 = N0->getOperand(0);
23211     if (N0.getConstantOperandVal(1) == 0 && N00.getValueType() == MVT::i32)
23212       return DAG.getNode(X86ISD::MMX_MOVW2D, SDLoc(N00), VT, N00);
23213   }
23214
23215   // Convert a bitcasted integer logic operation that has one bitcasted
23216   // floating-point operand and one constant operand into a floating-point
23217   // logic operation. This may create a load of the constant, but that is
23218   // cheaper than materializing the constant in an integer register and
23219   // transferring it to an SSE register or transferring the SSE operand to
23220   // integer register and back.
23221   unsigned FPOpcode;
23222   switch (N0.getOpcode()) {
23223     case ISD::AND: FPOpcode = X86ISD::FAND; break;
23224     case ISD::OR:  FPOpcode = X86ISD::FOR;  break;
23225     case ISD::XOR: FPOpcode = X86ISD::FXOR; break;
23226     default: return SDValue();
23227   }
23228   if (((Subtarget->hasSSE1() && VT == MVT::f32) ||
23229        (Subtarget->hasSSE2() && VT == MVT::f64)) &&
23230       isa<ConstantSDNode>(N0.getOperand(1)) &&
23231       N0.getOperand(0).getOpcode() == ISD::BITCAST &&
23232       N0.getOperand(0).getOperand(0).getValueType() == VT) {
23233     SDValue N000 = N0.getOperand(0).getOperand(0);
23234     SDValue FPConst = DAG.getBitcast(VT, N0.getOperand(1));
23235     return DAG.getNode(FPOpcode, SDLoc(N0), VT, N000, FPConst);
23236   }
23237
23238   return SDValue();
23239 }
23240
23241 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
23242 /// generation and convert it from being a bunch of shuffles and extracts
23243 /// into a somewhat faster sequence. For i686, the best sequence is apparently
23244 /// storing the value and loading scalars back, while for x64 we should
23245 /// use 64-bit extracts and shifts.
23246 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
23247                                          TargetLowering::DAGCombinerInfo &DCI) {
23248   if (SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI))
23249     return NewOp;
23250
23251   SDValue InputVector = N->getOperand(0);
23252   SDLoc dl(InputVector);
23253   // Detect mmx to i32 conversion through a v2i32 elt extract.
23254   if (InputVector.getOpcode() == ISD::BITCAST && InputVector.hasOneUse() &&
23255       N->getValueType(0) == MVT::i32 &&
23256       InputVector.getValueType() == MVT::v2i32) {
23257
23258     // The bitcast source is a direct mmx result.
23259     SDValue MMXSrc = InputVector.getNode()->getOperand(0);
23260     if (MMXSrc.getValueType() == MVT::x86mmx)
23261       return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
23262                          N->getValueType(0),
23263                          InputVector.getNode()->getOperand(0));
23264
23265     // The mmx is indirect: (i64 extract_elt (v1i64 bitcast (x86mmx ...))).
23266     if (MMXSrc.getOpcode() == ISD::EXTRACT_VECTOR_ELT && MMXSrc.hasOneUse() &&
23267         MMXSrc.getValueType() == MVT::i64) {
23268       SDValue MMXSrcOp = MMXSrc.getOperand(0);
23269       if (MMXSrcOp.hasOneUse() && MMXSrcOp.getOpcode() == ISD::BITCAST &&
23270           MMXSrcOp.getValueType() == MVT::v1i64 &&
23271           MMXSrcOp.getOperand(0).getValueType() == MVT::x86mmx)
23272         return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
23273                            N->getValueType(0), MMXSrcOp.getOperand(0));
23274     }
23275   }
23276
23277   EVT VT = N->getValueType(0);
23278
23279   if (VT == MVT::i1 && isa<ConstantSDNode>(N->getOperand(1)) &&
23280       InputVector.getOpcode() == ISD::BITCAST &&
23281       isa<ConstantSDNode>(InputVector.getOperand(0))) {
23282     uint64_t ExtractedElt =
23283         cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
23284     uint64_t InputValue =
23285         cast<ConstantSDNode>(InputVector.getOperand(0))->getZExtValue();
23286     uint64_t Res = (InputValue >> ExtractedElt) & 1;
23287     return DAG.getConstant(Res, dl, MVT::i1);
23288   }
23289   // Only operate on vectors of 4 elements, where the alternative shuffling
23290   // gets to be more expensive.
23291   if (InputVector.getValueType() != MVT::v4i32)
23292     return SDValue();
23293
23294   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
23295   // single use which is a sign-extend or zero-extend, and all elements are
23296   // used.
23297   SmallVector<SDNode *, 4> Uses;
23298   unsigned ExtractedElements = 0;
23299   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
23300        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
23301     if (UI.getUse().getResNo() != InputVector.getResNo())
23302       return SDValue();
23303
23304     SDNode *Extract = *UI;
23305     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
23306       return SDValue();
23307
23308     if (Extract->getValueType(0) != MVT::i32)
23309       return SDValue();
23310     if (!Extract->hasOneUse())
23311       return SDValue();
23312     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
23313         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
23314       return SDValue();
23315     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
23316       return SDValue();
23317
23318     // Record which element was extracted.
23319     ExtractedElements |=
23320       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
23321
23322     Uses.push_back(Extract);
23323   }
23324
23325   // If not all the elements were used, this may not be worthwhile.
23326   if (ExtractedElements != 15)
23327     return SDValue();
23328
23329   // Ok, we've now decided to do the transformation.
23330   // If 64-bit shifts are legal, use the extract-shift sequence,
23331   // otherwise bounce the vector off the cache.
23332   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23333   SDValue Vals[4];
23334
23335   if (TLI.isOperationLegal(ISD::SRA, MVT::i64)) {
23336     SDValue Cst = DAG.getBitcast(MVT::v2i64, InputVector);
23337     auto &DL = DAG.getDataLayout();
23338     EVT VecIdxTy = DAG.getTargetLoweringInfo().getVectorIdxTy(DL);
23339     SDValue BottomHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
23340       DAG.getConstant(0, dl, VecIdxTy));
23341     SDValue TopHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
23342       DAG.getConstant(1, dl, VecIdxTy));
23343
23344     SDValue ShAmt = DAG.getConstant(
23345         32, dl, DAG.getTargetLoweringInfo().getShiftAmountTy(MVT::i64, DL));
23346     Vals[0] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BottomHalf);
23347     Vals[1] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
23348       DAG.getNode(ISD::SRA, dl, MVT::i64, BottomHalf, ShAmt));
23349     Vals[2] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, TopHalf);
23350     Vals[3] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
23351       DAG.getNode(ISD::SRA, dl, MVT::i64, TopHalf, ShAmt));
23352   } else {
23353     // Store the value to a temporary stack slot.
23354     SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
23355     SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
23356       MachinePointerInfo(), false, false, 0);
23357
23358     EVT ElementType = InputVector.getValueType().getVectorElementType();
23359     unsigned EltSize = ElementType.getSizeInBits() / 8;
23360
23361     // Replace each use (extract) with a load of the appropriate element.
23362     for (unsigned i = 0; i < 4; ++i) {
23363       uint64_t Offset = EltSize * i;
23364       auto PtrVT = TLI.getPointerTy(DAG.getDataLayout());
23365       SDValue OffsetVal = DAG.getConstant(Offset, dl, PtrVT);
23366
23367       SDValue ScalarAddr =
23368           DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, OffsetVal);
23369
23370       // Load the scalar.
23371       Vals[i] = DAG.getLoad(ElementType, dl, Ch,
23372                             ScalarAddr, MachinePointerInfo(),
23373                             false, false, false, 0);
23374
23375     }
23376   }
23377
23378   // Replace the extracts
23379   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
23380     UE = Uses.end(); UI != UE; ++UI) {
23381     SDNode *Extract = *UI;
23382
23383     SDValue Idx = Extract->getOperand(1);
23384     uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
23385     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), Vals[IdxVal]);
23386   }
23387
23388   // The replacement was made in place; don't return anything.
23389   return SDValue();
23390 }
23391
23392 static SDValue
23393 transformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
23394                                       const X86Subtarget *Subtarget) {
23395   SDLoc dl(N);
23396   SDValue Cond = N->getOperand(0);
23397   SDValue LHS = N->getOperand(1);
23398   SDValue RHS = N->getOperand(2);
23399
23400   if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
23401     SDValue CondSrc = Cond->getOperand(0);
23402     if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
23403       Cond = CondSrc->getOperand(0);
23404   }
23405
23406   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
23407     return SDValue();
23408
23409   // A vselect where all conditions and data are constants can be optimized into
23410   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
23411   if (ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
23412       ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
23413     return SDValue();
23414
23415   unsigned MaskValue = 0;
23416   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
23417     return SDValue();
23418
23419   MVT VT = N->getSimpleValueType(0);
23420   unsigned NumElems = VT.getVectorNumElements();
23421   SmallVector<int, 8> ShuffleMask(NumElems, -1);
23422   for (unsigned i = 0; i < NumElems; ++i) {
23423     // Be sure we emit undef where we can.
23424     if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
23425       ShuffleMask[i] = -1;
23426     else
23427       ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
23428   }
23429
23430   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23431   if (!TLI.isShuffleMaskLegal(ShuffleMask, VT))
23432     return SDValue();
23433   return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
23434 }
23435
23436 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
23437 /// nodes.
23438 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
23439                                     TargetLowering::DAGCombinerInfo &DCI,
23440                                     const X86Subtarget *Subtarget) {
23441   SDLoc DL(N);
23442   SDValue Cond = N->getOperand(0);
23443   // Get the LHS/RHS of the select.
23444   SDValue LHS = N->getOperand(1);
23445   SDValue RHS = N->getOperand(2);
23446   EVT VT = LHS.getValueType();
23447   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23448
23449   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
23450   // instructions match the semantics of the common C idiom x<y?x:y but not
23451   // x<=y?x:y, because of how they handle negative zero (which can be
23452   // ignored in unsafe-math mode).
23453   // We also try to create v2f32 min/max nodes, which we later widen to v4f32.
23454   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
23455       VT != MVT::f80 && (TLI.isTypeLegal(VT) || VT == MVT::v2f32) &&
23456       (Subtarget->hasSSE2() ||
23457        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
23458     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
23459
23460     unsigned Opcode = 0;
23461     // Check for x CC y ? x : y.
23462     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
23463         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
23464       switch (CC) {
23465       default: break;
23466       case ISD::SETULT:
23467         // Converting this to a min would handle NaNs incorrectly, and swapping
23468         // the operands would cause it to handle comparisons between positive
23469         // and negative zero incorrectly.
23470         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
23471           if (!DAG.getTarget().Options.UnsafeFPMath &&
23472               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
23473             break;
23474           std::swap(LHS, RHS);
23475         }
23476         Opcode = X86ISD::FMIN;
23477         break;
23478       case ISD::SETOLE:
23479         // Converting this to a min would handle comparisons between positive
23480         // and negative zero incorrectly.
23481         if (!DAG.getTarget().Options.UnsafeFPMath &&
23482             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
23483           break;
23484         Opcode = X86ISD::FMIN;
23485         break;
23486       case ISD::SETULE:
23487         // Converting this to a min would handle both negative zeros and NaNs
23488         // incorrectly, but we can swap the operands to fix both.
23489         std::swap(LHS, RHS);
23490       case ISD::SETOLT:
23491       case ISD::SETLT:
23492       case ISD::SETLE:
23493         Opcode = X86ISD::FMIN;
23494         break;
23495
23496       case ISD::SETOGE:
23497         // Converting this to a max would handle comparisons between positive
23498         // and negative zero incorrectly.
23499         if (!DAG.getTarget().Options.UnsafeFPMath &&
23500             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
23501           break;
23502         Opcode = X86ISD::FMAX;
23503         break;
23504       case ISD::SETUGT:
23505         // Converting this to a max would handle NaNs incorrectly, and swapping
23506         // the operands would cause it to handle comparisons between positive
23507         // and negative zero incorrectly.
23508         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
23509           if (!DAG.getTarget().Options.UnsafeFPMath &&
23510               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
23511             break;
23512           std::swap(LHS, RHS);
23513         }
23514         Opcode = X86ISD::FMAX;
23515         break;
23516       case ISD::SETUGE:
23517         // Converting this to a max would handle both negative zeros and NaNs
23518         // incorrectly, but we can swap the operands to fix both.
23519         std::swap(LHS, RHS);
23520       case ISD::SETOGT:
23521       case ISD::SETGT:
23522       case ISD::SETGE:
23523         Opcode = X86ISD::FMAX;
23524         break;
23525       }
23526     // Check for x CC y ? y : x -- a min/max with reversed arms.
23527     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
23528                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
23529       switch (CC) {
23530       default: break;
23531       case ISD::SETOGE:
23532         // Converting this to a min would handle comparisons between positive
23533         // and negative zero incorrectly, and swapping the operands would
23534         // cause it to handle NaNs incorrectly.
23535         if (!DAG.getTarget().Options.UnsafeFPMath &&
23536             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
23537           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
23538             break;
23539           std::swap(LHS, RHS);
23540         }
23541         Opcode = X86ISD::FMIN;
23542         break;
23543       case ISD::SETUGT:
23544         // Converting this to a min would handle NaNs incorrectly.
23545         if (!DAG.getTarget().Options.UnsafeFPMath &&
23546             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
23547           break;
23548         Opcode = X86ISD::FMIN;
23549         break;
23550       case ISD::SETUGE:
23551         // Converting this to a min would handle both negative zeros and NaNs
23552         // incorrectly, but we can swap the operands to fix both.
23553         std::swap(LHS, RHS);
23554       case ISD::SETOGT:
23555       case ISD::SETGT:
23556       case ISD::SETGE:
23557         Opcode = X86ISD::FMIN;
23558         break;
23559
23560       case ISD::SETULT:
23561         // Converting this to a max would handle NaNs incorrectly.
23562         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
23563           break;
23564         Opcode = X86ISD::FMAX;
23565         break;
23566       case ISD::SETOLE:
23567         // Converting this to a max would handle comparisons between positive
23568         // and negative zero incorrectly, and swapping the operands would
23569         // cause it to handle NaNs incorrectly.
23570         if (!DAG.getTarget().Options.UnsafeFPMath &&
23571             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
23572           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
23573             break;
23574           std::swap(LHS, RHS);
23575         }
23576         Opcode = X86ISD::FMAX;
23577         break;
23578       case ISD::SETULE:
23579         // Converting this to a max would handle both negative zeros and NaNs
23580         // incorrectly, but we can swap the operands to fix both.
23581         std::swap(LHS, RHS);
23582       case ISD::SETOLT:
23583       case ISD::SETLT:
23584       case ISD::SETLE:
23585         Opcode = X86ISD::FMAX;
23586         break;
23587       }
23588     }
23589
23590     if (Opcode)
23591       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
23592   }
23593
23594   EVT CondVT = Cond.getValueType();
23595   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
23596       CondVT.getVectorElementType() == MVT::i1) {
23597     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
23598     // lowering on KNL. In this case we convert it to
23599     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
23600     // The same situation for all 128 and 256-bit vectors of i8 and i16.
23601     // Since SKX these selects have a proper lowering.
23602     EVT OpVT = LHS.getValueType();
23603     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
23604         (OpVT.getVectorElementType() == MVT::i8 ||
23605          OpVT.getVectorElementType() == MVT::i16) &&
23606         !(Subtarget->hasBWI() && Subtarget->hasVLX())) {
23607       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
23608       DCI.AddToWorklist(Cond.getNode());
23609       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
23610     }
23611   }
23612   // If this is a select between two integer constants, try to do some
23613   // optimizations.
23614   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
23615     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
23616       // Don't do this for crazy integer types.
23617       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
23618         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
23619         // so that TrueC (the true value) is larger than FalseC.
23620         bool NeedsCondInvert = false;
23621
23622         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
23623             // Efficiently invertible.
23624             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
23625              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
23626               isa<ConstantSDNode>(Cond.getOperand(1))))) {
23627           NeedsCondInvert = true;
23628           std::swap(TrueC, FalseC);
23629         }
23630
23631         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
23632         if (FalseC->getAPIntValue() == 0 &&
23633             TrueC->getAPIntValue().isPowerOf2()) {
23634           if (NeedsCondInvert) // Invert the condition if needed.
23635             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
23636                                DAG.getConstant(1, DL, Cond.getValueType()));
23637
23638           // Zero extend the condition if needed.
23639           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
23640
23641           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
23642           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
23643                              DAG.getConstant(ShAmt, DL, MVT::i8));
23644         }
23645
23646         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
23647         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
23648           if (NeedsCondInvert) // Invert the condition if needed.
23649             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
23650                                DAG.getConstant(1, DL, Cond.getValueType()));
23651
23652           // Zero extend the condition if needed.
23653           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
23654                              FalseC->getValueType(0), Cond);
23655           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23656                              SDValue(FalseC, 0));
23657         }
23658
23659         // Optimize cases that will turn into an LEA instruction.  This requires
23660         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
23661         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
23662           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
23663           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
23664
23665           bool isFastMultiplier = false;
23666           if (Diff < 10) {
23667             switch ((unsigned char)Diff) {
23668               default: break;
23669               case 1:  // result = add base, cond
23670               case 2:  // result = lea base(    , cond*2)
23671               case 3:  // result = lea base(cond, cond*2)
23672               case 4:  // result = lea base(    , cond*4)
23673               case 5:  // result = lea base(cond, cond*4)
23674               case 8:  // result = lea base(    , cond*8)
23675               case 9:  // result = lea base(cond, cond*8)
23676                 isFastMultiplier = true;
23677                 break;
23678             }
23679           }
23680
23681           if (isFastMultiplier) {
23682             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
23683             if (NeedsCondInvert) // Invert the condition if needed.
23684               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
23685                                  DAG.getConstant(1, DL, Cond.getValueType()));
23686
23687             // Zero extend the condition if needed.
23688             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
23689                                Cond);
23690             // Scale the condition by the difference.
23691             if (Diff != 1)
23692               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
23693                                  DAG.getConstant(Diff, DL,
23694                                                  Cond.getValueType()));
23695
23696             // Add the base if non-zero.
23697             if (FalseC->getAPIntValue() != 0)
23698               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23699                                  SDValue(FalseC, 0));
23700             return Cond;
23701           }
23702         }
23703       }
23704   }
23705
23706   // Canonicalize max and min:
23707   // (x > y) ? x : y -> (x >= y) ? x : y
23708   // (x < y) ? x : y -> (x <= y) ? x : y
23709   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
23710   // the need for an extra compare
23711   // against zero. e.g.
23712   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
23713   // subl   %esi, %edi
23714   // testl  %edi, %edi
23715   // movl   $0, %eax
23716   // cmovgl %edi, %eax
23717   // =>
23718   // xorl   %eax, %eax
23719   // subl   %esi, $edi
23720   // cmovsl %eax, %edi
23721   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
23722       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
23723       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
23724     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
23725     switch (CC) {
23726     default: break;
23727     case ISD::SETLT:
23728     case ISD::SETGT: {
23729       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
23730       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
23731                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
23732       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
23733     }
23734     }
23735   }
23736
23737   // Early exit check
23738   if (!TLI.isTypeLegal(VT))
23739     return SDValue();
23740
23741   // Match VSELECTs into subs with unsigned saturation.
23742   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
23743       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
23744       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
23745        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
23746     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
23747
23748     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
23749     // left side invert the predicate to simplify logic below.
23750     SDValue Other;
23751     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
23752       Other = RHS;
23753       CC = ISD::getSetCCInverse(CC, true);
23754     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
23755       Other = LHS;
23756     }
23757
23758     if (Other.getNode() && Other->getNumOperands() == 2 &&
23759         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
23760       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
23761       SDValue CondRHS = Cond->getOperand(1);
23762
23763       // Look for a general sub with unsigned saturation first.
23764       // x >= y ? x-y : 0 --> subus x, y
23765       // x >  y ? x-y : 0 --> subus x, y
23766       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
23767           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
23768         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
23769
23770       if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
23771         if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
23772           if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
23773             if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
23774               // If the RHS is a constant we have to reverse the const
23775               // canonicalization.
23776               // x > C-1 ? x+-C : 0 --> subus x, C
23777               if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
23778                   CondRHSConst->getAPIntValue() ==
23779                       (-OpRHSConst->getAPIntValue() - 1))
23780                 return DAG.getNode(
23781                     X86ISD::SUBUS, DL, VT, OpLHS,
23782                     DAG.getConstant(-OpRHSConst->getAPIntValue(), DL, VT));
23783
23784           // Another special case: If C was a sign bit, the sub has been
23785           // canonicalized into a xor.
23786           // FIXME: Would it be better to use computeKnownBits to determine
23787           //        whether it's safe to decanonicalize the xor?
23788           // x s< 0 ? x^C : 0 --> subus x, C
23789           if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
23790               ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
23791               OpRHSConst->getAPIntValue().isSignBit())
23792             // Note that we have to rebuild the RHS constant here to ensure we
23793             // don't rely on particular values of undef lanes.
23794             return DAG.getNode(
23795                 X86ISD::SUBUS, DL, VT, OpLHS,
23796                 DAG.getConstant(OpRHSConst->getAPIntValue(), DL, VT));
23797         }
23798     }
23799   }
23800
23801   // Simplify vector selection if condition value type matches vselect
23802   // operand type
23803   if (N->getOpcode() == ISD::VSELECT && CondVT == VT) {
23804     assert(Cond.getValueType().isVector() &&
23805            "vector select expects a vector selector!");
23806
23807     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
23808     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
23809
23810     // Try invert the condition if true value is not all 1s and false value
23811     // is not all 0s.
23812     if (!TValIsAllOnes && !FValIsAllZeros &&
23813         // Check if the selector will be produced by CMPP*/PCMP*
23814         Cond.getOpcode() == ISD::SETCC &&
23815         // Check if SETCC has already been promoted
23816         TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT) ==
23817             CondVT) {
23818       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
23819       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
23820
23821       if (TValIsAllZeros || FValIsAllOnes) {
23822         SDValue CC = Cond.getOperand(2);
23823         ISD::CondCode NewCC =
23824           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
23825                                Cond.getOperand(0).getValueType().isInteger());
23826         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
23827         std::swap(LHS, RHS);
23828         TValIsAllOnes = FValIsAllOnes;
23829         FValIsAllZeros = TValIsAllZeros;
23830       }
23831     }
23832
23833     if (TValIsAllOnes || FValIsAllZeros) {
23834       SDValue Ret;
23835
23836       if (TValIsAllOnes && FValIsAllZeros)
23837         Ret = Cond;
23838       else if (TValIsAllOnes)
23839         Ret =
23840             DAG.getNode(ISD::OR, DL, CondVT, Cond, DAG.getBitcast(CondVT, RHS));
23841       else if (FValIsAllZeros)
23842         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
23843                           DAG.getBitcast(CondVT, LHS));
23844
23845       return DAG.getBitcast(VT, Ret);
23846     }
23847   }
23848
23849   // We should generate an X86ISD::BLENDI from a vselect if its argument
23850   // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
23851   // constants. This specific pattern gets generated when we split a
23852   // selector for a 512 bit vector in a machine without AVX512 (but with
23853   // 256-bit vectors), during legalization:
23854   //
23855   // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
23856   //
23857   // Iff we find this pattern and the build_vectors are built from
23858   // constants, we translate the vselect into a shuffle_vector that we
23859   // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
23860   if ((N->getOpcode() == ISD::VSELECT ||
23861        N->getOpcode() == X86ISD::SHRUNKBLEND) &&
23862       !DCI.isBeforeLegalize() && !VT.is512BitVector()) {
23863     SDValue Shuffle = transformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
23864     if (Shuffle.getNode())
23865       return Shuffle;
23866   }
23867
23868   // If this is a *dynamic* select (non-constant condition) and we can match
23869   // this node with one of the variable blend instructions, restructure the
23870   // condition so that the blends can use the high bit of each element and use
23871   // SimplifyDemandedBits to simplify the condition operand.
23872   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
23873       !DCI.isBeforeLegalize() &&
23874       !ISD::isBuildVectorOfConstantSDNodes(Cond.getNode())) {
23875     unsigned BitWidth = Cond.getValueType().getScalarSizeInBits();
23876
23877     // Don't optimize vector selects that map to mask-registers.
23878     if (BitWidth == 1)
23879       return SDValue();
23880
23881     // We can only handle the cases where VSELECT is directly legal on the
23882     // subtarget. We custom lower VSELECT nodes with constant conditions and
23883     // this makes it hard to see whether a dynamic VSELECT will correctly
23884     // lower, so we both check the operation's status and explicitly handle the
23885     // cases where a *dynamic* blend will fail even though a constant-condition
23886     // blend could be custom lowered.
23887     // FIXME: We should find a better way to handle this class of problems.
23888     // Potentially, we should combine constant-condition vselect nodes
23889     // pre-legalization into shuffles and not mark as many types as custom
23890     // lowered.
23891     if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
23892       return SDValue();
23893     // FIXME: We don't support i16-element blends currently. We could and
23894     // should support them by making *all* the bits in the condition be set
23895     // rather than just the high bit and using an i8-element blend.
23896     if (VT.getVectorElementType() == MVT::i16)
23897       return SDValue();
23898     // Dynamic blending was only available from SSE4.1 onward.
23899     if (VT.is128BitVector() && !Subtarget->hasSSE41())
23900       return SDValue();
23901     // Byte blends are only available in AVX2
23902     if (VT == MVT::v32i8 && !Subtarget->hasAVX2())
23903       return SDValue();
23904
23905     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
23906     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
23907
23908     APInt KnownZero, KnownOne;
23909     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
23910                                           DCI.isBeforeLegalizeOps());
23911     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
23912         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne,
23913                                  TLO)) {
23914       // If we changed the computation somewhere in the DAG, this change
23915       // will affect all users of Cond.
23916       // Make sure it is fine and update all the nodes so that we do not
23917       // use the generic VSELECT anymore. Otherwise, we may perform
23918       // wrong optimizations as we messed up with the actual expectation
23919       // for the vector boolean values.
23920       if (Cond != TLO.Old) {
23921         // Check all uses of that condition operand to check whether it will be
23922         // consumed by non-BLEND instructions, which may depend on all bits are
23923         // set properly.
23924         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
23925              I != E; ++I)
23926           if (I->getOpcode() != ISD::VSELECT)
23927             // TODO: Add other opcodes eventually lowered into BLEND.
23928             return SDValue();
23929
23930         // Update all the users of the condition, before committing the change,
23931         // so that the VSELECT optimizations that expect the correct vector
23932         // boolean value will not be triggered.
23933         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
23934              I != E; ++I)
23935           DAG.ReplaceAllUsesOfValueWith(
23936               SDValue(*I, 0),
23937               DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(*I), I->getValueType(0),
23938                           Cond, I->getOperand(1), I->getOperand(2)));
23939         DCI.CommitTargetLoweringOpt(TLO);
23940         return SDValue();
23941       }
23942       // At this point, only Cond is changed. Change the condition
23943       // just for N to keep the opportunity to optimize all other
23944       // users their own way.
23945       DAG.ReplaceAllUsesOfValueWith(
23946           SDValue(N, 0),
23947           DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(N), N->getValueType(0),
23948                       TLO.New, N->getOperand(1), N->getOperand(2)));
23949       return SDValue();
23950     }
23951   }
23952
23953   return SDValue();
23954 }
23955
23956 // Check whether a boolean test is testing a boolean value generated by
23957 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
23958 // code.
23959 //
23960 // Simplify the following patterns:
23961 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
23962 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
23963 // to (Op EFLAGS Cond)
23964 //
23965 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
23966 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
23967 // to (Op EFLAGS !Cond)
23968 //
23969 // where Op could be BRCOND or CMOV.
23970 //
23971 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
23972   // Quit if not CMP and SUB with its value result used.
23973   if (Cmp.getOpcode() != X86ISD::CMP &&
23974       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
23975       return SDValue();
23976
23977   // Quit if not used as a boolean value.
23978   if (CC != X86::COND_E && CC != X86::COND_NE)
23979     return SDValue();
23980
23981   // Check CMP operands. One of them should be 0 or 1 and the other should be
23982   // an SetCC or extended from it.
23983   SDValue Op1 = Cmp.getOperand(0);
23984   SDValue Op2 = Cmp.getOperand(1);
23985
23986   SDValue SetCC;
23987   const ConstantSDNode* C = nullptr;
23988   bool needOppositeCond = (CC == X86::COND_E);
23989   bool checkAgainstTrue = false; // Is it a comparison against 1?
23990
23991   if ((C = dyn_cast<ConstantSDNode>(Op1)))
23992     SetCC = Op2;
23993   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
23994     SetCC = Op1;
23995   else // Quit if all operands are not constants.
23996     return SDValue();
23997
23998   if (C->getZExtValue() == 1) {
23999     needOppositeCond = !needOppositeCond;
24000     checkAgainstTrue = true;
24001   } else if (C->getZExtValue() != 0)
24002     // Quit if the constant is neither 0 or 1.
24003     return SDValue();
24004
24005   bool truncatedToBoolWithAnd = false;
24006   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
24007   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
24008          SetCC.getOpcode() == ISD::TRUNCATE ||
24009          SetCC.getOpcode() == ISD::AND) {
24010     if (SetCC.getOpcode() == ISD::AND) {
24011       int OpIdx = -1;
24012       ConstantSDNode *CS;
24013       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
24014           CS->getZExtValue() == 1)
24015         OpIdx = 1;
24016       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
24017           CS->getZExtValue() == 1)
24018         OpIdx = 0;
24019       if (OpIdx == -1)
24020         break;
24021       SetCC = SetCC.getOperand(OpIdx);
24022       truncatedToBoolWithAnd = true;
24023     } else
24024       SetCC = SetCC.getOperand(0);
24025   }
24026
24027   switch (SetCC.getOpcode()) {
24028   case X86ISD::SETCC_CARRY:
24029     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
24030     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
24031     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
24032     // truncated to i1 using 'and'.
24033     if (checkAgainstTrue && !truncatedToBoolWithAnd)
24034       break;
24035     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
24036            "Invalid use of SETCC_CARRY!");
24037     // FALL THROUGH
24038   case X86ISD::SETCC:
24039     // Set the condition code or opposite one if necessary.
24040     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
24041     if (needOppositeCond)
24042       CC = X86::GetOppositeBranchCondition(CC);
24043     return SetCC.getOperand(1);
24044   case X86ISD::CMOV: {
24045     // Check whether false/true value has canonical one, i.e. 0 or 1.
24046     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
24047     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
24048     // Quit if true value is not a constant.
24049     if (!TVal)
24050       return SDValue();
24051     // Quit if false value is not a constant.
24052     if (!FVal) {
24053       SDValue Op = SetCC.getOperand(0);
24054       // Skip 'zext' or 'trunc' node.
24055       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
24056           Op.getOpcode() == ISD::TRUNCATE)
24057         Op = Op.getOperand(0);
24058       // A special case for rdrand/rdseed, where 0 is set if false cond is
24059       // found.
24060       if ((Op.getOpcode() != X86ISD::RDRAND &&
24061            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
24062         return SDValue();
24063     }
24064     // Quit if false value is not the constant 0 or 1.
24065     bool FValIsFalse = true;
24066     if (FVal && FVal->getZExtValue() != 0) {
24067       if (FVal->getZExtValue() != 1)
24068         return SDValue();
24069       // If FVal is 1, opposite cond is needed.
24070       needOppositeCond = !needOppositeCond;
24071       FValIsFalse = false;
24072     }
24073     // Quit if TVal is not the constant opposite of FVal.
24074     if (FValIsFalse && TVal->getZExtValue() != 1)
24075       return SDValue();
24076     if (!FValIsFalse && TVal->getZExtValue() != 0)
24077       return SDValue();
24078     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
24079     if (needOppositeCond)
24080       CC = X86::GetOppositeBranchCondition(CC);
24081     return SetCC.getOperand(3);
24082   }
24083   }
24084
24085   return SDValue();
24086 }
24087
24088 /// Check whether Cond is an AND/OR of SETCCs off of the same EFLAGS.
24089 /// Match:
24090 ///   (X86or (X86setcc) (X86setcc))
24091 ///   (X86cmp (and (X86setcc) (X86setcc)), 0)
24092 static bool checkBoolTestAndOrSetCCCombine(SDValue Cond, X86::CondCode &CC0,
24093                                            X86::CondCode &CC1, SDValue &Flags,
24094                                            bool &isAnd) {
24095   if (Cond->getOpcode() == X86ISD::CMP) {
24096     ConstantSDNode *CondOp1C = dyn_cast<ConstantSDNode>(Cond->getOperand(1));
24097     if (!CondOp1C || !CondOp1C->isNullValue())
24098       return false;
24099
24100     Cond = Cond->getOperand(0);
24101   }
24102
24103   isAnd = false;
24104
24105   SDValue SetCC0, SetCC1;
24106   switch (Cond->getOpcode()) {
24107   default: return false;
24108   case ISD::AND:
24109   case X86ISD::AND:
24110     isAnd = true;
24111     // fallthru
24112   case ISD::OR:
24113   case X86ISD::OR:
24114     SetCC0 = Cond->getOperand(0);
24115     SetCC1 = Cond->getOperand(1);
24116     break;
24117   };
24118
24119   // Make sure we have SETCC nodes, using the same flags value.
24120   if (SetCC0.getOpcode() != X86ISD::SETCC ||
24121       SetCC1.getOpcode() != X86ISD::SETCC ||
24122       SetCC0->getOperand(1) != SetCC1->getOperand(1))
24123     return false;
24124
24125   CC0 = (X86::CondCode)SetCC0->getConstantOperandVal(0);
24126   CC1 = (X86::CondCode)SetCC1->getConstantOperandVal(0);
24127   Flags = SetCC0->getOperand(1);
24128   return true;
24129 }
24130
24131 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
24132 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
24133                                   TargetLowering::DAGCombinerInfo &DCI,
24134                                   const X86Subtarget *Subtarget) {
24135   SDLoc DL(N);
24136
24137   // If the flag operand isn't dead, don't touch this CMOV.
24138   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
24139     return SDValue();
24140
24141   SDValue FalseOp = N->getOperand(0);
24142   SDValue TrueOp = N->getOperand(1);
24143   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
24144   SDValue Cond = N->getOperand(3);
24145
24146   if (CC == X86::COND_E || CC == X86::COND_NE) {
24147     switch (Cond.getOpcode()) {
24148     default: break;
24149     case X86ISD::BSR:
24150     case X86ISD::BSF:
24151       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
24152       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
24153         return (CC == X86::COND_E) ? FalseOp : TrueOp;
24154     }
24155   }
24156
24157   SDValue Flags;
24158
24159   Flags = checkBoolTestSetCCCombine(Cond, CC);
24160   if (Flags.getNode() &&
24161       // Extra check as FCMOV only supports a subset of X86 cond.
24162       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
24163     SDValue Ops[] = { FalseOp, TrueOp,
24164                       DAG.getConstant(CC, DL, MVT::i8), Flags };
24165     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
24166   }
24167
24168   // If this is a select between two integer constants, try to do some
24169   // optimizations.  Note that the operands are ordered the opposite of SELECT
24170   // operands.
24171   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
24172     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
24173       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
24174       // larger than FalseC (the false value).
24175       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
24176         CC = X86::GetOppositeBranchCondition(CC);
24177         std::swap(TrueC, FalseC);
24178         std::swap(TrueOp, FalseOp);
24179       }
24180
24181       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
24182       // This is efficient for any integer data type (including i8/i16) and
24183       // shift amount.
24184       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
24185         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
24186                            DAG.getConstant(CC, DL, MVT::i8), Cond);
24187
24188         // Zero extend the condition if needed.
24189         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
24190
24191         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
24192         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
24193                            DAG.getConstant(ShAmt, DL, MVT::i8));
24194         if (N->getNumValues() == 2)  // Dead flag value?
24195           return DCI.CombineTo(N, Cond, SDValue());
24196         return Cond;
24197       }
24198
24199       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
24200       // for any integer data type, including i8/i16.
24201       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
24202         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
24203                            DAG.getConstant(CC, DL, MVT::i8), Cond);
24204
24205         // Zero extend the condition if needed.
24206         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
24207                            FalseC->getValueType(0), Cond);
24208         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
24209                            SDValue(FalseC, 0));
24210
24211         if (N->getNumValues() == 2)  // Dead flag value?
24212           return DCI.CombineTo(N, Cond, SDValue());
24213         return Cond;
24214       }
24215
24216       // Optimize cases that will turn into an LEA instruction.  This requires
24217       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
24218       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
24219         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
24220         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
24221
24222         bool isFastMultiplier = false;
24223         if (Diff < 10) {
24224           switch ((unsigned char)Diff) {
24225           default: break;
24226           case 1:  // result = add base, cond
24227           case 2:  // result = lea base(    , cond*2)
24228           case 3:  // result = lea base(cond, cond*2)
24229           case 4:  // result = lea base(    , cond*4)
24230           case 5:  // result = lea base(cond, cond*4)
24231           case 8:  // result = lea base(    , cond*8)
24232           case 9:  // result = lea base(cond, cond*8)
24233             isFastMultiplier = true;
24234             break;
24235           }
24236         }
24237
24238         if (isFastMultiplier) {
24239           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
24240           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
24241                              DAG.getConstant(CC, DL, MVT::i8), Cond);
24242           // Zero extend the condition if needed.
24243           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
24244                              Cond);
24245           // Scale the condition by the difference.
24246           if (Diff != 1)
24247             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
24248                                DAG.getConstant(Diff, DL, Cond.getValueType()));
24249
24250           // Add the base if non-zero.
24251           if (FalseC->getAPIntValue() != 0)
24252             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
24253                                SDValue(FalseC, 0));
24254           if (N->getNumValues() == 2)  // Dead flag value?
24255             return DCI.CombineTo(N, Cond, SDValue());
24256           return Cond;
24257         }
24258       }
24259     }
24260   }
24261
24262   // Handle these cases:
24263   //   (select (x != c), e, c) -> select (x != c), e, x),
24264   //   (select (x == c), c, e) -> select (x == c), x, e)
24265   // where the c is an integer constant, and the "select" is the combination
24266   // of CMOV and CMP.
24267   //
24268   // The rationale for this change is that the conditional-move from a constant
24269   // needs two instructions, however, conditional-move from a register needs
24270   // only one instruction.
24271   //
24272   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
24273   //  some instruction-combining opportunities. This opt needs to be
24274   //  postponed as late as possible.
24275   //
24276   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
24277     // the DCI.xxxx conditions are provided to postpone the optimization as
24278     // late as possible.
24279
24280     ConstantSDNode *CmpAgainst = nullptr;
24281     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
24282         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
24283         !isa<ConstantSDNode>(Cond.getOperand(0))) {
24284
24285       if (CC == X86::COND_NE &&
24286           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
24287         CC = X86::GetOppositeBranchCondition(CC);
24288         std::swap(TrueOp, FalseOp);
24289       }
24290
24291       if (CC == X86::COND_E &&
24292           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
24293         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
24294                           DAG.getConstant(CC, DL, MVT::i8), Cond };
24295         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
24296       }
24297     }
24298   }
24299
24300   // Fold and/or of setcc's to double CMOV:
24301   //   (CMOV F, T, ((cc1 | cc2) != 0)) -> (CMOV (CMOV F, T, cc1), T, cc2)
24302   //   (CMOV F, T, ((cc1 & cc2) != 0)) -> (CMOV (CMOV T, F, !cc1), F, !cc2)
24303   //
24304   // This combine lets us generate:
24305   //   cmovcc1 (jcc1 if we don't have CMOV)
24306   //   cmovcc2 (same)
24307   // instead of:
24308   //   setcc1
24309   //   setcc2
24310   //   and/or
24311   //   cmovne (jne if we don't have CMOV)
24312   // When we can't use the CMOV instruction, it might increase branch
24313   // mispredicts.
24314   // When we can use CMOV, or when there is no mispredict, this improves
24315   // throughput and reduces register pressure.
24316   //
24317   if (CC == X86::COND_NE) {
24318     SDValue Flags;
24319     X86::CondCode CC0, CC1;
24320     bool isAndSetCC;
24321     if (checkBoolTestAndOrSetCCCombine(Cond, CC0, CC1, Flags, isAndSetCC)) {
24322       if (isAndSetCC) {
24323         std::swap(FalseOp, TrueOp);
24324         CC0 = X86::GetOppositeBranchCondition(CC0);
24325         CC1 = X86::GetOppositeBranchCondition(CC1);
24326       }
24327
24328       SDValue LOps[] = {FalseOp, TrueOp, DAG.getConstant(CC0, DL, MVT::i8),
24329         Flags};
24330       SDValue LCMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), LOps);
24331       SDValue Ops[] = {LCMOV, TrueOp, DAG.getConstant(CC1, DL, MVT::i8), Flags};
24332       SDValue CMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
24333       DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SDValue(CMOV.getNode(), 1));
24334       return CMOV;
24335     }
24336   }
24337
24338   return SDValue();
24339 }
24340
24341 /// PerformMulCombine - Optimize a single multiply with constant into two
24342 /// in order to implement it with two cheaper instructions, e.g.
24343 /// LEA + SHL, LEA + LEA.
24344 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
24345                                  TargetLowering::DAGCombinerInfo &DCI) {
24346   // An imul is usually smaller than the alternative sequence.
24347   if (DAG.getMachineFunction().getFunction()->optForMinSize())
24348     return SDValue();
24349
24350   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
24351     return SDValue();
24352
24353   EVT VT = N->getValueType(0);
24354   if (VT != MVT::i64 && VT != MVT::i32)
24355     return SDValue();
24356
24357   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
24358   if (!C)
24359     return SDValue();
24360   uint64_t MulAmt = C->getZExtValue();
24361   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
24362     return SDValue();
24363
24364   uint64_t MulAmt1 = 0;
24365   uint64_t MulAmt2 = 0;
24366   if ((MulAmt % 9) == 0) {
24367     MulAmt1 = 9;
24368     MulAmt2 = MulAmt / 9;
24369   } else if ((MulAmt % 5) == 0) {
24370     MulAmt1 = 5;
24371     MulAmt2 = MulAmt / 5;
24372   } else if ((MulAmt % 3) == 0) {
24373     MulAmt1 = 3;
24374     MulAmt2 = MulAmt / 3;
24375   }
24376   if (MulAmt2 &&
24377       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
24378     SDLoc DL(N);
24379
24380     if (isPowerOf2_64(MulAmt2) &&
24381         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
24382       // If second multiplifer is pow2, issue it first. We want the multiply by
24383       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
24384       // is an add.
24385       std::swap(MulAmt1, MulAmt2);
24386
24387     SDValue NewMul;
24388     if (isPowerOf2_64(MulAmt1))
24389       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
24390                            DAG.getConstant(Log2_64(MulAmt1), DL, MVT::i8));
24391     else
24392       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
24393                            DAG.getConstant(MulAmt1, DL, VT));
24394
24395     if (isPowerOf2_64(MulAmt2))
24396       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
24397                            DAG.getConstant(Log2_64(MulAmt2), DL, MVT::i8));
24398     else
24399       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
24400                            DAG.getConstant(MulAmt2, DL, VT));
24401
24402     // Do not add new nodes to DAG combiner worklist.
24403     DCI.CombineTo(N, NewMul, false);
24404   }
24405   return SDValue();
24406 }
24407
24408 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
24409   SDValue N0 = N->getOperand(0);
24410   SDValue N1 = N->getOperand(1);
24411   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
24412   EVT VT = N0.getValueType();
24413
24414   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
24415   // since the result of setcc_c is all zero's or all ones.
24416   if (VT.isInteger() && !VT.isVector() &&
24417       N1C && N0.getOpcode() == ISD::AND &&
24418       N0.getOperand(1).getOpcode() == ISD::Constant) {
24419     SDValue N00 = N0.getOperand(0);
24420     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
24421     APInt ShAmt = N1C->getAPIntValue();
24422     Mask = Mask.shl(ShAmt);
24423     bool MaskOK = false;
24424     // We can handle cases concerning bit-widening nodes containing setcc_c if
24425     // we carefully interrogate the mask to make sure we are semantics
24426     // preserving.
24427     // The transform is not safe if the result of C1 << C2 exceeds the bitwidth
24428     // of the underlying setcc_c operation if the setcc_c was zero extended.
24429     // Consider the following example:
24430     //   zext(setcc_c)                 -> i32 0x0000FFFF
24431     //   c1                            -> i32 0x0000FFFF
24432     //   c2                            -> i32 0x00000001
24433     //   (shl (and (setcc_c), c1), c2) -> i32 0x0001FFFE
24434     //   (and setcc_c, (c1 << c2))     -> i32 0x0000FFFE
24435     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
24436       MaskOK = true;
24437     } else if (N00.getOpcode() == ISD::SIGN_EXTEND &&
24438                N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
24439       MaskOK = true;
24440     } else if ((N00.getOpcode() == ISD::ZERO_EXTEND ||
24441                 N00.getOpcode() == ISD::ANY_EXTEND) &&
24442                N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
24443       MaskOK = Mask.isIntN(N00.getOperand(0).getValueSizeInBits());
24444     }
24445     if (MaskOK && Mask != 0) {
24446       SDLoc DL(N);
24447       return DAG.getNode(ISD::AND, DL, VT, N00, DAG.getConstant(Mask, DL, VT));
24448     }
24449   }
24450
24451   // Hardware support for vector shifts is sparse which makes us scalarize the
24452   // vector operations in many cases. Also, on sandybridge ADD is faster than
24453   // shl.
24454   // (shl V, 1) -> add V,V
24455   if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
24456     if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
24457       assert(N0.getValueType().isVector() && "Invalid vector shift type");
24458       // We shift all of the values by one. In many cases we do not have
24459       // hardware support for this operation. This is better expressed as an ADD
24460       // of two values.
24461       if (N1SplatC->getAPIntValue() == 1)
24462         return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
24463     }
24464
24465   return SDValue();
24466 }
24467
24468 /// \brief Returns a vector of 0s if the node in input is a vector logical
24469 /// shift by a constant amount which is known to be bigger than or equal
24470 /// to the vector element size in bits.
24471 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
24472                                       const X86Subtarget *Subtarget) {
24473   EVT VT = N->getValueType(0);
24474
24475   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
24476       (!Subtarget->hasInt256() ||
24477        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
24478     return SDValue();
24479
24480   SDValue Amt = N->getOperand(1);
24481   SDLoc DL(N);
24482   if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
24483     if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
24484       APInt ShiftAmt = AmtSplat->getAPIntValue();
24485       unsigned MaxAmount =
24486         VT.getSimpleVT().getVectorElementType().getSizeInBits();
24487
24488       // SSE2/AVX2 logical shifts always return a vector of 0s
24489       // if the shift amount is bigger than or equal to
24490       // the element size. The constant shift amount will be
24491       // encoded as a 8-bit immediate.
24492       if (ShiftAmt.trunc(8).uge(MaxAmount))
24493         return getZeroVector(VT, Subtarget, DAG, DL);
24494     }
24495
24496   return SDValue();
24497 }
24498
24499 /// PerformShiftCombine - Combine shifts.
24500 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
24501                                    TargetLowering::DAGCombinerInfo &DCI,
24502                                    const X86Subtarget *Subtarget) {
24503   if (N->getOpcode() == ISD::SHL)
24504     if (SDValue V = PerformSHLCombine(N, DAG))
24505       return V;
24506
24507   // Try to fold this logical shift into a zero vector.
24508   if (N->getOpcode() != ISD::SRA)
24509     if (SDValue V = performShiftToAllZeros(N, DAG, Subtarget))
24510       return V;
24511
24512   return SDValue();
24513 }
24514
24515 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
24516 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
24517 // and friends.  Likewise for OR -> CMPNEQSS.
24518 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
24519                             TargetLowering::DAGCombinerInfo &DCI,
24520                             const X86Subtarget *Subtarget) {
24521   unsigned opcode;
24522
24523   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
24524   // we're requiring SSE2 for both.
24525   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
24526     SDValue N0 = N->getOperand(0);
24527     SDValue N1 = N->getOperand(1);
24528     SDValue CMP0 = N0->getOperand(1);
24529     SDValue CMP1 = N1->getOperand(1);
24530     SDLoc DL(N);
24531
24532     // The SETCCs should both refer to the same CMP.
24533     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
24534       return SDValue();
24535
24536     SDValue CMP00 = CMP0->getOperand(0);
24537     SDValue CMP01 = CMP0->getOperand(1);
24538     EVT     VT    = CMP00.getValueType();
24539
24540     if (VT == MVT::f32 || VT == MVT::f64) {
24541       bool ExpectingFlags = false;
24542       // Check for any users that want flags:
24543       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
24544            !ExpectingFlags && UI != UE; ++UI)
24545         switch (UI->getOpcode()) {
24546         default:
24547         case ISD::BR_CC:
24548         case ISD::BRCOND:
24549         case ISD::SELECT:
24550           ExpectingFlags = true;
24551           break;
24552         case ISD::CopyToReg:
24553         case ISD::SIGN_EXTEND:
24554         case ISD::ZERO_EXTEND:
24555         case ISD::ANY_EXTEND:
24556           break;
24557         }
24558
24559       if (!ExpectingFlags) {
24560         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
24561         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
24562
24563         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
24564           X86::CondCode tmp = cc0;
24565           cc0 = cc1;
24566           cc1 = tmp;
24567         }
24568
24569         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
24570             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
24571           // FIXME: need symbolic constants for these magic numbers.
24572           // See X86ATTInstPrinter.cpp:printSSECC().
24573           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
24574           if (Subtarget->hasAVX512()) {
24575             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
24576                                          CMP01,
24577                                          DAG.getConstant(x86cc, DL, MVT::i8));
24578             if (N->getValueType(0) != MVT::i1)
24579               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
24580                                  FSetCC);
24581             return FSetCC;
24582           }
24583           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
24584                                               CMP00.getValueType(), CMP00, CMP01,
24585                                               DAG.getConstant(x86cc, DL,
24586                                                               MVT::i8));
24587
24588           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
24589           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
24590
24591           if (is64BitFP && !Subtarget->is64Bit()) {
24592             // On a 32-bit target, we cannot bitcast the 64-bit float to a
24593             // 64-bit integer, since that's not a legal type. Since
24594             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
24595             // bits, but can do this little dance to extract the lowest 32 bits
24596             // and work with those going forward.
24597             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
24598                                            OnesOrZeroesF);
24599             SDValue Vector32 = DAG.getBitcast(MVT::v4f32, Vector64);
24600             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
24601                                         Vector32, DAG.getIntPtrConstant(0, DL));
24602             IntVT = MVT::i32;
24603           }
24604
24605           SDValue OnesOrZeroesI = DAG.getBitcast(IntVT, OnesOrZeroesF);
24606           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
24607                                       DAG.getConstant(1, DL, IntVT));
24608           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8,
24609                                               ANDed);
24610           return OneBitOfTruth;
24611         }
24612       }
24613     }
24614   }
24615   return SDValue();
24616 }
24617
24618 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
24619 /// so it can be folded inside ANDNP.
24620 static bool CanFoldXORWithAllOnes(const SDNode *N) {
24621   EVT VT = N->getValueType(0);
24622
24623   // Match direct AllOnes for 128 and 256-bit vectors
24624   if (ISD::isBuildVectorAllOnes(N))
24625     return true;
24626
24627   // Look through a bit convert.
24628   if (N->getOpcode() == ISD::BITCAST)
24629     N = N->getOperand(0).getNode();
24630
24631   // Sometimes the operand may come from a insert_subvector building a 256-bit
24632   // allones vector
24633   if (VT.is256BitVector() &&
24634       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
24635     SDValue V1 = N->getOperand(0);
24636     SDValue V2 = N->getOperand(1);
24637
24638     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
24639         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
24640         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
24641         ISD::isBuildVectorAllOnes(V2.getNode()))
24642       return true;
24643   }
24644
24645   return false;
24646 }
24647
24648 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
24649 // register. In most cases we actually compare or select YMM-sized registers
24650 // and mixing the two types creates horrible code. This method optimizes
24651 // some of the transition sequences.
24652 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
24653                                  TargetLowering::DAGCombinerInfo &DCI,
24654                                  const X86Subtarget *Subtarget) {
24655   EVT VT = N->getValueType(0);
24656   if (!VT.is256BitVector())
24657     return SDValue();
24658
24659   assert((N->getOpcode() == ISD::ANY_EXTEND ||
24660           N->getOpcode() == ISD::ZERO_EXTEND ||
24661           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
24662
24663   SDValue Narrow = N->getOperand(0);
24664   EVT NarrowVT = Narrow->getValueType(0);
24665   if (!NarrowVT.is128BitVector())
24666     return SDValue();
24667
24668   if (Narrow->getOpcode() != ISD::XOR &&
24669       Narrow->getOpcode() != ISD::AND &&
24670       Narrow->getOpcode() != ISD::OR)
24671     return SDValue();
24672
24673   SDValue N0  = Narrow->getOperand(0);
24674   SDValue N1  = Narrow->getOperand(1);
24675   SDLoc DL(Narrow);
24676
24677   // The Left side has to be a trunc.
24678   if (N0.getOpcode() != ISD::TRUNCATE)
24679     return SDValue();
24680
24681   // The type of the truncated inputs.
24682   EVT WideVT = N0->getOperand(0)->getValueType(0);
24683   if (WideVT != VT)
24684     return SDValue();
24685
24686   // The right side has to be a 'trunc' or a constant vector.
24687   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
24688   ConstantSDNode *RHSConstSplat = nullptr;
24689   if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
24690     RHSConstSplat = RHSBV->getConstantSplatNode();
24691   if (!RHSTrunc && !RHSConstSplat)
24692     return SDValue();
24693
24694   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24695
24696   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
24697     return SDValue();
24698
24699   // Set N0 and N1 to hold the inputs to the new wide operation.
24700   N0 = N0->getOperand(0);
24701   if (RHSConstSplat) {
24702     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getVectorElementType(),
24703                      SDValue(RHSConstSplat, 0));
24704     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
24705     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
24706   } else if (RHSTrunc) {
24707     N1 = N1->getOperand(0);
24708   }
24709
24710   // Generate the wide operation.
24711   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
24712   unsigned Opcode = N->getOpcode();
24713   switch (Opcode) {
24714   case ISD::ANY_EXTEND:
24715     return Op;
24716   case ISD::ZERO_EXTEND: {
24717     unsigned InBits = NarrowVT.getScalarSizeInBits();
24718     APInt Mask = APInt::getAllOnesValue(InBits);
24719     Mask = Mask.zext(VT.getScalarSizeInBits());
24720     return DAG.getNode(ISD::AND, DL, VT,
24721                        Op, DAG.getConstant(Mask, DL, VT));
24722   }
24723   case ISD::SIGN_EXTEND:
24724     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
24725                        Op, DAG.getValueType(NarrowVT));
24726   default:
24727     llvm_unreachable("Unexpected opcode");
24728   }
24729 }
24730
24731 static SDValue VectorZextCombine(SDNode *N, SelectionDAG &DAG,
24732                                  TargetLowering::DAGCombinerInfo &DCI,
24733                                  const X86Subtarget *Subtarget) {
24734   SDValue N0 = N->getOperand(0);
24735   SDValue N1 = N->getOperand(1);
24736   SDLoc DL(N);
24737
24738   // A vector zext_in_reg may be represented as a shuffle,
24739   // feeding into a bitcast (this represents anyext) feeding into
24740   // an and with a mask.
24741   // We'd like to try to combine that into a shuffle with zero
24742   // plus a bitcast, removing the and.
24743   if (N0.getOpcode() != ISD::BITCAST ||
24744       N0.getOperand(0).getOpcode() != ISD::VECTOR_SHUFFLE)
24745     return SDValue();
24746
24747   // The other side of the AND should be a splat of 2^C, where C
24748   // is the number of bits in the source type.
24749   if (N1.getOpcode() == ISD::BITCAST)
24750     N1 = N1.getOperand(0);
24751   if (N1.getOpcode() != ISD::BUILD_VECTOR)
24752     return SDValue();
24753   BuildVectorSDNode *Vector = cast<BuildVectorSDNode>(N1);
24754
24755   ShuffleVectorSDNode *Shuffle = cast<ShuffleVectorSDNode>(N0.getOperand(0));
24756   EVT SrcType = Shuffle->getValueType(0);
24757
24758   // We expect a single-source shuffle
24759   if (Shuffle->getOperand(1)->getOpcode() != ISD::UNDEF)
24760     return SDValue();
24761
24762   unsigned SrcSize = SrcType.getScalarSizeInBits();
24763
24764   APInt SplatValue, SplatUndef;
24765   unsigned SplatBitSize;
24766   bool HasAnyUndefs;
24767   if (!Vector->isConstantSplat(SplatValue, SplatUndef,
24768                                 SplatBitSize, HasAnyUndefs))
24769     return SDValue();
24770
24771   unsigned ResSize = N1.getValueType().getScalarSizeInBits();
24772   // Make sure the splat matches the mask we expect
24773   if (SplatBitSize > ResSize ||
24774       (SplatValue + 1).exactLogBase2() != (int)SrcSize)
24775     return SDValue();
24776
24777   // Make sure the input and output size make sense
24778   if (SrcSize >= ResSize || ResSize % SrcSize)
24779     return SDValue();
24780
24781   // We expect a shuffle of the form <0, u, u, u, 1, u, u, u...>
24782   // The number of u's between each two values depends on the ratio between
24783   // the source and dest type.
24784   unsigned ZextRatio = ResSize / SrcSize;
24785   bool IsZext = true;
24786   for (unsigned i = 0; i < SrcType.getVectorNumElements(); ++i) {
24787     if (i % ZextRatio) {
24788       if (Shuffle->getMaskElt(i) > 0) {
24789         // Expected undef
24790         IsZext = false;
24791         break;
24792       }
24793     } else {
24794       if (Shuffle->getMaskElt(i) != (int)(i / ZextRatio)) {
24795         // Expected element number
24796         IsZext = false;
24797         break;
24798       }
24799     }
24800   }
24801
24802   if (!IsZext)
24803     return SDValue();
24804
24805   // Ok, perform the transformation - replace the shuffle with
24806   // a shuffle of the form <0, k, k, k, 1, k, k, k> with zero
24807   // (instead of undef) where the k elements come from the zero vector.
24808   SmallVector<int, 8> Mask;
24809   unsigned NumElems = SrcType.getVectorNumElements();
24810   for (unsigned i = 0; i < NumElems; ++i)
24811     if (i % ZextRatio)
24812       Mask.push_back(NumElems);
24813     else
24814       Mask.push_back(i / ZextRatio);
24815
24816   SDValue NewShuffle = DAG.getVectorShuffle(Shuffle->getValueType(0), DL,
24817     Shuffle->getOperand(0), DAG.getConstant(0, DL, SrcType), Mask);
24818   return DAG.getBitcast(N0.getValueType(), NewShuffle);
24819 }
24820
24821 /// If both input operands of a logic op are being cast from floating point
24822 /// types, try to convert this into a floating point logic node to avoid
24823 /// unnecessary moves from SSE to integer registers.
24824 static SDValue convertIntLogicToFPLogic(SDNode *N, SelectionDAG &DAG,
24825                                         const X86Subtarget *Subtarget) {
24826   unsigned FPOpcode = ISD::DELETED_NODE;
24827   if (N->getOpcode() == ISD::AND)
24828     FPOpcode = X86ISD::FAND;
24829   else if (N->getOpcode() == ISD::OR)
24830     FPOpcode = X86ISD::FOR;
24831   else if (N->getOpcode() == ISD::XOR)
24832     FPOpcode = X86ISD::FXOR;
24833
24834   assert(FPOpcode != ISD::DELETED_NODE &&
24835          "Unexpected input node for FP logic conversion");
24836
24837   EVT VT = N->getValueType(0);
24838   SDValue N0 = N->getOperand(0);
24839   SDValue N1 = N->getOperand(1);
24840   SDLoc DL(N);
24841   if (N0.getOpcode() == ISD::BITCAST && N1.getOpcode() == ISD::BITCAST &&
24842       ((Subtarget->hasSSE1() && VT == MVT::i32) ||
24843        (Subtarget->hasSSE2() && VT == MVT::i64))) {
24844     SDValue N00 = N0.getOperand(0);
24845     SDValue N10 = N1.getOperand(0);
24846     EVT N00Type = N00.getValueType();
24847     EVT N10Type = N10.getValueType();
24848     if (N00Type.isFloatingPoint() && N10Type.isFloatingPoint()) {
24849       SDValue FPLogic = DAG.getNode(FPOpcode, DL, N00Type, N00, N10);
24850       return DAG.getBitcast(VT, FPLogic);
24851     }
24852   }
24853   return SDValue();
24854 }
24855
24856 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
24857                                  TargetLowering::DAGCombinerInfo &DCI,
24858                                  const X86Subtarget *Subtarget) {
24859   if (DCI.isBeforeLegalizeOps())
24860     return SDValue();
24861
24862   if (SDValue Zext = VectorZextCombine(N, DAG, DCI, Subtarget))
24863     return Zext;
24864
24865   if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
24866     return R;
24867
24868   if (SDValue FPLogic = convertIntLogicToFPLogic(N, DAG, Subtarget))
24869     return FPLogic;
24870
24871   EVT VT = N->getValueType(0);
24872   SDValue N0 = N->getOperand(0);
24873   SDValue N1 = N->getOperand(1);
24874   SDLoc DL(N);
24875
24876   // Create BEXTR instructions
24877   // BEXTR is ((X >> imm) & (2**size-1))
24878   if (VT == MVT::i32 || VT == MVT::i64) {
24879     // Check for BEXTR.
24880     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
24881         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
24882       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
24883       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
24884       if (MaskNode && ShiftNode) {
24885         uint64_t Mask = MaskNode->getZExtValue();
24886         uint64_t Shift = ShiftNode->getZExtValue();
24887         if (isMask_64(Mask)) {
24888           uint64_t MaskSize = countPopulation(Mask);
24889           if (Shift + MaskSize <= VT.getSizeInBits())
24890             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
24891                                DAG.getConstant(Shift | (MaskSize << 8), DL,
24892                                                VT));
24893         }
24894       }
24895     } // BEXTR
24896
24897     return SDValue();
24898   }
24899
24900   // Want to form ANDNP nodes:
24901   // 1) In the hopes of then easily combining them with OR and AND nodes
24902   //    to form PBLEND/PSIGN.
24903   // 2) To match ANDN packed intrinsics
24904   if (VT != MVT::v2i64 && VT != MVT::v4i64)
24905     return SDValue();
24906
24907   // Check LHS for vnot
24908   if (N0.getOpcode() == ISD::XOR &&
24909       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
24910       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
24911     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
24912
24913   // Check RHS for vnot
24914   if (N1.getOpcode() == ISD::XOR &&
24915       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
24916       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
24917     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
24918
24919   return SDValue();
24920 }
24921
24922 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
24923                                 TargetLowering::DAGCombinerInfo &DCI,
24924                                 const X86Subtarget *Subtarget) {
24925   if (DCI.isBeforeLegalizeOps())
24926     return SDValue();
24927
24928   if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
24929     return R;
24930
24931   if (SDValue FPLogic = convertIntLogicToFPLogic(N, DAG, Subtarget))
24932     return FPLogic;
24933
24934   SDValue N0 = N->getOperand(0);
24935   SDValue N1 = N->getOperand(1);
24936   EVT VT = N->getValueType(0);
24937
24938   // look for psign/blend
24939   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
24940     if (!Subtarget->hasSSSE3() ||
24941         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
24942       return SDValue();
24943
24944     // Canonicalize pandn to RHS
24945     if (N0.getOpcode() == X86ISD::ANDNP)
24946       std::swap(N0, N1);
24947     // or (and (m, y), (pandn m, x))
24948     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
24949       SDValue Mask = N1.getOperand(0);
24950       SDValue X    = N1.getOperand(1);
24951       SDValue Y;
24952       if (N0.getOperand(0) == Mask)
24953         Y = N0.getOperand(1);
24954       if (N0.getOperand(1) == Mask)
24955         Y = N0.getOperand(0);
24956
24957       // Check to see if the mask appeared in both the AND and ANDNP and
24958       if (!Y.getNode())
24959         return SDValue();
24960
24961       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
24962       // Look through mask bitcast.
24963       if (Mask.getOpcode() == ISD::BITCAST)
24964         Mask = Mask.getOperand(0);
24965       if (X.getOpcode() == ISD::BITCAST)
24966         X = X.getOperand(0);
24967       if (Y.getOpcode() == ISD::BITCAST)
24968         Y = Y.getOperand(0);
24969
24970       EVT MaskVT = Mask.getValueType();
24971
24972       // Validate that the Mask operand is a vector sra node.
24973       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
24974       // there is no psrai.b
24975       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
24976       unsigned SraAmt = ~0;
24977       if (Mask.getOpcode() == ISD::SRA) {
24978         if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
24979           if (auto *AmtConst = AmtBV->getConstantSplatNode())
24980             SraAmt = AmtConst->getZExtValue();
24981       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
24982         SDValue SraC = Mask.getOperand(1);
24983         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
24984       }
24985       if ((SraAmt + 1) != EltBits)
24986         return SDValue();
24987
24988       SDLoc DL(N);
24989
24990       // Now we know we at least have a plendvb with the mask val.  See if
24991       // we can form a psignb/w/d.
24992       // psign = x.type == y.type == mask.type && y = sub(0, x);
24993       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
24994           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
24995           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
24996         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
24997                "Unsupported VT for PSIGN");
24998         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
24999         return DAG.getBitcast(VT, Mask);
25000       }
25001       // PBLENDVB only available on SSE 4.1
25002       if (!Subtarget->hasSSE41())
25003         return SDValue();
25004
25005       MVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
25006
25007       X = DAG.getBitcast(BlendVT, X);
25008       Y = DAG.getBitcast(BlendVT, Y);
25009       Mask = DAG.getBitcast(BlendVT, Mask);
25010       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
25011       return DAG.getBitcast(VT, Mask);
25012     }
25013   }
25014
25015   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
25016     return SDValue();
25017
25018   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
25019   bool OptForSize = DAG.getMachineFunction().getFunction()->optForSize();
25020
25021   // SHLD/SHRD instructions have lower register pressure, but on some
25022   // platforms they have higher latency than the equivalent
25023   // series of shifts/or that would otherwise be generated.
25024   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
25025   // have higher latencies and we are not optimizing for size.
25026   if (!OptForSize && Subtarget->isSHLDSlow())
25027     return SDValue();
25028
25029   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
25030     std::swap(N0, N1);
25031   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
25032     return SDValue();
25033   if (!N0.hasOneUse() || !N1.hasOneUse())
25034     return SDValue();
25035
25036   SDValue ShAmt0 = N0.getOperand(1);
25037   if (ShAmt0.getValueType() != MVT::i8)
25038     return SDValue();
25039   SDValue ShAmt1 = N1.getOperand(1);
25040   if (ShAmt1.getValueType() != MVT::i8)
25041     return SDValue();
25042   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
25043     ShAmt0 = ShAmt0.getOperand(0);
25044   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
25045     ShAmt1 = ShAmt1.getOperand(0);
25046
25047   SDLoc DL(N);
25048   unsigned Opc = X86ISD::SHLD;
25049   SDValue Op0 = N0.getOperand(0);
25050   SDValue Op1 = N1.getOperand(0);
25051   if (ShAmt0.getOpcode() == ISD::SUB) {
25052     Opc = X86ISD::SHRD;
25053     std::swap(Op0, Op1);
25054     std::swap(ShAmt0, ShAmt1);
25055   }
25056
25057   unsigned Bits = VT.getSizeInBits();
25058   if (ShAmt1.getOpcode() == ISD::SUB) {
25059     SDValue Sum = ShAmt1.getOperand(0);
25060     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
25061       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
25062       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
25063         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
25064       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
25065         return DAG.getNode(Opc, DL, VT,
25066                            Op0, Op1,
25067                            DAG.getNode(ISD::TRUNCATE, DL,
25068                                        MVT::i8, ShAmt0));
25069     }
25070   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
25071     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
25072     if (ShAmt0C &&
25073         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
25074       return DAG.getNode(Opc, DL, VT,
25075                          N0.getOperand(0), N1.getOperand(0),
25076                          DAG.getNode(ISD::TRUNCATE, DL,
25077                                        MVT::i8, ShAmt0));
25078   }
25079
25080   return SDValue();
25081 }
25082
25083 // Generate NEG and CMOV for integer abs.
25084 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
25085   EVT VT = N->getValueType(0);
25086
25087   // Since X86 does not have CMOV for 8-bit integer, we don't convert
25088   // 8-bit integer abs to NEG and CMOV.
25089   if (VT.isInteger() && VT.getSizeInBits() == 8)
25090     return SDValue();
25091
25092   SDValue N0 = N->getOperand(0);
25093   SDValue N1 = N->getOperand(1);
25094   SDLoc DL(N);
25095
25096   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
25097   // and change it to SUB and CMOV.
25098   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
25099       N0.getOpcode() == ISD::ADD &&
25100       N0.getOperand(1) == N1 &&
25101       N1.getOpcode() == ISD::SRA &&
25102       N1.getOperand(0) == N0.getOperand(0))
25103     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
25104       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
25105         // Generate SUB & CMOV.
25106         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
25107                                   DAG.getConstant(0, DL, VT), N0.getOperand(0));
25108
25109         SDValue Ops[] = { N0.getOperand(0), Neg,
25110                           DAG.getConstant(X86::COND_GE, DL, MVT::i8),
25111                           SDValue(Neg.getNode(), 1) };
25112         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
25113       }
25114   return SDValue();
25115 }
25116
25117 // Try to turn tests against the signbit in the form of:
25118 //   XOR(TRUNCATE(SRL(X, size(X)-1)), 1)
25119 // into:
25120 //   SETGT(X, -1)
25121 static SDValue foldXorTruncShiftIntoCmp(SDNode *N, SelectionDAG &DAG) {
25122   // This is only worth doing if the output type is i8.
25123   if (N->getValueType(0) != MVT::i8)
25124     return SDValue();
25125
25126   SDValue N0 = N->getOperand(0);
25127   SDValue N1 = N->getOperand(1);
25128
25129   // We should be performing an xor against a truncated shift.
25130   if (N0.getOpcode() != ISD::TRUNCATE || !N0.hasOneUse())
25131     return SDValue();
25132
25133   // Make sure we are performing an xor against one.
25134   if (!isa<ConstantSDNode>(N1) || !cast<ConstantSDNode>(N1)->isOne())
25135     return SDValue();
25136
25137   // SetCC on x86 zero extends so only act on this if it's a logical shift.
25138   SDValue Shift = N0.getOperand(0);
25139   if (Shift.getOpcode() != ISD::SRL || !Shift.hasOneUse())
25140     return SDValue();
25141
25142   // Make sure we are truncating from one of i16, i32 or i64.
25143   EVT ShiftTy = Shift.getValueType();
25144   if (ShiftTy != MVT::i16 && ShiftTy != MVT::i32 && ShiftTy != MVT::i64)
25145     return SDValue();
25146
25147   // Make sure the shift amount extracts the sign bit.
25148   if (!isa<ConstantSDNode>(Shift.getOperand(1)) ||
25149       Shift.getConstantOperandVal(1) != ShiftTy.getSizeInBits() - 1)
25150     return SDValue();
25151
25152   // Create a greater-than comparison against -1.
25153   // N.B. Using SETGE against 0 works but we want a canonical looking
25154   // comparison, using SETGT matches up with what TranslateX86CC.
25155   SDLoc DL(N);
25156   SDValue ShiftOp = Shift.getOperand(0);
25157   EVT ShiftOpTy = ShiftOp.getValueType();
25158   SDValue Cond = DAG.getSetCC(DL, MVT::i8, ShiftOp,
25159                               DAG.getConstant(-1, DL, ShiftOpTy), ISD::SETGT);
25160   return Cond;
25161 }
25162
25163 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
25164                                  TargetLowering::DAGCombinerInfo &DCI,
25165                                  const X86Subtarget *Subtarget) {
25166   if (DCI.isBeforeLegalizeOps())
25167     return SDValue();
25168
25169   if (SDValue RV = foldXorTruncShiftIntoCmp(N, DAG))
25170     return RV;
25171
25172   if (Subtarget->hasCMov())
25173     if (SDValue RV = performIntegerAbsCombine(N, DAG))
25174       return RV;
25175
25176   if (SDValue FPLogic = convertIntLogicToFPLogic(N, DAG, Subtarget))
25177     return FPLogic;
25178
25179   return SDValue();
25180 }
25181
25182 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
25183 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
25184                                   TargetLowering::DAGCombinerInfo &DCI,
25185                                   const X86Subtarget *Subtarget) {
25186   LoadSDNode *Ld = cast<LoadSDNode>(N);
25187   EVT RegVT = Ld->getValueType(0);
25188   EVT MemVT = Ld->getMemoryVT();
25189   SDLoc dl(Ld);
25190   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25191
25192   // For chips with slow 32-byte unaligned loads, break the 32-byte operation
25193   // into two 16-byte operations.
25194   ISD::LoadExtType Ext = Ld->getExtensionType();
25195   bool Fast;
25196   unsigned AddressSpace = Ld->getAddressSpace();
25197   unsigned Alignment = Ld->getAlignment();
25198   if (RegVT.is256BitVector() && !DCI.isBeforeLegalizeOps() &&
25199       Ext == ISD::NON_EXTLOAD &&
25200       TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), RegVT,
25201                              AddressSpace, Alignment, &Fast) && !Fast) {
25202     unsigned NumElems = RegVT.getVectorNumElements();
25203     if (NumElems < 2)
25204       return SDValue();
25205
25206     SDValue Ptr = Ld->getBasePtr();
25207     SDValue Increment =
25208         DAG.getConstant(16, dl, TLI.getPointerTy(DAG.getDataLayout()));
25209
25210     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
25211                                   NumElems/2);
25212     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
25213                                 Ld->getPointerInfo(), Ld->isVolatile(),
25214                                 Ld->isNonTemporal(), Ld->isInvariant(),
25215                                 Alignment);
25216     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
25217     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
25218                                 Ld->getPointerInfo(), Ld->isVolatile(),
25219                                 Ld->isNonTemporal(), Ld->isInvariant(),
25220                                 std::min(16U, Alignment));
25221     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
25222                              Load1.getValue(1),
25223                              Load2.getValue(1));
25224
25225     SDValue NewVec = DAG.getUNDEF(RegVT);
25226     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
25227     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
25228     return DCI.CombineTo(N, NewVec, TF, true);
25229   }
25230
25231   return SDValue();
25232 }
25233
25234 /// PerformMLOADCombine - Resolve extending loads
25235 static SDValue PerformMLOADCombine(SDNode *N, SelectionDAG &DAG,
25236                                    TargetLowering::DAGCombinerInfo &DCI,
25237                                    const X86Subtarget *Subtarget) {
25238   MaskedLoadSDNode *Mld = cast<MaskedLoadSDNode>(N);
25239   if (Mld->getExtensionType() != ISD::SEXTLOAD)
25240     return SDValue();
25241
25242   EVT VT = Mld->getValueType(0);
25243   unsigned NumElems = VT.getVectorNumElements();
25244   EVT LdVT = Mld->getMemoryVT();
25245   SDLoc dl(Mld);
25246
25247   assert(LdVT != VT && "Cannot extend to the same type");
25248   unsigned ToSz = VT.getVectorElementType().getSizeInBits();
25249   unsigned FromSz = LdVT.getVectorElementType().getSizeInBits();
25250   // From, To sizes and ElemCount must be pow of two
25251   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
25252     "Unexpected size for extending masked load");
25253
25254   unsigned SizeRatio  = ToSz / FromSz;
25255   assert(SizeRatio * NumElems * FromSz == VT.getSizeInBits());
25256
25257   // Create a type on which we perform the shuffle
25258   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
25259           LdVT.getScalarType(), NumElems*SizeRatio);
25260   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
25261
25262   // Convert Src0 value
25263   SDValue WideSrc0 = DAG.getBitcast(WideVecVT, Mld->getSrc0());
25264   if (Mld->getSrc0().getOpcode() != ISD::UNDEF) {
25265     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
25266     for (unsigned i = 0; i != NumElems; ++i)
25267       ShuffleVec[i] = i * SizeRatio;
25268
25269     // Can't shuffle using an illegal type.
25270     assert(DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT) &&
25271            "WideVecVT should be legal");
25272     WideSrc0 = DAG.getVectorShuffle(WideVecVT, dl, WideSrc0,
25273                                     DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
25274   }
25275   // Prepare the new mask
25276   SDValue NewMask;
25277   SDValue Mask = Mld->getMask();
25278   if (Mask.getValueType() == VT) {
25279     // Mask and original value have the same type
25280     NewMask = DAG.getBitcast(WideVecVT, Mask);
25281     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
25282     for (unsigned i = 0; i != NumElems; ++i)
25283       ShuffleVec[i] = i * SizeRatio;
25284     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
25285       ShuffleVec[i] = NumElems*SizeRatio;
25286     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
25287                                    DAG.getConstant(0, dl, WideVecVT),
25288                                    &ShuffleVec[0]);
25289   }
25290   else {
25291     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
25292     unsigned WidenNumElts = NumElems*SizeRatio;
25293     unsigned MaskNumElts = VT.getVectorNumElements();
25294     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
25295                                      WidenNumElts);
25296
25297     unsigned NumConcat = WidenNumElts / MaskNumElts;
25298     SmallVector<SDValue, 16> Ops(NumConcat);
25299     SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
25300     Ops[0] = Mask;
25301     for (unsigned i = 1; i != NumConcat; ++i)
25302       Ops[i] = ZeroVal;
25303
25304     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
25305   }
25306
25307   SDValue WideLd = DAG.getMaskedLoad(WideVecVT, dl, Mld->getChain(),
25308                                      Mld->getBasePtr(), NewMask, WideSrc0,
25309                                      Mld->getMemoryVT(), Mld->getMemOperand(),
25310                                      ISD::NON_EXTLOAD);
25311   SDValue NewVec = DAG.getNode(X86ISD::VSEXT, dl, VT, WideLd);
25312   return DCI.CombineTo(N, NewVec, WideLd.getValue(1), true);
25313 }
25314 /// PerformMSTORECombine - Resolve truncating stores
25315 static SDValue PerformMSTORECombine(SDNode *N, SelectionDAG &DAG,
25316                                     const X86Subtarget *Subtarget) {
25317   MaskedStoreSDNode *Mst = cast<MaskedStoreSDNode>(N);
25318   if (!Mst->isTruncatingStore())
25319     return SDValue();
25320
25321   EVT VT = Mst->getValue().getValueType();
25322   unsigned NumElems = VT.getVectorNumElements();
25323   EVT StVT = Mst->getMemoryVT();
25324   SDLoc dl(Mst);
25325
25326   assert(StVT != VT && "Cannot truncate to the same type");
25327   unsigned FromSz = VT.getVectorElementType().getSizeInBits();
25328   unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
25329
25330   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25331
25332   // The truncating store is legal in some cases. For example
25333   // vpmovqb, vpmovqw, vpmovqd, vpmovdb, vpmovdw
25334   // are designated for truncate store.
25335   // In this case we don't need any further transformations.
25336   if (TLI.isTruncStoreLegal(VT, StVT))
25337     return SDValue();
25338
25339   // From, To sizes and ElemCount must be pow of two
25340   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
25341     "Unexpected size for truncating masked store");
25342   // We are going to use the original vector elt for storing.
25343   // Accumulated smaller vector elements must be a multiple of the store size.
25344   assert (((NumElems * FromSz) % ToSz) == 0 &&
25345           "Unexpected ratio for truncating masked store");
25346
25347   unsigned SizeRatio  = FromSz / ToSz;
25348   assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
25349
25350   // Create a type on which we perform the shuffle
25351   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
25352           StVT.getScalarType(), NumElems*SizeRatio);
25353
25354   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
25355
25356   SDValue WideVec = DAG.getBitcast(WideVecVT, Mst->getValue());
25357   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
25358   for (unsigned i = 0; i != NumElems; ++i)
25359     ShuffleVec[i] = i * SizeRatio;
25360
25361   // Can't shuffle using an illegal type.
25362   assert(DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT) &&
25363          "WideVecVT should be legal");
25364
25365   SDValue TruncatedVal = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
25366                                         DAG.getUNDEF(WideVecVT),
25367                                         &ShuffleVec[0]);
25368
25369   SDValue NewMask;
25370   SDValue Mask = Mst->getMask();
25371   if (Mask.getValueType() == VT) {
25372     // Mask and original value have the same type
25373     NewMask = DAG.getBitcast(WideVecVT, Mask);
25374     for (unsigned i = 0; i != NumElems; ++i)
25375       ShuffleVec[i] = i * SizeRatio;
25376     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
25377       ShuffleVec[i] = NumElems*SizeRatio;
25378     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
25379                                    DAG.getConstant(0, dl, WideVecVT),
25380                                    &ShuffleVec[0]);
25381   }
25382   else {
25383     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
25384     unsigned WidenNumElts = NumElems*SizeRatio;
25385     unsigned MaskNumElts = VT.getVectorNumElements();
25386     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
25387                                      WidenNumElts);
25388
25389     unsigned NumConcat = WidenNumElts / MaskNumElts;
25390     SmallVector<SDValue, 16> Ops(NumConcat);
25391     SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
25392     Ops[0] = Mask;
25393     for (unsigned i = 1; i != NumConcat; ++i)
25394       Ops[i] = ZeroVal;
25395
25396     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
25397   }
25398
25399   return DAG.getMaskedStore(Mst->getChain(), dl, TruncatedVal, Mst->getBasePtr(),
25400                             NewMask, StVT, Mst->getMemOperand(), false);
25401 }
25402 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
25403 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
25404                                    const X86Subtarget *Subtarget) {
25405   StoreSDNode *St = cast<StoreSDNode>(N);
25406   EVT VT = St->getValue().getValueType();
25407   EVT StVT = St->getMemoryVT();
25408   SDLoc dl(St);
25409   SDValue StoredVal = St->getOperand(1);
25410   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25411
25412   // If we are saving a concatenation of two XMM registers and 32-byte stores
25413   // are slow, such as on Sandy Bridge, perform two 16-byte stores.
25414   bool Fast;
25415   unsigned AddressSpace = St->getAddressSpace();
25416   unsigned Alignment = St->getAlignment();
25417   if (VT.is256BitVector() && StVT == VT &&
25418       TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
25419                              AddressSpace, Alignment, &Fast) && !Fast) {
25420     unsigned NumElems = VT.getVectorNumElements();
25421     if (NumElems < 2)
25422       return SDValue();
25423
25424     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
25425     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
25426
25427     SDValue Stride =
25428         DAG.getConstant(16, dl, TLI.getPointerTy(DAG.getDataLayout()));
25429     SDValue Ptr0 = St->getBasePtr();
25430     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
25431
25432     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
25433                                 St->getPointerInfo(), St->isVolatile(),
25434                                 St->isNonTemporal(), Alignment);
25435     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
25436                                 St->getPointerInfo(), St->isVolatile(),
25437                                 St->isNonTemporal(),
25438                                 std::min(16U, Alignment));
25439     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
25440   }
25441
25442   // Optimize trunc store (of multiple scalars) to shuffle and store.
25443   // First, pack all of the elements in one place. Next, store to memory
25444   // in fewer chunks.
25445   if (St->isTruncatingStore() && VT.isVector()) {
25446     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25447     unsigned NumElems = VT.getVectorNumElements();
25448     assert(StVT != VT && "Cannot truncate to the same type");
25449     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
25450     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
25451
25452     // The truncating store is legal in some cases. For example
25453     // vpmovqb, vpmovqw, vpmovqd, vpmovdb, vpmovdw
25454     // are designated for truncate store.
25455     // In this case we don't need any further transformations.
25456     if (TLI.isTruncStoreLegal(VT, StVT))
25457       return SDValue();
25458
25459     // From, To sizes and ElemCount must be pow of two
25460     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
25461     // We are going to use the original vector elt for storing.
25462     // Accumulated smaller vector elements must be a multiple of the store size.
25463     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
25464
25465     unsigned SizeRatio  = FromSz / ToSz;
25466
25467     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
25468
25469     // Create a type on which we perform the shuffle
25470     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
25471             StVT.getScalarType(), NumElems*SizeRatio);
25472
25473     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
25474
25475     SDValue WideVec = DAG.getBitcast(WideVecVT, St->getValue());
25476     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
25477     for (unsigned i = 0; i != NumElems; ++i)
25478       ShuffleVec[i] = i * SizeRatio;
25479
25480     // Can't shuffle using an illegal type.
25481     if (!TLI.isTypeLegal(WideVecVT))
25482       return SDValue();
25483
25484     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
25485                                          DAG.getUNDEF(WideVecVT),
25486                                          &ShuffleVec[0]);
25487     // At this point all of the data is stored at the bottom of the
25488     // register. We now need to save it to mem.
25489
25490     // Find the largest store unit
25491     MVT StoreType = MVT::i8;
25492     for (MVT Tp : MVT::integer_valuetypes()) {
25493       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
25494         StoreType = Tp;
25495     }
25496
25497     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
25498     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
25499         (64 <= NumElems * ToSz))
25500       StoreType = MVT::f64;
25501
25502     // Bitcast the original vector into a vector of store-size units
25503     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
25504             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
25505     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
25506     SDValue ShuffWide = DAG.getBitcast(StoreVecVT, Shuff);
25507     SmallVector<SDValue, 8> Chains;
25508     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, dl,
25509                                         TLI.getPointerTy(DAG.getDataLayout()));
25510     SDValue Ptr = St->getBasePtr();
25511
25512     // Perform one or more big stores into memory.
25513     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
25514       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
25515                                    StoreType, ShuffWide,
25516                                    DAG.getIntPtrConstant(i, dl));
25517       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
25518                                 St->getPointerInfo(), St->isVolatile(),
25519                                 St->isNonTemporal(), St->getAlignment());
25520       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
25521       Chains.push_back(Ch);
25522     }
25523
25524     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
25525   }
25526
25527   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
25528   // the FP state in cases where an emms may be missing.
25529   // A preferable solution to the general problem is to figure out the right
25530   // places to insert EMMS.  This qualifies as a quick hack.
25531
25532   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
25533   if (VT.getSizeInBits() != 64)
25534     return SDValue();
25535
25536   const Function *F = DAG.getMachineFunction().getFunction();
25537   bool NoImplicitFloatOps = F->hasFnAttribute(Attribute::NoImplicitFloat);
25538   bool F64IsLegal =
25539       !Subtarget->useSoftFloat() && !NoImplicitFloatOps && Subtarget->hasSSE2();
25540   if ((VT.isVector() ||
25541        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
25542       isa<LoadSDNode>(St->getValue()) &&
25543       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
25544       St->getChain().hasOneUse() && !St->isVolatile()) {
25545     SDNode* LdVal = St->getValue().getNode();
25546     LoadSDNode *Ld = nullptr;
25547     int TokenFactorIndex = -1;
25548     SmallVector<SDValue, 8> Ops;
25549     SDNode* ChainVal = St->getChain().getNode();
25550     // Must be a store of a load.  We currently handle two cases:  the load
25551     // is a direct child, and it's under an intervening TokenFactor.  It is
25552     // possible to dig deeper under nested TokenFactors.
25553     if (ChainVal == LdVal)
25554       Ld = cast<LoadSDNode>(St->getChain());
25555     else if (St->getValue().hasOneUse() &&
25556              ChainVal->getOpcode() == ISD::TokenFactor) {
25557       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
25558         if (ChainVal->getOperand(i).getNode() == LdVal) {
25559           TokenFactorIndex = i;
25560           Ld = cast<LoadSDNode>(St->getValue());
25561         } else
25562           Ops.push_back(ChainVal->getOperand(i));
25563       }
25564     }
25565
25566     if (!Ld || !ISD::isNormalLoad(Ld))
25567       return SDValue();
25568
25569     // If this is not the MMX case, i.e. we are just turning i64 load/store
25570     // into f64 load/store, avoid the transformation if there are multiple
25571     // uses of the loaded value.
25572     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
25573       return SDValue();
25574
25575     SDLoc LdDL(Ld);
25576     SDLoc StDL(N);
25577     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
25578     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
25579     // pair instead.
25580     if (Subtarget->is64Bit() || F64IsLegal) {
25581       MVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
25582       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
25583                                   Ld->getPointerInfo(), Ld->isVolatile(),
25584                                   Ld->isNonTemporal(), Ld->isInvariant(),
25585                                   Ld->getAlignment());
25586       SDValue NewChain = NewLd.getValue(1);
25587       if (TokenFactorIndex != -1) {
25588         Ops.push_back(NewChain);
25589         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
25590       }
25591       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
25592                           St->getPointerInfo(),
25593                           St->isVolatile(), St->isNonTemporal(),
25594                           St->getAlignment());
25595     }
25596
25597     // Otherwise, lower to two pairs of 32-bit loads / stores.
25598     SDValue LoAddr = Ld->getBasePtr();
25599     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
25600                                  DAG.getConstant(4, LdDL, MVT::i32));
25601
25602     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
25603                                Ld->getPointerInfo(),
25604                                Ld->isVolatile(), Ld->isNonTemporal(),
25605                                Ld->isInvariant(), Ld->getAlignment());
25606     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
25607                                Ld->getPointerInfo().getWithOffset(4),
25608                                Ld->isVolatile(), Ld->isNonTemporal(),
25609                                Ld->isInvariant(),
25610                                MinAlign(Ld->getAlignment(), 4));
25611
25612     SDValue NewChain = LoLd.getValue(1);
25613     if (TokenFactorIndex != -1) {
25614       Ops.push_back(LoLd);
25615       Ops.push_back(HiLd);
25616       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
25617     }
25618
25619     LoAddr = St->getBasePtr();
25620     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
25621                          DAG.getConstant(4, StDL, MVT::i32));
25622
25623     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
25624                                 St->getPointerInfo(),
25625                                 St->isVolatile(), St->isNonTemporal(),
25626                                 St->getAlignment());
25627     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
25628                                 St->getPointerInfo().getWithOffset(4),
25629                                 St->isVolatile(),
25630                                 St->isNonTemporal(),
25631                                 MinAlign(St->getAlignment(), 4));
25632     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
25633   }
25634
25635   // This is similar to the above case, but here we handle a scalar 64-bit
25636   // integer store that is extracted from a vector on a 32-bit target.
25637   // If we have SSE2, then we can treat it like a floating-point double
25638   // to get past legalization. The execution dependencies fixup pass will
25639   // choose the optimal machine instruction for the store if this really is
25640   // an integer or v2f32 rather than an f64.
25641   if (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit() &&
25642       St->getOperand(1).getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
25643     SDValue OldExtract = St->getOperand(1);
25644     SDValue ExtOp0 = OldExtract.getOperand(0);
25645     unsigned VecSize = ExtOp0.getValueSizeInBits();
25646     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, VecSize / 64);
25647     SDValue BitCast = DAG.getBitcast(VecVT, ExtOp0);
25648     SDValue NewExtract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
25649                                      BitCast, OldExtract.getOperand(1));
25650     return DAG.getStore(St->getChain(), dl, NewExtract, St->getBasePtr(),
25651                         St->getPointerInfo(), St->isVolatile(),
25652                         St->isNonTemporal(), St->getAlignment());
25653   }
25654
25655   return SDValue();
25656 }
25657
25658 /// Return 'true' if this vector operation is "horizontal"
25659 /// and return the operands for the horizontal operation in LHS and RHS.  A
25660 /// horizontal operation performs the binary operation on successive elements
25661 /// of its first operand, then on successive elements of its second operand,
25662 /// returning the resulting values in a vector.  For example, if
25663 ///   A = < float a0, float a1, float a2, float a3 >
25664 /// and
25665 ///   B = < float b0, float b1, float b2, float b3 >
25666 /// then the result of doing a horizontal operation on A and B is
25667 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
25668 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
25669 /// A horizontal-op B, for some already available A and B, and if so then LHS is
25670 /// set to A, RHS to B, and the routine returns 'true'.
25671 /// Note that the binary operation should have the property that if one of the
25672 /// operands is UNDEF then the result is UNDEF.
25673 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
25674   // Look for the following pattern: if
25675   //   A = < float a0, float a1, float a2, float a3 >
25676   //   B = < float b0, float b1, float b2, float b3 >
25677   // and
25678   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
25679   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
25680   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
25681   // which is A horizontal-op B.
25682
25683   // At least one of the operands should be a vector shuffle.
25684   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
25685       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
25686     return false;
25687
25688   MVT VT = LHS.getSimpleValueType();
25689
25690   assert((VT.is128BitVector() || VT.is256BitVector()) &&
25691          "Unsupported vector type for horizontal add/sub");
25692
25693   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
25694   // operate independently on 128-bit lanes.
25695   unsigned NumElts = VT.getVectorNumElements();
25696   unsigned NumLanes = VT.getSizeInBits()/128;
25697   unsigned NumLaneElts = NumElts / NumLanes;
25698   assert((NumLaneElts % 2 == 0) &&
25699          "Vector type should have an even number of elements in each lane");
25700   unsigned HalfLaneElts = NumLaneElts/2;
25701
25702   // View LHS in the form
25703   //   LHS = VECTOR_SHUFFLE A, B, LMask
25704   // If LHS is not a shuffle then pretend it is the shuffle
25705   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
25706   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
25707   // type VT.
25708   SDValue A, B;
25709   SmallVector<int, 16> LMask(NumElts);
25710   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
25711     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
25712       A = LHS.getOperand(0);
25713     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
25714       B = LHS.getOperand(1);
25715     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
25716     std::copy(Mask.begin(), Mask.end(), LMask.begin());
25717   } else {
25718     if (LHS.getOpcode() != ISD::UNDEF)
25719       A = LHS;
25720     for (unsigned i = 0; i != NumElts; ++i)
25721       LMask[i] = i;
25722   }
25723
25724   // Likewise, view RHS in the form
25725   //   RHS = VECTOR_SHUFFLE C, D, RMask
25726   SDValue C, D;
25727   SmallVector<int, 16> RMask(NumElts);
25728   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
25729     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
25730       C = RHS.getOperand(0);
25731     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
25732       D = RHS.getOperand(1);
25733     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
25734     std::copy(Mask.begin(), Mask.end(), RMask.begin());
25735   } else {
25736     if (RHS.getOpcode() != ISD::UNDEF)
25737       C = RHS;
25738     for (unsigned i = 0; i != NumElts; ++i)
25739       RMask[i] = i;
25740   }
25741
25742   // Check that the shuffles are both shuffling the same vectors.
25743   if (!(A == C && B == D) && !(A == D && B == C))
25744     return false;
25745
25746   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
25747   if (!A.getNode() && !B.getNode())
25748     return false;
25749
25750   // If A and B occur in reverse order in RHS, then "swap" them (which means
25751   // rewriting the mask).
25752   if (A != C)
25753     ShuffleVectorSDNode::commuteMask(RMask);
25754
25755   // At this point LHS and RHS are equivalent to
25756   //   LHS = VECTOR_SHUFFLE A, B, LMask
25757   //   RHS = VECTOR_SHUFFLE A, B, RMask
25758   // Check that the masks correspond to performing a horizontal operation.
25759   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
25760     for (unsigned i = 0; i != NumLaneElts; ++i) {
25761       int LIdx = LMask[i+l], RIdx = RMask[i+l];
25762
25763       // Ignore any UNDEF components.
25764       if (LIdx < 0 || RIdx < 0 ||
25765           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
25766           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
25767         continue;
25768
25769       // Check that successive elements are being operated on.  If not, this is
25770       // not a horizontal operation.
25771       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
25772       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
25773       if (!(LIdx == Index && RIdx == Index + 1) &&
25774           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
25775         return false;
25776     }
25777   }
25778
25779   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
25780   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
25781   return true;
25782 }
25783
25784 /// Do target-specific dag combines on floating point adds.
25785 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
25786                                   const X86Subtarget *Subtarget) {
25787   EVT VT = N->getValueType(0);
25788   SDValue LHS = N->getOperand(0);
25789   SDValue RHS = N->getOperand(1);
25790
25791   // Try to synthesize horizontal adds from adds of shuffles.
25792   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
25793        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
25794       isHorizontalBinOp(LHS, RHS, true))
25795     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
25796   return SDValue();
25797 }
25798
25799 /// Do target-specific dag combines on floating point subs.
25800 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
25801                                   const X86Subtarget *Subtarget) {
25802   EVT VT = N->getValueType(0);
25803   SDValue LHS = N->getOperand(0);
25804   SDValue RHS = N->getOperand(1);
25805
25806   // Try to synthesize horizontal subs from subs of shuffles.
25807   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
25808        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
25809       isHorizontalBinOp(LHS, RHS, false))
25810     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
25811   return SDValue();
25812 }
25813
25814 /// Do target-specific dag combines on X86ISD::FOR and X86ISD::FXOR nodes.
25815 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG,
25816                                  const X86Subtarget *Subtarget) {
25817   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
25818
25819   // F[X]OR(0.0, x) -> x
25820   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
25821     if (C->getValueAPF().isPosZero())
25822       return N->getOperand(1);
25823
25824   // F[X]OR(x, 0.0) -> x
25825   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
25826     if (C->getValueAPF().isPosZero())
25827       return N->getOperand(0);
25828
25829   EVT VT = N->getValueType(0);
25830   if (VT.is512BitVector() && !Subtarget->hasDQI()) {
25831     SDLoc dl(N);
25832     MVT IntScalar = MVT::getIntegerVT(VT.getScalarSizeInBits());
25833     MVT IntVT = MVT::getVectorVT(IntScalar, VT.getVectorNumElements());
25834
25835     SDValue Op0 = DAG.getNode(ISD::BITCAST, dl, IntVT, N->getOperand(0));
25836     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, IntVT, N->getOperand(1));
25837     unsigned IntOpcode = (N->getOpcode() == X86ISD::FOR) ? ISD::OR : ISD::XOR;
25838     SDValue IntOp = DAG.getNode(IntOpcode, dl, IntVT, Op0, Op1);
25839     return  DAG.getNode(ISD::BITCAST, dl, VT, IntOp);
25840   }
25841   return SDValue();
25842 }
25843
25844 /// Do target-specific dag combines on X86ISD::FMIN and X86ISD::FMAX nodes.
25845 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
25846   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
25847
25848   // Only perform optimizations if UnsafeMath is used.
25849   if (!DAG.getTarget().Options.UnsafeFPMath)
25850     return SDValue();
25851
25852   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
25853   // into FMINC and FMAXC, which are Commutative operations.
25854   unsigned NewOp = 0;
25855   switch (N->getOpcode()) {
25856     default: llvm_unreachable("unknown opcode");
25857     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
25858     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
25859   }
25860
25861   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
25862                      N->getOperand(0), N->getOperand(1));
25863 }
25864
25865 /// Do target-specific dag combines on X86ISD::FAND nodes.
25866 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
25867   // FAND(0.0, x) -> 0.0
25868   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
25869     if (C->getValueAPF().isPosZero())
25870       return N->getOperand(0);
25871
25872   // FAND(x, 0.0) -> 0.0
25873   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
25874     if (C->getValueAPF().isPosZero())
25875       return N->getOperand(1);
25876
25877   return SDValue();
25878 }
25879
25880 /// Do target-specific dag combines on X86ISD::FANDN nodes
25881 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
25882   // FANDN(0.0, x) -> x
25883   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
25884     if (C->getValueAPF().isPosZero())
25885       return N->getOperand(1);
25886
25887   // FANDN(x, 0.0) -> 0.0
25888   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
25889     if (C->getValueAPF().isPosZero())
25890       return N->getOperand(1);
25891
25892   return SDValue();
25893 }
25894
25895 static SDValue PerformBTCombine(SDNode *N,
25896                                 SelectionDAG &DAG,
25897                                 TargetLowering::DAGCombinerInfo &DCI) {
25898   // BT ignores high bits in the bit index operand.
25899   SDValue Op1 = N->getOperand(1);
25900   if (Op1.hasOneUse()) {
25901     unsigned BitWidth = Op1.getValueSizeInBits();
25902     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
25903     APInt KnownZero, KnownOne;
25904     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
25905                                           !DCI.isBeforeLegalizeOps());
25906     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25907     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
25908         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
25909       DCI.CommitTargetLoweringOpt(TLO);
25910   }
25911   return SDValue();
25912 }
25913
25914 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
25915   SDValue Op = N->getOperand(0);
25916   if (Op.getOpcode() == ISD::BITCAST)
25917     Op = Op.getOperand(0);
25918   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
25919   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
25920       VT.getVectorElementType().getSizeInBits() ==
25921       OpVT.getVectorElementType().getSizeInBits()) {
25922     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
25923   }
25924   return SDValue();
25925 }
25926
25927 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
25928                                                const X86Subtarget *Subtarget) {
25929   EVT VT = N->getValueType(0);
25930   if (!VT.isVector())
25931     return SDValue();
25932
25933   SDValue N0 = N->getOperand(0);
25934   SDValue N1 = N->getOperand(1);
25935   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
25936   SDLoc dl(N);
25937
25938   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
25939   // both SSE and AVX2 since there is no sign-extended shift right
25940   // operation on a vector with 64-bit elements.
25941   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
25942   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
25943   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
25944       N0.getOpcode() == ISD::SIGN_EXTEND)) {
25945     SDValue N00 = N0.getOperand(0);
25946
25947     // EXTLOAD has a better solution on AVX2,
25948     // it may be replaced with X86ISD::VSEXT node.
25949     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
25950       if (!ISD::isNormalLoad(N00.getNode()))
25951         return SDValue();
25952
25953     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
25954         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
25955                                   N00, N1);
25956       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
25957     }
25958   }
25959   return SDValue();
25960 }
25961
25962 /// sext(add_nsw(x, C)) --> add(sext(x), C_sext)
25963 /// Promoting a sign extension ahead of an 'add nsw' exposes opportunities
25964 /// to combine math ops, use an LEA, or use a complex addressing mode. This can
25965 /// eliminate extend, add, and shift instructions.
25966 static SDValue promoteSextBeforeAddNSW(SDNode *Sext, SelectionDAG &DAG,
25967                                        const X86Subtarget *Subtarget) {
25968   // TODO: This should be valid for other integer types.
25969   EVT VT = Sext->getValueType(0);
25970   if (VT != MVT::i64)
25971     return SDValue();
25972
25973   // We need an 'add nsw' feeding into the 'sext'.
25974   SDValue Add = Sext->getOperand(0);
25975   if (Add.getOpcode() != ISD::ADD || !Add->getFlags()->hasNoSignedWrap())
25976     return SDValue();
25977
25978   // Having a constant operand to the 'add' ensures that we are not increasing
25979   // the instruction count because the constant is extended for free below.
25980   // A constant operand can also become the displacement field of an LEA.
25981   auto *AddOp1 = dyn_cast<ConstantSDNode>(Add.getOperand(1));
25982   if (!AddOp1)
25983     return SDValue();
25984
25985   // Don't make the 'add' bigger if there's no hope of combining it with some
25986   // other 'add' or 'shl' instruction.
25987   // TODO: It may be profitable to generate simpler LEA instructions in place
25988   // of single 'add' instructions, but the cost model for selecting an LEA
25989   // currently has a high threshold.
25990   bool HasLEAPotential = false;
25991   for (auto *User : Sext->uses()) {
25992     if (User->getOpcode() == ISD::ADD || User->getOpcode() == ISD::SHL) {
25993       HasLEAPotential = true;
25994       break;
25995     }
25996   }
25997   if (!HasLEAPotential)
25998     return SDValue();
25999
26000   // Everything looks good, so pull the 'sext' ahead of the 'add'.
26001   int64_t AddConstant = AddOp1->getSExtValue();
26002   SDValue AddOp0 = Add.getOperand(0);
26003   SDValue NewSext = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(Sext), VT, AddOp0);
26004   SDValue NewConstant = DAG.getConstant(AddConstant, SDLoc(Add), VT);
26005
26006   // The wider add is guaranteed to not wrap because both operands are
26007   // sign-extended.
26008   SDNodeFlags Flags;
26009   Flags.setNoSignedWrap(true);
26010   return DAG.getNode(ISD::ADD, SDLoc(Add), VT, NewSext, NewConstant, &Flags);
26011 }
26012
26013 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
26014                                   TargetLowering::DAGCombinerInfo &DCI,
26015                                   const X86Subtarget *Subtarget) {
26016   SDValue N0 = N->getOperand(0);
26017   EVT VT = N->getValueType(0);
26018   EVT SVT = VT.getScalarType();
26019   EVT InVT = N0.getValueType();
26020   EVT InSVT = InVT.getScalarType();
26021   SDLoc DL(N);
26022
26023   // (i8,i32 sext (sdivrem (i8 x, i8 y)) ->
26024   // (i8,i32 (sdivrem_sext_hreg (i8 x, i8 y)
26025   // This exposes the sext to the sdivrem lowering, so that it directly extends
26026   // from AH (which we otherwise need to do contortions to access).
26027   if (N0.getOpcode() == ISD::SDIVREM && N0.getResNo() == 1 &&
26028       InVT == MVT::i8 && VT == MVT::i32) {
26029     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
26030     SDValue R = DAG.getNode(X86ISD::SDIVREM8_SEXT_HREG, DL, NodeTys,
26031                             N0.getOperand(0), N0.getOperand(1));
26032     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
26033     return R.getValue(1);
26034   }
26035
26036   if (!DCI.isBeforeLegalizeOps()) {
26037     if (InVT == MVT::i1) {
26038       SDValue Zero = DAG.getConstant(0, DL, VT);
26039       SDValue AllOnes =
26040         DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL, VT);
26041       return DAG.getNode(ISD::SELECT, DL, VT, N0, AllOnes, Zero);
26042     }
26043     return SDValue();
26044   }
26045
26046   if (VT.isVector() && Subtarget->hasSSE2()) {
26047     auto ExtendVecSize = [&DAG](SDLoc DL, SDValue N, unsigned Size) {
26048       EVT InVT = N.getValueType();
26049       EVT OutVT = EVT::getVectorVT(*DAG.getContext(), InVT.getScalarType(),
26050                                    Size / InVT.getScalarSizeInBits());
26051       SmallVector<SDValue, 8> Opnds(Size / InVT.getSizeInBits(),
26052                                     DAG.getUNDEF(InVT));
26053       Opnds[0] = N;
26054       return DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Opnds);
26055     };
26056
26057     // If target-size is less than 128-bits, extend to a type that would extend
26058     // to 128 bits, extend that and extract the original target vector.
26059     if (VT.getSizeInBits() < 128 && !(128 % VT.getSizeInBits()) &&
26060         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
26061         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
26062       unsigned Scale = 128 / VT.getSizeInBits();
26063       EVT ExVT =
26064           EVT::getVectorVT(*DAG.getContext(), SVT, 128 / SVT.getSizeInBits());
26065       SDValue Ex = ExtendVecSize(DL, N0, Scale * InVT.getSizeInBits());
26066       SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, ExVT, Ex);
26067       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, SExt,
26068                          DAG.getIntPtrConstant(0, DL));
26069     }
26070
26071     // If target-size is 128-bits, then convert to ISD::SIGN_EXTEND_VECTOR_INREG
26072     // which ensures lowering to X86ISD::VSEXT (pmovsx*).
26073     if (VT.getSizeInBits() == 128 &&
26074         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
26075         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
26076       SDValue ExOp = ExtendVecSize(DL, N0, 128);
26077       return DAG.getSignExtendVectorInReg(ExOp, DL, VT);
26078     }
26079
26080     // On pre-AVX2 targets, split into 128-bit nodes of
26081     // ISD::SIGN_EXTEND_VECTOR_INREG.
26082     if (!Subtarget->hasInt256() && !(VT.getSizeInBits() % 128) &&
26083         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
26084         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
26085       unsigned NumVecs = VT.getSizeInBits() / 128;
26086       unsigned NumSubElts = 128 / SVT.getSizeInBits();
26087       EVT SubVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumSubElts);
26088       EVT InSubVT = EVT::getVectorVT(*DAG.getContext(), InSVT, NumSubElts);
26089
26090       SmallVector<SDValue, 8> Opnds;
26091       for (unsigned i = 0, Offset = 0; i != NumVecs;
26092            ++i, Offset += NumSubElts) {
26093         SDValue SrcVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InSubVT, N0,
26094                                      DAG.getIntPtrConstant(Offset, DL));
26095         SrcVec = ExtendVecSize(DL, SrcVec, 128);
26096         SrcVec = DAG.getSignExtendVectorInReg(SrcVec, DL, SubVT);
26097         Opnds.push_back(SrcVec);
26098       }
26099       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Opnds);
26100     }
26101   }
26102
26103   if (Subtarget->hasAVX() && VT.is256BitVector())
26104     if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
26105       return R;
26106
26107   if (SDValue NewAdd = promoteSextBeforeAddNSW(N, DAG, Subtarget))
26108     return NewAdd;
26109
26110   return SDValue();
26111 }
26112
26113 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
26114                                  const X86Subtarget* Subtarget) {
26115   SDLoc dl(N);
26116   EVT VT = N->getValueType(0);
26117
26118   // Let legalize expand this if it isn't a legal type yet.
26119   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
26120     return SDValue();
26121
26122   EVT ScalarVT = VT.getScalarType();
26123   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
26124       (!Subtarget->hasFMA() && !Subtarget->hasFMA4() &&
26125        !Subtarget->hasAVX512()))
26126     return SDValue();
26127
26128   SDValue A = N->getOperand(0);
26129   SDValue B = N->getOperand(1);
26130   SDValue C = N->getOperand(2);
26131
26132   bool NegA = (A.getOpcode() == ISD::FNEG);
26133   bool NegB = (B.getOpcode() == ISD::FNEG);
26134   bool NegC = (C.getOpcode() == ISD::FNEG);
26135
26136   // Negative multiplication when NegA xor NegB
26137   bool NegMul = (NegA != NegB);
26138   if (NegA)
26139     A = A.getOperand(0);
26140   if (NegB)
26141     B = B.getOperand(0);
26142   if (NegC)
26143     C = C.getOperand(0);
26144
26145   unsigned Opcode;
26146   if (!NegMul)
26147     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
26148   else
26149     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
26150
26151   return DAG.getNode(Opcode, dl, VT, A, B, C);
26152 }
26153
26154 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
26155                                   TargetLowering::DAGCombinerInfo &DCI,
26156                                   const X86Subtarget *Subtarget) {
26157   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
26158   //           (and (i32 x86isd::setcc_carry), 1)
26159   // This eliminates the zext. This transformation is necessary because
26160   // ISD::SETCC is always legalized to i8.
26161   SDLoc dl(N);
26162   SDValue N0 = N->getOperand(0);
26163   EVT VT = N->getValueType(0);
26164
26165   if (N0.getOpcode() == ISD::AND &&
26166       N0.hasOneUse() &&
26167       N0.getOperand(0).hasOneUse()) {
26168     SDValue N00 = N0.getOperand(0);
26169     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
26170       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
26171       if (!C || C->getZExtValue() != 1)
26172         return SDValue();
26173       return DAG.getNode(ISD::AND, dl, VT,
26174                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
26175                                      N00.getOperand(0), N00.getOperand(1)),
26176                          DAG.getConstant(1, dl, VT));
26177     }
26178   }
26179
26180   if (N0.getOpcode() == ISD::TRUNCATE &&
26181       N0.hasOneUse() &&
26182       N0.getOperand(0).hasOneUse()) {
26183     SDValue N00 = N0.getOperand(0);
26184     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
26185       return DAG.getNode(ISD::AND, dl, VT,
26186                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
26187                                      N00.getOperand(0), N00.getOperand(1)),
26188                          DAG.getConstant(1, dl, VT));
26189     }
26190   }
26191
26192   if (VT.is256BitVector())
26193     if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
26194       return R;
26195
26196   // (i8,i32 zext (udivrem (i8 x, i8 y)) ->
26197   // (i8,i32 (udivrem_zext_hreg (i8 x, i8 y)
26198   // This exposes the zext to the udivrem lowering, so that it directly extends
26199   // from AH (which we otherwise need to do contortions to access).
26200   if (N0.getOpcode() == ISD::UDIVREM &&
26201       N0.getResNo() == 1 && N0.getValueType() == MVT::i8 &&
26202       (VT == MVT::i32 || VT == MVT::i64)) {
26203     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
26204     SDValue R = DAG.getNode(X86ISD::UDIVREM8_ZEXT_HREG, dl, NodeTys,
26205                             N0.getOperand(0), N0.getOperand(1));
26206     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
26207     return R.getValue(1);
26208   }
26209
26210   return SDValue();
26211 }
26212
26213 // Optimize x == -y --> x+y == 0
26214 //          x != -y --> x+y != 0
26215 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
26216                                       const X86Subtarget* Subtarget) {
26217   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
26218   SDValue LHS = N->getOperand(0);
26219   SDValue RHS = N->getOperand(1);
26220   EVT VT = N->getValueType(0);
26221   SDLoc DL(N);
26222
26223   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
26224     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
26225       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
26226         SDValue addV = DAG.getNode(ISD::ADD, DL, LHS.getValueType(), RHS,
26227                                    LHS.getOperand(1));
26228         return DAG.getSetCC(DL, N->getValueType(0), addV,
26229                             DAG.getConstant(0, DL, addV.getValueType()), CC);
26230       }
26231   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
26232     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
26233       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
26234         SDValue addV = DAG.getNode(ISD::ADD, DL, RHS.getValueType(), LHS,
26235                                    RHS.getOperand(1));
26236         return DAG.getSetCC(DL, N->getValueType(0), addV,
26237                             DAG.getConstant(0, DL, addV.getValueType()), CC);
26238       }
26239
26240   if (VT.getScalarType() == MVT::i1 &&
26241       (CC == ISD::SETNE || CC == ISD::SETEQ || ISD::isSignedIntSetCC(CC))) {
26242     bool IsSEXT0 =
26243         (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
26244         (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
26245     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
26246
26247     if (!IsSEXT0 || !IsVZero1) {
26248       // Swap the operands and update the condition code.
26249       std::swap(LHS, RHS);
26250       CC = ISD::getSetCCSwappedOperands(CC);
26251
26252       IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
26253                 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
26254       IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
26255     }
26256
26257     if (IsSEXT0 && IsVZero1) {
26258       assert(VT == LHS.getOperand(0).getValueType() &&
26259              "Uexpected operand type");
26260       if (CC == ISD::SETGT)
26261         return DAG.getConstant(0, DL, VT);
26262       if (CC == ISD::SETLE)
26263         return DAG.getConstant(1, DL, VT);
26264       if (CC == ISD::SETEQ || CC == ISD::SETGE)
26265         return DAG.getNOT(DL, LHS.getOperand(0), VT);
26266
26267       assert((CC == ISD::SETNE || CC == ISD::SETLT) &&
26268              "Unexpected condition code!");
26269       return LHS.getOperand(0);
26270     }
26271   }
26272
26273   return SDValue();
26274 }
26275
26276 static SDValue PerformBLENDICombine(SDNode *N, SelectionDAG &DAG) {
26277   SDValue V0 = N->getOperand(0);
26278   SDValue V1 = N->getOperand(1);
26279   SDLoc DL(N);
26280   EVT VT = N->getValueType(0);
26281
26282   // Canonicalize a v2f64 blend with a mask of 2 by swapping the vector
26283   // operands and changing the mask to 1. This saves us a bunch of
26284   // pattern-matching possibilities related to scalar math ops in SSE/AVX.
26285   // x86InstrInfo knows how to commute this back after instruction selection
26286   // if it would help register allocation.
26287
26288   // TODO: If optimizing for size or a processor that doesn't suffer from
26289   // partial register update stalls, this should be transformed into a MOVSD
26290   // instruction because a MOVSD is 1-2 bytes smaller than a BLENDPD.
26291
26292   if (VT == MVT::v2f64)
26293     if (auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(2)))
26294       if (Mask->getZExtValue() == 2 && !isShuffleFoldableLoad(V0)) {
26295         SDValue NewMask = DAG.getConstant(1, DL, MVT::i8);
26296         return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V0, NewMask);
26297       }
26298
26299   return SDValue();
26300 }
26301
26302 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
26303 // as "sbb reg,reg", since it can be extended without zext and produces
26304 // an all-ones bit which is more useful than 0/1 in some cases.
26305 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
26306                                MVT VT) {
26307   if (VT == MVT::i8)
26308     return DAG.getNode(ISD::AND, DL, VT,
26309                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
26310                                    DAG.getConstant(X86::COND_B, DL, MVT::i8),
26311                                    EFLAGS),
26312                        DAG.getConstant(1, DL, VT));
26313   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
26314   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
26315                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
26316                                  DAG.getConstant(X86::COND_B, DL, MVT::i8),
26317                                  EFLAGS));
26318 }
26319
26320 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
26321 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
26322                                    TargetLowering::DAGCombinerInfo &DCI,
26323                                    const X86Subtarget *Subtarget) {
26324   SDLoc DL(N);
26325   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
26326   SDValue EFLAGS = N->getOperand(1);
26327
26328   if (CC == X86::COND_A) {
26329     // Try to convert COND_A into COND_B in an attempt to facilitate
26330     // materializing "setb reg".
26331     //
26332     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
26333     // cannot take an immediate as its first operand.
26334     //
26335     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
26336         EFLAGS.getValueType().isInteger() &&
26337         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
26338       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
26339                                    EFLAGS.getNode()->getVTList(),
26340                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
26341       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
26342       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
26343     }
26344   }
26345
26346   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
26347   // a zext and produces an all-ones bit which is more useful than 0/1 in some
26348   // cases.
26349   if (CC == X86::COND_B)
26350     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
26351
26352   if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
26353     SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
26354     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
26355   }
26356
26357   return SDValue();
26358 }
26359
26360 // Optimize branch condition evaluation.
26361 //
26362 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
26363                                     TargetLowering::DAGCombinerInfo &DCI,
26364                                     const X86Subtarget *Subtarget) {
26365   SDLoc DL(N);
26366   SDValue Chain = N->getOperand(0);
26367   SDValue Dest = N->getOperand(1);
26368   SDValue EFLAGS = N->getOperand(3);
26369   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
26370
26371   if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
26372     SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
26373     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
26374                        Flags);
26375   }
26376
26377   return SDValue();
26378 }
26379
26380 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
26381                                                          SelectionDAG &DAG) {
26382   // Take advantage of vector comparisons producing 0 or -1 in each lane to
26383   // optimize away operation when it's from a constant.
26384   //
26385   // The general transformation is:
26386   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
26387   //       AND(VECTOR_CMP(x,y), constant2)
26388   //    constant2 = UNARYOP(constant)
26389
26390   // Early exit if this isn't a vector operation, the operand of the
26391   // unary operation isn't a bitwise AND, or if the sizes of the operations
26392   // aren't the same.
26393   EVT VT = N->getValueType(0);
26394   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
26395       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
26396       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
26397     return SDValue();
26398
26399   // Now check that the other operand of the AND is a constant. We could
26400   // make the transformation for non-constant splats as well, but it's unclear
26401   // that would be a benefit as it would not eliminate any operations, just
26402   // perform one more step in scalar code before moving to the vector unit.
26403   if (BuildVectorSDNode *BV =
26404           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
26405     // Bail out if the vector isn't a constant.
26406     if (!BV->isConstant())
26407       return SDValue();
26408
26409     // Everything checks out. Build up the new and improved node.
26410     SDLoc DL(N);
26411     EVT IntVT = BV->getValueType(0);
26412     // Create a new constant of the appropriate type for the transformed
26413     // DAG.
26414     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
26415     // The AND node needs bitcasts to/from an integer vector type around it.
26416     SDValue MaskConst = DAG.getBitcast(IntVT, SourceConst);
26417     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
26418                                  N->getOperand(0)->getOperand(0), MaskConst);
26419     SDValue Res = DAG.getBitcast(VT, NewAnd);
26420     return Res;
26421   }
26422
26423   return SDValue();
26424 }
26425
26426 static SDValue PerformUINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
26427                                         const X86Subtarget *Subtarget) {
26428   SDValue Op0 = N->getOperand(0);
26429   EVT VT = N->getValueType(0);
26430   EVT InVT = Op0.getValueType();
26431   EVT InSVT = InVT.getScalarType();
26432   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
26433
26434   // UINT_TO_FP(vXi8) -> SINT_TO_FP(ZEXT(vXi8 to vXi32))
26435   // UINT_TO_FP(vXi16) -> SINT_TO_FP(ZEXT(vXi16 to vXi32))
26436   if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
26437     SDLoc dl(N);
26438     EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
26439                                  InVT.getVectorNumElements());
26440     SDValue P = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Op0);
26441
26442     if (TLI.isOperationLegal(ISD::UINT_TO_FP, DstVT))
26443       return DAG.getNode(ISD::UINT_TO_FP, dl, VT, P);
26444
26445     return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
26446   }
26447
26448   return SDValue();
26449 }
26450
26451 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
26452                                         const X86Subtarget *Subtarget) {
26453   // First try to optimize away the conversion entirely when it's
26454   // conditionally from a constant. Vectors only.
26455   if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
26456     return Res;
26457
26458   // Now move on to more general possibilities.
26459   SDValue Op0 = N->getOperand(0);
26460   EVT VT = N->getValueType(0);
26461   EVT InVT = Op0.getValueType();
26462   EVT InSVT = InVT.getScalarType();
26463
26464   // SINT_TO_FP(vXi8) -> SINT_TO_FP(SEXT(vXi8 to vXi32))
26465   // SINT_TO_FP(vXi16) -> SINT_TO_FP(SEXT(vXi16 to vXi32))
26466   if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
26467     SDLoc dl(N);
26468     EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
26469                                  InVT.getVectorNumElements());
26470     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
26471     return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
26472   }
26473
26474   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
26475   // a 32-bit target where SSE doesn't support i64->FP operations.  
26476   if (!Subtarget->useSoftFloat() && Op0.getOpcode() == ISD::LOAD) {
26477     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
26478     EVT LdVT = Ld->getValueType(0);
26479
26480     // This transformation is not supported if the result type is f16
26481     if (VT == MVT::f16)
26482       return SDValue();
26483
26484     if (!Ld->isVolatile() && !VT.isVector() &&
26485         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
26486         !Subtarget->is64Bit() && LdVT == MVT::i64) {
26487       SDValue FILDChain = Subtarget->getTargetLowering()->BuildFILD(
26488           SDValue(N, 0), LdVT, Ld->getChain(), Op0, DAG);
26489       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
26490       return FILDChain;
26491     }
26492   }
26493   return SDValue();
26494 }
26495
26496 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
26497 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
26498                                  X86TargetLowering::DAGCombinerInfo &DCI) {
26499   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
26500   // the result is either zero or one (depending on the input carry bit).
26501   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
26502   if (X86::isZeroNode(N->getOperand(0)) &&
26503       X86::isZeroNode(N->getOperand(1)) &&
26504       // We don't have a good way to replace an EFLAGS use, so only do this when
26505       // dead right now.
26506       SDValue(N, 1).use_empty()) {
26507     SDLoc DL(N);
26508     EVT VT = N->getValueType(0);
26509     SDValue CarryOut = DAG.getConstant(0, DL, N->getValueType(1));
26510     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
26511                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
26512                                            DAG.getConstant(X86::COND_B, DL,
26513                                                            MVT::i8),
26514                                            N->getOperand(2)),
26515                                DAG.getConstant(1, DL, VT));
26516     return DCI.CombineTo(N, Res1, CarryOut);
26517   }
26518
26519   return SDValue();
26520 }
26521
26522 // fold (add Y, (sete  X, 0)) -> adc  0, Y
26523 //      (add Y, (setne X, 0)) -> sbb -1, Y
26524 //      (sub (sete  X, 0), Y) -> sbb  0, Y
26525 //      (sub (setne X, 0), Y) -> adc -1, Y
26526 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
26527   SDLoc DL(N);
26528
26529   // Look through ZExts.
26530   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
26531   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
26532     return SDValue();
26533
26534   SDValue SetCC = Ext.getOperand(0);
26535   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
26536     return SDValue();
26537
26538   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
26539   if (CC != X86::COND_E && CC != X86::COND_NE)
26540     return SDValue();
26541
26542   SDValue Cmp = SetCC.getOperand(1);
26543   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
26544       !X86::isZeroNode(Cmp.getOperand(1)) ||
26545       !Cmp.getOperand(0).getValueType().isInteger())
26546     return SDValue();
26547
26548   SDValue CmpOp0 = Cmp.getOperand(0);
26549   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
26550                                DAG.getConstant(1, DL, CmpOp0.getValueType()));
26551
26552   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
26553   if (CC == X86::COND_NE)
26554     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
26555                        DL, OtherVal.getValueType(), OtherVal,
26556                        DAG.getConstant(-1ULL, DL, OtherVal.getValueType()),
26557                        NewCmp);
26558   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
26559                      DL, OtherVal.getValueType(), OtherVal,
26560                      DAG.getConstant(0, DL, OtherVal.getValueType()), NewCmp);
26561 }
26562
26563 /// PerformADDCombine - Do target-specific dag combines on integer adds.
26564 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
26565                                  const X86Subtarget *Subtarget) {
26566   EVT VT = N->getValueType(0);
26567   SDValue Op0 = N->getOperand(0);
26568   SDValue Op1 = N->getOperand(1);
26569
26570   // Try to synthesize horizontal adds from adds of shuffles.
26571   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
26572        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
26573       isHorizontalBinOp(Op0, Op1, true))
26574     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
26575
26576   return OptimizeConditionalInDecrement(N, DAG);
26577 }
26578
26579 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
26580                                  const X86Subtarget *Subtarget) {
26581   SDValue Op0 = N->getOperand(0);
26582   SDValue Op1 = N->getOperand(1);
26583
26584   // X86 can't encode an immediate LHS of a sub. See if we can push the
26585   // negation into a preceding instruction.
26586   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
26587     // If the RHS of the sub is a XOR with one use and a constant, invert the
26588     // immediate. Then add one to the LHS of the sub so we can turn
26589     // X-Y -> X+~Y+1, saving one register.
26590     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
26591         isa<ConstantSDNode>(Op1.getOperand(1))) {
26592       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
26593       EVT VT = Op0.getValueType();
26594       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
26595                                    Op1.getOperand(0),
26596                                    DAG.getConstant(~XorC, SDLoc(Op1), VT));
26597       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
26598                          DAG.getConstant(C->getAPIntValue() + 1, SDLoc(N), VT));
26599     }
26600   }
26601
26602   // Try to synthesize horizontal adds from adds of shuffles.
26603   EVT VT = N->getValueType(0);
26604   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
26605        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
26606       isHorizontalBinOp(Op0, Op1, true))
26607     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
26608
26609   return OptimizeConditionalInDecrement(N, DAG);
26610 }
26611
26612 /// performVZEXTCombine - Performs build vector combines
26613 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
26614                                    TargetLowering::DAGCombinerInfo &DCI,
26615                                    const X86Subtarget *Subtarget) {
26616   SDLoc DL(N);
26617   MVT VT = N->getSimpleValueType(0);
26618   SDValue Op = N->getOperand(0);
26619   MVT OpVT = Op.getSimpleValueType();
26620   MVT OpEltVT = OpVT.getVectorElementType();
26621   unsigned InputBits = OpEltVT.getSizeInBits() * VT.getVectorNumElements();
26622
26623   // (vzext (bitcast (vzext (x)) -> (vzext x)
26624   SDValue V = Op;
26625   while (V.getOpcode() == ISD::BITCAST)
26626     V = V.getOperand(0);
26627
26628   if (V != Op && V.getOpcode() == X86ISD::VZEXT) {
26629     MVT InnerVT = V.getSimpleValueType();
26630     MVT InnerEltVT = InnerVT.getVectorElementType();
26631
26632     // If the element sizes match exactly, we can just do one larger vzext. This
26633     // is always an exact type match as vzext operates on integer types.
26634     if (OpEltVT == InnerEltVT) {
26635       assert(OpVT == InnerVT && "Types must match for vzext!");
26636       return DAG.getNode(X86ISD::VZEXT, DL, VT, V.getOperand(0));
26637     }
26638
26639     // The only other way we can combine them is if only a single element of the
26640     // inner vzext is used in the input to the outer vzext.
26641     if (InnerEltVT.getSizeInBits() < InputBits)
26642       return SDValue();
26643
26644     // In this case, the inner vzext is completely dead because we're going to
26645     // only look at bits inside of the low element. Just do the outer vzext on
26646     // a bitcast of the input to the inner.
26647     return DAG.getNode(X86ISD::VZEXT, DL, VT, DAG.getBitcast(OpVT, V));
26648   }
26649
26650   // Check if we can bypass extracting and re-inserting an element of an input
26651   // vector. Essentially:
26652   // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
26653   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR &&
26654       V.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
26655       V.getOperand(0).getSimpleValueType().getSizeInBits() == InputBits) {
26656     SDValue ExtractedV = V.getOperand(0);
26657     SDValue OrigV = ExtractedV.getOperand(0);
26658     if (auto *ExtractIdx = dyn_cast<ConstantSDNode>(ExtractedV.getOperand(1)))
26659       if (ExtractIdx->getZExtValue() == 0) {
26660         MVT OrigVT = OrigV.getSimpleValueType();
26661         // Extract a subvector if necessary...
26662         if (OrigVT.getSizeInBits() > OpVT.getSizeInBits()) {
26663           int Ratio = OrigVT.getSizeInBits() / OpVT.getSizeInBits();
26664           OrigVT = MVT::getVectorVT(OrigVT.getVectorElementType(),
26665                                     OrigVT.getVectorNumElements() / Ratio);
26666           OrigV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigVT, OrigV,
26667                               DAG.getIntPtrConstant(0, DL));
26668         }
26669         Op = DAG.getBitcast(OpVT, OrigV);
26670         return DAG.getNode(X86ISD::VZEXT, DL, VT, Op);
26671       }
26672   }
26673
26674   return SDValue();
26675 }
26676
26677 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
26678                                              DAGCombinerInfo &DCI) const {
26679   SelectionDAG &DAG = DCI.DAG;
26680   switch (N->getOpcode()) {
26681   default: break;
26682   case ISD::EXTRACT_VECTOR_ELT:
26683     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
26684   case ISD::VSELECT:
26685   case ISD::SELECT:
26686   case X86ISD::SHRUNKBLEND:
26687     return PerformSELECTCombine(N, DAG, DCI, Subtarget);
26688   case ISD::BITCAST:        return PerformBITCASTCombine(N, DAG, Subtarget);
26689   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
26690   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
26691   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
26692   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
26693   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
26694   case ISD::SHL:
26695   case ISD::SRA:
26696   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
26697   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
26698   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
26699   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
26700   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
26701   case ISD::MLOAD:          return PerformMLOADCombine(N, DAG, DCI, Subtarget);
26702   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
26703   case ISD::MSTORE:         return PerformMSTORECombine(N, DAG, Subtarget);
26704   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, Subtarget);
26705   case ISD::UINT_TO_FP:     return PerformUINT_TO_FPCombine(N, DAG, Subtarget);
26706   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
26707   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
26708   case X86ISD::FXOR:
26709   case X86ISD::FOR:         return PerformFORCombine(N, DAG, Subtarget);
26710   case X86ISD::FMIN:
26711   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
26712   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
26713   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
26714   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
26715   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
26716   case ISD::ANY_EXTEND:
26717   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
26718   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
26719   case ISD::SIGN_EXTEND_INREG:
26720     return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
26721   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
26722   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
26723   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
26724   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
26725   case X86ISD::SHUFP:       // Handle all target specific shuffles
26726   case X86ISD::PALIGNR:
26727   case X86ISD::UNPCKH:
26728   case X86ISD::UNPCKL:
26729   case X86ISD::MOVHLPS:
26730   case X86ISD::MOVLHPS:
26731   case X86ISD::PSHUFB:
26732   case X86ISD::PSHUFD:
26733   case X86ISD::PSHUFHW:
26734   case X86ISD::PSHUFLW:
26735   case X86ISD::MOVSS:
26736   case X86ISD::MOVSD:
26737   case X86ISD::VPERMILPI:
26738   case X86ISD::VPERM2X128:
26739   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
26740   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
26741   case X86ISD::BLENDI:    return PerformBLENDICombine(N, DAG);
26742   }
26743
26744   return SDValue();
26745 }
26746
26747 /// isTypeDesirableForOp - Return true if the target has native support for
26748 /// the specified value type and it is 'desirable' to use the type for the
26749 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
26750 /// instruction encodings are longer and some i16 instructions are slow.
26751 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
26752   if (!isTypeLegal(VT))
26753     return false;
26754   if (VT != MVT::i16)
26755     return true;
26756
26757   switch (Opc) {
26758   default:
26759     return true;
26760   case ISD::LOAD:
26761   case ISD::SIGN_EXTEND:
26762   case ISD::ZERO_EXTEND:
26763   case ISD::ANY_EXTEND:
26764   case ISD::SHL:
26765   case ISD::SRL:
26766   case ISD::SUB:
26767   case ISD::ADD:
26768   case ISD::MUL:
26769   case ISD::AND:
26770   case ISD::OR:
26771   case ISD::XOR:
26772     return false;
26773   }
26774 }
26775
26776 /// IsDesirableToPromoteOp - This method query the target whether it is
26777 /// beneficial for dag combiner to promote the specified node. If true, it
26778 /// should return the desired promotion type by reference.
26779 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
26780   EVT VT = Op.getValueType();
26781   if (VT != MVT::i16)
26782     return false;
26783
26784   bool Promote = false;
26785   bool Commute = false;
26786   switch (Op.getOpcode()) {
26787   default: break;
26788   case ISD::LOAD: {
26789     LoadSDNode *LD = cast<LoadSDNode>(Op);
26790     // If the non-extending load has a single use and it's not live out, then it
26791     // might be folded.
26792     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
26793                                                      Op.hasOneUse()*/) {
26794       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
26795              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
26796         // The only case where we'd want to promote LOAD (rather then it being
26797         // promoted as an operand is when it's only use is liveout.
26798         if (UI->getOpcode() != ISD::CopyToReg)
26799           return false;
26800       }
26801     }
26802     Promote = true;
26803     break;
26804   }
26805   case ISD::SIGN_EXTEND:
26806   case ISD::ZERO_EXTEND:
26807   case ISD::ANY_EXTEND:
26808     Promote = true;
26809     break;
26810   case ISD::SHL:
26811   case ISD::SRL: {
26812     SDValue N0 = Op.getOperand(0);
26813     // Look out for (store (shl (load), x)).
26814     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
26815       return false;
26816     Promote = true;
26817     break;
26818   }
26819   case ISD::ADD:
26820   case ISD::MUL:
26821   case ISD::AND:
26822   case ISD::OR:
26823   case ISD::XOR:
26824     Commute = true;
26825     // fallthrough
26826   case ISD::SUB: {
26827     SDValue N0 = Op.getOperand(0);
26828     SDValue N1 = Op.getOperand(1);
26829     if (!Commute && MayFoldLoad(N1))
26830       return false;
26831     // Avoid disabling potential load folding opportunities.
26832     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
26833       return false;
26834     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
26835       return false;
26836     Promote = true;
26837   }
26838   }
26839
26840   PVT = MVT::i32;
26841   return Promote;
26842 }
26843
26844 //===----------------------------------------------------------------------===//
26845 //                           X86 Inline Assembly Support
26846 //===----------------------------------------------------------------------===//
26847
26848 // Helper to match a string separated by whitespace.
26849 static bool matchAsm(StringRef S, ArrayRef<const char *> Pieces) {
26850   S = S.substr(S.find_first_not_of(" \t")); // Skip leading whitespace.
26851
26852   for (StringRef Piece : Pieces) {
26853     if (!S.startswith(Piece)) // Check if the piece matches.
26854       return false;
26855
26856     S = S.substr(Piece.size());
26857     StringRef::size_type Pos = S.find_first_not_of(" \t");
26858     if (Pos == 0) // We matched a prefix.
26859       return false;
26860
26861     S = S.substr(Pos);
26862   }
26863
26864   return S.empty();
26865 }
26866
26867 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
26868
26869   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
26870     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
26871         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
26872         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
26873
26874       if (AsmPieces.size() == 3)
26875         return true;
26876       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
26877         return true;
26878     }
26879   }
26880   return false;
26881 }
26882
26883 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
26884   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
26885
26886   std::string AsmStr = IA->getAsmString();
26887
26888   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
26889   if (!Ty || Ty->getBitWidth() % 16 != 0)
26890     return false;
26891
26892   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
26893   SmallVector<StringRef, 4> AsmPieces;
26894   SplitString(AsmStr, AsmPieces, ";\n");
26895
26896   switch (AsmPieces.size()) {
26897   default: return false;
26898   case 1:
26899     // FIXME: this should verify that we are targeting a 486 or better.  If not,
26900     // we will turn this bswap into something that will be lowered to logical
26901     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
26902     // lower so don't worry about this.
26903     // bswap $0
26904     if (matchAsm(AsmPieces[0], {"bswap", "$0"}) ||
26905         matchAsm(AsmPieces[0], {"bswapl", "$0"}) ||
26906         matchAsm(AsmPieces[0], {"bswapq", "$0"}) ||
26907         matchAsm(AsmPieces[0], {"bswap", "${0:q}"}) ||
26908         matchAsm(AsmPieces[0], {"bswapl", "${0:q}"}) ||
26909         matchAsm(AsmPieces[0], {"bswapq", "${0:q}"})) {
26910       // No need to check constraints, nothing other than the equivalent of
26911       // "=r,0" would be valid here.
26912       return IntrinsicLowering::LowerToByteSwap(CI);
26913     }
26914
26915     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
26916     if (CI->getType()->isIntegerTy(16) &&
26917         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
26918         (matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) ||
26919          matchAsm(AsmPieces[0], {"rolw", "$$8,", "${0:w}"}))) {
26920       AsmPieces.clear();
26921       StringRef ConstraintsStr = IA->getConstraintString();
26922       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
26923       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
26924       if (clobbersFlagRegisters(AsmPieces))
26925         return IntrinsicLowering::LowerToByteSwap(CI);
26926     }
26927     break;
26928   case 3:
26929     if (CI->getType()->isIntegerTy(32) &&
26930         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
26931         matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) &&
26932         matchAsm(AsmPieces[1], {"rorl", "$$16,", "$0"}) &&
26933         matchAsm(AsmPieces[2], {"rorw", "$$8,", "${0:w}"})) {
26934       AsmPieces.clear();
26935       StringRef ConstraintsStr = IA->getConstraintString();
26936       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
26937       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
26938       if (clobbersFlagRegisters(AsmPieces))
26939         return IntrinsicLowering::LowerToByteSwap(CI);
26940     }
26941
26942     if (CI->getType()->isIntegerTy(64)) {
26943       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
26944       if (Constraints.size() >= 2 &&
26945           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
26946           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
26947         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
26948         if (matchAsm(AsmPieces[0], {"bswap", "%eax"}) &&
26949             matchAsm(AsmPieces[1], {"bswap", "%edx"}) &&
26950             matchAsm(AsmPieces[2], {"xchgl", "%eax,", "%edx"}))
26951           return IntrinsicLowering::LowerToByteSwap(CI);
26952       }
26953     }
26954     break;
26955   }
26956   return false;
26957 }
26958
26959 /// getConstraintType - Given a constraint letter, return the type of
26960 /// constraint it is for this target.
26961 X86TargetLowering::ConstraintType
26962 X86TargetLowering::getConstraintType(StringRef Constraint) const {
26963   if (Constraint.size() == 1) {
26964     switch (Constraint[0]) {
26965     case 'R':
26966     case 'q':
26967     case 'Q':
26968     case 'f':
26969     case 't':
26970     case 'u':
26971     case 'y':
26972     case 'x':
26973     case 'Y':
26974     case 'l':
26975       return C_RegisterClass;
26976     case 'a':
26977     case 'b':
26978     case 'c':
26979     case 'd':
26980     case 'S':
26981     case 'D':
26982     case 'A':
26983       return C_Register;
26984     case 'I':
26985     case 'J':
26986     case 'K':
26987     case 'L':
26988     case 'M':
26989     case 'N':
26990     case 'G':
26991     case 'C':
26992     case 'e':
26993     case 'Z':
26994       return C_Other;
26995     default:
26996       break;
26997     }
26998   }
26999   return TargetLowering::getConstraintType(Constraint);
27000 }
27001
27002 /// Examine constraint type and operand type and determine a weight value.
27003 /// This object must already have been set up with the operand type
27004 /// and the current alternative constraint selected.
27005 TargetLowering::ConstraintWeight
27006   X86TargetLowering::getSingleConstraintMatchWeight(
27007     AsmOperandInfo &info, const char *constraint) const {
27008   ConstraintWeight weight = CW_Invalid;
27009   Value *CallOperandVal = info.CallOperandVal;
27010     // If we don't have a value, we can't do a match,
27011     // but allow it at the lowest weight.
27012   if (!CallOperandVal)
27013     return CW_Default;
27014   Type *type = CallOperandVal->getType();
27015   // Look at the constraint type.
27016   switch (*constraint) {
27017   default:
27018     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
27019   case 'R':
27020   case 'q':
27021   case 'Q':
27022   case 'a':
27023   case 'b':
27024   case 'c':
27025   case 'd':
27026   case 'S':
27027   case 'D':
27028   case 'A':
27029     if (CallOperandVal->getType()->isIntegerTy())
27030       weight = CW_SpecificReg;
27031     break;
27032   case 'f':
27033   case 't':
27034   case 'u':
27035     if (type->isFloatingPointTy())
27036       weight = CW_SpecificReg;
27037     break;
27038   case 'y':
27039     if (type->isX86_MMXTy() && Subtarget->hasMMX())
27040       weight = CW_SpecificReg;
27041     break;
27042   case 'x':
27043   case 'Y':
27044     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
27045         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
27046       weight = CW_Register;
27047     break;
27048   case 'I':
27049     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
27050       if (C->getZExtValue() <= 31)
27051         weight = CW_Constant;
27052     }
27053     break;
27054   case 'J':
27055     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
27056       if (C->getZExtValue() <= 63)
27057         weight = CW_Constant;
27058     }
27059     break;
27060   case 'K':
27061     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
27062       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
27063         weight = CW_Constant;
27064     }
27065     break;
27066   case 'L':
27067     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
27068       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
27069         weight = CW_Constant;
27070     }
27071     break;
27072   case 'M':
27073     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
27074       if (C->getZExtValue() <= 3)
27075         weight = CW_Constant;
27076     }
27077     break;
27078   case 'N':
27079     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
27080       if (C->getZExtValue() <= 0xff)
27081         weight = CW_Constant;
27082     }
27083     break;
27084   case 'G':
27085   case 'C':
27086     if (isa<ConstantFP>(CallOperandVal)) {
27087       weight = CW_Constant;
27088     }
27089     break;
27090   case 'e':
27091     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
27092       if ((C->getSExtValue() >= -0x80000000LL) &&
27093           (C->getSExtValue() <= 0x7fffffffLL))
27094         weight = CW_Constant;
27095     }
27096     break;
27097   case 'Z':
27098     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
27099       if (C->getZExtValue() <= 0xffffffff)
27100         weight = CW_Constant;
27101     }
27102     break;
27103   }
27104   return weight;
27105 }
27106
27107 /// LowerXConstraint - try to replace an X constraint, which matches anything,
27108 /// with another that has more specific requirements based on the type of the
27109 /// corresponding operand.
27110 const char *X86TargetLowering::
27111 LowerXConstraint(EVT ConstraintVT) const {
27112   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
27113   // 'f' like normal targets.
27114   if (ConstraintVT.isFloatingPoint()) {
27115     if (Subtarget->hasSSE2())
27116       return "Y";
27117     if (Subtarget->hasSSE1())
27118       return "x";
27119   }
27120
27121   return TargetLowering::LowerXConstraint(ConstraintVT);
27122 }
27123
27124 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
27125 /// vector.  If it is invalid, don't add anything to Ops.
27126 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
27127                                                      std::string &Constraint,
27128                                                      std::vector<SDValue>&Ops,
27129                                                      SelectionDAG &DAG) const {
27130   SDValue Result;
27131
27132   // Only support length 1 constraints for now.
27133   if (Constraint.length() > 1) return;
27134
27135   char ConstraintLetter = Constraint[0];
27136   switch (ConstraintLetter) {
27137   default: break;
27138   case 'I':
27139     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
27140       if (C->getZExtValue() <= 31) {
27141         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
27142                                        Op.getValueType());
27143         break;
27144       }
27145     }
27146     return;
27147   case 'J':
27148     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
27149       if (C->getZExtValue() <= 63) {
27150         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
27151                                        Op.getValueType());
27152         break;
27153       }
27154     }
27155     return;
27156   case 'K':
27157     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
27158       if (isInt<8>(C->getSExtValue())) {
27159         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
27160                                        Op.getValueType());
27161         break;
27162       }
27163     }
27164     return;
27165   case 'L':
27166     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
27167       if (C->getZExtValue() == 0xff || C->getZExtValue() == 0xffff ||
27168           (Subtarget->is64Bit() && C->getZExtValue() == 0xffffffff)) {
27169         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op),
27170                                        Op.getValueType());
27171         break;
27172       }
27173     }
27174     return;
27175   case 'M':
27176     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
27177       if (C->getZExtValue() <= 3) {
27178         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
27179                                        Op.getValueType());
27180         break;
27181       }
27182     }
27183     return;
27184   case 'N':
27185     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
27186       if (C->getZExtValue() <= 255) {
27187         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
27188                                        Op.getValueType());
27189         break;
27190       }
27191     }
27192     return;
27193   case 'O':
27194     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
27195       if (C->getZExtValue() <= 127) {
27196         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
27197                                        Op.getValueType());
27198         break;
27199       }
27200     }
27201     return;
27202   case 'e': {
27203     // 32-bit signed value
27204     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
27205       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
27206                                            C->getSExtValue())) {
27207         // Widen to 64 bits here to get it sign extended.
27208         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op), MVT::i64);
27209         break;
27210       }
27211     // FIXME gcc accepts some relocatable values here too, but only in certain
27212     // memory models; it's complicated.
27213     }
27214     return;
27215   }
27216   case 'Z': {
27217     // 32-bit unsigned value
27218     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
27219       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
27220                                            C->getZExtValue())) {
27221         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
27222                                        Op.getValueType());
27223         break;
27224       }
27225     }
27226     // FIXME gcc accepts some relocatable values here too, but only in certain
27227     // memory models; it's complicated.
27228     return;
27229   }
27230   case 'i': {
27231     // Literal immediates are always ok.
27232     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
27233       // Widen to 64 bits here to get it sign extended.
27234       Result = DAG.getTargetConstant(CST->getSExtValue(), SDLoc(Op), MVT::i64);
27235       break;
27236     }
27237
27238     // In any sort of PIC mode addresses need to be computed at runtime by
27239     // adding in a register or some sort of table lookup.  These can't
27240     // be used as immediates.
27241     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
27242       return;
27243
27244     // If we are in non-pic codegen mode, we allow the address of a global (with
27245     // an optional displacement) to be used with 'i'.
27246     GlobalAddressSDNode *GA = nullptr;
27247     int64_t Offset = 0;
27248
27249     // Match either (GA), (GA+C), (GA+C1+C2), etc.
27250     while (1) {
27251       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
27252         Offset += GA->getOffset();
27253         break;
27254       } else if (Op.getOpcode() == ISD::ADD) {
27255         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
27256           Offset += C->getZExtValue();
27257           Op = Op.getOperand(0);
27258           continue;
27259         }
27260       } else if (Op.getOpcode() == ISD::SUB) {
27261         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
27262           Offset += -C->getZExtValue();
27263           Op = Op.getOperand(0);
27264           continue;
27265         }
27266       }
27267
27268       // Otherwise, this isn't something we can handle, reject it.
27269       return;
27270     }
27271
27272     const GlobalValue *GV = GA->getGlobal();
27273     // If we require an extra load to get this address, as in PIC mode, we
27274     // can't accept it.
27275     if (isGlobalStubReference(
27276             Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
27277       return;
27278
27279     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
27280                                         GA->getValueType(0), Offset);
27281     break;
27282   }
27283   }
27284
27285   if (Result.getNode()) {
27286     Ops.push_back(Result);
27287     return;
27288   }
27289   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
27290 }
27291
27292 std::pair<unsigned, const TargetRegisterClass *>
27293 X86TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
27294                                                 StringRef Constraint,
27295                                                 MVT VT) const {
27296   // First, see if this is a constraint that directly corresponds to an LLVM
27297   // register class.
27298   if (Constraint.size() == 1) {
27299     // GCC Constraint Letters
27300     switch (Constraint[0]) {
27301     default: break;
27302       // TODO: Slight differences here in allocation order and leaving
27303       // RIP in the class. Do they matter any more here than they do
27304       // in the normal allocation?
27305     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
27306       if (Subtarget->is64Bit()) {
27307         if (VT == MVT::i32 || VT == MVT::f32)
27308           return std::make_pair(0U, &X86::GR32RegClass);
27309         if (VT == MVT::i16)
27310           return std::make_pair(0U, &X86::GR16RegClass);
27311         if (VT == MVT::i8 || VT == MVT::i1)
27312           return std::make_pair(0U, &X86::GR8RegClass);
27313         if (VT == MVT::i64 || VT == MVT::f64)
27314           return std::make_pair(0U, &X86::GR64RegClass);
27315         break;
27316       }
27317       // 32-bit fallthrough
27318     case 'Q':   // Q_REGS
27319       if (VT == MVT::i32 || VT == MVT::f32)
27320         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
27321       if (VT == MVT::i16)
27322         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
27323       if (VT == MVT::i8 || VT == MVT::i1)
27324         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
27325       if (VT == MVT::i64)
27326         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
27327       break;
27328     case 'r':   // GENERAL_REGS
27329     case 'l':   // INDEX_REGS
27330       if (VT == MVT::i8 || VT == MVT::i1)
27331         return std::make_pair(0U, &X86::GR8RegClass);
27332       if (VT == MVT::i16)
27333         return std::make_pair(0U, &X86::GR16RegClass);
27334       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
27335         return std::make_pair(0U, &X86::GR32RegClass);
27336       return std::make_pair(0U, &X86::GR64RegClass);
27337     case 'R':   // LEGACY_REGS
27338       if (VT == MVT::i8 || VT == MVT::i1)
27339         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
27340       if (VT == MVT::i16)
27341         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
27342       if (VT == MVT::i32 || !Subtarget->is64Bit())
27343         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
27344       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
27345     case 'f':  // FP Stack registers.
27346       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
27347       // value to the correct fpstack register class.
27348       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
27349         return std::make_pair(0U, &X86::RFP32RegClass);
27350       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
27351         return std::make_pair(0U, &X86::RFP64RegClass);
27352       return std::make_pair(0U, &X86::RFP80RegClass);
27353     case 'y':   // MMX_REGS if MMX allowed.
27354       if (!Subtarget->hasMMX()) break;
27355       return std::make_pair(0U, &X86::VR64RegClass);
27356     case 'Y':   // SSE_REGS if SSE2 allowed
27357       if (!Subtarget->hasSSE2()) break;
27358       // FALL THROUGH.
27359     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
27360       if (!Subtarget->hasSSE1()) break;
27361
27362       switch (VT.SimpleTy) {
27363       default: break;
27364       // Scalar SSE types.
27365       case MVT::f32:
27366       case MVT::i32:
27367         return std::make_pair(0U, &X86::FR32RegClass);
27368       case MVT::f64:
27369       case MVT::i64:
27370         return std::make_pair(0U, &X86::FR64RegClass);
27371       // Vector types.
27372       case MVT::v16i8:
27373       case MVT::v8i16:
27374       case MVT::v4i32:
27375       case MVT::v2i64:
27376       case MVT::v4f32:
27377       case MVT::v2f64:
27378         return std::make_pair(0U, &X86::VR128RegClass);
27379       // AVX types.
27380       case MVT::v32i8:
27381       case MVT::v16i16:
27382       case MVT::v8i32:
27383       case MVT::v4i64:
27384       case MVT::v8f32:
27385       case MVT::v4f64:
27386         return std::make_pair(0U, &X86::VR256RegClass);
27387       case MVT::v8f64:
27388       case MVT::v16f32:
27389       case MVT::v16i32:
27390       case MVT::v8i64:
27391         return std::make_pair(0U, &X86::VR512RegClass);
27392       }
27393       break;
27394     }
27395   }
27396
27397   // Use the default implementation in TargetLowering to convert the register
27398   // constraint into a member of a register class.
27399   std::pair<unsigned, const TargetRegisterClass*> Res;
27400   Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
27401
27402   // Not found as a standard register?
27403   if (!Res.second) {
27404     // Map st(0) -> st(7) -> ST0
27405     if (Constraint.size() == 7 && Constraint[0] == '{' &&
27406         tolower(Constraint[1]) == 's' &&
27407         tolower(Constraint[2]) == 't' &&
27408         Constraint[3] == '(' &&
27409         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
27410         Constraint[5] == ')' &&
27411         Constraint[6] == '}') {
27412
27413       Res.first = X86::FP0+Constraint[4]-'0';
27414       Res.second = &X86::RFP80RegClass;
27415       return Res;
27416     }
27417
27418     // GCC allows "st(0)" to be called just plain "st".
27419     if (StringRef("{st}").equals_lower(Constraint)) {
27420       Res.first = X86::FP0;
27421       Res.second = &X86::RFP80RegClass;
27422       return Res;
27423     }
27424
27425     // flags -> EFLAGS
27426     if (StringRef("{flags}").equals_lower(Constraint)) {
27427       Res.first = X86::EFLAGS;
27428       Res.second = &X86::CCRRegClass;
27429       return Res;
27430     }
27431
27432     // 'A' means EAX + EDX.
27433     if (Constraint == "A") {
27434       Res.first = X86::EAX;
27435       Res.second = &X86::GR32_ADRegClass;
27436       return Res;
27437     }
27438     return Res;
27439   }
27440
27441   // Otherwise, check to see if this is a register class of the wrong value
27442   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
27443   // turn into {ax},{dx}.
27444   // MVT::Other is used to specify clobber names.
27445   if (Res.second->hasType(VT) || VT == MVT::Other)
27446     return Res;   // Correct type already, nothing to do.
27447
27448   // Get a matching integer of the correct size. i.e. "ax" with MVT::32 should
27449   // return "eax". This should even work for things like getting 64bit integer
27450   // registers when given an f64 type.
27451   const TargetRegisterClass *Class = Res.second;
27452   if (Class == &X86::GR8RegClass || Class == &X86::GR16RegClass ||
27453       Class == &X86::GR32RegClass || Class == &X86::GR64RegClass) {
27454     unsigned Size = VT.getSizeInBits();
27455     MVT::SimpleValueType SimpleTy = Size == 1 || Size == 8 ? MVT::i8
27456                                   : Size == 16 ? MVT::i16
27457                                   : Size == 32 ? MVT::i32
27458                                   : Size == 64 ? MVT::i64
27459                                   : MVT::Other;
27460     unsigned DestReg = getX86SubSuperRegisterOrZero(Res.first, SimpleTy);
27461     if (DestReg > 0) {
27462       Res.first = DestReg;
27463       Res.second = SimpleTy == MVT::i8 ? &X86::GR8RegClass
27464                  : SimpleTy == MVT::i16 ? &X86::GR16RegClass
27465                  : SimpleTy == MVT::i32 ? &X86::GR32RegClass
27466                  : &X86::GR64RegClass;
27467       assert(Res.second->contains(Res.first) && "Register in register class");
27468     } else {
27469       // No register found/type mismatch.
27470       Res.first = 0;
27471       Res.second = nullptr;
27472     }
27473   } else if (Class == &X86::FR32RegClass || Class == &X86::FR64RegClass ||
27474              Class == &X86::VR128RegClass || Class == &X86::VR256RegClass ||
27475              Class == &X86::FR32XRegClass || Class == &X86::FR64XRegClass ||
27476              Class == &X86::VR128XRegClass || Class == &X86::VR256XRegClass ||
27477              Class == &X86::VR512RegClass) {
27478     // Handle references to XMM physical registers that got mapped into the
27479     // wrong class.  This can happen with constraints like {xmm0} where the
27480     // target independent register mapper will just pick the first match it can
27481     // find, ignoring the required type.
27482
27483     if (VT == MVT::f32 || VT == MVT::i32)
27484       Res.second = &X86::FR32RegClass;
27485     else if (VT == MVT::f64 || VT == MVT::i64)
27486       Res.second = &X86::FR64RegClass;
27487     else if (X86::VR128RegClass.hasType(VT))
27488       Res.second = &X86::VR128RegClass;
27489     else if (X86::VR256RegClass.hasType(VT))
27490       Res.second = &X86::VR256RegClass;
27491     else if (X86::VR512RegClass.hasType(VT))
27492       Res.second = &X86::VR512RegClass;
27493     else {
27494       // Type mismatch and not a clobber: Return an error;
27495       Res.first = 0;
27496       Res.second = nullptr;
27497     }
27498   }
27499
27500   return Res;
27501 }
27502
27503 int X86TargetLowering::getScalingFactorCost(const DataLayout &DL,
27504                                             const AddrMode &AM, Type *Ty,
27505                                             unsigned AS) const {
27506   // Scaling factors are not free at all.
27507   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
27508   // will take 2 allocations in the out of order engine instead of 1
27509   // for plain addressing mode, i.e. inst (reg1).
27510   // E.g.,
27511   // vaddps (%rsi,%drx), %ymm0, %ymm1
27512   // Requires two allocations (one for the load, one for the computation)
27513   // whereas:
27514   // vaddps (%rsi), %ymm0, %ymm1
27515   // Requires just 1 allocation, i.e., freeing allocations for other operations
27516   // and having less micro operations to execute.
27517   //
27518   // For some X86 architectures, this is even worse because for instance for
27519   // stores, the complex addressing mode forces the instruction to use the
27520   // "load" ports instead of the dedicated "store" port.
27521   // E.g., on Haswell:
27522   // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
27523   // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
27524   if (isLegalAddressingMode(DL, AM, Ty, AS))
27525     // Scale represents reg2 * scale, thus account for 1
27526     // as soon as we use a second register.
27527     return AM.Scale != 0;
27528   return -1;
27529 }
27530
27531 bool X86TargetLowering::isIntDivCheap(EVT VT, AttributeSet Attr) const {
27532   // Integer division on x86 is expensive. However, when aggressively optimizing
27533   // for code size, we prefer to use a div instruction, as it is usually smaller
27534   // than the alternative sequence.
27535   // The exception to this is vector division. Since x86 doesn't have vector
27536   // integer division, leaving the division as-is is a loss even in terms of
27537   // size, because it will have to be scalarized, while the alternative code
27538   // sequence can be performed in vector form.
27539   bool OptSize = Attr.hasAttribute(AttributeSet::FunctionIndex,
27540                                    Attribute::MinSize);
27541   return OptSize && !VT.isVector();
27542 }
27543
27544 void X86TargetLowering::markInRegArguments(SelectionDAG &DAG,
27545        TargetLowering::ArgListTy& Args) const {
27546   // The MCU psABI requires some arguments to be passed in-register.
27547   // For regular calls, the inreg arguments are marked by the front-end.
27548   // However, for compiler generated library calls, we have to patch this
27549   // up here.
27550   if (!Subtarget->isTargetMCU() || !Args.size())
27551     return;
27552
27553   unsigned FreeRegs = 3;
27554   for (auto &Arg : Args) {
27555     // For library functions, we do not expect any fancy types.
27556     unsigned Size = DAG.getDataLayout().getTypeSizeInBits(Arg.Ty);
27557     unsigned SizeInRegs = (Size + 31) / 32;
27558     if (SizeInRegs > 2 || SizeInRegs > FreeRegs)
27559       continue;
27560
27561     Arg.isInReg = true;
27562     FreeRegs -= SizeInRegs;
27563     if (!FreeRegs)
27564       break;
27565   }
27566 }