AVX-512: Implemented encoding , DAG lowering and intrinsics for Integer Truncate...
[oota-llvm.git] / lib / Target / X86 / X86ISelLowering.cpp
1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "X86ISelLowering.h"
16 #include "Utils/X86ShuffleDecode.h"
17 #include "X86CallingConv.h"
18 #include "X86FrameLowering.h"
19 #include "X86InstrBuilder.h"
20 #include "X86MachineFunctionInfo.h"
21 #include "X86TargetMachine.h"
22 #include "X86TargetObjectFile.h"
23 #include "llvm/ADT/SmallBitVector.h"
24 #include "llvm/ADT/SmallSet.h"
25 #include "llvm/ADT/Statistic.h"
26 #include "llvm/ADT/StringExtras.h"
27 #include "llvm/ADT/StringSwitch.h"
28 #include "llvm/CodeGen/IntrinsicLowering.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineFunction.h"
31 #include "llvm/CodeGen/MachineInstrBuilder.h"
32 #include "llvm/CodeGen/MachineJumpTableInfo.h"
33 #include "llvm/CodeGen/MachineModuleInfo.h"
34 #include "llvm/CodeGen/MachineRegisterInfo.h"
35 #include "llvm/CodeGen/WinEHFuncInfo.h"
36 #include "llvm/IR/CallSite.h"
37 #include "llvm/IR/CallingConv.h"
38 #include "llvm/IR/Constants.h"
39 #include "llvm/IR/DerivedTypes.h"
40 #include "llvm/IR/Function.h"
41 #include "llvm/IR/GlobalAlias.h"
42 #include "llvm/IR/GlobalVariable.h"
43 #include "llvm/IR/Instructions.h"
44 #include "llvm/IR/Intrinsics.h"
45 #include "llvm/MC/MCAsmInfo.h"
46 #include "llvm/MC/MCContext.h"
47 #include "llvm/MC/MCExpr.h"
48 #include "llvm/MC/MCSymbol.h"
49 #include "llvm/Support/CommandLine.h"
50 #include "llvm/Support/Debug.h"
51 #include "llvm/Support/ErrorHandling.h"
52 #include "llvm/Support/MathExtras.h"
53 #include "llvm/Target/TargetOptions.h"
54 #include "X86IntrinsicsInfo.h"
55 #include <bitset>
56 #include <numeric>
57 #include <cctype>
58 using namespace llvm;
59
60 #define DEBUG_TYPE "x86-isel"
61
62 STATISTIC(NumTailCalls, "Number of tail calls");
63
64 static cl::opt<bool> ExperimentalVectorWideningLegalization(
65     "x86-experimental-vector-widening-legalization", cl::init(false),
66     cl::desc("Enable an experimental vector type legalization through widening "
67              "rather than promotion."),
68     cl::Hidden);
69
70 // Forward declarations.
71 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
72                        SDValue V2);
73
74 X86TargetLowering::X86TargetLowering(const X86TargetMachine &TM,
75                                      const X86Subtarget &STI)
76     : TargetLowering(TM), Subtarget(&STI) {
77   X86ScalarSSEf64 = Subtarget->hasSSE2();
78   X86ScalarSSEf32 = Subtarget->hasSSE1();
79   TD = TM.getDataLayout();
80
81   // Set up the TargetLowering object.
82   static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
83
84   // X86 is weird. It always uses i8 for shift amounts and setcc results.
85   setBooleanContents(ZeroOrOneBooleanContent);
86   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
87   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
88
89   // For 64-bit, since we have so many registers, use the ILP scheduler.
90   // For 32-bit, use the register pressure specific scheduling.
91   // For Atom, always use ILP scheduling.
92   if (Subtarget->isAtom())
93     setSchedulingPreference(Sched::ILP);
94   else if (Subtarget->is64Bit())
95     setSchedulingPreference(Sched::ILP);
96   else
97     setSchedulingPreference(Sched::RegPressure);
98   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
99   setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
100
101   // Bypass expensive divides on Atom when compiling with O2.
102   if (TM.getOptLevel() >= CodeGenOpt::Default) {
103     if (Subtarget->hasSlowDivide32())
104       addBypassSlowDiv(32, 8);
105     if (Subtarget->hasSlowDivide64() && Subtarget->is64Bit())
106       addBypassSlowDiv(64, 16);
107   }
108
109   if (Subtarget->isTargetKnownWindowsMSVC()) {
110     // Setup Windows compiler runtime calls.
111     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
112     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
113     setLibcallName(RTLIB::SREM_I64, "_allrem");
114     setLibcallName(RTLIB::UREM_I64, "_aullrem");
115     setLibcallName(RTLIB::MUL_I64, "_allmul");
116     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
117     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
118     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
119     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
120     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
121
122     // The _ftol2 runtime function has an unusual calling conv, which
123     // is modeled by a special pseudo-instruction.
124     setLibcallName(RTLIB::FPTOUINT_F64_I64, nullptr);
125     setLibcallName(RTLIB::FPTOUINT_F32_I64, nullptr);
126     setLibcallName(RTLIB::FPTOUINT_F64_I32, nullptr);
127     setLibcallName(RTLIB::FPTOUINT_F32_I32, nullptr);
128   }
129
130   if (Subtarget->isTargetDarwin()) {
131     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
132     setUseUnderscoreSetJmp(false);
133     setUseUnderscoreLongJmp(false);
134   } else if (Subtarget->isTargetWindowsGNU()) {
135     // MS runtime is weird: it exports _setjmp, but longjmp!
136     setUseUnderscoreSetJmp(true);
137     setUseUnderscoreLongJmp(false);
138   } else {
139     setUseUnderscoreSetJmp(true);
140     setUseUnderscoreLongJmp(true);
141   }
142
143   // Set up the register classes.
144   addRegisterClass(MVT::i8, &X86::GR8RegClass);
145   addRegisterClass(MVT::i16, &X86::GR16RegClass);
146   addRegisterClass(MVT::i32, &X86::GR32RegClass);
147   if (Subtarget->is64Bit())
148     addRegisterClass(MVT::i64, &X86::GR64RegClass);
149
150   for (MVT VT : MVT::integer_valuetypes())
151     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
152
153   // We don't accept any truncstore of integer registers.
154   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
155   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
156   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
157   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
158   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
159   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
160
161   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
162
163   // SETOEQ and SETUNE require checking two conditions.
164   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
165   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
166   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
167   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
168   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
169   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
170
171   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
172   // operation.
173   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
174   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
175   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
176
177   if (Subtarget->is64Bit()) {
178     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
179     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
180   } else if (!Subtarget->useSoftFloat()) {
181     // We have an algorithm for SSE2->double, and we turn this into a
182     // 64-bit FILD followed by conditional FADD for other targets.
183     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
184     // We have an algorithm for SSE2, and we turn this into a 64-bit
185     // FILD for other targets.
186     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
187   }
188
189   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
190   // this operation.
191   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
192   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
193
194   if (!Subtarget->useSoftFloat()) {
195     // SSE has no i16 to fp conversion, only i32
196     if (X86ScalarSSEf32) {
197       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
198       // f32 and f64 cases are Legal, f80 case is not
199       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
200     } else {
201       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
202       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
203     }
204   } else {
205     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
206     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
207   }
208
209   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
210   // are Legal, f80 is custom lowered.
211   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
212   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
213
214   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
215   // this operation.
216   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
217   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
218
219   if (X86ScalarSSEf32) {
220     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
221     // f32 and f64 cases are Legal, f80 case is not
222     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
223   } else {
224     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
225     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
226   }
227
228   // Handle FP_TO_UINT by promoting the destination to a larger signed
229   // conversion.
230   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
231   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
232   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
233
234   if (Subtarget->is64Bit()) {
235     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
236     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
237   } else if (!Subtarget->useSoftFloat()) {
238     // Since AVX is a superset of SSE3, only check for SSE here.
239     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
240       // Expand FP_TO_UINT into a select.
241       // FIXME: We would like to use a Custom expander here eventually to do
242       // the optimal thing for SSE vs. the default expansion in the legalizer.
243       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
244     else
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
250   if (isTargetFTOL()) {
251     // Use the _ftol2 runtime function, which has a pseudo-instruction
252     // to handle its weird calling convention.
253     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
254   }
255
256   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
257   if (!X86ScalarSSEf64) {
258     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
259     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
260     if (Subtarget->is64Bit()) {
261       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
262       // Without SSE, i64->f64 goes through memory.
263       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
264     }
265   }
266
267   // Scalar integer divide and remainder are lowered to use operations that
268   // produce two results, to match the available instructions. This exposes
269   // the two-result form to trivial CSE, which is able to combine x/y and x%y
270   // into a single instruction.
271   //
272   // Scalar integer multiply-high is also lowered to use two-result
273   // operations, to match the available instructions. However, plain multiply
274   // (low) operations are left as Legal, as there are single-result
275   // instructions for this in x86. Using the two-result multiply instructions
276   // when both high and low results are needed must be arranged by dagcombine.
277   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
278     MVT VT = IntVTs[i];
279     setOperationAction(ISD::MULHS, VT, Expand);
280     setOperationAction(ISD::MULHU, VT, Expand);
281     setOperationAction(ISD::SDIV, VT, Expand);
282     setOperationAction(ISD::UDIV, VT, Expand);
283     setOperationAction(ISD::SREM, VT, Expand);
284     setOperationAction(ISD::UREM, VT, Expand);
285
286     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
287     setOperationAction(ISD::ADDC, VT, Custom);
288     setOperationAction(ISD::ADDE, VT, Custom);
289     setOperationAction(ISD::SUBC, VT, Custom);
290     setOperationAction(ISD::SUBE, VT, Custom);
291   }
292
293   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
294   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
295   setOperationAction(ISD::BR_CC            , MVT::f32,   Expand);
296   setOperationAction(ISD::BR_CC            , MVT::f64,   Expand);
297   setOperationAction(ISD::BR_CC            , MVT::f80,   Expand);
298   setOperationAction(ISD::BR_CC            , MVT::i8,    Expand);
299   setOperationAction(ISD::BR_CC            , MVT::i16,   Expand);
300   setOperationAction(ISD::BR_CC            , MVT::i32,   Expand);
301   setOperationAction(ISD::BR_CC            , MVT::i64,   Expand);
302   setOperationAction(ISD::SELECT_CC        , MVT::f32,   Expand);
303   setOperationAction(ISD::SELECT_CC        , MVT::f64,   Expand);
304   setOperationAction(ISD::SELECT_CC        , MVT::f80,   Expand);
305   setOperationAction(ISD::SELECT_CC        , MVT::i8,    Expand);
306   setOperationAction(ISD::SELECT_CC        , MVT::i16,   Expand);
307   setOperationAction(ISD::SELECT_CC        , MVT::i32,   Expand);
308   setOperationAction(ISD::SELECT_CC        , MVT::i64,   Expand);
309   if (Subtarget->is64Bit())
310     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
311   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
312   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
313   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
314   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
315   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
316   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
317   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
318   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
319
320   // Promote the i8 variants and force them on up to i32 which has a shorter
321   // encoding.
322   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
323   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
324   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
325   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
326   if (Subtarget->hasBMI()) {
327     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
328     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
329     if (Subtarget->is64Bit())
330       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
331   } else {
332     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
333     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
334     if (Subtarget->is64Bit())
335       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
336   }
337
338   if (Subtarget->hasLZCNT()) {
339     // When promoting the i8 variants, force them to i32 for a shorter
340     // encoding.
341     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
342     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
343     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
344     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
345     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
346     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
347     if (Subtarget->is64Bit())
348       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
349   } else {
350     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
351     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
352     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
353     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
354     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
355     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
356     if (Subtarget->is64Bit()) {
357       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
358       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
359     }
360   }
361
362   // Special handling for half-precision floating point conversions.
363   // If we don't have F16C support, then lower half float conversions
364   // into library calls.
365   if (Subtarget->useSoftFloat() || !Subtarget->hasF16C()) {
366     setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
367     setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
368   }
369
370   // There's never any support for operations beyond MVT::f32.
371   setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
372   setOperationAction(ISD::FP16_TO_FP, MVT::f80, Expand);
373   setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
374   setOperationAction(ISD::FP_TO_FP16, MVT::f80, Expand);
375
376   setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
377   setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
378   setLoadExtAction(ISD::EXTLOAD, MVT::f80, MVT::f16, Expand);
379   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
380   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
381   setTruncStoreAction(MVT::f80, MVT::f16, Expand);
382
383   if (Subtarget->hasPOPCNT()) {
384     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
385   } else {
386     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
387     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
388     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
389     if (Subtarget->is64Bit())
390       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
391   }
392
393   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
394
395   if (!Subtarget->hasMOVBE())
396     setOperationAction(ISD::BSWAP          , MVT::i16  , Expand);
397
398   // These should be promoted to a larger select which is supported.
399   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
400   // X86 wants to expand cmov itself.
401   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
402   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
403   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
404   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
405   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
406   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
407   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
408   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
409   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
410   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
411   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
412   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
413   if (Subtarget->is64Bit()) {
414     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
415     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
416   }
417   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
418   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
419   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
420   // support continuation, user-level threading, and etc.. As a result, no
421   // other SjLj exception interfaces are implemented and please don't build
422   // your own exception handling based on them.
423   // LLVM/Clang supports zero-cost DWARF exception handling.
424   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
425   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
426
427   // Darwin ABI issue.
428   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
429   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
430   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
431   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
432   if (Subtarget->is64Bit())
433     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
434   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
435   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
436   if (Subtarget->is64Bit()) {
437     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
438     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
439     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
440     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
441     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
442   }
443   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
444   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
445   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
446   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
447   if (Subtarget->is64Bit()) {
448     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
449     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
450     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
451   }
452
453   if (Subtarget->hasSSE1())
454     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
455
456   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
457
458   // Expand certain atomics
459   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
460     MVT VT = IntVTs[i];
461     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
462     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
463     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
464   }
465
466   if (Subtarget->hasCmpxchg16b()) {
467     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
468   }
469
470   // FIXME - use subtarget debug flags
471   if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetELF() &&
472       !Subtarget->isTargetCygMing() && !Subtarget->isTargetWin64()) {
473     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
474   }
475
476   if (Subtarget->is64Bit()) {
477     setExceptionPointerRegister(X86::RAX);
478     setExceptionSelectorRegister(X86::RDX);
479   } else {
480     setExceptionPointerRegister(X86::EAX);
481     setExceptionSelectorRegister(X86::EDX);
482   }
483   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
484   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
485
486   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
487   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
488
489   setOperationAction(ISD::TRAP, MVT::Other, Legal);
490   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
491
492   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
493   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
494   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
495   if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
496     // TargetInfo::X86_64ABIBuiltinVaList
497     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
498     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
499   } else {
500     // TargetInfo::CharPtrBuiltinVaList
501     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
502     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
503   }
504
505   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
506   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
507
508   setOperationAction(ISD::DYNAMIC_STACKALLOC, getPointerTy(*TD), Custom);
509
510   // GC_TRANSITION_START and GC_TRANSITION_END need custom lowering.
511   setOperationAction(ISD::GC_TRANSITION_START, MVT::Other, Custom);
512   setOperationAction(ISD::GC_TRANSITION_END, MVT::Other, Custom);
513
514   if (!Subtarget->useSoftFloat() && X86ScalarSSEf64) {
515     // f32 and f64 use SSE.
516     // Set up the FP register classes.
517     addRegisterClass(MVT::f32, &X86::FR32RegClass);
518     addRegisterClass(MVT::f64, &X86::FR64RegClass);
519
520     // Use ANDPD to simulate FABS.
521     setOperationAction(ISD::FABS , MVT::f64, Custom);
522     setOperationAction(ISD::FABS , MVT::f32, Custom);
523
524     // Use XORP to simulate FNEG.
525     setOperationAction(ISD::FNEG , MVT::f64, Custom);
526     setOperationAction(ISD::FNEG , MVT::f32, Custom);
527
528     // Use ANDPD and ORPD to simulate FCOPYSIGN.
529     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
530     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
531
532     // Lower this to FGETSIGNx86 plus an AND.
533     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
534     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
535
536     // We don't support sin/cos/fmod
537     setOperationAction(ISD::FSIN   , MVT::f64, Expand);
538     setOperationAction(ISD::FCOS   , MVT::f64, Expand);
539     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
540     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
541     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
542     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
543
544     // Expand FP immediates into loads from the stack, except for the special
545     // cases we handle.
546     addLegalFPImmediate(APFloat(+0.0)); // xorpd
547     addLegalFPImmediate(APFloat(+0.0f)); // xorps
548   } else if (!Subtarget->useSoftFloat() && X86ScalarSSEf32) {
549     // Use SSE for f32, x87 for f64.
550     // Set up the FP register classes.
551     addRegisterClass(MVT::f32, &X86::FR32RegClass);
552     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
553
554     // Use ANDPS to simulate FABS.
555     setOperationAction(ISD::FABS , MVT::f32, Custom);
556
557     // Use XORP to simulate FNEG.
558     setOperationAction(ISD::FNEG , MVT::f32, Custom);
559
560     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
561
562     // Use ANDPS and ORPS to simulate FCOPYSIGN.
563     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
564     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
565
566     // We don't support sin/cos/fmod
567     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
568     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
569     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
570
571     // Special cases we handle for FP constants.
572     addLegalFPImmediate(APFloat(+0.0f)); // xorps
573     addLegalFPImmediate(APFloat(+0.0)); // FLD0
574     addLegalFPImmediate(APFloat(+1.0)); // FLD1
575     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
576     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
577
578     if (!TM.Options.UnsafeFPMath) {
579       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
580       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
581       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
582     }
583   } else if (!Subtarget->useSoftFloat()) {
584     // f32 and f64 in x87.
585     // Set up the FP register classes.
586     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
587     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
588
589     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
590     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
591     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
592     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
593
594     if (!TM.Options.UnsafeFPMath) {
595       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
596       setOperationAction(ISD::FSIN   , MVT::f32, Expand);
597       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
598       setOperationAction(ISD::FCOS   , MVT::f32, Expand);
599       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
600       setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
601     }
602     addLegalFPImmediate(APFloat(+0.0)); // FLD0
603     addLegalFPImmediate(APFloat(+1.0)); // FLD1
604     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
605     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
606     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
607     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
608     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
609     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
610   }
611
612   // We don't support FMA.
613   setOperationAction(ISD::FMA, MVT::f64, Expand);
614   setOperationAction(ISD::FMA, MVT::f32, Expand);
615
616   // Long double always uses X87.
617   if (!Subtarget->useSoftFloat()) {
618     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
619     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
620     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
621     {
622       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
623       addLegalFPImmediate(TmpFlt);  // FLD0
624       TmpFlt.changeSign();
625       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
626
627       bool ignored;
628       APFloat TmpFlt2(+1.0);
629       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
630                       &ignored);
631       addLegalFPImmediate(TmpFlt2);  // FLD1
632       TmpFlt2.changeSign();
633       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
634     }
635
636     if (!TM.Options.UnsafeFPMath) {
637       setOperationAction(ISD::FSIN   , MVT::f80, Expand);
638       setOperationAction(ISD::FCOS   , MVT::f80, Expand);
639       setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
640     }
641
642     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
643     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
644     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
645     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
646     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
647     setOperationAction(ISD::FMA, MVT::f80, Expand);
648   }
649
650   // Always use a library call for pow.
651   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
652   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
653   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
654
655   setOperationAction(ISD::FLOG, MVT::f80, Expand);
656   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
657   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
658   setOperationAction(ISD::FEXP, MVT::f80, Expand);
659   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
660   setOperationAction(ISD::FMINNUM, MVT::f80, Expand);
661   setOperationAction(ISD::FMAXNUM, MVT::f80, Expand);
662
663   // First set operation action for all vector types to either promote
664   // (for widening) or expand (for scalarization). Then we will selectively
665   // turn on ones that can be effectively codegen'd.
666   for (MVT VT : MVT::vector_valuetypes()) {
667     setOperationAction(ISD::ADD , VT, Expand);
668     setOperationAction(ISD::SUB , VT, Expand);
669     setOperationAction(ISD::FADD, VT, Expand);
670     setOperationAction(ISD::FNEG, VT, Expand);
671     setOperationAction(ISD::FSUB, VT, Expand);
672     setOperationAction(ISD::MUL , VT, Expand);
673     setOperationAction(ISD::FMUL, VT, Expand);
674     setOperationAction(ISD::SDIV, VT, Expand);
675     setOperationAction(ISD::UDIV, VT, Expand);
676     setOperationAction(ISD::FDIV, VT, Expand);
677     setOperationAction(ISD::SREM, VT, Expand);
678     setOperationAction(ISD::UREM, VT, Expand);
679     setOperationAction(ISD::LOAD, VT, Expand);
680     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
681     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
682     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
683     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
684     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
685     setOperationAction(ISD::FABS, VT, Expand);
686     setOperationAction(ISD::FSIN, VT, Expand);
687     setOperationAction(ISD::FSINCOS, VT, Expand);
688     setOperationAction(ISD::FCOS, VT, Expand);
689     setOperationAction(ISD::FSINCOS, VT, Expand);
690     setOperationAction(ISD::FREM, VT, Expand);
691     setOperationAction(ISD::FMA,  VT, Expand);
692     setOperationAction(ISD::FPOWI, VT, Expand);
693     setOperationAction(ISD::FSQRT, VT, Expand);
694     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
695     setOperationAction(ISD::FFLOOR, VT, Expand);
696     setOperationAction(ISD::FCEIL, VT, Expand);
697     setOperationAction(ISD::FTRUNC, VT, Expand);
698     setOperationAction(ISD::FRINT, VT, Expand);
699     setOperationAction(ISD::FNEARBYINT, VT, Expand);
700     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
701     setOperationAction(ISD::MULHS, VT, Expand);
702     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
703     setOperationAction(ISD::MULHU, VT, Expand);
704     setOperationAction(ISD::SDIVREM, VT, Expand);
705     setOperationAction(ISD::UDIVREM, VT, Expand);
706     setOperationAction(ISD::FPOW, VT, Expand);
707     setOperationAction(ISD::CTPOP, VT, Expand);
708     setOperationAction(ISD::CTTZ, VT, Expand);
709     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
710     setOperationAction(ISD::CTLZ, VT, Expand);
711     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
712     setOperationAction(ISD::SHL, VT, Expand);
713     setOperationAction(ISD::SRA, VT, Expand);
714     setOperationAction(ISD::SRL, VT, Expand);
715     setOperationAction(ISD::ROTL, VT, Expand);
716     setOperationAction(ISD::ROTR, VT, Expand);
717     setOperationAction(ISD::BSWAP, VT, Expand);
718     setOperationAction(ISD::SETCC, VT, Expand);
719     setOperationAction(ISD::FLOG, VT, Expand);
720     setOperationAction(ISD::FLOG2, VT, Expand);
721     setOperationAction(ISD::FLOG10, VT, Expand);
722     setOperationAction(ISD::FEXP, VT, Expand);
723     setOperationAction(ISD::FEXP2, VT, Expand);
724     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
725     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
726     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
727     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
728     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
729     setOperationAction(ISD::TRUNCATE, VT, Expand);
730     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
731     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
732     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
733     setOperationAction(ISD::VSELECT, VT, Expand);
734     setOperationAction(ISD::SELECT_CC, VT, Expand);
735     for (MVT InnerVT : MVT::vector_valuetypes()) {
736       setTruncStoreAction(InnerVT, VT, Expand);
737
738       setLoadExtAction(ISD::SEXTLOAD, InnerVT, VT, Expand);
739       setLoadExtAction(ISD::ZEXTLOAD, InnerVT, VT, Expand);
740
741       // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like
742       // types, we have to deal with them whether we ask for Expansion or not.
743       // Setting Expand causes its own optimisation problems though, so leave
744       // them legal.
745       if (VT.getVectorElementType() == MVT::i1)
746         setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
747
748       // EXTLOAD for MVT::f16 vectors is not legal because f16 vectors are
749       // split/scalarized right now.
750       if (VT.getVectorElementType() == MVT::f16)
751         setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
752     }
753   }
754
755   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
756   // with -msoft-float, disable use of MMX as well.
757   if (!Subtarget->useSoftFloat() && Subtarget->hasMMX()) {
758     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
759     // No operations on x86mmx supported, everything uses intrinsics.
760   }
761
762   // MMX-sized vectors (other than x86mmx) are expected to be expanded
763   // into smaller operations.
764   for (MVT MMXTy : {MVT::v8i8, MVT::v4i16, MVT::v2i32, MVT::v1i64}) {
765     setOperationAction(ISD::MULHS,              MMXTy,      Expand);
766     setOperationAction(ISD::AND,                MMXTy,      Expand);
767     setOperationAction(ISD::OR,                 MMXTy,      Expand);
768     setOperationAction(ISD::XOR,                MMXTy,      Expand);
769     setOperationAction(ISD::SCALAR_TO_VECTOR,   MMXTy,      Expand);
770     setOperationAction(ISD::SELECT,             MMXTy,      Expand);
771     setOperationAction(ISD::BITCAST,            MMXTy,      Expand);
772   }
773   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
774
775   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE1()) {
776     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
777
778     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
779     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
780     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
781     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
782     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
783     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
784     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
785     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
786     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
787     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
788     setOperationAction(ISD::VSELECT,            MVT::v4f32, Custom);
789     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
790     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
791     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Custom);
792   }
793
794   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE2()) {
795     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
796
797     // FIXME: Unfortunately, -soft-float and -no-implicit-float mean XMM
798     // registers cannot be used even for integer operations.
799     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
800     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
801     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
802     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
803
804     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
805     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
806     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
807     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
808     setOperationAction(ISD::MUL,                MVT::v16i8, Custom);
809     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
810     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
811     setOperationAction(ISD::UMUL_LOHI,          MVT::v4i32, Custom);
812     setOperationAction(ISD::SMUL_LOHI,          MVT::v4i32, Custom);
813     setOperationAction(ISD::MULHU,              MVT::v8i16, Legal);
814     setOperationAction(ISD::MULHS,              MVT::v8i16, Legal);
815     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
816     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
817     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
818     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
819     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
820     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
821     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
822     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
823     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
824     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
825     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
826     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
827
828     setOperationAction(ISD::SMAX,               MVT::v8i16, Legal);
829     setOperationAction(ISD::UMAX,               MVT::v16i8, Legal);
830     setOperationAction(ISD::SMIN,               MVT::v8i16, Legal);
831     setOperationAction(ISD::UMIN,               MVT::v16i8, Legal);
832
833     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
834     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
835     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
836     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
837
838     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
839     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
840     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
841     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
842     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
843
844     setOperationAction(ISD::CTPOP,              MVT::v16i8, Custom);
845     setOperationAction(ISD::CTPOP,              MVT::v8i16, Custom);
846     setOperationAction(ISD::CTPOP,              MVT::v4i32, Custom);
847     setOperationAction(ISD::CTPOP,              MVT::v2i64, Custom);
848
849     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
850     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
851       MVT VT = (MVT::SimpleValueType)i;
852       // Do not attempt to custom lower non-power-of-2 vectors
853       if (!isPowerOf2_32(VT.getVectorNumElements()))
854         continue;
855       // Do not attempt to custom lower non-128-bit vectors
856       if (!VT.is128BitVector())
857         continue;
858       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
859       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
860       setOperationAction(ISD::VSELECT,            VT, Custom);
861       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
862     }
863
864     // We support custom legalizing of sext and anyext loads for specific
865     // memory vector types which we can load as a scalar (or sequence of
866     // scalars) and extend in-register to a legal 128-bit vector type. For sext
867     // loads these must work with a single scalar load.
868     for (MVT VT : MVT::integer_vector_valuetypes()) {
869       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i8, Custom);
870       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i16, Custom);
871       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v8i8, Custom);
872       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i8, Custom);
873       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i16, Custom);
874       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i32, Custom);
875       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i8, Custom);
876       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i16, Custom);
877       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8i8, Custom);
878     }
879
880     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
881     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
882     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
883     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
884     setOperationAction(ISD::VSELECT,            MVT::v2f64, Custom);
885     setOperationAction(ISD::VSELECT,            MVT::v2i64, Custom);
886     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
887     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
888
889     if (Subtarget->is64Bit()) {
890       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
891       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
892     }
893
894     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
895     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
896       MVT VT = (MVT::SimpleValueType)i;
897
898       // Do not attempt to promote non-128-bit vectors
899       if (!VT.is128BitVector())
900         continue;
901
902       setOperationAction(ISD::AND,    VT, Promote);
903       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
904       setOperationAction(ISD::OR,     VT, Promote);
905       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
906       setOperationAction(ISD::XOR,    VT, Promote);
907       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
908       setOperationAction(ISD::LOAD,   VT, Promote);
909       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
910       setOperationAction(ISD::SELECT, VT, Promote);
911       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
912     }
913
914     // Custom lower v2i64 and v2f64 selects.
915     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
916     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
917     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
918     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
919
920     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
921     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
922
923     setOperationAction(ISD::SINT_TO_FP,         MVT::v2i32, Custom);
924
925     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
926     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
927     // As there is no 64-bit GPR available, we need build a special custom
928     // sequence to convert from v2i32 to v2f32.
929     if (!Subtarget->is64Bit())
930       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
931
932     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
933     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
934
935     for (MVT VT : MVT::fp_vector_valuetypes())
936       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2f32, Legal);
937
938     setOperationAction(ISD::BITCAST,            MVT::v2i32, Custom);
939     setOperationAction(ISD::BITCAST,            MVT::v4i16, Custom);
940     setOperationAction(ISD::BITCAST,            MVT::v8i8,  Custom);
941   }
942
943   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE41()) {
944     for (MVT RoundedTy : {MVT::f32, MVT::f64, MVT::v4f32, MVT::v2f64}) {
945       setOperationAction(ISD::FFLOOR,           RoundedTy,  Legal);
946       setOperationAction(ISD::FCEIL,            RoundedTy,  Legal);
947       setOperationAction(ISD::FTRUNC,           RoundedTy,  Legal);
948       setOperationAction(ISD::FRINT,            RoundedTy,  Legal);
949       setOperationAction(ISD::FNEARBYINT,       RoundedTy,  Legal);
950     }
951
952     setOperationAction(ISD::SMAX,               MVT::v16i8, Legal);
953     setOperationAction(ISD::SMAX,               MVT::v4i32, Legal);
954     setOperationAction(ISD::UMAX,               MVT::v8i16, Legal);
955     setOperationAction(ISD::UMAX,               MVT::v4i32, Legal);
956     setOperationAction(ISD::SMIN,               MVT::v16i8, Legal);
957     setOperationAction(ISD::SMIN,               MVT::v4i32, Legal);
958     setOperationAction(ISD::UMIN,               MVT::v8i16, Legal);
959     setOperationAction(ISD::UMIN,               MVT::v4i32, Legal);
960
961     // FIXME: Do we need to handle scalar-to-vector here?
962     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
963
964     // We directly match byte blends in the backend as they match the VSELECT
965     // condition form.
966     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
967
968     // SSE41 brings specific instructions for doing vector sign extend even in
969     // cases where we don't have SRA.
970     for (MVT VT : MVT::integer_vector_valuetypes()) {
971       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i8, Custom);
972       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i16, Custom);
973       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i32, Custom);
974     }
975
976     // SSE41 also has vector sign/zero extending loads, PMOV[SZ]X
977     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i16, MVT::v8i8,  Legal);
978     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i8,  Legal);
979     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i8,  Legal);
980     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
981     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
982     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
983
984     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i16, MVT::v8i8,  Legal);
985     setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i8,  Legal);
986     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i8,  Legal);
987     setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
988     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
989     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
990
991     // i8 and i16 vectors are custom because the source register and source
992     // source memory operand types are not the same width.  f32 vectors are
993     // custom since the immediate controlling the insert encodes additional
994     // information.
995     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
996     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
997     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
998     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
999
1000     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1001     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1002     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1003     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1004
1005     // FIXME: these should be Legal, but that's only for the case where
1006     // the index is constant.  For now custom expand to deal with that.
1007     if (Subtarget->is64Bit()) {
1008       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1009       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1010     }
1011   }
1012
1013   if (Subtarget->hasSSE2()) {
1014     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v2i64, Custom);
1015     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v4i32, Custom);
1016     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v8i16, Custom);
1017
1018     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1019     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1020
1021     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1022     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1023
1024     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1025     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1026
1027     // In the customized shift lowering, the legal cases in AVX2 will be
1028     // recognized.
1029     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1030     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1031
1032     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1033     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1034
1035     setOperationAction(ISD::SRA,               MVT::v2i64, Custom);
1036     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1037   }
1038
1039   if (!Subtarget->useSoftFloat() && Subtarget->hasFp256()) {
1040     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1041     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1042     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1043     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1044     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1045     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1046
1047     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1048     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1049     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1050
1051     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1052     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1053     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1054     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1055     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1056     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1057     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1058     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1059     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1060     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1061     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1062     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1063
1064     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1065     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1066     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1067     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1068     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1069     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1070     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1071     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1072     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1073     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1074     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1075     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1076
1077     // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1078     // even though v8i16 is a legal type.
1079     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Promote);
1080     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i16, Promote);
1081     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1082
1083     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1084     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1085     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1086
1087     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1088     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1089
1090     for (MVT VT : MVT::fp_vector_valuetypes())
1091       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4f32, Legal);
1092
1093     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1094     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1095
1096     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1097     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1098
1099     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1100     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1101
1102     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1103     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1104     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1105     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1106
1107     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1108     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1109     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1110
1111     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1112     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1113     setOperationAction(ISD::SIGN_EXTEND,       MVT::v16i16, Custom);
1114     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1115     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1116     setOperationAction(ISD::ZERO_EXTEND,       MVT::v16i16, Custom);
1117     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1118     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1119     setOperationAction(ISD::ANY_EXTEND,        MVT::v16i16, Custom);
1120     setOperationAction(ISD::TRUNCATE,          MVT::v16i8, Custom);
1121     setOperationAction(ISD::TRUNCATE,          MVT::v8i16, Custom);
1122     setOperationAction(ISD::TRUNCATE,          MVT::v4i32, Custom);
1123
1124     setOperationAction(ISD::CTPOP,             MVT::v32i8, Custom);
1125     setOperationAction(ISD::CTPOP,             MVT::v16i16, Custom);
1126     setOperationAction(ISD::CTPOP,             MVT::v8i32, Custom);
1127     setOperationAction(ISD::CTPOP,             MVT::v4i64, Custom);
1128
1129     if (Subtarget->hasFMA() || Subtarget->hasFMA4() || Subtarget->hasAVX512()) {
1130       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1131       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1132       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1133       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1134       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1135       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1136     }
1137
1138     if (Subtarget->hasInt256()) {
1139       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1140       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1141       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1142       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1143
1144       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1145       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1146       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1147       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1148
1149       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1150       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1151       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1152       setOperationAction(ISD::MUL,             MVT::v32i8, Custom);
1153
1154       setOperationAction(ISD::UMUL_LOHI,       MVT::v8i32, Custom);
1155       setOperationAction(ISD::SMUL_LOHI,       MVT::v8i32, Custom);
1156       setOperationAction(ISD::MULHU,           MVT::v16i16, Legal);
1157       setOperationAction(ISD::MULHS,           MVT::v16i16, Legal);
1158
1159       setOperationAction(ISD::SMAX,            MVT::v32i8,  Legal);
1160       setOperationAction(ISD::SMAX,            MVT::v16i16, Legal);
1161       setOperationAction(ISD::SMAX,            MVT::v8i32,  Legal);
1162       setOperationAction(ISD::UMAX,            MVT::v32i8,  Legal);
1163       setOperationAction(ISD::UMAX,            MVT::v16i16, Legal);
1164       setOperationAction(ISD::UMAX,            MVT::v8i32,  Legal);
1165       setOperationAction(ISD::SMIN,            MVT::v32i8,  Legal);
1166       setOperationAction(ISD::SMIN,            MVT::v16i16, Legal);
1167       setOperationAction(ISD::SMIN,            MVT::v8i32,  Legal);
1168       setOperationAction(ISD::UMIN,            MVT::v32i8,  Legal);
1169       setOperationAction(ISD::UMIN,            MVT::v16i16, Legal);
1170       setOperationAction(ISD::UMIN,            MVT::v8i32,  Legal);
1171
1172       // The custom lowering for UINT_TO_FP for v8i32 becomes interesting
1173       // when we have a 256bit-wide blend with immediate.
1174       setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Custom);
1175
1176       // AVX2 also has wider vector sign/zero extending loads, VPMOV[SZ]X
1177       setLoadExtAction(ISD::SEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1178       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32,  MVT::v8i8,  Legal);
1179       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i8,  Legal);
1180       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32,  MVT::v8i16, Legal);
1181       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i16, Legal);
1182       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i32, Legal);
1183
1184       setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1185       setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32,  MVT::v8i8,  Legal);
1186       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i8,  Legal);
1187       setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32,  MVT::v8i16, Legal);
1188       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i16, Legal);
1189       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i32, Legal);
1190     } else {
1191       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1192       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1193       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1194       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1195
1196       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1197       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1198       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1199       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1200
1201       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1202       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1203       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1204       setOperationAction(ISD::MUL,             MVT::v32i8, Custom);
1205     }
1206
1207     // In the customized shift lowering, the legal cases in AVX2 will be
1208     // recognized.
1209     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1210     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1211
1212     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1213     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1214
1215     setOperationAction(ISD::SRA,               MVT::v4i64, Custom);
1216     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1217
1218     // Custom lower several nodes for 256-bit types.
1219     for (MVT VT : MVT::vector_valuetypes()) {
1220       if (VT.getScalarSizeInBits() >= 32) {
1221         setOperationAction(ISD::MLOAD,  VT, Legal);
1222         setOperationAction(ISD::MSTORE, VT, Legal);
1223       }
1224       // Extract subvector is special because the value type
1225       // (result) is 128-bit but the source is 256-bit wide.
1226       if (VT.is128BitVector()) {
1227         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1228       }
1229       // Do not attempt to custom lower other non-256-bit vectors
1230       if (!VT.is256BitVector())
1231         continue;
1232
1233       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1234       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1235       setOperationAction(ISD::VSELECT,            VT, Custom);
1236       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1237       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1238       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1239       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1240       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1241     }
1242
1243     if (Subtarget->hasInt256())
1244       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1245
1246
1247     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1248     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1249       MVT VT = (MVT::SimpleValueType)i;
1250
1251       // Do not attempt to promote non-256-bit vectors
1252       if (!VT.is256BitVector())
1253         continue;
1254
1255       setOperationAction(ISD::AND,    VT, Promote);
1256       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1257       setOperationAction(ISD::OR,     VT, Promote);
1258       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1259       setOperationAction(ISD::XOR,    VT, Promote);
1260       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1261       setOperationAction(ISD::LOAD,   VT, Promote);
1262       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1263       setOperationAction(ISD::SELECT, VT, Promote);
1264       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1265     }
1266   }
1267
1268   if (!Subtarget->useSoftFloat() && Subtarget->hasAVX512()) {
1269     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1270     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1271     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1272     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1273
1274     addRegisterClass(MVT::i1,     &X86::VK1RegClass);
1275     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1276     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1277
1278     for (MVT VT : MVT::fp_vector_valuetypes())
1279       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8f32, Legal);
1280
1281     setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i32, MVT::v16i8, Legal);
1282     setLoadExtAction(ISD::SEXTLOAD, MVT::v16i32, MVT::v16i8, Legal);
1283     setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i32, MVT::v16i16, Legal);
1284     setLoadExtAction(ISD::SEXTLOAD, MVT::v16i32, MVT::v16i16, Legal);
1285     setLoadExtAction(ISD::ZEXTLOAD, MVT::v32i16, MVT::v32i8, Legal);
1286     setLoadExtAction(ISD::SEXTLOAD, MVT::v32i16, MVT::v32i8, Legal);
1287     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i8,  Legal);
1288     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i8,  Legal);
1289     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i16,  Legal);
1290     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i16,  Legal);
1291     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i32,  Legal);
1292     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i32,  Legal);
1293
1294     setOperationAction(ISD::BR_CC,              MVT::i1,    Expand);
1295     setOperationAction(ISD::SETCC,              MVT::i1,    Custom);
1296     setOperationAction(ISD::XOR,                MVT::i1,    Legal);
1297     setOperationAction(ISD::OR,                 MVT::i1,    Legal);
1298     setOperationAction(ISD::AND,                MVT::i1,    Legal);
1299     setOperationAction(ISD::SUB,                MVT::i1,    Custom);
1300     setOperationAction(ISD::ADD,                MVT::i1,    Custom);
1301     setOperationAction(ISD::MUL,                MVT::i1,    Custom);
1302     setOperationAction(ISD::LOAD,               MVT::v16f32, Legal);
1303     setOperationAction(ISD::LOAD,               MVT::v8f64, Legal);
1304     setOperationAction(ISD::LOAD,               MVT::v8i64, Legal);
1305     setOperationAction(ISD::LOAD,               MVT::v16i32, Legal);
1306     setOperationAction(ISD::LOAD,               MVT::v16i1, Legal);
1307
1308     setOperationAction(ISD::FADD,               MVT::v16f32, Legal);
1309     setOperationAction(ISD::FSUB,               MVT::v16f32, Legal);
1310     setOperationAction(ISD::FMUL,               MVT::v16f32, Legal);
1311     setOperationAction(ISD::FDIV,               MVT::v16f32, Legal);
1312     setOperationAction(ISD::FSQRT,              MVT::v16f32, Legal);
1313     setOperationAction(ISD::FNEG,               MVT::v16f32, Custom);
1314
1315     setOperationAction(ISD::FADD,               MVT::v8f64, Legal);
1316     setOperationAction(ISD::FSUB,               MVT::v8f64, Legal);
1317     setOperationAction(ISD::FMUL,               MVT::v8f64, Legal);
1318     setOperationAction(ISD::FDIV,               MVT::v8f64, Legal);
1319     setOperationAction(ISD::FSQRT,              MVT::v8f64, Legal);
1320     setOperationAction(ISD::FNEG,               MVT::v8f64, Custom);
1321     setOperationAction(ISD::FMA,                MVT::v8f64, Legal);
1322     setOperationAction(ISD::FMA,                MVT::v16f32, Legal);
1323
1324     setOperationAction(ISD::FP_TO_SINT,         MVT::i32, Legal);
1325     setOperationAction(ISD::FP_TO_UINT,         MVT::i32, Legal);
1326     setOperationAction(ISD::SINT_TO_FP,         MVT::i32, Legal);
1327     setOperationAction(ISD::UINT_TO_FP,         MVT::i32, Legal);
1328     if (Subtarget->is64Bit()) {
1329       setOperationAction(ISD::FP_TO_UINT,       MVT::i64, Legal);
1330       setOperationAction(ISD::FP_TO_SINT,       MVT::i64, Legal);
1331       setOperationAction(ISD::SINT_TO_FP,       MVT::i64, Legal);
1332       setOperationAction(ISD::UINT_TO_FP,       MVT::i64, Legal);
1333     }
1334     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1335     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1336     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1337     setOperationAction(ISD::FP_TO_UINT,         MVT::v4i32, Legal);
1338     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1339     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i1,   Custom);
1340     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i1,  Custom);
1341     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i8,  Promote);
1342     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i16, Promote);
1343     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1344     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1345     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Legal);
1346     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i8, Custom);
1347     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i16, Custom);
1348     setOperationAction(ISD::FP_ROUND,           MVT::v8f32, Legal);
1349     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Legal);
1350
1351     setTruncStoreAction(MVT::v8i64,   MVT::v8i8,   Legal);
1352     setTruncStoreAction(MVT::v8i64,   MVT::v8i16,  Legal);
1353     setTruncStoreAction(MVT::v8i64,   MVT::v8i32,  Legal);
1354     setTruncStoreAction(MVT::v16i32,  MVT::v16i8,  Legal);
1355     setTruncStoreAction(MVT::v16i32,  MVT::v16i16, Legal);
1356     if (Subtarget->hasVLX()){
1357       setTruncStoreAction(MVT::v4i64, MVT::v4i8,  Legal);
1358       setTruncStoreAction(MVT::v4i64, MVT::v4i16, Legal);
1359       setTruncStoreAction(MVT::v4i64, MVT::v4i32, Legal);
1360       setTruncStoreAction(MVT::v8i32, MVT::v8i8,  Legal);
1361       setTruncStoreAction(MVT::v8i32, MVT::v8i16, Legal);
1362
1363       setTruncStoreAction(MVT::v2i64, MVT::v2i8,  Legal);
1364       setTruncStoreAction(MVT::v2i64, MVT::v2i16, Legal);
1365       setTruncStoreAction(MVT::v2i64, MVT::v2i32, Legal);
1366       setTruncStoreAction(MVT::v4i32, MVT::v4i8,  Legal);
1367       setTruncStoreAction(MVT::v4i32, MVT::v4i16, Legal);
1368     }
1369     setOperationAction(ISD::TRUNCATE,           MVT::i1, Custom);
1370     setOperationAction(ISD::TRUNCATE,           MVT::v16i8, Custom);
1371     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1372     if (Subtarget->hasDQI()) {
1373       setOperationAction(ISD::TRUNCATE,         MVT::v2i1, Custom);
1374       setOperationAction(ISD::TRUNCATE,         MVT::v4i1, Custom);
1375
1376       setOperationAction(ISD::SINT_TO_FP,       MVT::v8i64, Legal);
1377       setOperationAction(ISD::UINT_TO_FP,       MVT::v8i64, Legal);
1378       setOperationAction(ISD::FP_TO_SINT,       MVT::v8i64, Legal);
1379       setOperationAction(ISD::FP_TO_UINT,       MVT::v8i64, Legal);
1380       if (Subtarget->hasVLX()) {
1381         setOperationAction(ISD::SINT_TO_FP,    MVT::v4i64, Legal);
1382         setOperationAction(ISD::SINT_TO_FP,    MVT::v2i64, Legal);
1383         setOperationAction(ISD::UINT_TO_FP,    MVT::v4i64, Legal);
1384         setOperationAction(ISD::UINT_TO_FP,    MVT::v2i64, Legal);
1385         setOperationAction(ISD::FP_TO_SINT,    MVT::v4i64, Legal);
1386         setOperationAction(ISD::FP_TO_SINT,    MVT::v2i64, Legal);
1387         setOperationAction(ISD::FP_TO_UINT,    MVT::v4i64, Legal);
1388         setOperationAction(ISD::FP_TO_UINT,    MVT::v2i64, Legal);
1389       }
1390     }
1391     if (Subtarget->hasVLX()) {
1392       setOperationAction(ISD::SINT_TO_FP,       MVT::v8i32, Legal);
1393       setOperationAction(ISD::UINT_TO_FP,       MVT::v8i32, Legal);
1394       setOperationAction(ISD::FP_TO_SINT,       MVT::v8i32, Legal);
1395       setOperationAction(ISD::FP_TO_UINT,       MVT::v8i32, Legal);
1396       setOperationAction(ISD::SINT_TO_FP,       MVT::v4i32, Legal);
1397       setOperationAction(ISD::UINT_TO_FP,       MVT::v4i32, Legal);
1398       setOperationAction(ISD::FP_TO_SINT,       MVT::v4i32, Legal);
1399       setOperationAction(ISD::FP_TO_UINT,       MVT::v4i32, Legal);
1400     }
1401     setOperationAction(ISD::TRUNCATE,           MVT::v8i1, Custom);
1402     setOperationAction(ISD::TRUNCATE,           MVT::v16i1, Custom);
1403     setOperationAction(ISD::TRUNCATE,           MVT::v16i16, Custom);
1404     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1405     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1406     setOperationAction(ISD::ANY_EXTEND,         MVT::v16i32, Custom);
1407     setOperationAction(ISD::ANY_EXTEND,         MVT::v8i64, Custom);
1408     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1409     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1410     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i8, Custom);
1411     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i16, Custom);
1412     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i16, Custom);
1413     if (Subtarget->hasDQI()) {
1414       setOperationAction(ISD::SIGN_EXTEND,        MVT::v4i32, Custom);
1415       setOperationAction(ISD::SIGN_EXTEND,        MVT::v2i64, Custom);
1416     }
1417     setOperationAction(ISD::FFLOOR,             MVT::v16f32, Legal);
1418     setOperationAction(ISD::FFLOOR,             MVT::v8f64, Legal);
1419     setOperationAction(ISD::FCEIL,              MVT::v16f32, Legal);
1420     setOperationAction(ISD::FCEIL,              MVT::v8f64, Legal);
1421     setOperationAction(ISD::FTRUNC,             MVT::v16f32, Legal);
1422     setOperationAction(ISD::FTRUNC,             MVT::v8f64, Legal);
1423     setOperationAction(ISD::FRINT,              MVT::v16f32, Legal);
1424     setOperationAction(ISD::FRINT,              MVT::v8f64, Legal);
1425     setOperationAction(ISD::FNEARBYINT,         MVT::v16f32, Legal);
1426     setOperationAction(ISD::FNEARBYINT,         MVT::v8f64, Legal);
1427
1428     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1429     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1430     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1431     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1432     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i1, Legal);
1433
1434     setOperationAction(ISD::SETCC,              MVT::v16i1, Custom);
1435     setOperationAction(ISD::SETCC,              MVT::v8i1, Custom);
1436
1437     setOperationAction(ISD::MUL,              MVT::v8i64, Custom);
1438
1439     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1,  Custom);
1440     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1441     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i1, Custom);
1442     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i1, Custom);
1443     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i1, Custom);
1444     setOperationAction(ISD::BUILD_VECTOR,       MVT::v16i1, Custom);
1445     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1446     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1447     setOperationAction(ISD::SELECT,             MVT::v16f32, Custom);
1448     setOperationAction(ISD::SELECT,             MVT::v16i1, Custom);
1449     setOperationAction(ISD::SELECT,             MVT::v8i1,  Custom);
1450
1451     setOperationAction(ISD::SMAX,               MVT::v16i32, Legal);
1452     setOperationAction(ISD::SMAX,               MVT::v8i64, Legal);
1453     setOperationAction(ISD::UMAX,               MVT::v16i32, Legal);
1454     setOperationAction(ISD::UMAX,               MVT::v8i64, Legal);
1455     setOperationAction(ISD::SMIN,               MVT::v16i32, Legal);
1456     setOperationAction(ISD::SMIN,               MVT::v8i64, Legal);
1457     setOperationAction(ISD::UMIN,               MVT::v16i32, Legal);
1458     setOperationAction(ISD::UMIN,               MVT::v8i64, Legal);
1459
1460     setOperationAction(ISD::ADD,                MVT::v8i64, Legal);
1461     setOperationAction(ISD::ADD,                MVT::v16i32, Legal);
1462
1463     setOperationAction(ISD::SUB,                MVT::v8i64, Legal);
1464     setOperationAction(ISD::SUB,                MVT::v16i32, Legal);
1465
1466     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1467
1468     setOperationAction(ISD::SRL,                MVT::v8i64, Custom);
1469     setOperationAction(ISD::SRL,                MVT::v16i32, Custom);
1470
1471     setOperationAction(ISD::SHL,                MVT::v8i64, Custom);
1472     setOperationAction(ISD::SHL,                MVT::v16i32, Custom);
1473
1474     setOperationAction(ISD::SRA,                MVT::v8i64, Custom);
1475     setOperationAction(ISD::SRA,                MVT::v16i32, Custom);
1476
1477     setOperationAction(ISD::AND,                MVT::v8i64, Legal);
1478     setOperationAction(ISD::OR,                 MVT::v8i64, Legal);
1479     setOperationAction(ISD::XOR,                MVT::v8i64, Legal);
1480     setOperationAction(ISD::AND,                MVT::v16i32, Legal);
1481     setOperationAction(ISD::OR,                 MVT::v16i32, Legal);
1482     setOperationAction(ISD::XOR,                MVT::v16i32, Legal);
1483
1484     if (Subtarget->hasCDI()) {
1485       setOperationAction(ISD::CTLZ,             MVT::v8i64, Legal);
1486       setOperationAction(ISD::CTLZ,             MVT::v16i32, Legal);
1487     }
1488     if (Subtarget->hasDQI()) {
1489       setOperationAction(ISD::MUL,             MVT::v2i64, Legal);
1490       setOperationAction(ISD::MUL,             MVT::v4i64, Legal);
1491       setOperationAction(ISD::MUL,             MVT::v8i64, Legal);
1492     }
1493     // Custom lower several nodes.
1494     for (MVT VT : MVT::vector_valuetypes()) {
1495       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1496       if (EltSize == 1) {
1497         setOperationAction(ISD::AND, VT, Legal);
1498         setOperationAction(ISD::OR,  VT, Legal);
1499         setOperationAction(ISD::XOR,  VT, Legal);
1500       }
1501       if (EltSize >= 32 && VT.getSizeInBits() <= 512) {
1502         setOperationAction(ISD::MGATHER,  VT, Custom);
1503         setOperationAction(ISD::MSCATTER, VT, Custom);
1504       }
1505       // Extract subvector is special because the value type
1506       // (result) is 256/128-bit but the source is 512-bit wide.
1507       if (VT.is128BitVector() || VT.is256BitVector()) {
1508         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1509       }
1510       if (VT.getVectorElementType() == MVT::i1)
1511         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1512
1513       // Do not attempt to custom lower other non-512-bit vectors
1514       if (!VT.is512BitVector())
1515         continue;
1516
1517       if (EltSize >= 32) {
1518         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1519         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1520         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1521         setOperationAction(ISD::VSELECT,             VT, Legal);
1522         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1523         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1524         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1525         setOperationAction(ISD::MLOAD,               VT, Legal);
1526         setOperationAction(ISD::MSTORE,              VT, Legal);
1527       }
1528     }
1529     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1530       MVT VT = (MVT::SimpleValueType)i;
1531
1532       // Do not attempt to promote non-512-bit vectors.
1533       if (!VT.is512BitVector())
1534         continue;
1535
1536       setOperationAction(ISD::SELECT, VT, Promote);
1537       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1538     }
1539   }// has  AVX-512
1540
1541   if (!Subtarget->useSoftFloat() && Subtarget->hasBWI()) {
1542     addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1543     addRegisterClass(MVT::v64i8,  &X86::VR512RegClass);
1544
1545     addRegisterClass(MVT::v32i1,  &X86::VK32RegClass);
1546     addRegisterClass(MVT::v64i1,  &X86::VK64RegClass);
1547
1548     setOperationAction(ISD::LOAD,               MVT::v32i16, Legal);
1549     setOperationAction(ISD::LOAD,               MVT::v64i8, Legal);
1550     setOperationAction(ISD::SETCC,              MVT::v32i1, Custom);
1551     setOperationAction(ISD::SETCC,              MVT::v64i1, Custom);
1552     setOperationAction(ISD::ADD,                MVT::v32i16, Legal);
1553     setOperationAction(ISD::ADD,                MVT::v64i8, Legal);
1554     setOperationAction(ISD::SUB,                MVT::v32i16, Legal);
1555     setOperationAction(ISD::SUB,                MVT::v64i8, Legal);
1556     setOperationAction(ISD::MUL,                MVT::v32i16, Legal);
1557     setOperationAction(ISD::MULHS,              MVT::v32i16, Legal);
1558     setOperationAction(ISD::MULHU,              MVT::v32i16, Legal);
1559     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v32i1, Custom);
1560     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v64i1, Custom);
1561     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v32i1, Custom);
1562     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v64i1, Custom);
1563     setOperationAction(ISD::SELECT,             MVT::v32i1, Custom);
1564     setOperationAction(ISD::SELECT,             MVT::v64i1, Custom);
1565     setOperationAction(ISD::SIGN_EXTEND,        MVT::v32i8, Custom);
1566     setOperationAction(ISD::ZERO_EXTEND,        MVT::v32i8, Custom);
1567     setOperationAction(ISD::SIGN_EXTEND,        MVT::v32i16, Custom);
1568     setOperationAction(ISD::ZERO_EXTEND,        MVT::v32i16, Custom);
1569     setOperationAction(ISD::SIGN_EXTEND,        MVT::v64i8, Custom);
1570     setOperationAction(ISD::ZERO_EXTEND,        MVT::v64i8, Custom);
1571     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v32i1, Custom);
1572     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v64i1, Custom);
1573     setOperationAction(ISD::VSELECT,            MVT::v32i16, Legal);
1574     setOperationAction(ISD::VSELECT,            MVT::v64i8, Legal);
1575     setOperationAction(ISD::TRUNCATE,           MVT::v32i1, Custom);
1576     setOperationAction(ISD::TRUNCATE,           MVT::v64i1, Custom);
1577     setOperationAction(ISD::TRUNCATE,           MVT::v32i8, Custom);
1578
1579     setOperationAction(ISD::SMAX,               MVT::v64i8, Legal);
1580     setOperationAction(ISD::SMAX,               MVT::v32i16, Legal);
1581     setOperationAction(ISD::UMAX,               MVT::v64i8, Legal);
1582     setOperationAction(ISD::UMAX,               MVT::v32i16, Legal);
1583     setOperationAction(ISD::SMIN,               MVT::v64i8, Legal);
1584     setOperationAction(ISD::SMIN,               MVT::v32i16, Legal);
1585     setOperationAction(ISD::UMIN,               MVT::v64i8, Legal);
1586     setOperationAction(ISD::UMIN,               MVT::v32i16, Legal);
1587
1588     setTruncStoreAction(MVT::v32i16,  MVT::v32i8, Legal);
1589     setTruncStoreAction(MVT::v16i16,  MVT::v16i8, Legal);
1590     if (Subtarget->hasVLX())
1591       setTruncStoreAction(MVT::v8i16,   MVT::v8i8,  Legal);
1592
1593     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1594       const MVT VT = (MVT::SimpleValueType)i;
1595
1596       const unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1597
1598       // Do not attempt to promote non-512-bit vectors.
1599       if (!VT.is512BitVector())
1600         continue;
1601
1602       if (EltSize < 32) {
1603         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1604         setOperationAction(ISD::VSELECT,             VT, Legal);
1605       }
1606     }
1607   }
1608
1609   if (!Subtarget->useSoftFloat() && Subtarget->hasVLX()) {
1610     addRegisterClass(MVT::v4i1,   &X86::VK4RegClass);
1611     addRegisterClass(MVT::v2i1,   &X86::VK2RegClass);
1612
1613     setOperationAction(ISD::SETCC,              MVT::v4i1, Custom);
1614     setOperationAction(ISD::SETCC,              MVT::v2i1, Custom);
1615     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i1, Custom);
1616     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1, Custom);
1617     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v8i1, Custom);
1618     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v4i1, Custom);
1619     setOperationAction(ISD::SELECT,             MVT::v4i1, Custom);
1620     setOperationAction(ISD::SELECT,             MVT::v2i1, Custom);
1621     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4i1, Custom);
1622     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i1, Custom);
1623
1624     setOperationAction(ISD::AND,                MVT::v8i32, Legal);
1625     setOperationAction(ISD::OR,                 MVT::v8i32, Legal);
1626     setOperationAction(ISD::XOR,                MVT::v8i32, Legal);
1627     setOperationAction(ISD::AND,                MVT::v4i32, Legal);
1628     setOperationAction(ISD::OR,                 MVT::v4i32, Legal);
1629     setOperationAction(ISD::XOR,                MVT::v4i32, Legal);
1630     setOperationAction(ISD::SRA,                MVT::v2i64, Custom);
1631     setOperationAction(ISD::SRA,                MVT::v4i64, Custom);
1632
1633     setOperationAction(ISD::SMAX,               MVT::v2i64, Legal);
1634     setOperationAction(ISD::SMAX,               MVT::v4i64, Legal);
1635     setOperationAction(ISD::UMAX,               MVT::v2i64, Legal);
1636     setOperationAction(ISD::UMAX,               MVT::v4i64, Legal);
1637     setOperationAction(ISD::SMIN,               MVT::v2i64, Legal);
1638     setOperationAction(ISD::SMIN,               MVT::v4i64, Legal);
1639     setOperationAction(ISD::UMIN,               MVT::v2i64, Legal);
1640     setOperationAction(ISD::UMIN,               MVT::v4i64, Legal);
1641   }
1642
1643   // We want to custom lower some of our intrinsics.
1644   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1645   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1646   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1647   if (!Subtarget->is64Bit())
1648     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1649
1650   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1651   // handle type legalization for these operations here.
1652   //
1653   // FIXME: We really should do custom legalization for addition and
1654   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1655   // than generic legalization for 64-bit multiplication-with-overflow, though.
1656   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1657     // Add/Sub/Mul with overflow operations are custom lowered.
1658     MVT VT = IntVTs[i];
1659     setOperationAction(ISD::SADDO, VT, Custom);
1660     setOperationAction(ISD::UADDO, VT, Custom);
1661     setOperationAction(ISD::SSUBO, VT, Custom);
1662     setOperationAction(ISD::USUBO, VT, Custom);
1663     setOperationAction(ISD::SMULO, VT, Custom);
1664     setOperationAction(ISD::UMULO, VT, Custom);
1665   }
1666
1667
1668   if (!Subtarget->is64Bit()) {
1669     // These libcalls are not available in 32-bit.
1670     setLibcallName(RTLIB::SHL_I128, nullptr);
1671     setLibcallName(RTLIB::SRL_I128, nullptr);
1672     setLibcallName(RTLIB::SRA_I128, nullptr);
1673   }
1674
1675   // Combine sin / cos into one node or libcall if possible.
1676   if (Subtarget->hasSinCos()) {
1677     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1678     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1679     if (Subtarget->isTargetDarwin()) {
1680       // For MacOSX, we don't want the normal expansion of a libcall to sincos.
1681       // We want to issue a libcall to __sincos_stret to avoid memory traffic.
1682       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1683       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1684     }
1685   }
1686
1687   if (Subtarget->isTargetWin64()) {
1688     setOperationAction(ISD::SDIV, MVT::i128, Custom);
1689     setOperationAction(ISD::UDIV, MVT::i128, Custom);
1690     setOperationAction(ISD::SREM, MVT::i128, Custom);
1691     setOperationAction(ISD::UREM, MVT::i128, Custom);
1692     setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1693     setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1694   }
1695
1696   // We have target-specific dag combine patterns for the following nodes:
1697   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1698   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1699   setTargetDAGCombine(ISD::BITCAST);
1700   setTargetDAGCombine(ISD::VSELECT);
1701   setTargetDAGCombine(ISD::SELECT);
1702   setTargetDAGCombine(ISD::SHL);
1703   setTargetDAGCombine(ISD::SRA);
1704   setTargetDAGCombine(ISD::SRL);
1705   setTargetDAGCombine(ISD::OR);
1706   setTargetDAGCombine(ISD::AND);
1707   setTargetDAGCombine(ISD::ADD);
1708   setTargetDAGCombine(ISD::FADD);
1709   setTargetDAGCombine(ISD::FSUB);
1710   setTargetDAGCombine(ISD::FMA);
1711   setTargetDAGCombine(ISD::SUB);
1712   setTargetDAGCombine(ISD::LOAD);
1713   setTargetDAGCombine(ISD::MLOAD);
1714   setTargetDAGCombine(ISD::STORE);
1715   setTargetDAGCombine(ISD::MSTORE);
1716   setTargetDAGCombine(ISD::ZERO_EXTEND);
1717   setTargetDAGCombine(ISD::ANY_EXTEND);
1718   setTargetDAGCombine(ISD::SIGN_EXTEND);
1719   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1720   setTargetDAGCombine(ISD::SINT_TO_FP);
1721   setTargetDAGCombine(ISD::UINT_TO_FP);
1722   setTargetDAGCombine(ISD::SETCC);
1723   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1724   setTargetDAGCombine(ISD::BUILD_VECTOR);
1725   setTargetDAGCombine(ISD::MUL);
1726   setTargetDAGCombine(ISD::XOR);
1727
1728   computeRegisterProperties(Subtarget->getRegisterInfo());
1729
1730   // On Darwin, -Os means optimize for size without hurting performance,
1731   // do not reduce the limit.
1732   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1733   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1734   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1735   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1736   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1737   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1738   setPrefLoopAlignment(4); // 2^4 bytes.
1739
1740   // Predictable cmov don't hurt on atom because it's in-order.
1741   PredictableSelectIsExpensive = !Subtarget->isAtom();
1742   EnableExtLdPromotion = true;
1743   setPrefFunctionAlignment(4); // 2^4 bytes.
1744
1745   verifyIntrinsicTables();
1746 }
1747
1748 // This has so far only been implemented for 64-bit MachO.
1749 bool X86TargetLowering::useLoadStackGuardNode() const {
1750   return Subtarget->isTargetMachO() && Subtarget->is64Bit();
1751 }
1752
1753 TargetLoweringBase::LegalizeTypeAction
1754 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1755   if (ExperimentalVectorWideningLegalization &&
1756       VT.getVectorNumElements() != 1 &&
1757       VT.getVectorElementType().getSimpleVT() != MVT::i1)
1758     return TypeWidenVector;
1759
1760   return TargetLoweringBase::getPreferredVectorAction(VT);
1761 }
1762
1763 EVT X86TargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1764                                           EVT VT) const {
1765   if (!VT.isVector())
1766     return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1767
1768   const unsigned NumElts = VT.getVectorNumElements();
1769   const EVT EltVT = VT.getVectorElementType();
1770   if (VT.is512BitVector()) {
1771     if (Subtarget->hasAVX512())
1772       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1773           EltVT == MVT::f32 || EltVT == MVT::f64)
1774         switch(NumElts) {
1775         case  8: return MVT::v8i1;
1776         case 16: return MVT::v16i1;
1777       }
1778     if (Subtarget->hasBWI())
1779       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1780         switch(NumElts) {
1781         case 32: return MVT::v32i1;
1782         case 64: return MVT::v64i1;
1783       }
1784   }
1785
1786   if (VT.is256BitVector() || VT.is128BitVector()) {
1787     if (Subtarget->hasVLX())
1788       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1789           EltVT == MVT::f32 || EltVT == MVT::f64)
1790         switch(NumElts) {
1791         case 2: return MVT::v2i1;
1792         case 4: return MVT::v4i1;
1793         case 8: return MVT::v8i1;
1794       }
1795     if (Subtarget->hasBWI() && Subtarget->hasVLX())
1796       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1797         switch(NumElts) {
1798         case  8: return MVT::v8i1;
1799         case 16: return MVT::v16i1;
1800         case 32: return MVT::v32i1;
1801       }
1802   }
1803
1804   return VT.changeVectorElementTypeToInteger();
1805 }
1806
1807 /// Helper for getByValTypeAlignment to determine
1808 /// the desired ByVal argument alignment.
1809 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1810   if (MaxAlign == 16)
1811     return;
1812   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1813     if (VTy->getBitWidth() == 128)
1814       MaxAlign = 16;
1815   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1816     unsigned EltAlign = 0;
1817     getMaxByValAlign(ATy->getElementType(), EltAlign);
1818     if (EltAlign > MaxAlign)
1819       MaxAlign = EltAlign;
1820   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1821     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1822       unsigned EltAlign = 0;
1823       getMaxByValAlign(STy->getElementType(i), EltAlign);
1824       if (EltAlign > MaxAlign)
1825         MaxAlign = EltAlign;
1826       if (MaxAlign == 16)
1827         break;
1828     }
1829   }
1830 }
1831
1832 /// Return the desired alignment for ByVal aggregate
1833 /// function arguments in the caller parameter area. For X86, aggregates
1834 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1835 /// are at 4-byte boundaries.
1836 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty,
1837                                                   const DataLayout &DL) const {
1838   if (Subtarget->is64Bit()) {
1839     // Max of 8 and alignment of type.
1840     unsigned TyAlign = DL.getABITypeAlignment(Ty);
1841     if (TyAlign > 8)
1842       return TyAlign;
1843     return 8;
1844   }
1845
1846   unsigned Align = 4;
1847   if (Subtarget->hasSSE1())
1848     getMaxByValAlign(Ty, Align);
1849   return Align;
1850 }
1851
1852 /// Returns the target specific optimal type for load
1853 /// and store operations as a result of memset, memcpy, and memmove
1854 /// lowering. If DstAlign is zero that means it's safe to destination
1855 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1856 /// means there isn't a need to check it against alignment requirement,
1857 /// probably because the source does not need to be loaded. If 'IsMemset' is
1858 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1859 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1860 /// source is constant so it does not need to be loaded.
1861 /// It returns EVT::Other if the type should be determined using generic
1862 /// target-independent logic.
1863 EVT
1864 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1865                                        unsigned DstAlign, unsigned SrcAlign,
1866                                        bool IsMemset, bool ZeroMemset,
1867                                        bool MemcpyStrSrc,
1868                                        MachineFunction &MF) const {
1869   const Function *F = MF.getFunction();
1870   if ((!IsMemset || ZeroMemset) &&
1871       !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1872     if (Size >= 16 &&
1873         (Subtarget->isUnalignedMemAccessFast() ||
1874          ((DstAlign == 0 || DstAlign >= 16) &&
1875           (SrcAlign == 0 || SrcAlign >= 16)))) {
1876       if (Size >= 32) {
1877         if (Subtarget->hasInt256())
1878           return MVT::v8i32;
1879         if (Subtarget->hasFp256())
1880           return MVT::v8f32;
1881       }
1882       if (Subtarget->hasSSE2())
1883         return MVT::v4i32;
1884       if (Subtarget->hasSSE1())
1885         return MVT::v4f32;
1886     } else if (!MemcpyStrSrc && Size >= 8 &&
1887                !Subtarget->is64Bit() &&
1888                Subtarget->hasSSE2()) {
1889       // Do not use f64 to lower memcpy if source is string constant. It's
1890       // better to use i32 to avoid the loads.
1891       return MVT::f64;
1892     }
1893   }
1894   if (Subtarget->is64Bit() && Size >= 8)
1895     return MVT::i64;
1896   return MVT::i32;
1897 }
1898
1899 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1900   if (VT == MVT::f32)
1901     return X86ScalarSSEf32;
1902   else if (VT == MVT::f64)
1903     return X86ScalarSSEf64;
1904   return true;
1905 }
1906
1907 bool
1908 X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1909                                                   unsigned,
1910                                                   unsigned,
1911                                                   bool *Fast) const {
1912   if (Fast)
1913     *Fast = Subtarget->isUnalignedMemAccessFast();
1914   return true;
1915 }
1916
1917 /// Return the entry encoding for a jump table in the
1918 /// current function.  The returned value is a member of the
1919 /// MachineJumpTableInfo::JTEntryKind enum.
1920 unsigned X86TargetLowering::getJumpTableEncoding() const {
1921   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1922   // symbol.
1923   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1924       Subtarget->isPICStyleGOT())
1925     return MachineJumpTableInfo::EK_Custom32;
1926
1927   // Otherwise, use the normal jump table encoding heuristics.
1928   return TargetLowering::getJumpTableEncoding();
1929 }
1930
1931 bool X86TargetLowering::useSoftFloat() const {
1932   return Subtarget->useSoftFloat();
1933 }
1934
1935 const MCExpr *
1936 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1937                                              const MachineBasicBlock *MBB,
1938                                              unsigned uid,MCContext &Ctx) const{
1939   assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
1940          Subtarget->isPICStyleGOT());
1941   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1942   // entries.
1943   return MCSymbolRefExpr::create(MBB->getSymbol(),
1944                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1945 }
1946
1947 /// Returns relocation base for the given PIC jumptable.
1948 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1949                                                     SelectionDAG &DAG) const {
1950   if (!Subtarget->is64Bit())
1951     // This doesn't have SDLoc associated with it, but is not really the
1952     // same as a Register.
1953     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
1954                        getPointerTy(DAG.getDataLayout()));
1955   return Table;
1956 }
1957
1958 /// This returns the relocation base for the given PIC jumptable,
1959 /// the same as getPICJumpTableRelocBase, but as an MCExpr.
1960 const MCExpr *X86TargetLowering::
1961 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1962                              MCContext &Ctx) const {
1963   // X86-64 uses RIP relative addressing based on the jump table label.
1964   if (Subtarget->isPICStyleRIPRel())
1965     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1966
1967   // Otherwise, the reference is relative to the PIC base.
1968   return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
1969 }
1970
1971 std::pair<const TargetRegisterClass *, uint8_t>
1972 X86TargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1973                                            MVT VT) const {
1974   const TargetRegisterClass *RRC = nullptr;
1975   uint8_t Cost = 1;
1976   switch (VT.SimpleTy) {
1977   default:
1978     return TargetLowering::findRepresentativeClass(TRI, VT);
1979   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1980     RRC = Subtarget->is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
1981     break;
1982   case MVT::x86mmx:
1983     RRC = &X86::VR64RegClass;
1984     break;
1985   case MVT::f32: case MVT::f64:
1986   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1987   case MVT::v4f32: case MVT::v2f64:
1988   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1989   case MVT::v4f64:
1990     RRC = &X86::VR128RegClass;
1991     break;
1992   }
1993   return std::make_pair(RRC, Cost);
1994 }
1995
1996 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1997                                                unsigned &Offset) const {
1998   if (!Subtarget->isTargetLinux())
1999     return false;
2000
2001   if (Subtarget->is64Bit()) {
2002     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
2003     Offset = 0x28;
2004     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
2005       AddressSpace = 256;
2006     else
2007       AddressSpace = 257;
2008   } else {
2009     // %gs:0x14 on i386
2010     Offset = 0x14;
2011     AddressSpace = 256;
2012   }
2013   return true;
2014 }
2015
2016 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
2017                                             unsigned DestAS) const {
2018   assert(SrcAS != DestAS && "Expected different address spaces!");
2019
2020   return SrcAS < 256 && DestAS < 256;
2021 }
2022
2023 //===----------------------------------------------------------------------===//
2024 //               Return Value Calling Convention Implementation
2025 //===----------------------------------------------------------------------===//
2026
2027 #include "X86GenCallingConv.inc"
2028
2029 bool
2030 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2031                                   MachineFunction &MF, bool isVarArg,
2032                         const SmallVectorImpl<ISD::OutputArg> &Outs,
2033                         LLVMContext &Context) const {
2034   SmallVector<CCValAssign, 16> RVLocs;
2035   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2036   return CCInfo.CheckReturn(Outs, RetCC_X86);
2037 }
2038
2039 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
2040   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
2041   return ScratchRegs;
2042 }
2043
2044 SDValue
2045 X86TargetLowering::LowerReturn(SDValue Chain,
2046                                CallingConv::ID CallConv, bool isVarArg,
2047                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2048                                const SmallVectorImpl<SDValue> &OutVals,
2049                                SDLoc dl, SelectionDAG &DAG) const {
2050   MachineFunction &MF = DAG.getMachineFunction();
2051   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2052
2053   SmallVector<CCValAssign, 16> RVLocs;
2054   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
2055   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
2056
2057   SDValue Flag;
2058   SmallVector<SDValue, 6> RetOps;
2059   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2060   // Operand #1 = Bytes To Pop
2061   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(), dl,
2062                    MVT::i16));
2063
2064   // Copy the result values into the output registers.
2065   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2066     CCValAssign &VA = RVLocs[i];
2067     assert(VA.isRegLoc() && "Can only return in registers!");
2068     SDValue ValToCopy = OutVals[i];
2069     EVT ValVT = ValToCopy.getValueType();
2070
2071     // Promote values to the appropriate types.
2072     if (VA.getLocInfo() == CCValAssign::SExt)
2073       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2074     else if (VA.getLocInfo() == CCValAssign::ZExt)
2075       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
2076     else if (VA.getLocInfo() == CCValAssign::AExt) {
2077       if (ValVT.isVector() && ValVT.getScalarType() == MVT::i1)
2078         ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2079       else
2080         ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
2081     }
2082     else if (VA.getLocInfo() == CCValAssign::BCvt)
2083       ValToCopy = DAG.getBitcast(VA.getLocVT(), ValToCopy);
2084
2085     assert(VA.getLocInfo() != CCValAssign::FPExt &&
2086            "Unexpected FP-extend for return value.");
2087
2088     // If this is x86-64, and we disabled SSE, we can't return FP values,
2089     // or SSE or MMX vectors.
2090     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
2091          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
2092           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
2093       report_fatal_error("SSE register return with SSE disabled");
2094     }
2095     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
2096     // llvm-gcc has never done it right and no one has noticed, so this
2097     // should be OK for now.
2098     if (ValVT == MVT::f64 &&
2099         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
2100       report_fatal_error("SSE2 register return with SSE2 disabled");
2101
2102     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
2103     // the RET instruction and handled by the FP Stackifier.
2104     if (VA.getLocReg() == X86::FP0 ||
2105         VA.getLocReg() == X86::FP1) {
2106       // If this is a copy from an xmm register to ST(0), use an FPExtend to
2107       // change the value to the FP stack register class.
2108       if (isScalarFPTypeInSSEReg(VA.getValVT()))
2109         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
2110       RetOps.push_back(ValToCopy);
2111       // Don't emit a copytoreg.
2112       continue;
2113     }
2114
2115     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
2116     // which is returned in RAX / RDX.
2117     if (Subtarget->is64Bit()) {
2118       if (ValVT == MVT::x86mmx) {
2119         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
2120           ValToCopy = DAG.getBitcast(MVT::i64, ValToCopy);
2121           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
2122                                   ValToCopy);
2123           // If we don't have SSE2 available, convert to v4f32 so the generated
2124           // register is legal.
2125           if (!Subtarget->hasSSE2())
2126             ValToCopy = DAG.getBitcast(MVT::v4f32, ValToCopy);
2127         }
2128       }
2129     }
2130
2131     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
2132     Flag = Chain.getValue(1);
2133     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2134   }
2135
2136   // All x86 ABIs require that for returning structs by value we copy
2137   // the sret argument into %rax/%eax (depending on ABI) for the return.
2138   // We saved the argument into a virtual register in the entry block,
2139   // so now we copy the value out and into %rax/%eax.
2140   //
2141   // Checking Function.hasStructRetAttr() here is insufficient because the IR
2142   // may not have an explicit sret argument. If FuncInfo.CanLowerReturn is
2143   // false, then an sret argument may be implicitly inserted in the SelDAG. In
2144   // either case FuncInfo->setSRetReturnReg() will have been called.
2145   if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
2146     SDValue Val = DAG.getCopyFromReg(Chain, dl, SRetReg,
2147                                      getPointerTy(MF.getDataLayout()));
2148
2149     unsigned RetValReg
2150         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
2151           X86::RAX : X86::EAX;
2152     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2153     Flag = Chain.getValue(1);
2154
2155     // RAX/EAX now acts like a return value.
2156     RetOps.push_back(
2157         DAG.getRegister(RetValReg, getPointerTy(DAG.getDataLayout())));
2158   }
2159
2160   RetOps[0] = Chain;  // Update chain.
2161
2162   // Add the flag if we have it.
2163   if (Flag.getNode())
2164     RetOps.push_back(Flag);
2165
2166   return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
2167 }
2168
2169 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2170   if (N->getNumValues() != 1)
2171     return false;
2172   if (!N->hasNUsesOfValue(1, 0))
2173     return false;
2174
2175   SDValue TCChain = Chain;
2176   SDNode *Copy = *N->use_begin();
2177   if (Copy->getOpcode() == ISD::CopyToReg) {
2178     // If the copy has a glue operand, we conservatively assume it isn't safe to
2179     // perform a tail call.
2180     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2181       return false;
2182     TCChain = Copy->getOperand(0);
2183   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2184     return false;
2185
2186   bool HasRet = false;
2187   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2188        UI != UE; ++UI) {
2189     if (UI->getOpcode() != X86ISD::RET_FLAG)
2190       return false;
2191     // If we are returning more than one value, we can definitely
2192     // not make a tail call see PR19530
2193     if (UI->getNumOperands() > 4)
2194       return false;
2195     if (UI->getNumOperands() == 4 &&
2196         UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2197       return false;
2198     HasRet = true;
2199   }
2200
2201   if (!HasRet)
2202     return false;
2203
2204   Chain = TCChain;
2205   return true;
2206 }
2207
2208 EVT
2209 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
2210                                             ISD::NodeType ExtendKind) const {
2211   MVT ReturnMVT;
2212   // TODO: Is this also valid on 32-bit?
2213   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2214     ReturnMVT = MVT::i8;
2215   else
2216     ReturnMVT = MVT::i32;
2217
2218   EVT MinVT = getRegisterType(Context, ReturnMVT);
2219   return VT.bitsLT(MinVT) ? MinVT : VT;
2220 }
2221
2222 /// Lower the result values of a call into the
2223 /// appropriate copies out of appropriate physical registers.
2224 ///
2225 SDValue
2226 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2227                                    CallingConv::ID CallConv, bool isVarArg,
2228                                    const SmallVectorImpl<ISD::InputArg> &Ins,
2229                                    SDLoc dl, SelectionDAG &DAG,
2230                                    SmallVectorImpl<SDValue> &InVals) const {
2231
2232   // Assign locations to each value returned by this call.
2233   SmallVector<CCValAssign, 16> RVLocs;
2234   bool Is64Bit = Subtarget->is64Bit();
2235   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2236                  *DAG.getContext());
2237   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2238
2239   // Copy all of the result registers out of their specified physreg.
2240   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2241     CCValAssign &VA = RVLocs[i];
2242     EVT CopyVT = VA.getLocVT();
2243
2244     // If this is x86-64, and we disabled SSE, we can't return FP values
2245     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2246         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2247       report_fatal_error("SSE register return with SSE disabled");
2248     }
2249
2250     // If we prefer to use the value in xmm registers, copy it out as f80 and
2251     // use a truncate to move it from fp stack reg to xmm reg.
2252     bool RoundAfterCopy = false;
2253     if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2254         isScalarFPTypeInSSEReg(VA.getValVT())) {
2255       CopyVT = MVT::f80;
2256       RoundAfterCopy = (CopyVT != VA.getLocVT());
2257     }
2258
2259     Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2260                                CopyVT, InFlag).getValue(1);
2261     SDValue Val = Chain.getValue(0);
2262
2263     if (RoundAfterCopy)
2264       Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2265                         // This truncation won't change the value.
2266                         DAG.getIntPtrConstant(1, dl));
2267
2268     if (VA.isExtInLoc() && VA.getValVT().getScalarType() == MVT::i1)
2269       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
2270
2271     InFlag = Chain.getValue(2);
2272     InVals.push_back(Val);
2273   }
2274
2275   return Chain;
2276 }
2277
2278 //===----------------------------------------------------------------------===//
2279 //                C & StdCall & Fast Calling Convention implementation
2280 //===----------------------------------------------------------------------===//
2281 //  StdCall calling convention seems to be standard for many Windows' API
2282 //  routines and around. It differs from C calling convention just a little:
2283 //  callee should clean up the stack, not caller. Symbols should be also
2284 //  decorated in some fancy way :) It doesn't support any vector arguments.
2285 //  For info on fast calling convention see Fast Calling Convention (tail call)
2286 //  implementation LowerX86_32FastCCCallTo.
2287
2288 /// CallIsStructReturn - Determines whether a call uses struct return
2289 /// semantics.
2290 enum StructReturnType {
2291   NotStructReturn,
2292   RegStructReturn,
2293   StackStructReturn
2294 };
2295 static StructReturnType
2296 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2297   if (Outs.empty())
2298     return NotStructReturn;
2299
2300   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2301   if (!Flags.isSRet())
2302     return NotStructReturn;
2303   if (Flags.isInReg())
2304     return RegStructReturn;
2305   return StackStructReturn;
2306 }
2307
2308 /// Determines whether a function uses struct return semantics.
2309 static StructReturnType
2310 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2311   if (Ins.empty())
2312     return NotStructReturn;
2313
2314   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2315   if (!Flags.isSRet())
2316     return NotStructReturn;
2317   if (Flags.isInReg())
2318     return RegStructReturn;
2319   return StackStructReturn;
2320 }
2321
2322 /// Make a copy of an aggregate at address specified by "Src" to address
2323 /// "Dst" with size and alignment information specified by the specific
2324 /// parameter attribute. The copy will be passed as a byval function parameter.
2325 static SDValue
2326 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2327                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2328                           SDLoc dl) {
2329   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
2330
2331   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2332                        /*isVolatile*/false, /*AlwaysInline=*/true,
2333                        /*isTailCall*/false,
2334                        MachinePointerInfo(), MachinePointerInfo());
2335 }
2336
2337 /// Return true if the calling convention is one that
2338 /// supports tail call optimization.
2339 static bool IsTailCallConvention(CallingConv::ID CC) {
2340   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2341           CC == CallingConv::HiPE);
2342 }
2343
2344 /// \brief Return true if the calling convention is a C calling convention.
2345 static bool IsCCallConvention(CallingConv::ID CC) {
2346   return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2347           CC == CallingConv::X86_64_SysV);
2348 }
2349
2350 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2351   auto Attr =
2352       CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2353   if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2354     return false;
2355
2356   CallSite CS(CI);
2357   CallingConv::ID CalleeCC = CS.getCallingConv();
2358   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2359     return false;
2360
2361   return true;
2362 }
2363
2364 /// Return true if the function is being made into
2365 /// a tailcall target by changing its ABI.
2366 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2367                                    bool GuaranteedTailCallOpt) {
2368   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2369 }
2370
2371 SDValue
2372 X86TargetLowering::LowerMemArgument(SDValue Chain,
2373                                     CallingConv::ID CallConv,
2374                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2375                                     SDLoc dl, SelectionDAG &DAG,
2376                                     const CCValAssign &VA,
2377                                     MachineFrameInfo *MFI,
2378                                     unsigned i) const {
2379   // Create the nodes corresponding to a load from this parameter slot.
2380   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2381   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2382       CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2383   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2384   EVT ValVT;
2385
2386   // If value is passed by pointer we have address passed instead of the value
2387   // itself.
2388   bool ExtendedInMem = VA.isExtInLoc() &&
2389     VA.getValVT().getScalarType() == MVT::i1;
2390
2391   if (VA.getLocInfo() == CCValAssign::Indirect || ExtendedInMem)
2392     ValVT = VA.getLocVT();
2393   else
2394     ValVT = VA.getValVT();
2395
2396   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2397   // changed with more analysis.
2398   // In case of tail call optimization mark all arguments mutable. Since they
2399   // could be overwritten by lowering of arguments in case of a tail call.
2400   if (Flags.isByVal()) {
2401     unsigned Bytes = Flags.getByValSize();
2402     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2403     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2404     return DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2405   } else {
2406     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2407                                     VA.getLocMemOffset(), isImmutable);
2408     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2409     SDValue Val =  DAG.getLoad(ValVT, dl, Chain, FIN,
2410                                MachinePointerInfo::getFixedStack(FI),
2411                                false, false, false, 0);
2412     return ExtendedInMem ?
2413       DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val) : Val;
2414   }
2415 }
2416
2417 // FIXME: Get this from tablegen.
2418 static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
2419                                                 const X86Subtarget *Subtarget) {
2420   assert(Subtarget->is64Bit());
2421
2422   if (Subtarget->isCallingConvWin64(CallConv)) {
2423     static const MCPhysReg GPR64ArgRegsWin64[] = {
2424       X86::RCX, X86::RDX, X86::R8,  X86::R9
2425     };
2426     return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
2427   }
2428
2429   static const MCPhysReg GPR64ArgRegs64Bit[] = {
2430     X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2431   };
2432   return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
2433 }
2434
2435 // FIXME: Get this from tablegen.
2436 static ArrayRef<MCPhysReg> get64BitArgumentXMMs(MachineFunction &MF,
2437                                                 CallingConv::ID CallConv,
2438                                                 const X86Subtarget *Subtarget) {
2439   assert(Subtarget->is64Bit());
2440   if (Subtarget->isCallingConvWin64(CallConv)) {
2441     // The XMM registers which might contain var arg parameters are shadowed
2442     // in their paired GPR.  So we only need to save the GPR to their home
2443     // slots.
2444     // TODO: __vectorcall will change this.
2445     return None;
2446   }
2447
2448   const Function *Fn = MF.getFunction();
2449   bool NoImplicitFloatOps = Fn->hasFnAttribute(Attribute::NoImplicitFloat);
2450   bool isSoftFloat = Subtarget->useSoftFloat();
2451   assert(!(isSoftFloat && NoImplicitFloatOps) &&
2452          "SSE register cannot be used when SSE is disabled!");
2453   if (isSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
2454     // Kernel mode asks for SSE to be disabled, so there are no XMM argument
2455     // registers.
2456     return None;
2457
2458   static const MCPhysReg XMMArgRegs64Bit[] = {
2459     X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2460     X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2461   };
2462   return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
2463 }
2464
2465 SDValue
2466 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2467                                         CallingConv::ID CallConv,
2468                                         bool isVarArg,
2469                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2470                                         SDLoc dl,
2471                                         SelectionDAG &DAG,
2472                                         SmallVectorImpl<SDValue> &InVals)
2473                                           const {
2474   MachineFunction &MF = DAG.getMachineFunction();
2475   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2476   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
2477
2478   const Function* Fn = MF.getFunction();
2479   if (Fn->hasExternalLinkage() &&
2480       Subtarget->isTargetCygMing() &&
2481       Fn->getName() == "main")
2482     FuncInfo->setForceFramePointer(true);
2483
2484   MachineFrameInfo *MFI = MF.getFrameInfo();
2485   bool Is64Bit = Subtarget->is64Bit();
2486   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2487
2488   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2489          "Var args not supported with calling convention fastcc, ghc or hipe");
2490
2491   // Assign locations to all of the incoming arguments.
2492   SmallVector<CCValAssign, 16> ArgLocs;
2493   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2494
2495   // Allocate shadow area for Win64
2496   if (IsWin64)
2497     CCInfo.AllocateStack(32, 8);
2498
2499   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2500
2501   unsigned LastVal = ~0U;
2502   SDValue ArgValue;
2503   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2504     CCValAssign &VA = ArgLocs[i];
2505     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2506     // places.
2507     assert(VA.getValNo() != LastVal &&
2508            "Don't support value assigned to multiple locs yet");
2509     (void)LastVal;
2510     LastVal = VA.getValNo();
2511
2512     if (VA.isRegLoc()) {
2513       EVT RegVT = VA.getLocVT();
2514       const TargetRegisterClass *RC;
2515       if (RegVT == MVT::i32)
2516         RC = &X86::GR32RegClass;
2517       else if (Is64Bit && RegVT == MVT::i64)
2518         RC = &X86::GR64RegClass;
2519       else if (RegVT == MVT::f32)
2520         RC = &X86::FR32RegClass;
2521       else if (RegVT == MVT::f64)
2522         RC = &X86::FR64RegClass;
2523       else if (RegVT.is512BitVector())
2524         RC = &X86::VR512RegClass;
2525       else if (RegVT.is256BitVector())
2526         RC = &X86::VR256RegClass;
2527       else if (RegVT.is128BitVector())
2528         RC = &X86::VR128RegClass;
2529       else if (RegVT == MVT::x86mmx)
2530         RC = &X86::VR64RegClass;
2531       else if (RegVT == MVT::i1)
2532         RC = &X86::VK1RegClass;
2533       else if (RegVT == MVT::v8i1)
2534         RC = &X86::VK8RegClass;
2535       else if (RegVT == MVT::v16i1)
2536         RC = &X86::VK16RegClass;
2537       else if (RegVT == MVT::v32i1)
2538         RC = &X86::VK32RegClass;
2539       else if (RegVT == MVT::v64i1)
2540         RC = &X86::VK64RegClass;
2541       else
2542         llvm_unreachable("Unknown argument type!");
2543
2544       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2545       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2546
2547       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2548       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2549       // right size.
2550       if (VA.getLocInfo() == CCValAssign::SExt)
2551         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2552                                DAG.getValueType(VA.getValVT()));
2553       else if (VA.getLocInfo() == CCValAssign::ZExt)
2554         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2555                                DAG.getValueType(VA.getValVT()));
2556       else if (VA.getLocInfo() == CCValAssign::BCvt)
2557         ArgValue = DAG.getBitcast(VA.getValVT(), ArgValue);
2558
2559       if (VA.isExtInLoc()) {
2560         // Handle MMX values passed in XMM regs.
2561         if (RegVT.isVector() && VA.getValVT().getScalarType() != MVT::i1)
2562           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2563         else
2564           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2565       }
2566     } else {
2567       assert(VA.isMemLoc());
2568       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2569     }
2570
2571     // If value is passed via pointer - do a load.
2572     if (VA.getLocInfo() == CCValAssign::Indirect)
2573       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2574                              MachinePointerInfo(), false, false, false, 0);
2575
2576     InVals.push_back(ArgValue);
2577   }
2578
2579   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2580     // All x86 ABIs require that for returning structs by value we copy the
2581     // sret argument into %rax/%eax (depending on ABI) for the return. Save
2582     // the argument into a virtual register so that we can access it from the
2583     // return points.
2584     if (Ins[i].Flags.isSRet()) {
2585       unsigned Reg = FuncInfo->getSRetReturnReg();
2586       if (!Reg) {
2587         MVT PtrTy = getPointerTy(DAG.getDataLayout());
2588         Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2589         FuncInfo->setSRetReturnReg(Reg);
2590       }
2591       SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2592       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2593       break;
2594     }
2595   }
2596
2597   unsigned StackSize = CCInfo.getNextStackOffset();
2598   // Align stack specially for tail calls.
2599   if (FuncIsMadeTailCallSafe(CallConv,
2600                              MF.getTarget().Options.GuaranteedTailCallOpt))
2601     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2602
2603   // If the function takes variable number of arguments, make a frame index for
2604   // the start of the first vararg value... for expansion of llvm.va_start. We
2605   // can skip this if there are no va_start calls.
2606   if (MFI->hasVAStart() &&
2607       (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2608                    CallConv != CallingConv::X86_ThisCall))) {
2609     FuncInfo->setVarArgsFrameIndex(
2610         MFI->CreateFixedObject(1, StackSize, true));
2611   }
2612
2613   MachineModuleInfo &MMI = MF.getMMI();
2614   const Function *WinEHParent = nullptr;
2615   if (MMI.hasWinEHFuncInfo(Fn))
2616     WinEHParent = MMI.getWinEHParent(Fn);
2617   bool IsWinEHOutlined = WinEHParent && WinEHParent != Fn;
2618   bool IsWinEHParent = WinEHParent && WinEHParent == Fn;
2619
2620   // Figure out if XMM registers are in use.
2621   assert(!(Subtarget->useSoftFloat() &&
2622            Fn->hasFnAttribute(Attribute::NoImplicitFloat)) &&
2623          "SSE register cannot be used when SSE is disabled!");
2624
2625   // 64-bit calling conventions support varargs and register parameters, so we
2626   // have to do extra work to spill them in the prologue.
2627   if (Is64Bit && isVarArg && MFI->hasVAStart()) {
2628     // Find the first unallocated argument registers.
2629     ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
2630     ArrayRef<MCPhysReg> ArgXMMs = get64BitArgumentXMMs(MF, CallConv, Subtarget);
2631     unsigned NumIntRegs = CCInfo.getFirstUnallocated(ArgGPRs);
2632     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(ArgXMMs);
2633     assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2634            "SSE register cannot be used when SSE is disabled!");
2635
2636     // Gather all the live in physical registers.
2637     SmallVector<SDValue, 6> LiveGPRs;
2638     SmallVector<SDValue, 8> LiveXMMRegs;
2639     SDValue ALVal;
2640     for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
2641       unsigned GPR = MF.addLiveIn(Reg, &X86::GR64RegClass);
2642       LiveGPRs.push_back(
2643           DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64));
2644     }
2645     if (!ArgXMMs.empty()) {
2646       unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2647       ALVal = DAG.getCopyFromReg(Chain, dl, AL, MVT::i8);
2648       for (MCPhysReg Reg : ArgXMMs.slice(NumXMMRegs)) {
2649         unsigned XMMReg = MF.addLiveIn(Reg, &X86::VR128RegClass);
2650         LiveXMMRegs.push_back(
2651             DAG.getCopyFromReg(Chain, dl, XMMReg, MVT::v4f32));
2652       }
2653     }
2654
2655     if (IsWin64) {
2656       // Get to the caller-allocated home save location.  Add 8 to account
2657       // for the return address.
2658       int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2659       FuncInfo->setRegSaveFrameIndex(
2660           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2661       // Fixup to set vararg frame on shadow area (4 x i64).
2662       if (NumIntRegs < 4)
2663         FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2664     } else {
2665       // For X86-64, if there are vararg parameters that are passed via
2666       // registers, then we must store them to their spots on the stack so
2667       // they may be loaded by deferencing the result of va_next.
2668       FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2669       FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
2670       FuncInfo->setRegSaveFrameIndex(MFI->CreateStackObject(
2671           ArgGPRs.size() * 8 + ArgXMMs.size() * 16, 16, false));
2672     }
2673
2674     // Store the integer parameter registers.
2675     SmallVector<SDValue, 8> MemOps;
2676     SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2677                                       getPointerTy(DAG.getDataLayout()));
2678     unsigned Offset = FuncInfo->getVarArgsGPOffset();
2679     for (SDValue Val : LiveGPRs) {
2680       SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2681                                 RSFIN, DAG.getIntPtrConstant(Offset, dl));
2682       SDValue Store =
2683         DAG.getStore(Val.getValue(1), dl, Val, FIN,
2684                      MachinePointerInfo::getFixedStack(
2685                        FuncInfo->getRegSaveFrameIndex(), Offset),
2686                      false, false, 0);
2687       MemOps.push_back(Store);
2688       Offset += 8;
2689     }
2690
2691     if (!ArgXMMs.empty() && NumXMMRegs != ArgXMMs.size()) {
2692       // Now store the XMM (fp + vector) parameter registers.
2693       SmallVector<SDValue, 12> SaveXMMOps;
2694       SaveXMMOps.push_back(Chain);
2695       SaveXMMOps.push_back(ALVal);
2696       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2697                              FuncInfo->getRegSaveFrameIndex(), dl));
2698       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2699                              FuncInfo->getVarArgsFPOffset(), dl));
2700       SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
2701                         LiveXMMRegs.end());
2702       MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2703                                    MVT::Other, SaveXMMOps));
2704     }
2705
2706     if (!MemOps.empty())
2707       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2708   } else if (IsWin64 && IsWinEHOutlined) {
2709     // Get to the caller-allocated home save location.  Add 8 to account
2710     // for the return address.
2711     int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2712     FuncInfo->setRegSaveFrameIndex(MFI->CreateFixedObject(
2713         /*Size=*/1, /*SPOffset=*/HomeOffset + 8, /*Immutable=*/false));
2714
2715     MMI.getWinEHFuncInfo(Fn)
2716         .CatchHandlerParentFrameObjIdx[const_cast<Function *>(Fn)] =
2717         FuncInfo->getRegSaveFrameIndex();
2718
2719     // Store the second integer parameter (rdx) into rsp+16 relative to the
2720     // stack pointer at the entry of the function.
2721     SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2722                                       getPointerTy(DAG.getDataLayout()));
2723     unsigned GPR = MF.addLiveIn(X86::RDX, &X86::GR64RegClass);
2724     SDValue Val = DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64);
2725     Chain = DAG.getStore(
2726         Val.getValue(1), dl, Val, RSFIN,
2727         MachinePointerInfo::getFixedStack(FuncInfo->getRegSaveFrameIndex()),
2728         /*isVolatile=*/true, /*isNonTemporal=*/false, /*Alignment=*/0);
2729   }
2730
2731   if (isVarArg && MFI->hasMustTailInVarArgFunc()) {
2732     // Find the largest legal vector type.
2733     MVT VecVT = MVT::Other;
2734     // FIXME: Only some x86_32 calling conventions support AVX512.
2735     if (Subtarget->hasAVX512() &&
2736         (Is64Bit || (CallConv == CallingConv::X86_VectorCall ||
2737                      CallConv == CallingConv::Intel_OCL_BI)))
2738       VecVT = MVT::v16f32;
2739     else if (Subtarget->hasAVX())
2740       VecVT = MVT::v8f32;
2741     else if (Subtarget->hasSSE2())
2742       VecVT = MVT::v4f32;
2743
2744     // We forward some GPRs and some vector types.
2745     SmallVector<MVT, 2> RegParmTypes;
2746     MVT IntVT = Is64Bit ? MVT::i64 : MVT::i32;
2747     RegParmTypes.push_back(IntVT);
2748     if (VecVT != MVT::Other)
2749       RegParmTypes.push_back(VecVT);
2750
2751     // Compute the set of forwarded registers. The rest are scratch.
2752     SmallVectorImpl<ForwardedRegister> &Forwards =
2753         FuncInfo->getForwardedMustTailRegParms();
2754     CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, CC_X86);
2755
2756     // Conservatively forward AL on x86_64, since it might be used for varargs.
2757     if (Is64Bit && !CCInfo.isAllocated(X86::AL)) {
2758       unsigned ALVReg = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2759       Forwards.push_back(ForwardedRegister(ALVReg, X86::AL, MVT::i8));
2760     }
2761
2762     // Copy all forwards from physical to virtual registers.
2763     for (ForwardedRegister &F : Forwards) {
2764       // FIXME: Can we use a less constrained schedule?
2765       SDValue RegVal = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2766       F.VReg = MF.getRegInfo().createVirtualRegister(getRegClassFor(F.VT));
2767       Chain = DAG.getCopyToReg(Chain, dl, F.VReg, RegVal);
2768     }
2769   }
2770
2771   // Some CCs need callee pop.
2772   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2773                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2774     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2775   } else {
2776     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2777     // If this is an sret function, the return should pop the hidden pointer.
2778     if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2779         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2780         argsAreStructReturn(Ins) == StackStructReturn)
2781       FuncInfo->setBytesToPopOnReturn(4);
2782   }
2783
2784   if (!Is64Bit) {
2785     // RegSaveFrameIndex is X86-64 only.
2786     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2787     if (CallConv == CallingConv::X86_FastCall ||
2788         CallConv == CallingConv::X86_ThisCall)
2789       // fastcc functions can't have varargs.
2790       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2791   }
2792
2793   FuncInfo->setArgumentStackSize(StackSize);
2794
2795   if (IsWinEHParent) {
2796     if (Is64Bit) {
2797       int UnwindHelpFI = MFI->CreateStackObject(8, 8, /*isSS=*/false);
2798       SDValue StackSlot = DAG.getFrameIndex(UnwindHelpFI, MVT::i64);
2799       MMI.getWinEHFuncInfo(MF.getFunction()).UnwindHelpFrameIdx = UnwindHelpFI;
2800       SDValue Neg2 = DAG.getConstant(-2, dl, MVT::i64);
2801       Chain = DAG.getStore(Chain, dl, Neg2, StackSlot,
2802                            MachinePointerInfo::getFixedStack(UnwindHelpFI),
2803                            /*isVolatile=*/true,
2804                            /*isNonTemporal=*/false, /*Alignment=*/0);
2805     } else {
2806       // Functions using Win32 EH are considered to have opaque SP adjustments
2807       // to force local variables to be addressed from the frame or base
2808       // pointers.
2809       MFI->setHasOpaqueSPAdjustment(true);
2810     }
2811   }
2812
2813   return Chain;
2814 }
2815
2816 SDValue
2817 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2818                                     SDValue StackPtr, SDValue Arg,
2819                                     SDLoc dl, SelectionDAG &DAG,
2820                                     const CCValAssign &VA,
2821                                     ISD::ArgFlagsTy Flags) const {
2822   unsigned LocMemOffset = VA.getLocMemOffset();
2823   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
2824   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2825                        StackPtr, PtrOff);
2826   if (Flags.isByVal())
2827     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2828
2829   return DAG.getStore(Chain, dl, Arg, PtrOff,
2830                       MachinePointerInfo::getStack(LocMemOffset),
2831                       false, false, 0);
2832 }
2833
2834 /// Emit a load of return address if tail call
2835 /// optimization is performed and it is required.
2836 SDValue
2837 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2838                                            SDValue &OutRetAddr, SDValue Chain,
2839                                            bool IsTailCall, bool Is64Bit,
2840                                            int FPDiff, SDLoc dl) const {
2841   // Adjust the Return address stack slot.
2842   EVT VT = getPointerTy(DAG.getDataLayout());
2843   OutRetAddr = getReturnAddressFrameIndex(DAG);
2844
2845   // Load the "old" Return address.
2846   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2847                            false, false, false, 0);
2848   return SDValue(OutRetAddr.getNode(), 1);
2849 }
2850
2851 /// Emit a store of the return address if tail call
2852 /// optimization is performed and it is required (FPDiff!=0).
2853 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2854                                         SDValue Chain, SDValue RetAddrFrIdx,
2855                                         EVT PtrVT, unsigned SlotSize,
2856                                         int FPDiff, SDLoc dl) {
2857   // Store the return address to the appropriate stack slot.
2858   if (!FPDiff) return Chain;
2859   // Calculate the new stack slot for the return address.
2860   int NewReturnAddrFI =
2861     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2862                                          false);
2863   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2864   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2865                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2866                        false, false, 0);
2867   return Chain;
2868 }
2869
2870 SDValue
2871 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2872                              SmallVectorImpl<SDValue> &InVals) const {
2873   SelectionDAG &DAG                     = CLI.DAG;
2874   SDLoc &dl                             = CLI.DL;
2875   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2876   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2877   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2878   SDValue Chain                         = CLI.Chain;
2879   SDValue Callee                        = CLI.Callee;
2880   CallingConv::ID CallConv              = CLI.CallConv;
2881   bool &isTailCall                      = CLI.IsTailCall;
2882   bool isVarArg                         = CLI.IsVarArg;
2883
2884   MachineFunction &MF = DAG.getMachineFunction();
2885   bool Is64Bit        = Subtarget->is64Bit();
2886   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2887   StructReturnType SR = callIsStructReturn(Outs);
2888   bool IsSibcall      = false;
2889   X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2890   auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls");
2891
2892   if (Attr.getValueAsString() == "true")
2893     isTailCall = false;
2894
2895   if (Subtarget->isPICStyleGOT() &&
2896       !MF.getTarget().Options.GuaranteedTailCallOpt) {
2897     // If we are using a GOT, disable tail calls to external symbols with
2898     // default visibility. Tail calling such a symbol requires using a GOT
2899     // relocation, which forces early binding of the symbol. This breaks code
2900     // that require lazy function symbol resolution. Using musttail or
2901     // GuaranteedTailCallOpt will override this.
2902     GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2903     if (!G || (!G->getGlobal()->hasLocalLinkage() &&
2904                G->getGlobal()->hasDefaultVisibility()))
2905       isTailCall = false;
2906   }
2907
2908   bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2909   if (IsMustTail) {
2910     // Force this to be a tail call.  The verifier rules are enough to ensure
2911     // that we can lower this successfully without moving the return address
2912     // around.
2913     isTailCall = true;
2914   } else if (isTailCall) {
2915     // Check if it's really possible to do a tail call.
2916     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2917                     isVarArg, SR != NotStructReturn,
2918                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2919                     Outs, OutVals, Ins, DAG);
2920
2921     // Sibcalls are automatically detected tailcalls which do not require
2922     // ABI changes.
2923     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2924       IsSibcall = true;
2925
2926     if (isTailCall)
2927       ++NumTailCalls;
2928   }
2929
2930   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2931          "Var args not supported with calling convention fastcc, ghc or hipe");
2932
2933   // Analyze operands of the call, assigning locations to each operand.
2934   SmallVector<CCValAssign, 16> ArgLocs;
2935   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2936
2937   // Allocate shadow area for Win64
2938   if (IsWin64)
2939     CCInfo.AllocateStack(32, 8);
2940
2941   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2942
2943   // Get a count of how many bytes are to be pushed on the stack.
2944   unsigned NumBytes = CCInfo.getNextStackOffset();
2945   if (IsSibcall)
2946     // This is a sibcall. The memory operands are available in caller's
2947     // own caller's stack.
2948     NumBytes = 0;
2949   else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
2950            IsTailCallConvention(CallConv))
2951     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2952
2953   int FPDiff = 0;
2954   if (isTailCall && !IsSibcall && !IsMustTail) {
2955     // Lower arguments at fp - stackoffset + fpdiff.
2956     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2957
2958     FPDiff = NumBytesCallerPushed - NumBytes;
2959
2960     // Set the delta of movement of the returnaddr stackslot.
2961     // But only set if delta is greater than previous delta.
2962     if (FPDiff < X86Info->getTCReturnAddrDelta())
2963       X86Info->setTCReturnAddrDelta(FPDiff);
2964   }
2965
2966   unsigned NumBytesToPush = NumBytes;
2967   unsigned NumBytesToPop = NumBytes;
2968
2969   // If we have an inalloca argument, all stack space has already been allocated
2970   // for us and be right at the top of the stack.  We don't support multiple
2971   // arguments passed in memory when using inalloca.
2972   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2973     NumBytesToPush = 0;
2974     if (!ArgLocs.back().isMemLoc())
2975       report_fatal_error("cannot use inalloca attribute on a register "
2976                          "parameter");
2977     if (ArgLocs.back().getLocMemOffset() != 0)
2978       report_fatal_error("any parameter with the inalloca attribute must be "
2979                          "the only memory argument");
2980   }
2981
2982   if (!IsSibcall)
2983     Chain = DAG.getCALLSEQ_START(
2984         Chain, DAG.getIntPtrConstant(NumBytesToPush, dl, true), dl);
2985
2986   SDValue RetAddrFrIdx;
2987   // Load return address for tail calls.
2988   if (isTailCall && FPDiff)
2989     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2990                                     Is64Bit, FPDiff, dl);
2991
2992   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2993   SmallVector<SDValue, 8> MemOpChains;
2994   SDValue StackPtr;
2995
2996   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2997   // of tail call optimization arguments are handle later.
2998   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
2999   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3000     // Skip inalloca arguments, they have already been written.
3001     ISD::ArgFlagsTy Flags = Outs[i].Flags;
3002     if (Flags.isInAlloca())
3003       continue;
3004
3005     CCValAssign &VA = ArgLocs[i];
3006     EVT RegVT = VA.getLocVT();
3007     SDValue Arg = OutVals[i];
3008     bool isByVal = Flags.isByVal();
3009
3010     // Promote the value if needed.
3011     switch (VA.getLocInfo()) {
3012     default: llvm_unreachable("Unknown loc info!");
3013     case CCValAssign::Full: break;
3014     case CCValAssign::SExt:
3015       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
3016       break;
3017     case CCValAssign::ZExt:
3018       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
3019       break;
3020     case CCValAssign::AExt:
3021       if (Arg.getValueType().isVector() &&
3022           Arg.getValueType().getScalarType() == MVT::i1)
3023         Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
3024       else if (RegVT.is128BitVector()) {
3025         // Special case: passing MMX values in XMM registers.
3026         Arg = DAG.getBitcast(MVT::i64, Arg);
3027         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
3028         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
3029       } else
3030         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
3031       break;
3032     case CCValAssign::BCvt:
3033       Arg = DAG.getBitcast(RegVT, Arg);
3034       break;
3035     case CCValAssign::Indirect: {
3036       // Store the argument.
3037       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
3038       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
3039       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
3040                            MachinePointerInfo::getFixedStack(FI),
3041                            false, false, 0);
3042       Arg = SpillSlot;
3043       break;
3044     }
3045     }
3046
3047     if (VA.isRegLoc()) {
3048       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3049       if (isVarArg && IsWin64) {
3050         // Win64 ABI requires argument XMM reg to be copied to the corresponding
3051         // shadow reg if callee is a varargs function.
3052         unsigned ShadowReg = 0;
3053         switch (VA.getLocReg()) {
3054         case X86::XMM0: ShadowReg = X86::RCX; break;
3055         case X86::XMM1: ShadowReg = X86::RDX; break;
3056         case X86::XMM2: ShadowReg = X86::R8; break;
3057         case X86::XMM3: ShadowReg = X86::R9; break;
3058         }
3059         if (ShadowReg)
3060           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
3061       }
3062     } else if (!IsSibcall && (!isTailCall || isByVal)) {
3063       assert(VA.isMemLoc());
3064       if (!StackPtr.getNode())
3065         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3066                                       getPointerTy(DAG.getDataLayout()));
3067       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
3068                                              dl, DAG, VA, Flags));
3069     }
3070   }
3071
3072   if (!MemOpChains.empty())
3073     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
3074
3075   if (Subtarget->isPICStyleGOT()) {
3076     // ELF / PIC requires GOT in the EBX register before function calls via PLT
3077     // GOT pointer.
3078     if (!isTailCall) {
3079       RegsToPass.push_back(std::make_pair(
3080           unsigned(X86::EBX), DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
3081                                           getPointerTy(DAG.getDataLayout()))));
3082     } else {
3083       // If we are tail calling and generating PIC/GOT style code load the
3084       // address of the callee into ECX. The value in ecx is used as target of
3085       // the tail jump. This is done to circumvent the ebx/callee-saved problem
3086       // for tail calls on PIC/GOT architectures. Normally we would just put the
3087       // address of GOT into ebx and then call target@PLT. But for tail calls
3088       // ebx would be restored (since ebx is callee saved) before jumping to the
3089       // target@PLT.
3090
3091       // Note: The actual moving to ECX is done further down.
3092       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
3093       if (G && !G->getGlobal()->hasLocalLinkage() &&
3094           G->getGlobal()->hasDefaultVisibility())
3095         Callee = LowerGlobalAddress(Callee, DAG);
3096       else if (isa<ExternalSymbolSDNode>(Callee))
3097         Callee = LowerExternalSymbol(Callee, DAG);
3098     }
3099   }
3100
3101   if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail) {
3102     // From AMD64 ABI document:
3103     // For calls that may call functions that use varargs or stdargs
3104     // (prototype-less calls or calls to functions containing ellipsis (...) in
3105     // the declaration) %al is used as hidden argument to specify the number
3106     // of SSE registers used. The contents of %al do not need to match exactly
3107     // the number of registers, but must be an ubound on the number of SSE
3108     // registers used and is in the range 0 - 8 inclusive.
3109
3110     // Count the number of XMM registers allocated.
3111     static const MCPhysReg XMMArgRegs[] = {
3112       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3113       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
3114     };
3115     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
3116     assert((Subtarget->hasSSE1() || !NumXMMRegs)
3117            && "SSE registers cannot be used when SSE is disabled");
3118
3119     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
3120                                         DAG.getConstant(NumXMMRegs, dl,
3121                                                         MVT::i8)));
3122   }
3123
3124   if (isVarArg && IsMustTail) {
3125     const auto &Forwards = X86Info->getForwardedMustTailRegParms();
3126     for (const auto &F : Forwards) {
3127       SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
3128       RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
3129     }
3130   }
3131
3132   // For tail calls lower the arguments to the 'real' stack slots.  Sibcalls
3133   // don't need this because the eligibility check rejects calls that require
3134   // shuffling arguments passed in memory.
3135   if (!IsSibcall && isTailCall) {
3136     // Force all the incoming stack arguments to be loaded from the stack
3137     // before any new outgoing arguments are stored to the stack, because the
3138     // outgoing stack slots may alias the incoming argument stack slots, and
3139     // the alias isn't otherwise explicit. This is slightly more conservative
3140     // than necessary, because it means that each store effectively depends
3141     // on every argument instead of just those arguments it would clobber.
3142     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
3143
3144     SmallVector<SDValue, 8> MemOpChains2;
3145     SDValue FIN;
3146     int FI = 0;
3147     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3148       CCValAssign &VA = ArgLocs[i];
3149       if (VA.isRegLoc())
3150         continue;
3151       assert(VA.isMemLoc());
3152       SDValue Arg = OutVals[i];
3153       ISD::ArgFlagsTy Flags = Outs[i].Flags;
3154       // Skip inalloca arguments.  They don't require any work.
3155       if (Flags.isInAlloca())
3156         continue;
3157       // Create frame index.
3158       int32_t Offset = VA.getLocMemOffset()+FPDiff;
3159       uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
3160       FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3161       FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3162
3163       if (Flags.isByVal()) {
3164         // Copy relative to framepointer.
3165         SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset(), dl);
3166         if (!StackPtr.getNode())
3167           StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3168                                         getPointerTy(DAG.getDataLayout()));
3169         Source = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
3170                              StackPtr, Source);
3171
3172         MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
3173                                                          ArgChain,
3174                                                          Flags, DAG, dl));
3175       } else {
3176         // Store relative to framepointer.
3177         MemOpChains2.push_back(
3178           DAG.getStore(ArgChain, dl, Arg, FIN,
3179                        MachinePointerInfo::getFixedStack(FI),
3180                        false, false, 0));
3181       }
3182     }
3183
3184     if (!MemOpChains2.empty())
3185       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3186
3187     // Store the return address to the appropriate stack slot.
3188     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
3189                                      getPointerTy(DAG.getDataLayout()),
3190                                      RegInfo->getSlotSize(), FPDiff, dl);
3191   }
3192
3193   // Build a sequence of copy-to-reg nodes chained together with token chain
3194   // and flag operands which copy the outgoing args into registers.
3195   SDValue InFlag;
3196   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3197     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3198                              RegsToPass[i].second, InFlag);
3199     InFlag = Chain.getValue(1);
3200   }
3201
3202   if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
3203     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
3204     // In the 64-bit large code model, we have to make all calls
3205     // through a register, since the call instruction's 32-bit
3206     // pc-relative offset may not be large enough to hold the whole
3207     // address.
3208   } else if (Callee->getOpcode() == ISD::GlobalAddress) {
3209     // If the callee is a GlobalAddress node (quite common, every direct call
3210     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
3211     // it.
3212     GlobalAddressSDNode* G = cast<GlobalAddressSDNode>(Callee);
3213
3214     // We should use extra load for direct calls to dllimported functions in
3215     // non-JIT mode.
3216     const GlobalValue *GV = G->getGlobal();
3217     if (!GV->hasDLLImportStorageClass()) {
3218       unsigned char OpFlags = 0;
3219       bool ExtraLoad = false;
3220       unsigned WrapperKind = ISD::DELETED_NODE;
3221
3222       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
3223       // external symbols most go through the PLT in PIC mode.  If the symbol
3224       // has hidden or protected visibility, or if it is static or local, then
3225       // we don't need to use the PLT - we can directly call it.
3226       if (Subtarget->isTargetELF() &&
3227           DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
3228           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
3229         OpFlags = X86II::MO_PLT;
3230       } else if (Subtarget->isPICStyleStubAny() &&
3231                  !GV->isStrongDefinitionForLinker() &&
3232                  (!Subtarget->getTargetTriple().isMacOSX() ||
3233                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3234         // PC-relative references to external symbols should go through $stub,
3235         // unless we're building with the leopard linker or later, which
3236         // automatically synthesizes these stubs.
3237         OpFlags = X86II::MO_DARWIN_STUB;
3238       } else if (Subtarget->isPICStyleRIPRel() && isa<Function>(GV) &&
3239                  cast<Function>(GV)->hasFnAttribute(Attribute::NonLazyBind)) {
3240         // If the function is marked as non-lazy, generate an indirect call
3241         // which loads from the GOT directly. This avoids runtime overhead
3242         // at the cost of eager binding (and one extra byte of encoding).
3243         OpFlags = X86II::MO_GOTPCREL;
3244         WrapperKind = X86ISD::WrapperRIP;
3245         ExtraLoad = true;
3246       }
3247
3248       Callee = DAG.getTargetGlobalAddress(
3249           GV, dl, getPointerTy(DAG.getDataLayout()), G->getOffset(), OpFlags);
3250
3251       // Add a wrapper if needed.
3252       if (WrapperKind != ISD::DELETED_NODE)
3253         Callee = DAG.getNode(X86ISD::WrapperRIP, dl,
3254                              getPointerTy(DAG.getDataLayout()), Callee);
3255       // Add extra indirection if needed.
3256       if (ExtraLoad)
3257         Callee = DAG.getLoad(
3258             getPointerTy(DAG.getDataLayout()), dl, DAG.getEntryNode(), Callee,
3259             MachinePointerInfo::getGOT(), false, false, false, 0);
3260     }
3261   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3262     unsigned char OpFlags = 0;
3263
3264     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
3265     // external symbols should go through the PLT.
3266     if (Subtarget->isTargetELF() &&
3267         DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
3268       OpFlags = X86II::MO_PLT;
3269     } else if (Subtarget->isPICStyleStubAny() &&
3270                (!Subtarget->getTargetTriple().isMacOSX() ||
3271                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3272       // PC-relative references to external symbols should go through $stub,
3273       // unless we're building with the leopard linker or later, which
3274       // automatically synthesizes these stubs.
3275       OpFlags = X86II::MO_DARWIN_STUB;
3276     }
3277
3278     Callee = DAG.getTargetExternalSymbol(
3279         S->getSymbol(), getPointerTy(DAG.getDataLayout()), OpFlags);
3280   } else if (Subtarget->isTarget64BitILP32() &&
3281              Callee->getValueType(0) == MVT::i32) {
3282     // Zero-extend the 32-bit Callee address into a 64-bit according to x32 ABI
3283     Callee = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Callee);
3284   }
3285
3286   // Returns a chain & a flag for retval copy to use.
3287   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3288   SmallVector<SDValue, 8> Ops;
3289
3290   if (!IsSibcall && isTailCall) {
3291     Chain = DAG.getCALLSEQ_END(Chain,
3292                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3293                                DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
3294     InFlag = Chain.getValue(1);
3295   }
3296
3297   Ops.push_back(Chain);
3298   Ops.push_back(Callee);
3299
3300   if (isTailCall)
3301     Ops.push_back(DAG.getConstant(FPDiff, dl, MVT::i32));
3302
3303   // Add argument registers to the end of the list so that they are known live
3304   // into the call.
3305   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3306     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3307                                   RegsToPass[i].second.getValueType()));
3308
3309   // Add a register mask operand representing the call-preserved registers.
3310   const uint32_t *Mask = RegInfo->getCallPreservedMask(MF, CallConv);
3311   assert(Mask && "Missing call preserved mask for calling convention");
3312
3313   // If this is an invoke in a 32-bit function using an MSVC personality, assume
3314   // the function clobbers all registers. If an exception is thrown, the runtime
3315   // will not restore CSRs.
3316   // FIXME: Model this more precisely so that we can register allocate across
3317   // the normal edge and spill and fill across the exceptional edge.
3318   if (!Is64Bit && CLI.CS && CLI.CS->isInvoke()) {
3319     const Function *CallerFn = MF.getFunction();
3320     EHPersonality Pers =
3321         CallerFn->hasPersonalityFn()
3322             ? classifyEHPersonality(CallerFn->getPersonalityFn())
3323             : EHPersonality::Unknown;
3324     if (isMSVCEHPersonality(Pers))
3325       Mask = RegInfo->getNoPreservedMask();
3326   }
3327
3328   Ops.push_back(DAG.getRegisterMask(Mask));
3329
3330   if (InFlag.getNode())
3331     Ops.push_back(InFlag);
3332
3333   if (isTailCall) {
3334     // We used to do:
3335     //// If this is the first return lowered for this function, add the regs
3336     //// to the liveout set for the function.
3337     // This isn't right, although it's probably harmless on x86; liveouts
3338     // should be computed from returns not tail calls.  Consider a void
3339     // function making a tail call to a function returning int.
3340     MF.getFrameInfo()->setHasTailCall();
3341     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3342   }
3343
3344   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3345   InFlag = Chain.getValue(1);
3346
3347   // Create the CALLSEQ_END node.
3348   unsigned NumBytesForCalleeToPop;
3349   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3350                        DAG.getTarget().Options.GuaranteedTailCallOpt))
3351     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
3352   else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
3353            !Subtarget->getTargetTriple().isOSMSVCRT() &&
3354            SR == StackStructReturn)
3355     // If this is a call to a struct-return function, the callee
3356     // pops the hidden struct pointer, so we have to push it back.
3357     // This is common for Darwin/X86, Linux & Mingw32 targets.
3358     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3359     NumBytesForCalleeToPop = 4;
3360   else
3361     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
3362
3363   // Returns a flag for retval copy to use.
3364   if (!IsSibcall) {
3365     Chain = DAG.getCALLSEQ_END(Chain,
3366                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3367                                DAG.getIntPtrConstant(NumBytesForCalleeToPop, dl,
3368                                                      true),
3369                                InFlag, dl);
3370     InFlag = Chain.getValue(1);
3371   }
3372
3373   // Handle result values, copying them out of physregs into vregs that we
3374   // return.
3375   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3376                          Ins, dl, DAG, InVals);
3377 }
3378
3379 //===----------------------------------------------------------------------===//
3380 //                Fast Calling Convention (tail call) implementation
3381 //===----------------------------------------------------------------------===//
3382
3383 //  Like std call, callee cleans arguments, convention except that ECX is
3384 //  reserved for storing the tail called function address. Only 2 registers are
3385 //  free for argument passing (inreg). Tail call optimization is performed
3386 //  provided:
3387 //                * tailcallopt is enabled
3388 //                * caller/callee are fastcc
3389 //  On X86_64 architecture with GOT-style position independent code only local
3390 //  (within module) calls are supported at the moment.
3391 //  To keep the stack aligned according to platform abi the function
3392 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
3393 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3394 //  If a tail called function callee has more arguments than the caller the
3395 //  caller needs to make sure that there is room to move the RETADDR to. This is
3396 //  achieved by reserving an area the size of the argument delta right after the
3397 //  original RETADDR, but before the saved framepointer or the spilled registers
3398 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3399 //  stack layout:
3400 //    arg1
3401 //    arg2
3402 //    RETADDR
3403 //    [ new RETADDR
3404 //      move area ]
3405 //    (possible EBP)
3406 //    ESI
3407 //    EDI
3408 //    local1 ..
3409
3410 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3411 /// for a 16 byte align requirement.
3412 unsigned
3413 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3414                                                SelectionDAG& DAG) const {
3415   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3416   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
3417   unsigned StackAlignment = TFI.getStackAlignment();
3418   uint64_t AlignMask = StackAlignment - 1;
3419   int64_t Offset = StackSize;
3420   unsigned SlotSize = RegInfo->getSlotSize();
3421   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3422     // Number smaller than 12 so just add the difference.
3423     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3424   } else {
3425     // Mask out lower bits, add stackalignment once plus the 12 bytes.
3426     Offset = ((~AlignMask) & Offset) + StackAlignment +
3427       (StackAlignment-SlotSize);
3428   }
3429   return Offset;
3430 }
3431
3432 /// MatchingStackOffset - Return true if the given stack call argument is
3433 /// already available in the same position (relatively) of the caller's
3434 /// incoming argument stack.
3435 static
3436 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3437                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3438                          const X86InstrInfo *TII) {
3439   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3440   int FI = INT_MAX;
3441   if (Arg.getOpcode() == ISD::CopyFromReg) {
3442     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3443     if (!TargetRegisterInfo::isVirtualRegister(VR))
3444       return false;
3445     MachineInstr *Def = MRI->getVRegDef(VR);
3446     if (!Def)
3447       return false;
3448     if (!Flags.isByVal()) {
3449       if (!TII->isLoadFromStackSlot(Def, FI))
3450         return false;
3451     } else {
3452       unsigned Opcode = Def->getOpcode();
3453       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r ||
3454            Opcode == X86::LEA64_32r) &&
3455           Def->getOperand(1).isFI()) {
3456         FI = Def->getOperand(1).getIndex();
3457         Bytes = Flags.getByValSize();
3458       } else
3459         return false;
3460     }
3461   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3462     if (Flags.isByVal())
3463       // ByVal argument is passed in as a pointer but it's now being
3464       // dereferenced. e.g.
3465       // define @foo(%struct.X* %A) {
3466       //   tail call @bar(%struct.X* byval %A)
3467       // }
3468       return false;
3469     SDValue Ptr = Ld->getBasePtr();
3470     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3471     if (!FINode)
3472       return false;
3473     FI = FINode->getIndex();
3474   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3475     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3476     FI = FINode->getIndex();
3477     Bytes = Flags.getByValSize();
3478   } else
3479     return false;
3480
3481   assert(FI != INT_MAX);
3482   if (!MFI->isFixedObjectIndex(FI))
3483     return false;
3484   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3485 }
3486
3487 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3488 /// for tail call optimization. Targets which want to do tail call
3489 /// optimization should implement this function.
3490 bool
3491 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3492                                                      CallingConv::ID CalleeCC,
3493                                                      bool isVarArg,
3494                                                      bool isCalleeStructRet,
3495                                                      bool isCallerStructRet,
3496                                                      Type *RetTy,
3497                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3498                                     const SmallVectorImpl<SDValue> &OutVals,
3499                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3500                                                      SelectionDAG &DAG) const {
3501   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3502     return false;
3503
3504   // If -tailcallopt is specified, make fastcc functions tail-callable.
3505   const MachineFunction &MF = DAG.getMachineFunction();
3506   const Function *CallerF = MF.getFunction();
3507
3508   // If the function return type is x86_fp80 and the callee return type is not,
3509   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3510   // perform a tailcall optimization here.
3511   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3512     return false;
3513
3514   CallingConv::ID CallerCC = CallerF->getCallingConv();
3515   bool CCMatch = CallerCC == CalleeCC;
3516   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3517   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3518
3519   // Win64 functions have extra shadow space for argument homing. Don't do the
3520   // sibcall if the caller and callee have mismatched expectations for this
3521   // space.
3522   if (IsCalleeWin64 != IsCallerWin64)
3523     return false;
3524
3525   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3526     if (IsTailCallConvention(CalleeCC) && CCMatch)
3527       return true;
3528     return false;
3529   }
3530
3531   // Look for obvious safe cases to perform tail call optimization that do not
3532   // require ABI changes. This is what gcc calls sibcall.
3533
3534   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3535   // emit a special epilogue.
3536   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3537   if (RegInfo->needsStackRealignment(MF))
3538     return false;
3539
3540   // Also avoid sibcall optimization if either caller or callee uses struct
3541   // return semantics.
3542   if (isCalleeStructRet || isCallerStructRet)
3543     return false;
3544
3545   // An stdcall/thiscall caller is expected to clean up its arguments; the
3546   // callee isn't going to do that.
3547   // FIXME: this is more restrictive than needed. We could produce a tailcall
3548   // when the stack adjustment matches. For example, with a thiscall that takes
3549   // only one argument.
3550   if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3551                    CallerCC == CallingConv::X86_ThisCall))
3552     return false;
3553
3554   // Do not sibcall optimize vararg calls unless all arguments are passed via
3555   // registers.
3556   if (isVarArg && !Outs.empty()) {
3557
3558     // Optimizing for varargs on Win64 is unlikely to be safe without
3559     // additional testing.
3560     if (IsCalleeWin64 || IsCallerWin64)
3561       return false;
3562
3563     SmallVector<CCValAssign, 16> ArgLocs;
3564     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3565                    *DAG.getContext());
3566
3567     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3568     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3569       if (!ArgLocs[i].isRegLoc())
3570         return false;
3571   }
3572
3573   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3574   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3575   // this into a sibcall.
3576   bool Unused = false;
3577   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3578     if (!Ins[i].Used) {
3579       Unused = true;
3580       break;
3581     }
3582   }
3583   if (Unused) {
3584     SmallVector<CCValAssign, 16> RVLocs;
3585     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), RVLocs,
3586                    *DAG.getContext());
3587     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3588     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3589       CCValAssign &VA = RVLocs[i];
3590       if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3591         return false;
3592     }
3593   }
3594
3595   // If the calling conventions do not match, then we'd better make sure the
3596   // results are returned in the same way as what the caller expects.
3597   if (!CCMatch) {
3598     SmallVector<CCValAssign, 16> RVLocs1;
3599     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
3600                     *DAG.getContext());
3601     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3602
3603     SmallVector<CCValAssign, 16> RVLocs2;
3604     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
3605                     *DAG.getContext());
3606     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3607
3608     if (RVLocs1.size() != RVLocs2.size())
3609       return false;
3610     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3611       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3612         return false;
3613       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3614         return false;
3615       if (RVLocs1[i].isRegLoc()) {
3616         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3617           return false;
3618       } else {
3619         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3620           return false;
3621       }
3622     }
3623   }
3624
3625   // If the callee takes no arguments then go on to check the results of the
3626   // call.
3627   if (!Outs.empty()) {
3628     // Check if stack adjustment is needed. For now, do not do this if any
3629     // argument is passed on the stack.
3630     SmallVector<CCValAssign, 16> ArgLocs;
3631     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3632                    *DAG.getContext());
3633
3634     // Allocate shadow area for Win64
3635     if (IsCalleeWin64)
3636       CCInfo.AllocateStack(32, 8);
3637
3638     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3639     if (CCInfo.getNextStackOffset()) {
3640       MachineFunction &MF = DAG.getMachineFunction();
3641       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3642         return false;
3643
3644       // Check if the arguments are already laid out in the right way as
3645       // the caller's fixed stack objects.
3646       MachineFrameInfo *MFI = MF.getFrameInfo();
3647       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3648       const X86InstrInfo *TII = Subtarget->getInstrInfo();
3649       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3650         CCValAssign &VA = ArgLocs[i];
3651         SDValue Arg = OutVals[i];
3652         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3653         if (VA.getLocInfo() == CCValAssign::Indirect)
3654           return false;
3655         if (!VA.isRegLoc()) {
3656           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3657                                    MFI, MRI, TII))
3658             return false;
3659         }
3660       }
3661     }
3662
3663     // If the tailcall address may be in a register, then make sure it's
3664     // possible to register allocate for it. In 32-bit, the call address can
3665     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3666     // callee-saved registers are restored. These happen to be the same
3667     // registers used to pass 'inreg' arguments so watch out for those.
3668     if (!Subtarget->is64Bit() &&
3669         ((!isa<GlobalAddressSDNode>(Callee) &&
3670           !isa<ExternalSymbolSDNode>(Callee)) ||
3671          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3672       unsigned NumInRegs = 0;
3673       // In PIC we need an extra register to formulate the address computation
3674       // for the callee.
3675       unsigned MaxInRegs =
3676         (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3677
3678       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3679         CCValAssign &VA = ArgLocs[i];
3680         if (!VA.isRegLoc())
3681           continue;
3682         unsigned Reg = VA.getLocReg();
3683         switch (Reg) {
3684         default: break;
3685         case X86::EAX: case X86::EDX: case X86::ECX:
3686           if (++NumInRegs == MaxInRegs)
3687             return false;
3688           break;
3689         }
3690       }
3691     }
3692   }
3693
3694   return true;
3695 }
3696
3697 FastISel *
3698 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3699                                   const TargetLibraryInfo *libInfo) const {
3700   return X86::createFastISel(funcInfo, libInfo);
3701 }
3702
3703 //===----------------------------------------------------------------------===//
3704 //                           Other Lowering Hooks
3705 //===----------------------------------------------------------------------===//
3706
3707 static bool MayFoldLoad(SDValue Op) {
3708   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3709 }
3710
3711 static bool MayFoldIntoStore(SDValue Op) {
3712   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3713 }
3714
3715 static bool isTargetShuffle(unsigned Opcode) {
3716   switch(Opcode) {
3717   default: return false;
3718   case X86ISD::BLENDI:
3719   case X86ISD::PSHUFB:
3720   case X86ISD::PSHUFD:
3721   case X86ISD::PSHUFHW:
3722   case X86ISD::PSHUFLW:
3723   case X86ISD::SHUFP:
3724   case X86ISD::PALIGNR:
3725   case X86ISD::MOVLHPS:
3726   case X86ISD::MOVLHPD:
3727   case X86ISD::MOVHLPS:
3728   case X86ISD::MOVLPS:
3729   case X86ISD::MOVLPD:
3730   case X86ISD::MOVSHDUP:
3731   case X86ISD::MOVSLDUP:
3732   case X86ISD::MOVDDUP:
3733   case X86ISD::MOVSS:
3734   case X86ISD::MOVSD:
3735   case X86ISD::UNPCKL:
3736   case X86ISD::UNPCKH:
3737   case X86ISD::VPERMILPI:
3738   case X86ISD::VPERM2X128:
3739   case X86ISD::VPERMI:
3740     return true;
3741   }
3742 }
3743
3744 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3745                                     SDValue V1, unsigned TargetMask,
3746                                     SelectionDAG &DAG) {
3747   switch(Opc) {
3748   default: llvm_unreachable("Unknown x86 shuffle node");
3749   case X86ISD::PSHUFD:
3750   case X86ISD::PSHUFHW:
3751   case X86ISD::PSHUFLW:
3752   case X86ISD::VPERMILPI:
3753   case X86ISD::VPERMI:
3754     return DAG.getNode(Opc, dl, VT, V1,
3755                        DAG.getConstant(TargetMask, dl, MVT::i8));
3756   }
3757 }
3758
3759 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3760                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3761   switch(Opc) {
3762   default: llvm_unreachable("Unknown x86 shuffle node");
3763   case X86ISD::MOVLHPS:
3764   case X86ISD::MOVLHPD:
3765   case X86ISD::MOVHLPS:
3766   case X86ISD::MOVLPS:
3767   case X86ISD::MOVLPD:
3768   case X86ISD::MOVSS:
3769   case X86ISD::MOVSD:
3770   case X86ISD::UNPCKL:
3771   case X86ISD::UNPCKH:
3772     return DAG.getNode(Opc, dl, VT, V1, V2);
3773   }
3774 }
3775
3776 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3777   MachineFunction &MF = DAG.getMachineFunction();
3778   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3779   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3780   int ReturnAddrIndex = FuncInfo->getRAIndex();
3781
3782   if (ReturnAddrIndex == 0) {
3783     // Set up a frame object for the return address.
3784     unsigned SlotSize = RegInfo->getSlotSize();
3785     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3786                                                            -(int64_t)SlotSize,
3787                                                            false);
3788     FuncInfo->setRAIndex(ReturnAddrIndex);
3789   }
3790
3791   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy(DAG.getDataLayout()));
3792 }
3793
3794 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3795                                        bool hasSymbolicDisplacement) {
3796   // Offset should fit into 32 bit immediate field.
3797   if (!isInt<32>(Offset))
3798     return false;
3799
3800   // If we don't have a symbolic displacement - we don't have any extra
3801   // restrictions.
3802   if (!hasSymbolicDisplacement)
3803     return true;
3804
3805   // FIXME: Some tweaks might be needed for medium code model.
3806   if (M != CodeModel::Small && M != CodeModel::Kernel)
3807     return false;
3808
3809   // For small code model we assume that latest object is 16MB before end of 31
3810   // bits boundary. We may also accept pretty large negative constants knowing
3811   // that all objects are in the positive half of address space.
3812   if (M == CodeModel::Small && Offset < 16*1024*1024)
3813     return true;
3814
3815   // For kernel code model we know that all object resist in the negative half
3816   // of 32bits address space. We may not accept negative offsets, since they may
3817   // be just off and we may accept pretty large positive ones.
3818   if (M == CodeModel::Kernel && Offset >= 0)
3819     return true;
3820
3821   return false;
3822 }
3823
3824 /// isCalleePop - Determines whether the callee is required to pop its
3825 /// own arguments. Callee pop is necessary to support tail calls.
3826 bool X86::isCalleePop(CallingConv::ID CallingConv,
3827                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3828   switch (CallingConv) {
3829   default:
3830     return false;
3831   case CallingConv::X86_StdCall:
3832   case CallingConv::X86_FastCall:
3833   case CallingConv::X86_ThisCall:
3834     return !is64Bit;
3835   case CallingConv::Fast:
3836   case CallingConv::GHC:
3837   case CallingConv::HiPE:
3838     if (IsVarArg)
3839       return false;
3840     return TailCallOpt;
3841   }
3842 }
3843
3844 /// \brief Return true if the condition is an unsigned comparison operation.
3845 static bool isX86CCUnsigned(unsigned X86CC) {
3846   switch (X86CC) {
3847   default: llvm_unreachable("Invalid integer condition!");
3848   case X86::COND_E:     return true;
3849   case X86::COND_G:     return false;
3850   case X86::COND_GE:    return false;
3851   case X86::COND_L:     return false;
3852   case X86::COND_LE:    return false;
3853   case X86::COND_NE:    return true;
3854   case X86::COND_B:     return true;
3855   case X86::COND_A:     return true;
3856   case X86::COND_BE:    return true;
3857   case X86::COND_AE:    return true;
3858   }
3859   llvm_unreachable("covered switch fell through?!");
3860 }
3861
3862 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3863 /// specific condition code, returning the condition code and the LHS/RHS of the
3864 /// comparison to make.
3865 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, SDLoc DL, bool isFP,
3866                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3867   if (!isFP) {
3868     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3869       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3870         // X > -1   -> X == 0, jump !sign.
3871         RHS = DAG.getConstant(0, DL, RHS.getValueType());
3872         return X86::COND_NS;
3873       }
3874       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3875         // X < 0   -> X == 0, jump on sign.
3876         return X86::COND_S;
3877       }
3878       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3879         // X < 1   -> X <= 0
3880         RHS = DAG.getConstant(0, DL, RHS.getValueType());
3881         return X86::COND_LE;
3882       }
3883     }
3884
3885     switch (SetCCOpcode) {
3886     default: llvm_unreachable("Invalid integer condition!");
3887     case ISD::SETEQ:  return X86::COND_E;
3888     case ISD::SETGT:  return X86::COND_G;
3889     case ISD::SETGE:  return X86::COND_GE;
3890     case ISD::SETLT:  return X86::COND_L;
3891     case ISD::SETLE:  return X86::COND_LE;
3892     case ISD::SETNE:  return X86::COND_NE;
3893     case ISD::SETULT: return X86::COND_B;
3894     case ISD::SETUGT: return X86::COND_A;
3895     case ISD::SETULE: return X86::COND_BE;
3896     case ISD::SETUGE: return X86::COND_AE;
3897     }
3898   }
3899
3900   // First determine if it is required or is profitable to flip the operands.
3901
3902   // If LHS is a foldable load, but RHS is not, flip the condition.
3903   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3904       !ISD::isNON_EXTLoad(RHS.getNode())) {
3905     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3906     std::swap(LHS, RHS);
3907   }
3908
3909   switch (SetCCOpcode) {
3910   default: break;
3911   case ISD::SETOLT:
3912   case ISD::SETOLE:
3913   case ISD::SETUGT:
3914   case ISD::SETUGE:
3915     std::swap(LHS, RHS);
3916     break;
3917   }
3918
3919   // On a floating point condition, the flags are set as follows:
3920   // ZF  PF  CF   op
3921   //  0 | 0 | 0 | X > Y
3922   //  0 | 0 | 1 | X < Y
3923   //  1 | 0 | 0 | X == Y
3924   //  1 | 1 | 1 | unordered
3925   switch (SetCCOpcode) {
3926   default: llvm_unreachable("Condcode should be pre-legalized away");
3927   case ISD::SETUEQ:
3928   case ISD::SETEQ:   return X86::COND_E;
3929   case ISD::SETOLT:              // flipped
3930   case ISD::SETOGT:
3931   case ISD::SETGT:   return X86::COND_A;
3932   case ISD::SETOLE:              // flipped
3933   case ISD::SETOGE:
3934   case ISD::SETGE:   return X86::COND_AE;
3935   case ISD::SETUGT:              // flipped
3936   case ISD::SETULT:
3937   case ISD::SETLT:   return X86::COND_B;
3938   case ISD::SETUGE:              // flipped
3939   case ISD::SETULE:
3940   case ISD::SETLE:   return X86::COND_BE;
3941   case ISD::SETONE:
3942   case ISD::SETNE:   return X86::COND_NE;
3943   case ISD::SETUO:   return X86::COND_P;
3944   case ISD::SETO:    return X86::COND_NP;
3945   case ISD::SETOEQ:
3946   case ISD::SETUNE:  return X86::COND_INVALID;
3947   }
3948 }
3949
3950 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3951 /// code. Current x86 isa includes the following FP cmov instructions:
3952 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3953 static bool hasFPCMov(unsigned X86CC) {
3954   switch (X86CC) {
3955   default:
3956     return false;
3957   case X86::COND_B:
3958   case X86::COND_BE:
3959   case X86::COND_E:
3960   case X86::COND_P:
3961   case X86::COND_A:
3962   case X86::COND_AE:
3963   case X86::COND_NE:
3964   case X86::COND_NP:
3965     return true;
3966   }
3967 }
3968
3969 /// isFPImmLegal - Returns true if the target can instruction select the
3970 /// specified FP immediate natively. If false, the legalizer will
3971 /// materialize the FP immediate as a load from a constant pool.
3972 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3973   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3974     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3975       return true;
3976   }
3977   return false;
3978 }
3979
3980 bool X86TargetLowering::shouldReduceLoadWidth(SDNode *Load,
3981                                               ISD::LoadExtType ExtTy,
3982                                               EVT NewVT) const {
3983   // "ELF Handling for Thread-Local Storage" specifies that R_X86_64_GOTTPOFF
3984   // relocation target a movq or addq instruction: don't let the load shrink.
3985   SDValue BasePtr = cast<LoadSDNode>(Load)->getBasePtr();
3986   if (BasePtr.getOpcode() == X86ISD::WrapperRIP)
3987     if (const auto *GA = dyn_cast<GlobalAddressSDNode>(BasePtr.getOperand(0)))
3988       return GA->getTargetFlags() != X86II::MO_GOTTPOFF;
3989   return true;
3990 }
3991
3992 /// \brief Returns true if it is beneficial to convert a load of a constant
3993 /// to just the constant itself.
3994 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3995                                                           Type *Ty) const {
3996   assert(Ty->isIntegerTy());
3997
3998   unsigned BitSize = Ty->getPrimitiveSizeInBits();
3999   if (BitSize == 0 || BitSize > 64)
4000     return false;
4001   return true;
4002 }
4003
4004 bool X86TargetLowering::isExtractSubvectorCheap(EVT ResVT,
4005                                                 unsigned Index) const {
4006   if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
4007     return false;
4008
4009   return (Index == 0 || Index == ResVT.getVectorNumElements());
4010 }
4011
4012 bool X86TargetLowering::isCheapToSpeculateCttz() const {
4013   // Speculate cttz only if we can directly use TZCNT.
4014   return Subtarget->hasBMI();
4015 }
4016
4017 bool X86TargetLowering::isCheapToSpeculateCtlz() const {
4018   // Speculate ctlz only if we can directly use LZCNT.
4019   return Subtarget->hasLZCNT();
4020 }
4021
4022 /// isUndefInRange - Return true if every element in Mask, beginning
4023 /// from position Pos and ending in Pos+Size is undef.
4024 static bool isUndefInRange(ArrayRef<int> Mask, unsigned Pos, unsigned Size) {
4025   for (unsigned i = Pos, e = Pos + Size; i != e; ++i)
4026     if (0 <= Mask[i])
4027       return false;
4028   return true;
4029 }
4030
4031 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
4032 /// the specified range (L, H].
4033 static bool isUndefOrInRange(int Val, int Low, int Hi) {
4034   return (Val < 0) || (Val >= Low && Val < Hi);
4035 }
4036
4037 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
4038 /// specified value.
4039 static bool isUndefOrEqual(int Val, int CmpVal) {
4040   return (Val < 0 || Val == CmpVal);
4041 }
4042
4043 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
4044 /// from position Pos and ending in Pos+Size, falls within the specified
4045 /// sequential range (Low, Low+Size]. or is undef.
4046 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
4047                                        unsigned Pos, unsigned Size, int Low) {
4048   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
4049     if (!isUndefOrEqual(Mask[i], Low))
4050       return false;
4051   return true;
4052 }
4053
4054 /// isVEXTRACTIndex - Return true if the specified
4055 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4056 /// suitable for instruction that extract 128 or 256 bit vectors
4057 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4058   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4059   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4060     return false;
4061
4062   // The index should be aligned on a vecWidth-bit boundary.
4063   uint64_t Index =
4064     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4065
4066   MVT VT = N->getSimpleValueType(0);
4067   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4068   bool Result = (Index * ElSize) % vecWidth == 0;
4069
4070   return Result;
4071 }
4072
4073 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4074 /// operand specifies a subvector insert that is suitable for input to
4075 /// insertion of 128 or 256-bit subvectors
4076 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4077   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4078   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4079     return false;
4080   // The index should be aligned on a vecWidth-bit boundary.
4081   uint64_t Index =
4082     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4083
4084   MVT VT = N->getSimpleValueType(0);
4085   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4086   bool Result = (Index * ElSize) % vecWidth == 0;
4087
4088   return Result;
4089 }
4090
4091 bool X86::isVINSERT128Index(SDNode *N) {
4092   return isVINSERTIndex(N, 128);
4093 }
4094
4095 bool X86::isVINSERT256Index(SDNode *N) {
4096   return isVINSERTIndex(N, 256);
4097 }
4098
4099 bool X86::isVEXTRACT128Index(SDNode *N) {
4100   return isVEXTRACTIndex(N, 128);
4101 }
4102
4103 bool X86::isVEXTRACT256Index(SDNode *N) {
4104   return isVEXTRACTIndex(N, 256);
4105 }
4106
4107 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4108   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4109   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4110     llvm_unreachable("Illegal extract subvector for VEXTRACT");
4111
4112   uint64_t Index =
4113     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4114
4115   MVT VecVT = N->getOperand(0).getSimpleValueType();
4116   MVT ElVT = VecVT.getVectorElementType();
4117
4118   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4119   return Index / NumElemsPerChunk;
4120 }
4121
4122 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4123   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4124   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4125     llvm_unreachable("Illegal insert subvector for VINSERT");
4126
4127   uint64_t Index =
4128     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4129
4130   MVT VecVT = N->getSimpleValueType(0);
4131   MVT ElVT = VecVT.getVectorElementType();
4132
4133   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4134   return Index / NumElemsPerChunk;
4135 }
4136
4137 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4138 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4139 /// and VINSERTI128 instructions.
4140 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4141   return getExtractVEXTRACTImmediate(N, 128);
4142 }
4143
4144 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4145 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4146 /// and VINSERTI64x4 instructions.
4147 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4148   return getExtractVEXTRACTImmediate(N, 256);
4149 }
4150
4151 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4152 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4153 /// and VINSERTI128 instructions.
4154 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4155   return getInsertVINSERTImmediate(N, 128);
4156 }
4157
4158 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4159 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4160 /// and VINSERTI64x4 instructions.
4161 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4162   return getInsertVINSERTImmediate(N, 256);
4163 }
4164
4165 /// isZero - Returns true if Elt is a constant integer zero
4166 static bool isZero(SDValue V) {
4167   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4168   return C && C->isNullValue();
4169 }
4170
4171 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4172 /// constant +0.0.
4173 bool X86::isZeroNode(SDValue Elt) {
4174   if (isZero(Elt))
4175     return true;
4176   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4177     return CFP->getValueAPF().isPosZero();
4178   return false;
4179 }
4180
4181 /// getZeroVector - Returns a vector of specified type with all zero elements.
4182 ///
4183 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4184                              SelectionDAG &DAG, SDLoc dl) {
4185   assert(VT.isVector() && "Expected a vector type");
4186
4187   // Always build SSE zero vectors as <4 x i32> bitcasted
4188   // to their dest type. This ensures they get CSE'd.
4189   SDValue Vec;
4190   if (VT.is128BitVector()) {  // SSE
4191     if (Subtarget->hasSSE2()) {  // SSE2
4192       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4193       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4194     } else { // SSE1
4195       SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4196       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4197     }
4198   } else if (VT.is256BitVector()) { // AVX
4199     if (Subtarget->hasInt256()) { // AVX2
4200       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4201       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4202       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4203     } else {
4204       // 256-bit logic and arithmetic instructions in AVX are all
4205       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4206       SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4207       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4208       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4209     }
4210   } else if (VT.is512BitVector()) { // AVX-512
4211       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4212       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4213                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4214       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4215   } else if (VT.getScalarType() == MVT::i1) {
4216
4217     assert((Subtarget->hasBWI() || VT.getVectorNumElements() <= 16)
4218             && "Unexpected vector type");
4219     assert((Subtarget->hasVLX() || VT.getVectorNumElements() >= 8)
4220             && "Unexpected vector type");
4221     SDValue Cst = DAG.getConstant(0, dl, MVT::i1);
4222     SmallVector<SDValue, 64> Ops(VT.getVectorNumElements(), Cst);
4223     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4224   } else
4225     llvm_unreachable("Unexpected vector type");
4226
4227   return DAG.getBitcast(VT, Vec);
4228 }
4229
4230 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
4231                                 SelectionDAG &DAG, SDLoc dl,
4232                                 unsigned vectorWidth) {
4233   assert((vectorWidth == 128 || vectorWidth == 256) &&
4234          "Unsupported vector width");
4235   EVT VT = Vec.getValueType();
4236   EVT ElVT = VT.getVectorElementType();
4237   unsigned Factor = VT.getSizeInBits()/vectorWidth;
4238   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
4239                                   VT.getVectorNumElements()/Factor);
4240
4241   // Extract from UNDEF is UNDEF.
4242   if (Vec.getOpcode() == ISD::UNDEF)
4243     return DAG.getUNDEF(ResultVT);
4244
4245   // Extract the relevant vectorWidth bits.  Generate an EXTRACT_SUBVECTOR
4246   unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
4247
4248   // This is the index of the first element of the vectorWidth-bit chunk
4249   // we want.
4250   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
4251                                * ElemsPerChunk);
4252
4253   // If the input is a buildvector just emit a smaller one.
4254   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
4255     return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
4256                        makeArrayRef(Vec->op_begin() + NormalizedIdxVal,
4257                                     ElemsPerChunk));
4258
4259   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4260   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec, VecIdx);
4261 }
4262
4263 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
4264 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
4265 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
4266 /// instructions or a simple subregister reference. Idx is an index in the
4267 /// 128 bits we want.  It need not be aligned to a 128-bit boundary.  That makes
4268 /// lowering EXTRACT_VECTOR_ELT operations easier.
4269 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
4270                                    SelectionDAG &DAG, SDLoc dl) {
4271   assert((Vec.getValueType().is256BitVector() ||
4272           Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
4273   return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
4274 }
4275
4276 /// Generate a DAG to grab 256-bits from a 512-bit vector.
4277 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
4278                                    SelectionDAG &DAG, SDLoc dl) {
4279   assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
4280   return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
4281 }
4282
4283 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
4284                                unsigned IdxVal, SelectionDAG &DAG,
4285                                SDLoc dl, unsigned vectorWidth) {
4286   assert((vectorWidth == 128 || vectorWidth == 256) &&
4287          "Unsupported vector width");
4288   // Inserting UNDEF is Result
4289   if (Vec.getOpcode() == ISD::UNDEF)
4290     return Result;
4291   EVT VT = Vec.getValueType();
4292   EVT ElVT = VT.getVectorElementType();
4293   EVT ResultVT = Result.getValueType();
4294
4295   // Insert the relevant vectorWidth bits.
4296   unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
4297
4298   // This is the index of the first element of the vectorWidth-bit chunk
4299   // we want.
4300   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
4301                                * ElemsPerChunk);
4302
4303   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4304   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec, VecIdx);
4305 }
4306
4307 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
4308 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
4309 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
4310 /// simple superregister reference.  Idx is an index in the 128 bits
4311 /// we want.  It need not be aligned to a 128-bit boundary.  That makes
4312 /// lowering INSERT_VECTOR_ELT operations easier.
4313 static SDValue Insert128BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4314                                   SelectionDAG &DAG, SDLoc dl) {
4315   assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
4316
4317   // For insertion into the zero index (low half) of a 256-bit vector, it is
4318   // more efficient to generate a blend with immediate instead of an insert*128.
4319   // We are still creating an INSERT_SUBVECTOR below with an undef node to
4320   // extend the subvector to the size of the result vector. Make sure that
4321   // we are not recursing on that node by checking for undef here.
4322   if (IdxVal == 0 && Result.getValueType().is256BitVector() &&
4323       Result.getOpcode() != ISD::UNDEF) {
4324     EVT ResultVT = Result.getValueType();
4325     SDValue ZeroIndex = DAG.getIntPtrConstant(0, dl);
4326     SDValue Undef = DAG.getUNDEF(ResultVT);
4327     SDValue Vec256 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Undef,
4328                                  Vec, ZeroIndex);
4329
4330     // The blend instruction, and therefore its mask, depend on the data type.
4331     MVT ScalarType = ResultVT.getScalarType().getSimpleVT();
4332     if (ScalarType.isFloatingPoint()) {
4333       // Choose either vblendps (float) or vblendpd (double).
4334       unsigned ScalarSize = ScalarType.getSizeInBits();
4335       assert((ScalarSize == 64 || ScalarSize == 32) && "Unknown float type");
4336       unsigned MaskVal = (ScalarSize == 64) ? 0x03 : 0x0f;
4337       SDValue Mask = DAG.getConstant(MaskVal, dl, MVT::i8);
4338       return DAG.getNode(X86ISD::BLENDI, dl, ResultVT, Result, Vec256, Mask);
4339     }
4340
4341     const X86Subtarget &Subtarget =
4342     static_cast<const X86Subtarget &>(DAG.getSubtarget());
4343
4344     // AVX2 is needed for 256-bit integer blend support.
4345     // Integers must be cast to 32-bit because there is only vpblendd;
4346     // vpblendw can't be used for this because it has a handicapped mask.
4347
4348     // If we don't have AVX2, then cast to float. Using a wrong domain blend
4349     // is still more efficient than using the wrong domain vinsertf128 that
4350     // will be created by InsertSubVector().
4351     MVT CastVT = Subtarget.hasAVX2() ? MVT::v8i32 : MVT::v8f32;
4352
4353     SDValue Mask = DAG.getConstant(0x0f, dl, MVT::i8);
4354     Vec256 = DAG.getBitcast(CastVT, Vec256);
4355     Vec256 = DAG.getNode(X86ISD::BLENDI, dl, CastVT, Result, Vec256, Mask);
4356     return DAG.getBitcast(ResultVT, Vec256);
4357   }
4358
4359   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
4360 }
4361
4362 static SDValue Insert256BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4363                                   SelectionDAG &DAG, SDLoc dl) {
4364   assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
4365   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
4366 }
4367
4368 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
4369 /// instructions. This is used because creating CONCAT_VECTOR nodes of
4370 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
4371 /// large BUILD_VECTORS.
4372 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
4373                                    unsigned NumElems, SelectionDAG &DAG,
4374                                    SDLoc dl) {
4375   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4376   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
4377 }
4378
4379 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
4380                                    unsigned NumElems, SelectionDAG &DAG,
4381                                    SDLoc dl) {
4382   SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4383   return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
4384 }
4385
4386 /// getOnesVector - Returns a vector of specified type with all bits set.
4387 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4388 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4389 /// Then bitcast to their original type, ensuring they get CSE'd.
4390 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4391                              SDLoc dl) {
4392   assert(VT.isVector() && "Expected a vector type");
4393
4394   SDValue Cst = DAG.getConstant(~0U, dl, MVT::i32);
4395   SDValue Vec;
4396   if (VT.is256BitVector()) {
4397     if (HasInt256) { // AVX2
4398       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4399       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4400     } else { // AVX
4401       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4402       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4403     }
4404   } else if (VT.is128BitVector()) {
4405     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4406   } else
4407     llvm_unreachable("Unexpected vector type");
4408
4409   return DAG.getBitcast(VT, Vec);
4410 }
4411
4412 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4413 /// operation of specified width.
4414 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4415                        SDValue V2) {
4416   unsigned NumElems = VT.getVectorNumElements();
4417   SmallVector<int, 8> Mask;
4418   Mask.push_back(NumElems);
4419   for (unsigned i = 1; i != NumElems; ++i)
4420     Mask.push_back(i);
4421   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4422 }
4423
4424 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4425 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4426                           SDValue V2) {
4427   unsigned NumElems = VT.getVectorNumElements();
4428   SmallVector<int, 8> Mask;
4429   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4430     Mask.push_back(i);
4431     Mask.push_back(i + NumElems);
4432   }
4433   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4434 }
4435
4436 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4437 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4438                           SDValue V2) {
4439   unsigned NumElems = VT.getVectorNumElements();
4440   SmallVector<int, 8> Mask;
4441   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4442     Mask.push_back(i + Half);
4443     Mask.push_back(i + NumElems + Half);
4444   }
4445   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4446 }
4447
4448 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4449 /// vector of zero or undef vector.  This produces a shuffle where the low
4450 /// element of V2 is swizzled into the zero/undef vector, landing at element
4451 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4452 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4453                                            bool IsZero,
4454                                            const X86Subtarget *Subtarget,
4455                                            SelectionDAG &DAG) {
4456   MVT VT = V2.getSimpleValueType();
4457   SDValue V1 = IsZero
4458     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
4459   unsigned NumElems = VT.getVectorNumElements();
4460   SmallVector<int, 16> MaskVec;
4461   for (unsigned i = 0; i != NumElems; ++i)
4462     // If this is the insertion idx, put the low elt of V2 here.
4463     MaskVec.push_back(i == Idx ? NumElems : i);
4464   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
4465 }
4466
4467 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4468 /// target specific opcode. Returns true if the Mask could be calculated. Sets
4469 /// IsUnary to true if only uses one source. Note that this will set IsUnary for
4470 /// shuffles which use a single input multiple times, and in those cases it will
4471 /// adjust the mask to only have indices within that single input.
4472 /// FIXME: Add support for Decode*Mask functions that return SM_SentinelZero.
4473 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4474                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
4475   unsigned NumElems = VT.getVectorNumElements();
4476   SDValue ImmN;
4477
4478   IsUnary = false;
4479   bool IsFakeUnary = false;
4480   switch(N->getOpcode()) {
4481   case X86ISD::BLENDI:
4482     ImmN = N->getOperand(N->getNumOperands()-1);
4483     DecodeBLENDMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4484     break;
4485   case X86ISD::SHUFP:
4486     ImmN = N->getOperand(N->getNumOperands()-1);
4487     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4488     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4489     break;
4490   case X86ISD::UNPCKH:
4491     DecodeUNPCKHMask(VT, Mask);
4492     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4493     break;
4494   case X86ISD::UNPCKL:
4495     DecodeUNPCKLMask(VT, Mask);
4496     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4497     break;
4498   case X86ISD::MOVHLPS:
4499     DecodeMOVHLPSMask(NumElems, Mask);
4500     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4501     break;
4502   case X86ISD::MOVLHPS:
4503     DecodeMOVLHPSMask(NumElems, Mask);
4504     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4505     break;
4506   case X86ISD::PALIGNR:
4507     ImmN = N->getOperand(N->getNumOperands()-1);
4508     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4509     break;
4510   case X86ISD::PSHUFD:
4511   case X86ISD::VPERMILPI:
4512     ImmN = N->getOperand(N->getNumOperands()-1);
4513     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4514     IsUnary = true;
4515     break;
4516   case X86ISD::PSHUFHW:
4517     ImmN = N->getOperand(N->getNumOperands()-1);
4518     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4519     IsUnary = true;
4520     break;
4521   case X86ISD::PSHUFLW:
4522     ImmN = N->getOperand(N->getNumOperands()-1);
4523     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4524     IsUnary = true;
4525     break;
4526   case X86ISD::PSHUFB: {
4527     IsUnary = true;
4528     SDValue MaskNode = N->getOperand(1);
4529     while (MaskNode->getOpcode() == ISD::BITCAST)
4530       MaskNode = MaskNode->getOperand(0);
4531
4532     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4533       // If we have a build-vector, then things are easy.
4534       EVT VT = MaskNode.getValueType();
4535       assert(VT.isVector() &&
4536              "Can't produce a non-vector with a build_vector!");
4537       if (!VT.isInteger())
4538         return false;
4539
4540       int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
4541
4542       SmallVector<uint64_t, 32> RawMask;
4543       for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
4544         SDValue Op = MaskNode->getOperand(i);
4545         if (Op->getOpcode() == ISD::UNDEF) {
4546           RawMask.push_back((uint64_t)SM_SentinelUndef);
4547           continue;
4548         }
4549         auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4550         if (!CN)
4551           return false;
4552         APInt MaskElement = CN->getAPIntValue();
4553
4554         // We now have to decode the element which could be any integer size and
4555         // extract each byte of it.
4556         for (int j = 0; j < NumBytesPerElement; ++j) {
4557           // Note that this is x86 and so always little endian: the low byte is
4558           // the first byte of the mask.
4559           RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
4560           MaskElement = MaskElement.lshr(8);
4561         }
4562       }
4563       DecodePSHUFBMask(RawMask, Mask);
4564       break;
4565     }
4566
4567     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4568     if (!MaskLoad)
4569       return false;
4570
4571     SDValue Ptr = MaskLoad->getBasePtr();
4572     if (Ptr->getOpcode() == X86ISD::Wrapper ||
4573         Ptr->getOpcode() == X86ISD::WrapperRIP)
4574       Ptr = Ptr->getOperand(0);
4575
4576     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4577     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4578       return false;
4579
4580     if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
4581       DecodePSHUFBMask(C, Mask);
4582       if (Mask.empty())
4583         return false;
4584       break;
4585     }
4586
4587     return false;
4588   }
4589   case X86ISD::VPERMI:
4590     ImmN = N->getOperand(N->getNumOperands()-1);
4591     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4592     IsUnary = true;
4593     break;
4594   case X86ISD::MOVSS:
4595   case X86ISD::MOVSD:
4596     DecodeScalarMoveMask(VT, /* IsLoad */ false, Mask);
4597     break;
4598   case X86ISD::VPERM2X128:
4599     ImmN = N->getOperand(N->getNumOperands()-1);
4600     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4601     if (Mask.empty()) return false;
4602     // Mask only contains negative index if an element is zero.
4603     if (std::any_of(Mask.begin(), Mask.end(),
4604                     [](int M){ return M == SM_SentinelZero; }))
4605       return false;
4606     break;
4607   case X86ISD::MOVSLDUP:
4608     DecodeMOVSLDUPMask(VT, Mask);
4609     IsUnary = true;
4610     break;
4611   case X86ISD::MOVSHDUP:
4612     DecodeMOVSHDUPMask(VT, Mask);
4613     IsUnary = true;
4614     break;
4615   case X86ISD::MOVDDUP:
4616     DecodeMOVDDUPMask(VT, Mask);
4617     IsUnary = true;
4618     break;
4619   case X86ISD::MOVLHPD:
4620   case X86ISD::MOVLPD:
4621   case X86ISD::MOVLPS:
4622     // Not yet implemented
4623     return false;
4624   default: llvm_unreachable("unknown target shuffle node");
4625   }
4626
4627   // If we have a fake unary shuffle, the shuffle mask is spread across two
4628   // inputs that are actually the same node. Re-map the mask to always point
4629   // into the first input.
4630   if (IsFakeUnary)
4631     for (int &M : Mask)
4632       if (M >= (int)Mask.size())
4633         M -= Mask.size();
4634
4635   return true;
4636 }
4637
4638 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4639 /// element of the result of the vector shuffle.
4640 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4641                                    unsigned Depth) {
4642   if (Depth == 6)
4643     return SDValue();  // Limit search depth.
4644
4645   SDValue V = SDValue(N, 0);
4646   EVT VT = V.getValueType();
4647   unsigned Opcode = V.getOpcode();
4648
4649   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4650   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4651     int Elt = SV->getMaskElt(Index);
4652
4653     if (Elt < 0)
4654       return DAG.getUNDEF(VT.getVectorElementType());
4655
4656     unsigned NumElems = VT.getVectorNumElements();
4657     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4658                                          : SV->getOperand(1);
4659     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4660   }
4661
4662   // Recurse into target specific vector shuffles to find scalars.
4663   if (isTargetShuffle(Opcode)) {
4664     MVT ShufVT = V.getSimpleValueType();
4665     unsigned NumElems = ShufVT.getVectorNumElements();
4666     SmallVector<int, 16> ShuffleMask;
4667     bool IsUnary;
4668
4669     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4670       return SDValue();
4671
4672     int Elt = ShuffleMask[Index];
4673     if (Elt < 0)
4674       return DAG.getUNDEF(ShufVT.getVectorElementType());
4675
4676     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4677                                          : N->getOperand(1);
4678     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4679                                Depth+1);
4680   }
4681
4682   // Actual nodes that may contain scalar elements
4683   if (Opcode == ISD::BITCAST) {
4684     V = V.getOperand(0);
4685     EVT SrcVT = V.getValueType();
4686     unsigned NumElems = VT.getVectorNumElements();
4687
4688     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4689       return SDValue();
4690   }
4691
4692   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4693     return (Index == 0) ? V.getOperand(0)
4694                         : DAG.getUNDEF(VT.getVectorElementType());
4695
4696   if (V.getOpcode() == ISD::BUILD_VECTOR)
4697     return V.getOperand(Index);
4698
4699   return SDValue();
4700 }
4701
4702 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4703 ///
4704 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4705                                        unsigned NumNonZero, unsigned NumZero,
4706                                        SelectionDAG &DAG,
4707                                        const X86Subtarget* Subtarget,
4708                                        const TargetLowering &TLI) {
4709   if (NumNonZero > 8)
4710     return SDValue();
4711
4712   SDLoc dl(Op);
4713   SDValue V;
4714   bool First = true;
4715
4716   // SSE4.1 - use PINSRB to insert each byte directly.
4717   if (Subtarget->hasSSE41()) {
4718     for (unsigned i = 0; i < 16; ++i) {
4719       bool isNonZero = (NonZeros & (1 << i)) != 0;
4720       if (isNonZero) {
4721         if (First) {
4722           if (NumZero)
4723             V = getZeroVector(MVT::v16i8, Subtarget, DAG, dl);
4724           else
4725             V = DAG.getUNDEF(MVT::v16i8);
4726           First = false;
4727         }
4728         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4729                         MVT::v16i8, V, Op.getOperand(i),
4730                         DAG.getIntPtrConstant(i, dl));
4731       }
4732     }
4733
4734     return V;
4735   }
4736
4737   // Pre-SSE4.1 - merge byte pairs and insert with PINSRW.
4738   for (unsigned i = 0; i < 16; ++i) {
4739     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4740     if (ThisIsNonZero && First) {
4741       if (NumZero)
4742         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4743       else
4744         V = DAG.getUNDEF(MVT::v8i16);
4745       First = false;
4746     }
4747
4748     if ((i & 1) != 0) {
4749       SDValue ThisElt, LastElt;
4750       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4751       if (LastIsNonZero) {
4752         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4753                               MVT::i16, Op.getOperand(i-1));
4754       }
4755       if (ThisIsNonZero) {
4756         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4757         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4758                               ThisElt, DAG.getConstant(8, dl, MVT::i8));
4759         if (LastIsNonZero)
4760           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4761       } else
4762         ThisElt = LastElt;
4763
4764       if (ThisElt.getNode())
4765         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4766                         DAG.getIntPtrConstant(i/2, dl));
4767     }
4768   }
4769
4770   return DAG.getBitcast(MVT::v16i8, V);
4771 }
4772
4773 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4774 ///
4775 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4776                                      unsigned NumNonZero, unsigned NumZero,
4777                                      SelectionDAG &DAG,
4778                                      const X86Subtarget* Subtarget,
4779                                      const TargetLowering &TLI) {
4780   if (NumNonZero > 4)
4781     return SDValue();
4782
4783   SDLoc dl(Op);
4784   SDValue V;
4785   bool First = true;
4786   for (unsigned i = 0; i < 8; ++i) {
4787     bool isNonZero = (NonZeros & (1 << i)) != 0;
4788     if (isNonZero) {
4789       if (First) {
4790         if (NumZero)
4791           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4792         else
4793           V = DAG.getUNDEF(MVT::v8i16);
4794         First = false;
4795       }
4796       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4797                       MVT::v8i16, V, Op.getOperand(i),
4798                       DAG.getIntPtrConstant(i, dl));
4799     }
4800   }
4801
4802   return V;
4803 }
4804
4805 /// LowerBuildVectorv4x32 - Custom lower build_vector of v4i32 or v4f32.
4806 static SDValue LowerBuildVectorv4x32(SDValue Op, SelectionDAG &DAG,
4807                                      const X86Subtarget *Subtarget,
4808                                      const TargetLowering &TLI) {
4809   // Find all zeroable elements.
4810   std::bitset<4> Zeroable;
4811   for (int i=0; i < 4; ++i) {
4812     SDValue Elt = Op->getOperand(i);
4813     Zeroable[i] = (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt));
4814   }
4815   assert(Zeroable.size() - Zeroable.count() > 1 &&
4816          "We expect at least two non-zero elements!");
4817
4818   // We only know how to deal with build_vector nodes where elements are either
4819   // zeroable or extract_vector_elt with constant index.
4820   SDValue FirstNonZero;
4821   unsigned FirstNonZeroIdx;
4822   for (unsigned i=0; i < 4; ++i) {
4823     if (Zeroable[i])
4824       continue;
4825     SDValue Elt = Op->getOperand(i);
4826     if (Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4827         !isa<ConstantSDNode>(Elt.getOperand(1)))
4828       return SDValue();
4829     // Make sure that this node is extracting from a 128-bit vector.
4830     MVT VT = Elt.getOperand(0).getSimpleValueType();
4831     if (!VT.is128BitVector())
4832       return SDValue();
4833     if (!FirstNonZero.getNode()) {
4834       FirstNonZero = Elt;
4835       FirstNonZeroIdx = i;
4836     }
4837   }
4838
4839   assert(FirstNonZero.getNode() && "Unexpected build vector of all zeros!");
4840   SDValue V1 = FirstNonZero.getOperand(0);
4841   MVT VT = V1.getSimpleValueType();
4842
4843   // See if this build_vector can be lowered as a blend with zero.
4844   SDValue Elt;
4845   unsigned EltMaskIdx, EltIdx;
4846   int Mask[4];
4847   for (EltIdx = 0; EltIdx < 4; ++EltIdx) {
4848     if (Zeroable[EltIdx]) {
4849       // The zero vector will be on the right hand side.
4850       Mask[EltIdx] = EltIdx+4;
4851       continue;
4852     }
4853
4854     Elt = Op->getOperand(EltIdx);
4855     // By construction, Elt is a EXTRACT_VECTOR_ELT with constant index.
4856     EltMaskIdx = cast<ConstantSDNode>(Elt.getOperand(1))->getZExtValue();
4857     if (Elt.getOperand(0) != V1 || EltMaskIdx != EltIdx)
4858       break;
4859     Mask[EltIdx] = EltIdx;
4860   }
4861
4862   if (EltIdx == 4) {
4863     // Let the shuffle legalizer deal with blend operations.
4864     SDValue VZero = getZeroVector(VT, Subtarget, DAG, SDLoc(Op));
4865     if (V1.getSimpleValueType() != VT)
4866       V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), VT, V1);
4867     return DAG.getVectorShuffle(VT, SDLoc(V1), V1, VZero, &Mask[0]);
4868   }
4869
4870   // See if we can lower this build_vector to a INSERTPS.
4871   if (!Subtarget->hasSSE41())
4872     return SDValue();
4873
4874   SDValue V2 = Elt.getOperand(0);
4875   if (Elt == FirstNonZero && EltIdx == FirstNonZeroIdx)
4876     V1 = SDValue();
4877
4878   bool CanFold = true;
4879   for (unsigned i = EltIdx + 1; i < 4 && CanFold; ++i) {
4880     if (Zeroable[i])
4881       continue;
4882
4883     SDValue Current = Op->getOperand(i);
4884     SDValue SrcVector = Current->getOperand(0);
4885     if (!V1.getNode())
4886       V1 = SrcVector;
4887     CanFold = SrcVector == V1 &&
4888       cast<ConstantSDNode>(Current.getOperand(1))->getZExtValue() == i;
4889   }
4890
4891   if (!CanFold)
4892     return SDValue();
4893
4894   assert(V1.getNode() && "Expected at least two non-zero elements!");
4895   if (V1.getSimpleValueType() != MVT::v4f32)
4896     V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), MVT::v4f32, V1);
4897   if (V2.getSimpleValueType() != MVT::v4f32)
4898     V2 = DAG.getNode(ISD::BITCAST, SDLoc(V2), MVT::v4f32, V2);
4899
4900   // Ok, we can emit an INSERTPS instruction.
4901   unsigned ZMask = Zeroable.to_ulong();
4902
4903   unsigned InsertPSMask = EltMaskIdx << 6 | EltIdx << 4 | ZMask;
4904   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
4905   SDLoc DL(Op);
4906   SDValue Result = DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
4907                                DAG.getIntPtrConstant(InsertPSMask, DL));
4908   return DAG.getBitcast(VT, Result);
4909 }
4910
4911 /// Return a vector logical shift node.
4912 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4913                          unsigned NumBits, SelectionDAG &DAG,
4914                          const TargetLowering &TLI, SDLoc dl) {
4915   assert(VT.is128BitVector() && "Unknown type for VShift");
4916   MVT ShVT = MVT::v2i64;
4917   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4918   SrcOp = DAG.getBitcast(ShVT, SrcOp);
4919   MVT ScalarShiftTy = TLI.getScalarShiftAmountTy(DAG.getDataLayout(), VT);
4920   assert(NumBits % 8 == 0 && "Only support byte sized shifts");
4921   SDValue ShiftVal = DAG.getConstant(NumBits/8, dl, ScalarShiftTy);
4922   return DAG.getBitcast(VT, DAG.getNode(Opc, dl, ShVT, SrcOp, ShiftVal));
4923 }
4924
4925 static SDValue
4926 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
4927
4928   // Check if the scalar load can be widened into a vector load. And if
4929   // the address is "base + cst" see if the cst can be "absorbed" into
4930   // the shuffle mask.
4931   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4932     SDValue Ptr = LD->getBasePtr();
4933     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4934       return SDValue();
4935     EVT PVT = LD->getValueType(0);
4936     if (PVT != MVT::i32 && PVT != MVT::f32)
4937       return SDValue();
4938
4939     int FI = -1;
4940     int64_t Offset = 0;
4941     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4942       FI = FINode->getIndex();
4943       Offset = 0;
4944     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4945                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4946       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4947       Offset = Ptr.getConstantOperandVal(1);
4948       Ptr = Ptr.getOperand(0);
4949     } else {
4950       return SDValue();
4951     }
4952
4953     // FIXME: 256-bit vector instructions don't require a strict alignment,
4954     // improve this code to support it better.
4955     unsigned RequiredAlign = VT.getSizeInBits()/8;
4956     SDValue Chain = LD->getChain();
4957     // Make sure the stack object alignment is at least 16 or 32.
4958     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4959     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4960       if (MFI->isFixedObjectIndex(FI)) {
4961         // Can't change the alignment. FIXME: It's possible to compute
4962         // the exact stack offset and reference FI + adjust offset instead.
4963         // If someone *really* cares about this. That's the way to implement it.
4964         return SDValue();
4965       } else {
4966         MFI->setObjectAlignment(FI, RequiredAlign);
4967       }
4968     }
4969
4970     // (Offset % 16 or 32) must be multiple of 4. Then address is then
4971     // Ptr + (Offset & ~15).
4972     if (Offset < 0)
4973       return SDValue();
4974     if ((Offset % RequiredAlign) & 3)
4975       return SDValue();
4976     int64_t StartOffset = Offset & ~(RequiredAlign-1);
4977     if (StartOffset) {
4978       SDLoc DL(Ptr);
4979       Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
4980                         DAG.getConstant(StartOffset, DL, Ptr.getValueType()));
4981     }
4982
4983     int EltNo = (Offset - StartOffset) >> 2;
4984     unsigned NumElems = VT.getVectorNumElements();
4985
4986     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4987     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4988                              LD->getPointerInfo().getWithOffset(StartOffset),
4989                              false, false, false, 0);
4990
4991     SmallVector<int, 8> Mask(NumElems, EltNo);
4992
4993     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
4994   }
4995
4996   return SDValue();
4997 }
4998
4999 /// Given the initializing elements 'Elts' of a vector of type 'VT', see if the
5000 /// elements can be replaced by a single large load which has the same value as
5001 /// a build_vector or insert_subvector whose loaded operands are 'Elts'.
5002 ///
5003 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5004 ///
5005 /// FIXME: we'd also like to handle the case where the last elements are zero
5006 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5007 /// There's even a handy isZeroNode for that purpose.
5008 static SDValue EltsFromConsecutiveLoads(EVT VT, ArrayRef<SDValue> Elts,
5009                                         SDLoc &DL, SelectionDAG &DAG,
5010                                         bool isAfterLegalize) {
5011   unsigned NumElems = Elts.size();
5012
5013   LoadSDNode *LDBase = nullptr;
5014   unsigned LastLoadedElt = -1U;
5015
5016   // For each element in the initializer, see if we've found a load or an undef.
5017   // If we don't find an initial load element, or later load elements are
5018   // non-consecutive, bail out.
5019   for (unsigned i = 0; i < NumElems; ++i) {
5020     SDValue Elt = Elts[i];
5021     // Look through a bitcast.
5022     if (Elt.getNode() && Elt.getOpcode() == ISD::BITCAST)
5023       Elt = Elt.getOperand(0);
5024     if (!Elt.getNode() ||
5025         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5026       return SDValue();
5027     if (!LDBase) {
5028       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5029         return SDValue();
5030       LDBase = cast<LoadSDNode>(Elt.getNode());
5031       LastLoadedElt = i;
5032       continue;
5033     }
5034     if (Elt.getOpcode() == ISD::UNDEF)
5035       continue;
5036
5037     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5038     EVT LdVT = Elt.getValueType();
5039     // Each loaded element must be the correct fractional portion of the
5040     // requested vector load.
5041     if (LdVT.getSizeInBits() != VT.getSizeInBits() / NumElems)
5042       return SDValue();
5043     if (!DAG.isConsecutiveLoad(LD, LDBase, LdVT.getSizeInBits() / 8, i))
5044       return SDValue();
5045     LastLoadedElt = i;
5046   }
5047
5048   // If we have found an entire vector of loads and undefs, then return a large
5049   // load of the entire vector width starting at the base pointer.  If we found
5050   // consecutive loads for the low half, generate a vzext_load node.
5051   if (LastLoadedElt == NumElems - 1) {
5052     assert(LDBase && "Did not find base load for merging consecutive loads");
5053     EVT EltVT = LDBase->getValueType(0);
5054     // Ensure that the input vector size for the merged loads matches the
5055     // cumulative size of the input elements.
5056     if (VT.getSizeInBits() != EltVT.getSizeInBits() * NumElems)
5057       return SDValue();
5058
5059     if (isAfterLegalize &&
5060         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5061       return SDValue();
5062
5063     SDValue NewLd = SDValue();
5064
5065     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5066                         LDBase->getPointerInfo(), LDBase->isVolatile(),
5067                         LDBase->isNonTemporal(), LDBase->isInvariant(),
5068                         LDBase->getAlignment());
5069
5070     if (LDBase->hasAnyUseOfValue(1)) {
5071       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5072                                      SDValue(LDBase, 1),
5073                                      SDValue(NewLd.getNode(), 1));
5074       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5075       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5076                              SDValue(NewLd.getNode(), 1));
5077     }
5078
5079     return NewLd;
5080   }
5081
5082   //TODO: The code below fires only for for loading the low v2i32 / v2f32
5083   //of a v4i32 / v4f32. It's probably worth generalizing.
5084   EVT EltVT = VT.getVectorElementType();
5085   if (NumElems == 4 && LastLoadedElt == 1 && (EltVT.getSizeInBits() == 32) &&
5086       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5087     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5088     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5089     SDValue ResNode =
5090         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5091                                 LDBase->getPointerInfo(),
5092                                 LDBase->getAlignment(),
5093                                 false/*isVolatile*/, true/*ReadMem*/,
5094                                 false/*WriteMem*/);
5095
5096     // Make sure the newly-created LOAD is in the same position as LDBase in
5097     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5098     // update uses of LDBase's output chain to use the TokenFactor.
5099     if (LDBase->hasAnyUseOfValue(1)) {
5100       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5101                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5102       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5103       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5104                              SDValue(ResNode.getNode(), 1));
5105     }
5106
5107     return DAG.getBitcast(VT, ResNode);
5108   }
5109   return SDValue();
5110 }
5111
5112 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5113 /// to generate a splat value for the following cases:
5114 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5115 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5116 /// a scalar load, or a constant.
5117 /// The VBROADCAST node is returned when a pattern is found,
5118 /// or SDValue() otherwise.
5119 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5120                                     SelectionDAG &DAG) {
5121   // VBROADCAST requires AVX.
5122   // TODO: Splats could be generated for non-AVX CPUs using SSE
5123   // instructions, but there's less potential gain for only 128-bit vectors.
5124   if (!Subtarget->hasAVX())
5125     return SDValue();
5126
5127   MVT VT = Op.getSimpleValueType();
5128   SDLoc dl(Op);
5129
5130   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5131          "Unsupported vector type for broadcast.");
5132
5133   SDValue Ld;
5134   bool ConstSplatVal;
5135
5136   switch (Op.getOpcode()) {
5137     default:
5138       // Unknown pattern found.
5139       return SDValue();
5140
5141     case ISD::BUILD_VECTOR: {
5142       auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
5143       BitVector UndefElements;
5144       SDValue Splat = BVOp->getSplatValue(&UndefElements);
5145
5146       // We need a splat of a single value to use broadcast, and it doesn't
5147       // make any sense if the value is only in one element of the vector.
5148       if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
5149         return SDValue();
5150
5151       Ld = Splat;
5152       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5153                        Ld.getOpcode() == ISD::ConstantFP);
5154
5155       // Make sure that all of the users of a non-constant load are from the
5156       // BUILD_VECTOR node.
5157       if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
5158         return SDValue();
5159       break;
5160     }
5161
5162     case ISD::VECTOR_SHUFFLE: {
5163       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5164
5165       // Shuffles must have a splat mask where the first element is
5166       // broadcasted.
5167       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5168         return SDValue();
5169
5170       SDValue Sc = Op.getOperand(0);
5171       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5172           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5173
5174         if (!Subtarget->hasInt256())
5175           return SDValue();
5176
5177         // Use the register form of the broadcast instruction available on AVX2.
5178         if (VT.getSizeInBits() >= 256)
5179           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5180         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5181       }
5182
5183       Ld = Sc.getOperand(0);
5184       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5185                        Ld.getOpcode() == ISD::ConstantFP);
5186
5187       // The scalar_to_vector node and the suspected
5188       // load node must have exactly one user.
5189       // Constants may have multiple users.
5190
5191       // AVX-512 has register version of the broadcast
5192       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5193         Ld.getValueType().getSizeInBits() >= 32;
5194       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5195           !hasRegVer))
5196         return SDValue();
5197       break;
5198     }
5199   }
5200
5201   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5202   bool IsGE256 = (VT.getSizeInBits() >= 256);
5203
5204   // When optimizing for size, generate up to 5 extra bytes for a broadcast
5205   // instruction to save 8 or more bytes of constant pool data.
5206   // TODO: If multiple splats are generated to load the same constant,
5207   // it may be detrimental to overall size. There needs to be a way to detect
5208   // that condition to know if this is truly a size win.
5209   const Function *F = DAG.getMachineFunction().getFunction();
5210   bool OptForSize = F->hasFnAttribute(Attribute::OptimizeForSize);
5211
5212   // Handle broadcasting a single constant scalar from the constant pool
5213   // into a vector.
5214   // On Sandybridge (no AVX2), it is still better to load a constant vector
5215   // from the constant pool and not to broadcast it from a scalar.
5216   // But override that restriction when optimizing for size.
5217   // TODO: Check if splatting is recommended for other AVX-capable CPUs.
5218   if (ConstSplatVal && (Subtarget->hasAVX2() || OptForSize)) {
5219     EVT CVT = Ld.getValueType();
5220     assert(!CVT.isVector() && "Must not broadcast a vector type");
5221
5222     // Splat f32, i32, v4f64, v4i64 in all cases with AVX2.
5223     // For size optimization, also splat v2f64 and v2i64, and for size opt
5224     // with AVX2, also splat i8 and i16.
5225     // With pattern matching, the VBROADCAST node may become a VMOVDDUP.
5226     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5227         (OptForSize && (ScalarSize == 64 || Subtarget->hasAVX2()))) {
5228       const Constant *C = nullptr;
5229       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5230         C = CI->getConstantIntValue();
5231       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5232         C = CF->getConstantFPValue();
5233
5234       assert(C && "Invalid constant type");
5235
5236       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5237       SDValue CP =
5238           DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
5239       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5240       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5241                        MachinePointerInfo::getConstantPool(),
5242                        false, false, false, Alignment);
5243
5244       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5245     }
5246   }
5247
5248   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5249
5250   // Handle AVX2 in-register broadcasts.
5251   if (!IsLoad && Subtarget->hasInt256() &&
5252       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5253     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5254
5255   // The scalar source must be a normal load.
5256   if (!IsLoad)
5257     return SDValue();
5258
5259   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5260       (Subtarget->hasVLX() && ScalarSize == 64))
5261     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5262
5263   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5264   // double since there is no vbroadcastsd xmm
5265   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5266     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5267       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5268   }
5269
5270   // Unsupported broadcast.
5271   return SDValue();
5272 }
5273
5274 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5275 /// underlying vector and index.
5276 ///
5277 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5278 /// index.
5279 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5280                                          SDValue ExtIdx) {
5281   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5282   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5283     return Idx;
5284
5285   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5286   // lowered this:
5287   //   (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5288   // to:
5289   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
5290   //                           (extract_subvector (v8f32 %vreg0), Constant<4>),
5291   //                           undef)
5292   //                       Constant<0>)
5293   // In this case the vector is the extract_subvector expression and the index
5294   // is 2, as specified by the shuffle.
5295   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5296   SDValue ShuffleVec = SVOp->getOperand(0);
5297   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5298   assert(ShuffleVecVT.getVectorElementType() ==
5299          ExtractedFromVec.getSimpleValueType().getVectorElementType());
5300
5301   int ShuffleIdx = SVOp->getMaskElt(Idx);
5302   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5303     ExtractedFromVec = ShuffleVec;
5304     return ShuffleIdx;
5305   }
5306   return Idx;
5307 }
5308
5309 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5310   MVT VT = Op.getSimpleValueType();
5311
5312   // Skip if insert_vec_elt is not supported.
5313   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5314   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5315     return SDValue();
5316
5317   SDLoc DL(Op);
5318   unsigned NumElems = Op.getNumOperands();
5319
5320   SDValue VecIn1;
5321   SDValue VecIn2;
5322   SmallVector<unsigned, 4> InsertIndices;
5323   SmallVector<int, 8> Mask(NumElems, -1);
5324
5325   for (unsigned i = 0; i != NumElems; ++i) {
5326     unsigned Opc = Op.getOperand(i).getOpcode();
5327
5328     if (Opc == ISD::UNDEF)
5329       continue;
5330
5331     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5332       // Quit if more than 1 elements need inserting.
5333       if (InsertIndices.size() > 1)
5334         return SDValue();
5335
5336       InsertIndices.push_back(i);
5337       continue;
5338     }
5339
5340     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5341     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5342     // Quit if non-constant index.
5343     if (!isa<ConstantSDNode>(ExtIdx))
5344       return SDValue();
5345     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5346
5347     // Quit if extracted from vector of different type.
5348     if (ExtractedFromVec.getValueType() != VT)
5349       return SDValue();
5350
5351     if (!VecIn1.getNode())
5352       VecIn1 = ExtractedFromVec;
5353     else if (VecIn1 != ExtractedFromVec) {
5354       if (!VecIn2.getNode())
5355         VecIn2 = ExtractedFromVec;
5356       else if (VecIn2 != ExtractedFromVec)
5357         // Quit if more than 2 vectors to shuffle
5358         return SDValue();
5359     }
5360
5361     if (ExtractedFromVec == VecIn1)
5362       Mask[i] = Idx;
5363     else if (ExtractedFromVec == VecIn2)
5364       Mask[i] = Idx + NumElems;
5365   }
5366
5367   if (!VecIn1.getNode())
5368     return SDValue();
5369
5370   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5371   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5372   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5373     unsigned Idx = InsertIndices[i];
5374     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5375                      DAG.getIntPtrConstant(Idx, DL));
5376   }
5377
5378   return NV;
5379 }
5380
5381 static SDValue ConvertI1VectorToInteger(SDValue Op, SelectionDAG &DAG) {
5382   assert(ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
5383          Op.getScalarValueSizeInBits() == 1 &&
5384          "Can not convert non-constant vector");
5385   uint64_t Immediate = 0;
5386   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5387     SDValue In = Op.getOperand(idx);
5388     if (In.getOpcode() != ISD::UNDEF)
5389       Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5390   }
5391   SDLoc dl(Op);
5392   MVT VT =
5393    MVT::getIntegerVT(std::max((int)Op.getValueType().getSizeInBits(), 8));
5394   return DAG.getConstant(Immediate, dl, VT);
5395 }
5396 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5397 SDValue
5398 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5399
5400   MVT VT = Op.getSimpleValueType();
5401   assert((VT.getVectorElementType() == MVT::i1) &&
5402          "Unexpected type in LowerBUILD_VECTORvXi1!");
5403
5404   SDLoc dl(Op);
5405   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5406     SDValue Cst = DAG.getTargetConstant(0, dl, MVT::i1);
5407     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5408     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5409   }
5410
5411   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5412     SDValue Cst = DAG.getTargetConstant(1, dl, MVT::i1);
5413     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5414     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5415   }
5416
5417   if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
5418     SDValue Imm = ConvertI1VectorToInteger(Op, DAG);
5419     if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5420       return DAG.getBitcast(VT, Imm);
5421     SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5422     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5423                         DAG.getIntPtrConstant(0, dl));
5424   }
5425
5426   // Vector has one or more non-const elements
5427   uint64_t Immediate = 0;
5428   SmallVector<unsigned, 16> NonConstIdx;
5429   bool IsSplat = true;
5430   bool HasConstElts = false;
5431   int SplatIdx = -1;
5432   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5433     SDValue In = Op.getOperand(idx);
5434     if (In.getOpcode() == ISD::UNDEF)
5435       continue;
5436     if (!isa<ConstantSDNode>(In))
5437       NonConstIdx.push_back(idx);
5438     else {
5439       Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5440       HasConstElts = true;
5441     }
5442     if (SplatIdx == -1)
5443       SplatIdx = idx;
5444     else if (In != Op.getOperand(SplatIdx))
5445       IsSplat = false;
5446   }
5447
5448   // for splat use " (select i1 splat_elt, all-ones, all-zeroes)"
5449   if (IsSplat)
5450     return DAG.getNode(ISD::SELECT, dl, VT, Op.getOperand(SplatIdx),
5451                        DAG.getConstant(1, dl, VT),
5452                        DAG.getConstant(0, dl, VT));
5453
5454   // insert elements one by one
5455   SDValue DstVec;
5456   SDValue Imm;
5457   if (Immediate) {
5458     MVT ImmVT = MVT::getIntegerVT(std::max((int)VT.getSizeInBits(), 8));
5459     Imm = DAG.getConstant(Immediate, dl, ImmVT);
5460   }
5461   else if (HasConstElts)
5462     Imm = DAG.getConstant(0, dl, VT);
5463   else
5464     Imm = DAG.getUNDEF(VT);
5465   if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5466     DstVec = DAG.getBitcast(VT, Imm);
5467   else {
5468     SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5469     DstVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5470                          DAG.getIntPtrConstant(0, dl));
5471   }
5472
5473   for (unsigned i = 0; i < NonConstIdx.size(); ++i) {
5474     unsigned InsertIdx = NonConstIdx[i];
5475     DstVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5476                          Op.getOperand(InsertIdx),
5477                          DAG.getIntPtrConstant(InsertIdx, dl));
5478   }
5479   return DstVec;
5480 }
5481
5482 /// \brief Return true if \p N implements a horizontal binop and return the
5483 /// operands for the horizontal binop into V0 and V1.
5484 ///
5485 /// This is a helper function of LowerToHorizontalOp().
5486 /// This function checks that the build_vector \p N in input implements a
5487 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
5488 /// operation to match.
5489 /// For example, if \p Opcode is equal to ISD::ADD, then this function
5490 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
5491 /// is equal to ISD::SUB, then this function checks if this is a horizontal
5492 /// arithmetic sub.
5493 ///
5494 /// This function only analyzes elements of \p N whose indices are
5495 /// in range [BaseIdx, LastIdx).
5496 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
5497                               SelectionDAG &DAG,
5498                               unsigned BaseIdx, unsigned LastIdx,
5499                               SDValue &V0, SDValue &V1) {
5500   EVT VT = N->getValueType(0);
5501
5502   assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
5503   assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
5504          "Invalid Vector in input!");
5505
5506   bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
5507   bool CanFold = true;
5508   unsigned ExpectedVExtractIdx = BaseIdx;
5509   unsigned NumElts = LastIdx - BaseIdx;
5510   V0 = DAG.getUNDEF(VT);
5511   V1 = DAG.getUNDEF(VT);
5512
5513   // Check if N implements a horizontal binop.
5514   for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
5515     SDValue Op = N->getOperand(i + BaseIdx);
5516
5517     // Skip UNDEFs.
5518     if (Op->getOpcode() == ISD::UNDEF) {
5519       // Update the expected vector extract index.
5520       if (i * 2 == NumElts)
5521         ExpectedVExtractIdx = BaseIdx;
5522       ExpectedVExtractIdx += 2;
5523       continue;
5524     }
5525
5526     CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
5527
5528     if (!CanFold)
5529       break;
5530
5531     SDValue Op0 = Op.getOperand(0);
5532     SDValue Op1 = Op.getOperand(1);
5533
5534     // Try to match the following pattern:
5535     // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
5536     CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5537         Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5538         Op0.getOperand(0) == Op1.getOperand(0) &&
5539         isa<ConstantSDNode>(Op0.getOperand(1)) &&
5540         isa<ConstantSDNode>(Op1.getOperand(1)));
5541     if (!CanFold)
5542       break;
5543
5544     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5545     unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
5546
5547     if (i * 2 < NumElts) {
5548       if (V0.getOpcode() == ISD::UNDEF) {
5549         V0 = Op0.getOperand(0);
5550         if (V0.getValueType() != VT)
5551           return false;
5552       }
5553     } else {
5554       if (V1.getOpcode() == ISD::UNDEF) {
5555         V1 = Op0.getOperand(0);
5556         if (V1.getValueType() != VT)
5557           return false;
5558       }
5559       if (i * 2 == NumElts)
5560         ExpectedVExtractIdx = BaseIdx;
5561     }
5562
5563     SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
5564     if (I0 == ExpectedVExtractIdx)
5565       CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
5566     else if (IsCommutable && I1 == ExpectedVExtractIdx) {
5567       // Try to match the following dag sequence:
5568       // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
5569       CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
5570     } else
5571       CanFold = false;
5572
5573     ExpectedVExtractIdx += 2;
5574   }
5575
5576   return CanFold;
5577 }
5578
5579 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
5580 /// a concat_vector.
5581 ///
5582 /// This is a helper function of LowerToHorizontalOp().
5583 /// This function expects two 256-bit vectors called V0 and V1.
5584 /// At first, each vector is split into two separate 128-bit vectors.
5585 /// Then, the resulting 128-bit vectors are used to implement two
5586 /// horizontal binary operations.
5587 ///
5588 /// The kind of horizontal binary operation is defined by \p X86Opcode.
5589 ///
5590 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
5591 /// the two new horizontal binop.
5592 /// When Mode is set, the first horizontal binop dag node would take as input
5593 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
5594 /// horizontal binop dag node would take as input the lower 128-bit of V1
5595 /// and the upper 128-bit of V1.
5596 ///   Example:
5597 ///     HADD V0_LO, V0_HI
5598 ///     HADD V1_LO, V1_HI
5599 ///
5600 /// Otherwise, the first horizontal binop dag node takes as input the lower
5601 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
5602 /// dag node takes the upper 128-bit of V0 and the upper 128-bit of V1.
5603 ///   Example:
5604 ///     HADD V0_LO, V1_LO
5605 ///     HADD V0_HI, V1_HI
5606 ///
5607 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
5608 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
5609 /// the upper 128-bits of the result.
5610 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
5611                                      SDLoc DL, SelectionDAG &DAG,
5612                                      unsigned X86Opcode, bool Mode,
5613                                      bool isUndefLO, bool isUndefHI) {
5614   EVT VT = V0.getValueType();
5615   assert(VT.is256BitVector() && VT == V1.getValueType() &&
5616          "Invalid nodes in input!");
5617
5618   unsigned NumElts = VT.getVectorNumElements();
5619   SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
5620   SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
5621   SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
5622   SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
5623   EVT NewVT = V0_LO.getValueType();
5624
5625   SDValue LO = DAG.getUNDEF(NewVT);
5626   SDValue HI = DAG.getUNDEF(NewVT);
5627
5628   if (Mode) {
5629     // Don't emit a horizontal binop if the result is expected to be UNDEF.
5630     if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
5631       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
5632     if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
5633       HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
5634   } else {
5635     // Don't emit a horizontal binop if the result is expected to be UNDEF.
5636     if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
5637                        V1_LO->getOpcode() != ISD::UNDEF))
5638       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
5639
5640     if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
5641                        V1_HI->getOpcode() != ISD::UNDEF))
5642       HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
5643   }
5644
5645   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
5646 }
5647
5648 /// Try to fold a build_vector that performs an 'addsub' to an X86ISD::ADDSUB
5649 /// node.
5650 static SDValue LowerToAddSub(const BuildVectorSDNode *BV,
5651                              const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5652   EVT VT = BV->getValueType(0);
5653   if ((!Subtarget->hasSSE3() || (VT != MVT::v4f32 && VT != MVT::v2f64)) &&
5654       (!Subtarget->hasAVX() || (VT != MVT::v8f32 && VT != MVT::v4f64)))
5655     return SDValue();
5656
5657   SDLoc DL(BV);
5658   unsigned NumElts = VT.getVectorNumElements();
5659   SDValue InVec0 = DAG.getUNDEF(VT);
5660   SDValue InVec1 = DAG.getUNDEF(VT);
5661
5662   assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
5663           VT == MVT::v2f64) && "build_vector with an invalid type found!");
5664
5665   // Odd-numbered elements in the input build vector are obtained from
5666   // adding two integer/float elements.
5667   // Even-numbered elements in the input build vector are obtained from
5668   // subtracting two integer/float elements.
5669   unsigned ExpectedOpcode = ISD::FSUB;
5670   unsigned NextExpectedOpcode = ISD::FADD;
5671   bool AddFound = false;
5672   bool SubFound = false;
5673
5674   for (unsigned i = 0, e = NumElts; i != e; ++i) {
5675     SDValue Op = BV->getOperand(i);
5676
5677     // Skip 'undef' values.
5678     unsigned Opcode = Op.getOpcode();
5679     if (Opcode == ISD::UNDEF) {
5680       std::swap(ExpectedOpcode, NextExpectedOpcode);
5681       continue;
5682     }
5683
5684     // Early exit if we found an unexpected opcode.
5685     if (Opcode != ExpectedOpcode)
5686       return SDValue();
5687
5688     SDValue Op0 = Op.getOperand(0);
5689     SDValue Op1 = Op.getOperand(1);
5690
5691     // Try to match the following pattern:
5692     // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
5693     // Early exit if we cannot match that sequence.
5694     if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5695         Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5696         !isa<ConstantSDNode>(Op0.getOperand(1)) ||
5697         !isa<ConstantSDNode>(Op1.getOperand(1)) ||
5698         Op0.getOperand(1) != Op1.getOperand(1))
5699       return SDValue();
5700
5701     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5702     if (I0 != i)
5703       return SDValue();
5704
5705     // We found a valid add/sub node. Update the information accordingly.
5706     if (i & 1)
5707       AddFound = true;
5708     else
5709       SubFound = true;
5710
5711     // Update InVec0 and InVec1.
5712     if (InVec0.getOpcode() == ISD::UNDEF) {
5713       InVec0 = Op0.getOperand(0);
5714       if (InVec0.getValueType() != VT)
5715         return SDValue();
5716     }
5717     if (InVec1.getOpcode() == ISD::UNDEF) {
5718       InVec1 = Op1.getOperand(0);
5719       if (InVec1.getValueType() != VT)
5720         return SDValue();
5721     }
5722
5723     // Make sure that operands in input to each add/sub node always
5724     // come from a same pair of vectors.
5725     if (InVec0 != Op0.getOperand(0)) {
5726       if (ExpectedOpcode == ISD::FSUB)
5727         return SDValue();
5728
5729       // FADD is commutable. Try to commute the operands
5730       // and then test again.
5731       std::swap(Op0, Op1);
5732       if (InVec0 != Op0.getOperand(0))
5733         return SDValue();
5734     }
5735
5736     if (InVec1 != Op1.getOperand(0))
5737       return SDValue();
5738
5739     // Update the pair of expected opcodes.
5740     std::swap(ExpectedOpcode, NextExpectedOpcode);
5741   }
5742
5743   // Don't try to fold this build_vector into an ADDSUB if the inputs are undef.
5744   if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
5745       InVec1.getOpcode() != ISD::UNDEF)
5746     return DAG.getNode(X86ISD::ADDSUB, DL, VT, InVec0, InVec1);
5747
5748   return SDValue();
5749 }
5750
5751 /// Lower BUILD_VECTOR to a horizontal add/sub operation if possible.
5752 static SDValue LowerToHorizontalOp(const BuildVectorSDNode *BV,
5753                                    const X86Subtarget *Subtarget,
5754                                    SelectionDAG &DAG) {
5755   EVT VT = BV->getValueType(0);
5756   unsigned NumElts = VT.getVectorNumElements();
5757   unsigned NumUndefsLO = 0;
5758   unsigned NumUndefsHI = 0;
5759   unsigned Half = NumElts/2;
5760
5761   // Count the number of UNDEF operands in the build_vector in input.
5762   for (unsigned i = 0, e = Half; i != e; ++i)
5763     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5764       NumUndefsLO++;
5765
5766   for (unsigned i = Half, e = NumElts; i != e; ++i)
5767     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5768       NumUndefsHI++;
5769
5770   // Early exit if this is either a build_vector of all UNDEFs or all the
5771   // operands but one are UNDEF.
5772   if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
5773     return SDValue();
5774
5775   SDLoc DL(BV);
5776   SDValue InVec0, InVec1;
5777   if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
5778     // Try to match an SSE3 float HADD/HSUB.
5779     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5780       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5781
5782     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5783       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5784   } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
5785     // Try to match an SSSE3 integer HADD/HSUB.
5786     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5787       return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
5788
5789     if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5790       return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
5791   }
5792
5793   if (!Subtarget->hasAVX())
5794     return SDValue();
5795
5796   if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
5797     // Try to match an AVX horizontal add/sub of packed single/double
5798     // precision floating point values from 256-bit vectors.
5799     SDValue InVec2, InVec3;
5800     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
5801         isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
5802         ((InVec0.getOpcode() == ISD::UNDEF ||
5803           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5804         ((InVec1.getOpcode() == ISD::UNDEF ||
5805           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5806       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5807
5808     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
5809         isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
5810         ((InVec0.getOpcode() == ISD::UNDEF ||
5811           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5812         ((InVec1.getOpcode() == ISD::UNDEF ||
5813           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5814       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5815   } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
5816     // Try to match an AVX2 horizontal add/sub of signed integers.
5817     SDValue InVec2, InVec3;
5818     unsigned X86Opcode;
5819     bool CanFold = true;
5820
5821     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
5822         isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
5823         ((InVec0.getOpcode() == ISD::UNDEF ||
5824           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5825         ((InVec1.getOpcode() == ISD::UNDEF ||
5826           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5827       X86Opcode = X86ISD::HADD;
5828     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
5829         isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
5830         ((InVec0.getOpcode() == ISD::UNDEF ||
5831           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5832         ((InVec1.getOpcode() == ISD::UNDEF ||
5833           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5834       X86Opcode = X86ISD::HSUB;
5835     else
5836       CanFold = false;
5837
5838     if (CanFold) {
5839       // Fold this build_vector into a single horizontal add/sub.
5840       // Do this only if the target has AVX2.
5841       if (Subtarget->hasAVX2())
5842         return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
5843
5844       // Do not try to expand this build_vector into a pair of horizontal
5845       // add/sub if we can emit a pair of scalar add/sub.
5846       if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5847         return SDValue();
5848
5849       // Convert this build_vector into a pair of horizontal binop followed by
5850       // a concat vector.
5851       bool isUndefLO = NumUndefsLO == Half;
5852       bool isUndefHI = NumUndefsHI == Half;
5853       return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
5854                                    isUndefLO, isUndefHI);
5855     }
5856   }
5857
5858   if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
5859        VT == MVT::v16i16) && Subtarget->hasAVX()) {
5860     unsigned X86Opcode;
5861     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5862       X86Opcode = X86ISD::HADD;
5863     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5864       X86Opcode = X86ISD::HSUB;
5865     else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5866       X86Opcode = X86ISD::FHADD;
5867     else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5868       X86Opcode = X86ISD::FHSUB;
5869     else
5870       return SDValue();
5871
5872     // Don't try to expand this build_vector into a pair of horizontal add/sub
5873     // if we can simply emit a pair of scalar add/sub.
5874     if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5875       return SDValue();
5876
5877     // Convert this build_vector into two horizontal add/sub followed by
5878     // a concat vector.
5879     bool isUndefLO = NumUndefsLO == Half;
5880     bool isUndefHI = NumUndefsHI == Half;
5881     return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
5882                                  isUndefLO, isUndefHI);
5883   }
5884
5885   return SDValue();
5886 }
5887
5888 SDValue
5889 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5890   SDLoc dl(Op);
5891
5892   MVT VT = Op.getSimpleValueType();
5893   MVT ExtVT = VT.getVectorElementType();
5894   unsigned NumElems = Op.getNumOperands();
5895
5896   // Generate vectors for predicate vectors.
5897   if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
5898     return LowerBUILD_VECTORvXi1(Op, DAG);
5899
5900   // Vectors containing all zeros can be matched by pxor and xorps later
5901   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5902     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5903     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5904     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
5905       return Op;
5906
5907     return getZeroVector(VT, Subtarget, DAG, dl);
5908   }
5909
5910   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5911   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5912   // vpcmpeqd on 256-bit vectors.
5913   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5914     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5915       return Op;
5916
5917     if (!VT.is512BitVector())
5918       return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5919   }
5920
5921   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(Op.getNode());
5922   if (SDValue AddSub = LowerToAddSub(BV, Subtarget, DAG))
5923     return AddSub;
5924   if (SDValue HorizontalOp = LowerToHorizontalOp(BV, Subtarget, DAG))
5925     return HorizontalOp;
5926   if (SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG))
5927     return Broadcast;
5928
5929   unsigned EVTBits = ExtVT.getSizeInBits();
5930
5931   unsigned NumZero  = 0;
5932   unsigned NumNonZero = 0;
5933   unsigned NonZeros = 0;
5934   bool IsAllConstants = true;
5935   SmallSet<SDValue, 8> Values;
5936   for (unsigned i = 0; i < NumElems; ++i) {
5937     SDValue Elt = Op.getOperand(i);
5938     if (Elt.getOpcode() == ISD::UNDEF)
5939       continue;
5940     Values.insert(Elt);
5941     if (Elt.getOpcode() != ISD::Constant &&
5942         Elt.getOpcode() != ISD::ConstantFP)
5943       IsAllConstants = false;
5944     if (X86::isZeroNode(Elt))
5945       NumZero++;
5946     else {
5947       NonZeros |= (1 << i);
5948       NumNonZero++;
5949     }
5950   }
5951
5952   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5953   if (NumNonZero == 0)
5954     return DAG.getUNDEF(VT);
5955
5956   // Special case for single non-zero, non-undef, element.
5957   if (NumNonZero == 1) {
5958     unsigned Idx = countTrailingZeros(NonZeros);
5959     SDValue Item = Op.getOperand(Idx);
5960
5961     // If this is an insertion of an i64 value on x86-32, and if the top bits of
5962     // the value are obviously zero, truncate the value to i32 and do the
5963     // insertion that way.  Only do this if the value is non-constant or if the
5964     // value is a constant being inserted into element 0.  It is cheaper to do
5965     // a constant pool load than it is to do a movd + shuffle.
5966     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5967         (!IsAllConstants || Idx == 0)) {
5968       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5969         // Handle SSE only.
5970         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5971         EVT VecVT = MVT::v4i32;
5972
5973         // Truncate the value (which may itself be a constant) to i32, and
5974         // convert it to a vector with movd (S2V+shuffle to zero extend).
5975         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5976         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5977         return DAG.getBitcast(VT, getShuffleVectorZeroOrUndef(
5978                                       Item, Idx * 2, true, Subtarget, DAG));
5979       }
5980     }
5981
5982     // If we have a constant or non-constant insertion into the low element of
5983     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5984     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5985     // depending on what the source datatype is.
5986     if (Idx == 0) {
5987       if (NumZero == 0)
5988         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5989
5990       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5991           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5992         if (VT.is512BitVector()) {
5993           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5994           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5995                              Item, DAG.getIntPtrConstant(0, dl));
5996         }
5997         assert((VT.is128BitVector() || VT.is256BitVector()) &&
5998                "Expected an SSE value type!");
5999         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6000         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6001         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6002       }
6003
6004       // We can't directly insert an i8 or i16 into a vector, so zero extend
6005       // it to i32 first.
6006       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6007         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6008         if (VT.is256BitVector()) {
6009           if (Subtarget->hasAVX()) {
6010             Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v8i32, Item);
6011             Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6012           } else {
6013             // Without AVX, we need to extend to a 128-bit vector and then
6014             // insert into the 256-bit vector.
6015             Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6016             SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6017             Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6018           }
6019         } else {
6020           assert(VT.is128BitVector() && "Expected an SSE value type!");
6021           Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6022           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6023         }
6024         return DAG.getBitcast(VT, Item);
6025       }
6026     }
6027
6028     // Is it a vector logical left shift?
6029     if (NumElems == 2 && Idx == 1 &&
6030         X86::isZeroNode(Op.getOperand(0)) &&
6031         !X86::isZeroNode(Op.getOperand(1))) {
6032       unsigned NumBits = VT.getSizeInBits();
6033       return getVShift(true, VT,
6034                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6035                                    VT, Op.getOperand(1)),
6036                        NumBits/2, DAG, *this, dl);
6037     }
6038
6039     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6040       return SDValue();
6041
6042     // Otherwise, if this is a vector with i32 or f32 elements, and the element
6043     // is a non-constant being inserted into an element other than the low one,
6044     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
6045     // movd/movss) to move this into the low element, then shuffle it into
6046     // place.
6047     if (EVTBits == 32) {
6048       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6049       return getShuffleVectorZeroOrUndef(Item, Idx, NumZero > 0, Subtarget, DAG);
6050     }
6051   }
6052
6053   // Splat is obviously ok. Let legalizer expand it to a shuffle.
6054   if (Values.size() == 1) {
6055     if (EVTBits == 32) {
6056       // Instead of a shuffle like this:
6057       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6058       // Check if it's possible to issue this instead.
6059       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6060       unsigned Idx = countTrailingZeros(NonZeros);
6061       SDValue Item = Op.getOperand(Idx);
6062       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6063         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6064     }
6065     return SDValue();
6066   }
6067
6068   // A vector full of immediates; various special cases are already
6069   // handled, so this is best done with a single constant-pool load.
6070   if (IsAllConstants)
6071     return SDValue();
6072
6073   // For AVX-length vectors, see if we can use a vector load to get all of the
6074   // elements, otherwise build the individual 128-bit pieces and use
6075   // shuffles to put them in place.
6076   if (VT.is256BitVector() || VT.is512BitVector()) {
6077     SmallVector<SDValue, 64> V(Op->op_begin(), Op->op_begin() + NumElems);
6078
6079     // Check for a build vector of consecutive loads.
6080     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6081       return LD;
6082
6083     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6084
6085     // Build both the lower and upper subvector.
6086     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6087                                 makeArrayRef(&V[0], NumElems/2));
6088     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6089                                 makeArrayRef(&V[NumElems / 2], NumElems/2));
6090
6091     // Recreate the wider vector with the lower and upper part.
6092     if (VT.is256BitVector())
6093       return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6094     return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6095   }
6096
6097   // Let legalizer expand 2-wide build_vectors.
6098   if (EVTBits == 64) {
6099     if (NumNonZero == 1) {
6100       // One half is zero or undef.
6101       unsigned Idx = countTrailingZeros(NonZeros);
6102       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6103                                  Op.getOperand(Idx));
6104       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6105     }
6106     return SDValue();
6107   }
6108
6109   // If element VT is < 32 bits, convert it to inserts into a zero vector.
6110   if (EVTBits == 8 && NumElems == 16)
6111     if (SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6112                                         Subtarget, *this))
6113       return V;
6114
6115   if (EVTBits == 16 && NumElems == 8)
6116     if (SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6117                                       Subtarget, *this))
6118       return V;
6119
6120   // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6121   if (EVTBits == 32 && NumElems == 4)
6122     if (SDValue V = LowerBuildVectorv4x32(Op, DAG, Subtarget, *this))
6123       return V;
6124
6125   // If element VT is == 32 bits, turn it into a number of shuffles.
6126   SmallVector<SDValue, 8> V(NumElems);
6127   if (NumElems == 4 && NumZero > 0) {
6128     for (unsigned i = 0; i < 4; ++i) {
6129       bool isZero = !(NonZeros & (1 << i));
6130       if (isZero)
6131         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6132       else
6133         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6134     }
6135
6136     for (unsigned i = 0; i < 2; ++i) {
6137       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6138         default: break;
6139         case 0:
6140           V[i] = V[i*2];  // Must be a zero vector.
6141           break;
6142         case 1:
6143           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6144           break;
6145         case 2:
6146           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6147           break;
6148         case 3:
6149           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6150           break;
6151       }
6152     }
6153
6154     bool Reverse1 = (NonZeros & 0x3) == 2;
6155     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6156     int MaskVec[] = {
6157       Reverse1 ? 1 : 0,
6158       Reverse1 ? 0 : 1,
6159       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6160       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
6161     };
6162     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6163   }
6164
6165   if (Values.size() > 1 && VT.is128BitVector()) {
6166     // Check for a build vector of consecutive loads.
6167     for (unsigned i = 0; i < NumElems; ++i)
6168       V[i] = Op.getOperand(i);
6169
6170     // Check for elements which are consecutive loads.
6171     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6172       return LD;
6173
6174     // Check for a build vector from mostly shuffle plus few inserting.
6175     if (SDValue Sh = buildFromShuffleMostly(Op, DAG))
6176       return Sh;
6177
6178     // For SSE 4.1, use insertps to put the high elements into the low element.
6179     if (Subtarget->hasSSE41()) {
6180       SDValue Result;
6181       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6182         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6183       else
6184         Result = DAG.getUNDEF(VT);
6185
6186       for (unsigned i = 1; i < NumElems; ++i) {
6187         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6188         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6189                              Op.getOperand(i), DAG.getIntPtrConstant(i, dl));
6190       }
6191       return Result;
6192     }
6193
6194     // Otherwise, expand into a number of unpckl*, start by extending each of
6195     // our (non-undef) elements to the full vector width with the element in the
6196     // bottom slot of the vector (which generates no code for SSE).
6197     for (unsigned i = 0; i < NumElems; ++i) {
6198       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6199         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6200       else
6201         V[i] = DAG.getUNDEF(VT);
6202     }
6203
6204     // Next, we iteratively mix elements, e.g. for v4f32:
6205     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6206     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6207     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
6208     unsigned EltStride = NumElems >> 1;
6209     while (EltStride != 0) {
6210       for (unsigned i = 0; i < EltStride; ++i) {
6211         // If V[i+EltStride] is undef and this is the first round of mixing,
6212         // then it is safe to just drop this shuffle: V[i] is already in the
6213         // right place, the one element (since it's the first round) being
6214         // inserted as undef can be dropped.  This isn't safe for successive
6215         // rounds because they will permute elements within both vectors.
6216         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6217             EltStride == NumElems/2)
6218           continue;
6219
6220         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6221       }
6222       EltStride >>= 1;
6223     }
6224     return V[0];
6225   }
6226   return SDValue();
6227 }
6228
6229 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6230 // to create 256-bit vectors from two other 128-bit ones.
6231 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6232   SDLoc dl(Op);
6233   MVT ResVT = Op.getSimpleValueType();
6234
6235   assert((ResVT.is256BitVector() ||
6236           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6237
6238   SDValue V1 = Op.getOperand(0);
6239   SDValue V2 = Op.getOperand(1);
6240   unsigned NumElems = ResVT.getVectorNumElements();
6241   if (ResVT.is256BitVector())
6242     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6243
6244   if (Op.getNumOperands() == 4) {
6245     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6246                                 ResVT.getVectorNumElements()/2);
6247     SDValue V3 = Op.getOperand(2);
6248     SDValue V4 = Op.getOperand(3);
6249     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6250       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6251   }
6252   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6253 }
6254
6255 static SDValue LowerCONCAT_VECTORSvXi1(SDValue Op,
6256                                        const X86Subtarget *Subtarget,
6257                                        SelectionDAG & DAG) {
6258   SDLoc dl(Op);
6259   MVT ResVT = Op.getSimpleValueType();
6260   unsigned NumOfOperands = Op.getNumOperands();
6261
6262   assert(isPowerOf2_32(NumOfOperands) &&
6263          "Unexpected number of operands in CONCAT_VECTORS");
6264
6265   if (NumOfOperands > 2) {
6266     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6267                                   ResVT.getVectorNumElements()/2);
6268     SmallVector<SDValue, 2> Ops;
6269     for (unsigned i = 0; i < NumOfOperands/2; i++)
6270       Ops.push_back(Op.getOperand(i));
6271     SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6272     Ops.clear();
6273     for (unsigned i = NumOfOperands/2; i < NumOfOperands; i++)
6274       Ops.push_back(Op.getOperand(i));
6275     SDValue Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6276     return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Lo, Hi);
6277   }
6278
6279   SDValue V1 = Op.getOperand(0);
6280   SDValue V2 = Op.getOperand(1);
6281   bool IsZeroV1 = ISD::isBuildVectorAllZeros(V1.getNode());
6282   bool IsZeroV2 = ISD::isBuildVectorAllZeros(V2.getNode());
6283
6284   if (IsZeroV1 && IsZeroV2)
6285     return getZeroVector(ResVT, Subtarget, DAG, dl);
6286
6287   SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
6288   SDValue Undef = DAG.getUNDEF(ResVT);
6289   unsigned NumElems = ResVT.getVectorNumElements();
6290   SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
6291
6292   V2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V2, ZeroIdx);
6293   V2 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V2, ShiftBits);
6294   if (IsZeroV1)
6295     return V2;
6296
6297   V1 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V1, ZeroIdx);
6298   // Zero the upper bits of V1
6299   V1 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V1, ShiftBits);
6300   V1 = DAG.getNode(X86ISD::VSRLI, dl, ResVT, V1, ShiftBits);
6301   if (IsZeroV2)
6302     return V1;
6303   return DAG.getNode(ISD::OR, dl, ResVT, V1, V2);
6304 }
6305
6306 static SDValue LowerCONCAT_VECTORS(SDValue Op,
6307                                    const X86Subtarget *Subtarget,
6308                                    SelectionDAG &DAG) {
6309   MVT VT = Op.getSimpleValueType();
6310   if (VT.getVectorElementType() == MVT::i1)
6311     return LowerCONCAT_VECTORSvXi1(Op, Subtarget, DAG);
6312
6313   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6314          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6315           Op.getNumOperands() == 4)));
6316
6317   // AVX can use the vinsertf128 instruction to create 256-bit vectors
6318   // from two other 128-bit ones.
6319
6320   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6321   return LowerAVXCONCAT_VECTORS(Op, DAG);
6322 }
6323
6324
6325 //===----------------------------------------------------------------------===//
6326 // Vector shuffle lowering
6327 //
6328 // This is an experimental code path for lowering vector shuffles on x86. It is
6329 // designed to handle arbitrary vector shuffles and blends, gracefully
6330 // degrading performance as necessary. It works hard to recognize idiomatic
6331 // shuffles and lower them to optimal instruction patterns without leaving
6332 // a framework that allows reasonably efficient handling of all vector shuffle
6333 // patterns.
6334 //===----------------------------------------------------------------------===//
6335
6336 /// \brief Tiny helper function to identify a no-op mask.
6337 ///
6338 /// This is a somewhat boring predicate function. It checks whether the mask
6339 /// array input, which is assumed to be a single-input shuffle mask of the kind
6340 /// used by the X86 shuffle instructions (not a fully general
6341 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
6342 /// in-place shuffle are 'no-op's.
6343 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
6344   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6345     if (Mask[i] != -1 && Mask[i] != i)
6346       return false;
6347   return true;
6348 }
6349
6350 /// \brief Helper function to classify a mask as a single-input mask.
6351 ///
6352 /// This isn't a generic single-input test because in the vector shuffle
6353 /// lowering we canonicalize single inputs to be the first input operand. This
6354 /// means we can more quickly test for a single input by only checking whether
6355 /// an input from the second operand exists. We also assume that the size of
6356 /// mask corresponds to the size of the input vectors which isn't true in the
6357 /// fully general case.
6358 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
6359   for (int M : Mask)
6360     if (M >= (int)Mask.size())
6361       return false;
6362   return true;
6363 }
6364
6365 /// \brief Test whether there are elements crossing 128-bit lanes in this
6366 /// shuffle mask.
6367 ///
6368 /// X86 divides up its shuffles into in-lane and cross-lane shuffle operations
6369 /// and we routinely test for these.
6370 static bool is128BitLaneCrossingShuffleMask(MVT VT, ArrayRef<int> Mask) {
6371   int LaneSize = 128 / VT.getScalarSizeInBits();
6372   int Size = Mask.size();
6373   for (int i = 0; i < Size; ++i)
6374     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
6375       return true;
6376   return false;
6377 }
6378
6379 /// \brief Test whether a shuffle mask is equivalent within each 128-bit lane.
6380 ///
6381 /// This checks a shuffle mask to see if it is performing the same
6382 /// 128-bit lane-relative shuffle in each 128-bit lane. This trivially implies
6383 /// that it is also not lane-crossing. It may however involve a blend from the
6384 /// same lane of a second vector.
6385 ///
6386 /// The specific repeated shuffle mask is populated in \p RepeatedMask, as it is
6387 /// non-trivial to compute in the face of undef lanes. The representation is
6388 /// *not* suitable for use with existing 128-bit shuffles as it will contain
6389 /// entries from both V1 and V2 inputs to the wider mask.
6390 static bool
6391 is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
6392                                 SmallVectorImpl<int> &RepeatedMask) {
6393   int LaneSize = 128 / VT.getScalarSizeInBits();
6394   RepeatedMask.resize(LaneSize, -1);
6395   int Size = Mask.size();
6396   for (int i = 0; i < Size; ++i) {
6397     if (Mask[i] < 0)
6398       continue;
6399     if ((Mask[i] % Size) / LaneSize != i / LaneSize)
6400       // This entry crosses lanes, so there is no way to model this shuffle.
6401       return false;
6402
6403     // Ok, handle the in-lane shuffles by detecting if and when they repeat.
6404     if (RepeatedMask[i % LaneSize] == -1)
6405       // This is the first non-undef entry in this slot of a 128-bit lane.
6406       RepeatedMask[i % LaneSize] =
6407           Mask[i] < Size ? Mask[i] % LaneSize : Mask[i] % LaneSize + Size;
6408     else if (RepeatedMask[i % LaneSize] + (i / LaneSize) * LaneSize != Mask[i])
6409       // Found a mismatch with the repeated mask.
6410       return false;
6411   }
6412   return true;
6413 }
6414
6415 /// \brief Checks whether a shuffle mask is equivalent to an explicit list of
6416 /// arguments.
6417 ///
6418 /// This is a fast way to test a shuffle mask against a fixed pattern:
6419 ///
6420 ///   if (isShuffleEquivalent(Mask, 3, 2, {1, 0})) { ... }
6421 ///
6422 /// It returns true if the mask is exactly as wide as the argument list, and
6423 /// each element of the mask is either -1 (signifying undef) or the value given
6424 /// in the argument.
6425 static bool isShuffleEquivalent(SDValue V1, SDValue V2, ArrayRef<int> Mask,
6426                                 ArrayRef<int> ExpectedMask) {
6427   if (Mask.size() != ExpectedMask.size())
6428     return false;
6429
6430   int Size = Mask.size();
6431
6432   // If the values are build vectors, we can look through them to find
6433   // equivalent inputs that make the shuffles equivalent.
6434   auto *BV1 = dyn_cast<BuildVectorSDNode>(V1);
6435   auto *BV2 = dyn_cast<BuildVectorSDNode>(V2);
6436
6437   for (int i = 0; i < Size; ++i)
6438     if (Mask[i] != -1 && Mask[i] != ExpectedMask[i]) {
6439       auto *MaskBV = Mask[i] < Size ? BV1 : BV2;
6440       auto *ExpectedBV = ExpectedMask[i] < Size ? BV1 : BV2;
6441       if (!MaskBV || !ExpectedBV ||
6442           MaskBV->getOperand(Mask[i] % Size) !=
6443               ExpectedBV->getOperand(ExpectedMask[i] % Size))
6444         return false;
6445     }
6446
6447   return true;
6448 }
6449
6450 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
6451 ///
6452 /// This helper function produces an 8-bit shuffle immediate corresponding to
6453 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
6454 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
6455 /// example.
6456 ///
6457 /// NB: We rely heavily on "undef" masks preserving the input lane.
6458 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask, SDLoc DL,
6459                                           SelectionDAG &DAG) {
6460   assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
6461   assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
6462   assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
6463   assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
6464   assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
6465
6466   unsigned Imm = 0;
6467   Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
6468   Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
6469   Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
6470   Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
6471   return DAG.getConstant(Imm, DL, MVT::i8);
6472 }
6473
6474 /// \brief Try to emit a blend instruction for a shuffle using bit math.
6475 ///
6476 /// This is used as a fallback approach when first class blend instructions are
6477 /// unavailable. Currently it is only suitable for integer vectors, but could
6478 /// be generalized for floating point vectors if desirable.
6479 static SDValue lowerVectorShuffleAsBitBlend(SDLoc DL, MVT VT, SDValue V1,
6480                                             SDValue V2, ArrayRef<int> Mask,
6481                                             SelectionDAG &DAG) {
6482   assert(VT.isInteger() && "Only supports integer vector types!");
6483   MVT EltVT = VT.getScalarType();
6484   int NumEltBits = EltVT.getSizeInBits();
6485   SDValue Zero = DAG.getConstant(0, DL, EltVT);
6486   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6487                                     EltVT);
6488   SmallVector<SDValue, 16> MaskOps;
6489   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6490     if (Mask[i] != -1 && Mask[i] != i && Mask[i] != i + Size)
6491       return SDValue(); // Shuffled input!
6492     MaskOps.push_back(Mask[i] < Size ? AllOnes : Zero);
6493   }
6494
6495   SDValue V1Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, MaskOps);
6496   V1 = DAG.getNode(ISD::AND, DL, VT, V1, V1Mask);
6497   // We have to cast V2 around.
6498   MVT MaskVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
6499   V2 = DAG.getBitcast(VT, DAG.getNode(X86ISD::ANDNP, DL, MaskVT,
6500                                       DAG.getBitcast(MaskVT, V1Mask),
6501                                       DAG.getBitcast(MaskVT, V2)));
6502   return DAG.getNode(ISD::OR, DL, VT, V1, V2);
6503 }
6504
6505 /// \brief Try to emit a blend instruction for a shuffle.
6506 ///
6507 /// This doesn't do any checks for the availability of instructions for blending
6508 /// these values. It relies on the availability of the X86ISD::BLENDI pattern to
6509 /// be matched in the backend with the type given. What it does check for is
6510 /// that the shuffle mask is in fact a blend.
6511 static SDValue lowerVectorShuffleAsBlend(SDLoc DL, MVT VT, SDValue V1,
6512                                          SDValue V2, ArrayRef<int> Mask,
6513                                          const X86Subtarget *Subtarget,
6514                                          SelectionDAG &DAG) {
6515   unsigned BlendMask = 0;
6516   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6517     if (Mask[i] >= Size) {
6518       if (Mask[i] != i + Size)
6519         return SDValue(); // Shuffled V2 input!
6520       BlendMask |= 1u << i;
6521       continue;
6522     }
6523     if (Mask[i] >= 0 && Mask[i] != i)
6524       return SDValue(); // Shuffled V1 input!
6525   }
6526   switch (VT.SimpleTy) {
6527   case MVT::v2f64:
6528   case MVT::v4f32:
6529   case MVT::v4f64:
6530   case MVT::v8f32:
6531     return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V2,
6532                        DAG.getConstant(BlendMask, DL, MVT::i8));
6533
6534   case MVT::v4i64:
6535   case MVT::v8i32:
6536     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6537     // FALLTHROUGH
6538   case MVT::v2i64:
6539   case MVT::v4i32:
6540     // If we have AVX2 it is faster to use VPBLENDD when the shuffle fits into
6541     // that instruction.
6542     if (Subtarget->hasAVX2()) {
6543       // Scale the blend by the number of 32-bit dwords per element.
6544       int Scale =  VT.getScalarSizeInBits() / 32;
6545       BlendMask = 0;
6546       for (int i = 0, Size = Mask.size(); i < Size; ++i)
6547         if (Mask[i] >= Size)
6548           for (int j = 0; j < Scale; ++j)
6549             BlendMask |= 1u << (i * Scale + j);
6550
6551       MVT BlendVT = VT.getSizeInBits() > 128 ? MVT::v8i32 : MVT::v4i32;
6552       V1 = DAG.getBitcast(BlendVT, V1);
6553       V2 = DAG.getBitcast(BlendVT, V2);
6554       return DAG.getBitcast(
6555           VT, DAG.getNode(X86ISD::BLENDI, DL, BlendVT, V1, V2,
6556                           DAG.getConstant(BlendMask, DL, MVT::i8)));
6557     }
6558     // FALLTHROUGH
6559   case MVT::v8i16: {
6560     // For integer shuffles we need to expand the mask and cast the inputs to
6561     // v8i16s prior to blending.
6562     int Scale = 8 / VT.getVectorNumElements();
6563     BlendMask = 0;
6564     for (int i = 0, Size = Mask.size(); i < Size; ++i)
6565       if (Mask[i] >= Size)
6566         for (int j = 0; j < Scale; ++j)
6567           BlendMask |= 1u << (i * Scale + j);
6568
6569     V1 = DAG.getBitcast(MVT::v8i16, V1);
6570     V2 = DAG.getBitcast(MVT::v8i16, V2);
6571     return DAG.getBitcast(VT,
6572                           DAG.getNode(X86ISD::BLENDI, DL, MVT::v8i16, V1, V2,
6573                                       DAG.getConstant(BlendMask, DL, MVT::i8)));
6574   }
6575
6576   case MVT::v16i16: {
6577     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6578     SmallVector<int, 8> RepeatedMask;
6579     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
6580       // We can lower these with PBLENDW which is mirrored across 128-bit lanes.
6581       assert(RepeatedMask.size() == 8 && "Repeated mask size doesn't match!");
6582       BlendMask = 0;
6583       for (int i = 0; i < 8; ++i)
6584         if (RepeatedMask[i] >= 16)
6585           BlendMask |= 1u << i;
6586       return DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
6587                          DAG.getConstant(BlendMask, DL, MVT::i8));
6588     }
6589   }
6590     // FALLTHROUGH
6591   case MVT::v16i8:
6592   case MVT::v32i8: {
6593     assert((VT.getSizeInBits() == 128 || Subtarget->hasAVX2()) &&
6594            "256-bit byte-blends require AVX2 support!");
6595
6596     // Scale the blend by the number of bytes per element.
6597     int Scale = VT.getScalarSizeInBits() / 8;
6598
6599     // This form of blend is always done on bytes. Compute the byte vector
6600     // type.
6601     MVT BlendVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
6602
6603     // Compute the VSELECT mask. Note that VSELECT is really confusing in the
6604     // mix of LLVM's code generator and the x86 backend. We tell the code
6605     // generator that boolean values in the elements of an x86 vector register
6606     // are -1 for true and 0 for false. We then use the LLVM semantics of 'true'
6607     // mapping a select to operand #1, and 'false' mapping to operand #2. The
6608     // reality in x86 is that vector masks (pre-AVX-512) use only the high bit
6609     // of the element (the remaining are ignored) and 0 in that high bit would
6610     // mean operand #1 while 1 in the high bit would mean operand #2. So while
6611     // the LLVM model for boolean values in vector elements gets the relevant
6612     // bit set, it is set backwards and over constrained relative to x86's
6613     // actual model.
6614     SmallVector<SDValue, 32> VSELECTMask;
6615     for (int i = 0, Size = Mask.size(); i < Size; ++i)
6616       for (int j = 0; j < Scale; ++j)
6617         VSELECTMask.push_back(
6618             Mask[i] < 0 ? DAG.getUNDEF(MVT::i8)
6619                         : DAG.getConstant(Mask[i] < Size ? -1 : 0, DL,
6620                                           MVT::i8));
6621
6622     V1 = DAG.getBitcast(BlendVT, V1);
6623     V2 = DAG.getBitcast(BlendVT, V2);
6624     return DAG.getBitcast(VT, DAG.getNode(ISD::VSELECT, DL, BlendVT,
6625                                           DAG.getNode(ISD::BUILD_VECTOR, DL,
6626                                                       BlendVT, VSELECTMask),
6627                                           V1, V2));
6628   }
6629
6630   default:
6631     llvm_unreachable("Not a supported integer vector type!");
6632   }
6633 }
6634
6635 /// \brief Try to lower as a blend of elements from two inputs followed by
6636 /// a single-input permutation.
6637 ///
6638 /// This matches the pattern where we can blend elements from two inputs and
6639 /// then reduce the shuffle to a single-input permutation.
6640 static SDValue lowerVectorShuffleAsBlendAndPermute(SDLoc DL, MVT VT, SDValue V1,
6641                                                    SDValue V2,
6642                                                    ArrayRef<int> Mask,
6643                                                    SelectionDAG &DAG) {
6644   // We build up the blend mask while checking whether a blend is a viable way
6645   // to reduce the shuffle.
6646   SmallVector<int, 32> BlendMask(Mask.size(), -1);
6647   SmallVector<int, 32> PermuteMask(Mask.size(), -1);
6648
6649   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6650     if (Mask[i] < 0)
6651       continue;
6652
6653     assert(Mask[i] < Size * 2 && "Shuffle input is out of bounds.");
6654
6655     if (BlendMask[Mask[i] % Size] == -1)
6656       BlendMask[Mask[i] % Size] = Mask[i];
6657     else if (BlendMask[Mask[i] % Size] != Mask[i])
6658       return SDValue(); // Can't blend in the needed input!
6659
6660     PermuteMask[i] = Mask[i] % Size;
6661   }
6662
6663   SDValue V = DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6664   return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), PermuteMask);
6665 }
6666
6667 /// \brief Generic routine to decompose a shuffle and blend into indepndent
6668 /// blends and permutes.
6669 ///
6670 /// This matches the extremely common pattern for handling combined
6671 /// shuffle+blend operations on newer X86 ISAs where we have very fast blend
6672 /// operations. It will try to pick the best arrangement of shuffles and
6673 /// blends.
6674 static SDValue lowerVectorShuffleAsDecomposedShuffleBlend(SDLoc DL, MVT VT,
6675                                                           SDValue V1,
6676                                                           SDValue V2,
6677                                                           ArrayRef<int> Mask,
6678                                                           SelectionDAG &DAG) {
6679   // Shuffle the input elements into the desired positions in V1 and V2 and
6680   // blend them together.
6681   SmallVector<int, 32> V1Mask(Mask.size(), -1);
6682   SmallVector<int, 32> V2Mask(Mask.size(), -1);
6683   SmallVector<int, 32> BlendMask(Mask.size(), -1);
6684   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6685     if (Mask[i] >= 0 && Mask[i] < Size) {
6686       V1Mask[i] = Mask[i];
6687       BlendMask[i] = i;
6688     } else if (Mask[i] >= Size) {
6689       V2Mask[i] = Mask[i] - Size;
6690       BlendMask[i] = i + Size;
6691     }
6692
6693   // Try to lower with the simpler initial blend strategy unless one of the
6694   // input shuffles would be a no-op. We prefer to shuffle inputs as the
6695   // shuffle may be able to fold with a load or other benefit. However, when
6696   // we'll have to do 2x as many shuffles in order to achieve this, blending
6697   // first is a better strategy.
6698   if (!isNoopShuffleMask(V1Mask) && !isNoopShuffleMask(V2Mask))
6699     if (SDValue BlendPerm =
6700             lowerVectorShuffleAsBlendAndPermute(DL, VT, V1, V2, Mask, DAG))
6701       return BlendPerm;
6702
6703   V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
6704   V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
6705   return DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6706 }
6707
6708 /// \brief Try to lower a vector shuffle as a byte rotation.
6709 ///
6710 /// SSSE3 has a generic PALIGNR instruction in x86 that will do an arbitrary
6711 /// byte-rotation of the concatenation of two vectors; pre-SSSE3 can use
6712 /// a PSRLDQ/PSLLDQ/POR pattern to get a similar effect. This routine will
6713 /// try to generically lower a vector shuffle through such an pattern. It
6714 /// does not check for the profitability of lowering either as PALIGNR or
6715 /// PSRLDQ/PSLLDQ/POR, only whether the mask is valid to lower in that form.
6716 /// This matches shuffle vectors that look like:
6717 ///
6718 ///   v8i16 [11, 12, 13, 14, 15, 0, 1, 2]
6719 ///
6720 /// Essentially it concatenates V1 and V2, shifts right by some number of
6721 /// elements, and takes the low elements as the result. Note that while this is
6722 /// specified as a *right shift* because x86 is little-endian, it is a *left
6723 /// rotate* of the vector lanes.
6724 static SDValue lowerVectorShuffleAsByteRotate(SDLoc DL, MVT VT, SDValue V1,
6725                                               SDValue V2,
6726                                               ArrayRef<int> Mask,
6727                                               const X86Subtarget *Subtarget,
6728                                               SelectionDAG &DAG) {
6729   assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
6730
6731   int NumElts = Mask.size();
6732   int NumLanes = VT.getSizeInBits() / 128;
6733   int NumLaneElts = NumElts / NumLanes;
6734
6735   // We need to detect various ways of spelling a rotation:
6736   //   [11, 12, 13, 14, 15,  0,  1,  2]
6737   //   [-1, 12, 13, 14, -1, -1,  1, -1]
6738   //   [-1, -1, -1, -1, -1, -1,  1,  2]
6739   //   [ 3,  4,  5,  6,  7,  8,  9, 10]
6740   //   [-1,  4,  5,  6, -1, -1,  9, -1]
6741   //   [-1,  4,  5,  6, -1, -1, -1, -1]
6742   int Rotation = 0;
6743   SDValue Lo, Hi;
6744   for (int l = 0; l < NumElts; l += NumLaneElts) {
6745     for (int i = 0; i < NumLaneElts; ++i) {
6746       if (Mask[l + i] == -1)
6747         continue;
6748       assert(Mask[l + i] >= 0 && "Only -1 is a valid negative mask element!");
6749
6750       // Get the mod-Size index and lane correct it.
6751       int LaneIdx = (Mask[l + i] % NumElts) - l;
6752       // Make sure it was in this lane.
6753       if (LaneIdx < 0 || LaneIdx >= NumLaneElts)
6754         return SDValue();
6755
6756       // Determine where a rotated vector would have started.
6757       int StartIdx = i - LaneIdx;
6758       if (StartIdx == 0)
6759         // The identity rotation isn't interesting, stop.
6760         return SDValue();
6761
6762       // If we found the tail of a vector the rotation must be the missing
6763       // front. If we found the head of a vector, it must be how much of the
6764       // head.
6765       int CandidateRotation = StartIdx < 0 ? -StartIdx : NumLaneElts - StartIdx;
6766
6767       if (Rotation == 0)
6768         Rotation = CandidateRotation;
6769       else if (Rotation != CandidateRotation)
6770         // The rotations don't match, so we can't match this mask.
6771         return SDValue();
6772
6773       // Compute which value this mask is pointing at.
6774       SDValue MaskV = Mask[l + i] < NumElts ? V1 : V2;
6775
6776       // Compute which of the two target values this index should be assigned
6777       // to. This reflects whether the high elements are remaining or the low
6778       // elements are remaining.
6779       SDValue &TargetV = StartIdx < 0 ? Hi : Lo;
6780
6781       // Either set up this value if we've not encountered it before, or check
6782       // that it remains consistent.
6783       if (!TargetV)
6784         TargetV = MaskV;
6785       else if (TargetV != MaskV)
6786         // This may be a rotation, but it pulls from the inputs in some
6787         // unsupported interleaving.
6788         return SDValue();
6789     }
6790   }
6791
6792   // Check that we successfully analyzed the mask, and normalize the results.
6793   assert(Rotation != 0 && "Failed to locate a viable rotation!");
6794   assert((Lo || Hi) && "Failed to find a rotated input vector!");
6795   if (!Lo)
6796     Lo = Hi;
6797   else if (!Hi)
6798     Hi = Lo;
6799
6800   // The actual rotate instruction rotates bytes, so we need to scale the
6801   // rotation based on how many bytes are in the vector lane.
6802   int Scale = 16 / NumLaneElts;
6803
6804   // SSSE3 targets can use the palignr instruction.
6805   if (Subtarget->hasSSSE3()) {
6806     // Cast the inputs to i8 vector of correct length to match PALIGNR.
6807     MVT AlignVT = MVT::getVectorVT(MVT::i8, 16 * NumLanes);
6808     Lo = DAG.getBitcast(AlignVT, Lo);
6809     Hi = DAG.getBitcast(AlignVT, Hi);
6810
6811     return DAG.getBitcast(
6812         VT, DAG.getNode(X86ISD::PALIGNR, DL, AlignVT, Hi, Lo,
6813                         DAG.getConstant(Rotation * Scale, DL, MVT::i8)));
6814   }
6815
6816   assert(VT.getSizeInBits() == 128 &&
6817          "Rotate-based lowering only supports 128-bit lowering!");
6818   assert(Mask.size() <= 16 &&
6819          "Can shuffle at most 16 bytes in a 128-bit vector!");
6820
6821   // Default SSE2 implementation
6822   int LoByteShift = 16 - Rotation * Scale;
6823   int HiByteShift = Rotation * Scale;
6824
6825   // Cast the inputs to v2i64 to match PSLLDQ/PSRLDQ.
6826   Lo = DAG.getBitcast(MVT::v2i64, Lo);
6827   Hi = DAG.getBitcast(MVT::v2i64, Hi);
6828
6829   SDValue LoShift = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v2i64, Lo,
6830                                 DAG.getConstant(LoByteShift, DL, MVT::i8));
6831   SDValue HiShift = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v2i64, Hi,
6832                                 DAG.getConstant(HiByteShift, DL, MVT::i8));
6833   return DAG.getBitcast(VT,
6834                         DAG.getNode(ISD::OR, DL, MVT::v2i64, LoShift, HiShift));
6835 }
6836
6837 /// \brief Compute whether each element of a shuffle is zeroable.
6838 ///
6839 /// A "zeroable" vector shuffle element is one which can be lowered to zero.
6840 /// Either it is an undef element in the shuffle mask, the element of the input
6841 /// referenced is undef, or the element of the input referenced is known to be
6842 /// zero. Many x86 shuffles can zero lanes cheaply and we often want to handle
6843 /// as many lanes with this technique as possible to simplify the remaining
6844 /// shuffle.
6845 static SmallBitVector computeZeroableShuffleElements(ArrayRef<int> Mask,
6846                                                      SDValue V1, SDValue V2) {
6847   SmallBitVector Zeroable(Mask.size(), false);
6848
6849   while (V1.getOpcode() == ISD::BITCAST)
6850     V1 = V1->getOperand(0);
6851   while (V2.getOpcode() == ISD::BITCAST)
6852     V2 = V2->getOperand(0);
6853
6854   bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
6855   bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
6856
6857   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6858     int M = Mask[i];
6859     // Handle the easy cases.
6860     if (M < 0 || (M >= 0 && M < Size && V1IsZero) || (M >= Size && V2IsZero)) {
6861       Zeroable[i] = true;
6862       continue;
6863     }
6864
6865     // If this is an index into a build_vector node (which has the same number
6866     // of elements), dig out the input value and use it.
6867     SDValue V = M < Size ? V1 : V2;
6868     if (V.getOpcode() != ISD::BUILD_VECTOR || Size != (int)V.getNumOperands())
6869       continue;
6870
6871     SDValue Input = V.getOperand(M % Size);
6872     // The UNDEF opcode check really should be dead code here, but not quite
6873     // worth asserting on (it isn't invalid, just unexpected).
6874     if (Input.getOpcode() == ISD::UNDEF || X86::isZeroNode(Input))
6875       Zeroable[i] = true;
6876   }
6877
6878   return Zeroable;
6879 }
6880
6881 /// \brief Try to emit a bitmask instruction for a shuffle.
6882 ///
6883 /// This handles cases where we can model a blend exactly as a bitmask due to
6884 /// one of the inputs being zeroable.
6885 static SDValue lowerVectorShuffleAsBitMask(SDLoc DL, MVT VT, SDValue V1,
6886                                            SDValue V2, ArrayRef<int> Mask,
6887                                            SelectionDAG &DAG) {
6888   MVT EltVT = VT.getScalarType();
6889   int NumEltBits = EltVT.getSizeInBits();
6890   MVT IntEltVT = MVT::getIntegerVT(NumEltBits);
6891   SDValue Zero = DAG.getConstant(0, DL, IntEltVT);
6892   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6893                                     IntEltVT);
6894   if (EltVT.isFloatingPoint()) {
6895     Zero = DAG.getBitcast(EltVT, Zero);
6896     AllOnes = DAG.getBitcast(EltVT, AllOnes);
6897   }
6898   SmallVector<SDValue, 16> VMaskOps(Mask.size(), Zero);
6899   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6900   SDValue V;
6901   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6902     if (Zeroable[i])
6903       continue;
6904     if (Mask[i] % Size != i)
6905       return SDValue(); // Not a blend.
6906     if (!V)
6907       V = Mask[i] < Size ? V1 : V2;
6908     else if (V != (Mask[i] < Size ? V1 : V2))
6909       return SDValue(); // Can only let one input through the mask.
6910
6911     VMaskOps[i] = AllOnes;
6912   }
6913   if (!V)
6914     return SDValue(); // No non-zeroable elements!
6915
6916   SDValue VMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, VMaskOps);
6917   V = DAG.getNode(VT.isFloatingPoint()
6918                   ? (unsigned) X86ISD::FAND : (unsigned) ISD::AND,
6919                   DL, VT, V, VMask);
6920   return V;
6921 }
6922
6923 /// \brief Try to lower a vector shuffle as a bit shift (shifts in zeros).
6924 ///
6925 /// Attempts to match a shuffle mask against the PSLL(W/D/Q/DQ) and
6926 /// PSRL(W/D/Q/DQ) SSE2 and AVX2 logical bit-shift instructions. The function
6927 /// matches elements from one of the input vectors shuffled to the left or
6928 /// right with zeroable elements 'shifted in'. It handles both the strictly
6929 /// bit-wise element shifts and the byte shift across an entire 128-bit double
6930 /// quad word lane.
6931 ///
6932 /// PSHL : (little-endian) left bit shift.
6933 /// [ zz, 0, zz,  2 ]
6934 /// [ -1, 4, zz, -1 ]
6935 /// PSRL : (little-endian) right bit shift.
6936 /// [  1, zz,  3, zz]
6937 /// [ -1, -1,  7, zz]
6938 /// PSLLDQ : (little-endian) left byte shift
6939 /// [ zz,  0,  1,  2,  3,  4,  5,  6]
6940 /// [ zz, zz, -1, -1,  2,  3,  4, -1]
6941 /// [ zz, zz, zz, zz, zz, zz, -1,  1]
6942 /// PSRLDQ : (little-endian) right byte shift
6943 /// [  5, 6,  7, zz, zz, zz, zz, zz]
6944 /// [ -1, 5,  6,  7, zz, zz, zz, zz]
6945 /// [  1, 2, -1, -1, -1, -1, zz, zz]
6946 static SDValue lowerVectorShuffleAsShift(SDLoc DL, MVT VT, SDValue V1,
6947                                          SDValue V2, ArrayRef<int> Mask,
6948                                          SelectionDAG &DAG) {
6949   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6950
6951   int Size = Mask.size();
6952   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
6953
6954   auto CheckZeros = [&](int Shift, int Scale, bool Left) {
6955     for (int i = 0; i < Size; i += Scale)
6956       for (int j = 0; j < Shift; ++j)
6957         if (!Zeroable[i + j + (Left ? 0 : (Scale - Shift))])
6958           return false;
6959
6960     return true;
6961   };
6962
6963   auto MatchShift = [&](int Shift, int Scale, bool Left, SDValue V) {
6964     for (int i = 0; i != Size; i += Scale) {
6965       unsigned Pos = Left ? i + Shift : i;
6966       unsigned Low = Left ? i : i + Shift;
6967       unsigned Len = Scale - Shift;
6968       if (!isSequentialOrUndefInRange(Mask, Pos, Len,
6969                                       Low + (V == V1 ? 0 : Size)))
6970         return SDValue();
6971     }
6972
6973     int ShiftEltBits = VT.getScalarSizeInBits() * Scale;
6974     bool ByteShift = ShiftEltBits > 64;
6975     unsigned OpCode = Left ? (ByteShift ? X86ISD::VSHLDQ : X86ISD::VSHLI)
6976                            : (ByteShift ? X86ISD::VSRLDQ : X86ISD::VSRLI);
6977     int ShiftAmt = Shift * VT.getScalarSizeInBits() / (ByteShift ? 8 : 1);
6978
6979     // Normalize the scale for byte shifts to still produce an i64 element
6980     // type.
6981     Scale = ByteShift ? Scale / 2 : Scale;
6982
6983     // We need to round trip through the appropriate type for the shift.
6984     MVT ShiftSVT = MVT::getIntegerVT(VT.getScalarSizeInBits() * Scale);
6985     MVT ShiftVT = MVT::getVectorVT(ShiftSVT, Size / Scale);
6986     assert(DAG.getTargetLoweringInfo().isTypeLegal(ShiftVT) &&
6987            "Illegal integer vector type");
6988     V = DAG.getBitcast(ShiftVT, V);
6989
6990     V = DAG.getNode(OpCode, DL, ShiftVT, V,
6991                     DAG.getConstant(ShiftAmt, DL, MVT::i8));
6992     return DAG.getBitcast(VT, V);
6993   };
6994
6995   // SSE/AVX supports logical shifts up to 64-bit integers - so we can just
6996   // keep doubling the size of the integer elements up to that. We can
6997   // then shift the elements of the integer vector by whole multiples of
6998   // their width within the elements of the larger integer vector. Test each
6999   // multiple to see if we can find a match with the moved element indices
7000   // and that the shifted in elements are all zeroable.
7001   for (int Scale = 2; Scale * VT.getScalarSizeInBits() <= 128; Scale *= 2)
7002     for (int Shift = 1; Shift != Scale; ++Shift)
7003       for (bool Left : {true, false})
7004         if (CheckZeros(Shift, Scale, Left))
7005           for (SDValue V : {V1, V2})
7006             if (SDValue Match = MatchShift(Shift, Scale, Left, V))
7007               return Match;
7008
7009   // no match
7010   return SDValue();
7011 }
7012
7013 /// \brief Try to lower a vector shuffle using SSE4a EXTRQ/INSERTQ.
7014 static SDValue lowerVectorShuffleWithSSE4A(SDLoc DL, MVT VT, SDValue V1,
7015                                            SDValue V2, ArrayRef<int> Mask,
7016                                            SelectionDAG &DAG) {
7017   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7018   assert(!Zeroable.all() && "Fully zeroable shuffle mask");
7019
7020   int Size = Mask.size();
7021   int HalfSize = Size / 2;
7022   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
7023
7024   // Upper half must be undefined.
7025   if (!isUndefInRange(Mask, HalfSize, HalfSize))
7026     return SDValue();
7027
7028   // EXTRQ: Extract Len elements from lower half of source, starting at Idx.
7029   // Remainder of lower half result is zero and upper half is all undef.
7030   auto LowerAsEXTRQ = [&]() {
7031     // Determine the extraction length from the part of the
7032     // lower half that isn't zeroable.
7033     int Len = HalfSize;
7034     for (; Len >= 0; --Len)
7035       if (!Zeroable[Len - 1])
7036         break;
7037     assert(Len > 0 && "Zeroable shuffle mask");
7038
7039     // Attempt to match first Len sequential elements from the lower half.
7040     SDValue Src;
7041     int Idx = -1;
7042     for (int i = 0; i != Len; ++i) {
7043       int M = Mask[i];
7044       if (M < 0)
7045         continue;
7046       SDValue &V = (M < Size ? V1 : V2);
7047       M = M % Size;
7048
7049       // All mask elements must be in the lower half.
7050       if (M > HalfSize)
7051         return SDValue();
7052
7053       if (Idx < 0 || (Src == V && Idx == (M - i))) {
7054         Src = V;
7055         Idx = M - i;
7056         continue;
7057       }
7058       return SDValue();
7059     }
7060
7061     if (Idx < 0)
7062       return SDValue();
7063
7064     assert((Idx + Len) <= HalfSize && "Illegal extraction mask");
7065     int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
7066     int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
7067     return DAG.getNode(X86ISD::EXTRQI, DL, VT, Src,
7068                        DAG.getConstant(BitLen, DL, MVT::i8),
7069                        DAG.getConstant(BitIdx, DL, MVT::i8));
7070   };
7071
7072   if (SDValue ExtrQ = LowerAsEXTRQ())
7073     return ExtrQ;
7074
7075   // INSERTQ: Extract lowest Len elements from lower half of second source and
7076   // insert over first source, starting at Idx.
7077   // { A[0], .., A[Idx-1], B[0], .., B[Len-1], A[Idx+Len], .., UNDEF, ... }
7078   auto LowerAsInsertQ = [&]() {
7079     for (int Idx = 0; Idx != HalfSize; ++Idx) {
7080       SDValue Base;
7081
7082       // Attempt to match first source from mask before insertion point.
7083       if (isUndefInRange(Mask, 0, Idx)) {
7084         /* EMPTY */
7085       } else if (isSequentialOrUndefInRange(Mask, 0, Idx, 0)) {
7086         Base = V1;
7087       } else if (isSequentialOrUndefInRange(Mask, 0, Idx, Size)) {
7088         Base = V2;
7089       } else {
7090         continue;
7091       }
7092
7093       // Extend the extraction length looking to match both the insertion of
7094       // the second source and the remaining elements of the first.
7095       for (int Hi = Idx + 1; Hi <= HalfSize; ++Hi) {
7096         SDValue Insert;
7097         int Len = Hi - Idx;
7098
7099         // Match insertion.
7100         if (isSequentialOrUndefInRange(Mask, Idx, Len, 0)) {
7101           Insert = V1;
7102         } else if (isSequentialOrUndefInRange(Mask, Idx, Len, Size)) {
7103           Insert = V2;
7104         } else {
7105           continue;
7106         }
7107
7108         // Match the remaining elements of the lower half.
7109         if (isUndefInRange(Mask, Hi, HalfSize - Hi)) {
7110           /* EMPTY */
7111         } else if ((!Base || (Base == V1)) &&
7112                    isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi, Hi)) {
7113           Base = V1;
7114         } else if ((!Base || (Base == V2)) &&
7115                    isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi,
7116                                               Size + Hi)) {
7117           Base = V2;
7118         } else {
7119           continue;
7120         }
7121
7122         // We may not have a base (first source) - this can safely be undefined.
7123         if (!Base)
7124           Base = DAG.getUNDEF(VT);
7125
7126         int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
7127         int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
7128         return DAG.getNode(X86ISD::INSERTQI, DL, VT, Base, Insert,
7129                            DAG.getConstant(BitLen, DL, MVT::i8),
7130                            DAG.getConstant(BitIdx, DL, MVT::i8));
7131       }
7132     }
7133
7134     return SDValue();
7135   };
7136
7137   if (SDValue InsertQ = LowerAsInsertQ())
7138     return InsertQ;
7139
7140   return SDValue();
7141 }
7142
7143 /// \brief Lower a vector shuffle as a zero or any extension.
7144 ///
7145 /// Given a specific number of elements, element bit width, and extension
7146 /// stride, produce either a zero or any extension based on the available
7147 /// features of the subtarget.
7148 static SDValue lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7149     SDLoc DL, MVT VT, int Scale, bool AnyExt, SDValue InputV,
7150     ArrayRef<int> Mask, const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7151   assert(Scale > 1 && "Need a scale to extend.");
7152   int NumElements = VT.getVectorNumElements();
7153   int EltBits = VT.getScalarSizeInBits();
7154   assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
7155          "Only 8, 16, and 32 bit elements can be extended.");
7156   assert(Scale * EltBits <= 64 && "Cannot zero extend past 64 bits.");
7157
7158   // Found a valid zext mask! Try various lowering strategies based on the
7159   // input type and available ISA extensions.
7160   if (Subtarget->hasSSE41()) {
7161     MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits * Scale),
7162                                  NumElements / Scale);
7163     return DAG.getBitcast(VT, DAG.getNode(X86ISD::VZEXT, DL, ExtVT, InputV));
7164   }
7165
7166   // For any extends we can cheat for larger element sizes and use shuffle
7167   // instructions that can fold with a load and/or copy.
7168   if (AnyExt && EltBits == 32) {
7169     int PSHUFDMask[4] = {0, -1, 1, -1};
7170     return DAG.getBitcast(
7171         VT, DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7172                         DAG.getBitcast(MVT::v4i32, InputV),
7173                         getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
7174   }
7175   if (AnyExt && EltBits == 16 && Scale > 2) {
7176     int PSHUFDMask[4] = {0, -1, 0, -1};
7177     InputV = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7178                          DAG.getBitcast(MVT::v4i32, InputV),
7179                          getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG));
7180     int PSHUFHWMask[4] = {1, -1, -1, -1};
7181     return DAG.getBitcast(
7182         VT, DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16,
7183                         DAG.getBitcast(MVT::v8i16, InputV),
7184                         getV4X86ShuffleImm8ForMask(PSHUFHWMask, DL, DAG)));
7185   }
7186
7187   // The SSE4A EXTRQ instruction can efficiently extend the first 2 lanes
7188   // to 64-bits.
7189   if ((Scale * EltBits) == 64 && EltBits < 32 && Subtarget->hasSSE4A()) {
7190     assert(NumElements == (int)Mask.size() && "Unexpected shuffle mask size!");
7191     assert(VT.getSizeInBits() == 128 && "Unexpected vector width!");
7192
7193     SDValue Lo = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7194                              DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7195                                          DAG.getConstant(EltBits, DL, MVT::i8),
7196                                          DAG.getConstant(0, DL, MVT::i8)));
7197     if (isUndefInRange(Mask, NumElements/2, NumElements/2))
7198       return DAG.getNode(ISD::BITCAST, DL, VT, Lo);
7199
7200     SDValue Hi =
7201         DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7202                     DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7203                                 DAG.getConstant(EltBits, DL, MVT::i8),
7204                                 DAG.getConstant(EltBits, DL, MVT::i8)));
7205     return DAG.getNode(ISD::BITCAST, DL, VT,
7206                        DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, Lo, Hi));
7207   }
7208
7209   // If this would require more than 2 unpack instructions to expand, use
7210   // pshufb when available. We can only use more than 2 unpack instructions
7211   // when zero extending i8 elements which also makes it easier to use pshufb.
7212   if (Scale > 4 && EltBits == 8 && Subtarget->hasSSSE3()) {
7213     assert(NumElements == 16 && "Unexpected byte vector width!");
7214     SDValue PSHUFBMask[16];
7215     for (int i = 0; i < 16; ++i)
7216       PSHUFBMask[i] =
7217           DAG.getConstant((i % Scale == 0) ? i / Scale : 0x80, DL, MVT::i8);
7218     InputV = DAG.getBitcast(MVT::v16i8, InputV);
7219     return DAG.getBitcast(VT,
7220                           DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, InputV,
7221                                       DAG.getNode(ISD::BUILD_VECTOR, DL,
7222                                                   MVT::v16i8, PSHUFBMask)));
7223   }
7224
7225   // Otherwise emit a sequence of unpacks.
7226   do {
7227     MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
7228     SDValue Ext = AnyExt ? DAG.getUNDEF(InputVT)
7229                          : getZeroVector(InputVT, Subtarget, DAG, DL);
7230     InputV = DAG.getBitcast(InputVT, InputV);
7231     InputV = DAG.getNode(X86ISD::UNPCKL, DL, InputVT, InputV, Ext);
7232     Scale /= 2;
7233     EltBits *= 2;
7234     NumElements /= 2;
7235   } while (Scale > 1);
7236   return DAG.getBitcast(VT, InputV);
7237 }
7238
7239 /// \brief Try to lower a vector shuffle as a zero extension on any microarch.
7240 ///
7241 /// This routine will try to do everything in its power to cleverly lower
7242 /// a shuffle which happens to match the pattern of a zero extend. It doesn't
7243 /// check for the profitability of this lowering,  it tries to aggressively
7244 /// match this pattern. It will use all of the micro-architectural details it
7245 /// can to emit an efficient lowering. It handles both blends with all-zero
7246 /// inputs to explicitly zero-extend and undef-lanes (sometimes undef due to
7247 /// masking out later).
7248 ///
7249 /// The reason we have dedicated lowering for zext-style shuffles is that they
7250 /// are both incredibly common and often quite performance sensitive.
7251 static SDValue lowerVectorShuffleAsZeroOrAnyExtend(
7252     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7253     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7254   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7255
7256   int Bits = VT.getSizeInBits();
7257   int NumElements = VT.getVectorNumElements();
7258   assert(VT.getScalarSizeInBits() <= 32 &&
7259          "Exceeds 32-bit integer zero extension limit");
7260   assert((int)Mask.size() == NumElements && "Unexpected shuffle mask size");
7261
7262   // Define a helper function to check a particular ext-scale and lower to it if
7263   // valid.
7264   auto Lower = [&](int Scale) -> SDValue {
7265     SDValue InputV;
7266     bool AnyExt = true;
7267     for (int i = 0; i < NumElements; ++i) {
7268       if (Mask[i] == -1)
7269         continue; // Valid anywhere but doesn't tell us anything.
7270       if (i % Scale != 0) {
7271         // Each of the extended elements need to be zeroable.
7272         if (!Zeroable[i])
7273           return SDValue();
7274
7275         // We no longer are in the anyext case.
7276         AnyExt = false;
7277         continue;
7278       }
7279
7280       // Each of the base elements needs to be consecutive indices into the
7281       // same input vector.
7282       SDValue V = Mask[i] < NumElements ? V1 : V2;
7283       if (!InputV)
7284         InputV = V;
7285       else if (InputV != V)
7286         return SDValue(); // Flip-flopping inputs.
7287
7288       if (Mask[i] % NumElements != i / Scale)
7289         return SDValue(); // Non-consecutive strided elements.
7290     }
7291
7292     // If we fail to find an input, we have a zero-shuffle which should always
7293     // have already been handled.
7294     // FIXME: Maybe handle this here in case during blending we end up with one?
7295     if (!InputV)
7296       return SDValue();
7297
7298     return lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7299         DL, VT, Scale, AnyExt, InputV, Mask, Subtarget, DAG);
7300   };
7301
7302   // The widest scale possible for extending is to a 64-bit integer.
7303   assert(Bits % 64 == 0 &&
7304          "The number of bits in a vector must be divisible by 64 on x86!");
7305   int NumExtElements = Bits / 64;
7306
7307   // Each iteration, try extending the elements half as much, but into twice as
7308   // many elements.
7309   for (; NumExtElements < NumElements; NumExtElements *= 2) {
7310     assert(NumElements % NumExtElements == 0 &&
7311            "The input vector size must be divisible by the extended size.");
7312     if (SDValue V = Lower(NumElements / NumExtElements))
7313       return V;
7314   }
7315
7316   // General extends failed, but 128-bit vectors may be able to use MOVQ.
7317   if (Bits != 128)
7318     return SDValue();
7319
7320   // Returns one of the source operands if the shuffle can be reduced to a
7321   // MOVQ, copying the lower 64-bits and zero-extending to the upper 64-bits.
7322   auto CanZExtLowHalf = [&]() {
7323     for (int i = NumElements / 2; i != NumElements; ++i)
7324       if (!Zeroable[i])
7325         return SDValue();
7326     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, 0))
7327       return V1;
7328     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, NumElements))
7329       return V2;
7330     return SDValue();
7331   };
7332
7333   if (SDValue V = CanZExtLowHalf()) {
7334     V = DAG.getBitcast(MVT::v2i64, V);
7335     V = DAG.getNode(X86ISD::VZEXT_MOVL, DL, MVT::v2i64, V);
7336     return DAG.getBitcast(VT, V);
7337   }
7338
7339   // No viable ext lowering found.
7340   return SDValue();
7341 }
7342
7343 /// \brief Try to get a scalar value for a specific element of a vector.
7344 ///
7345 /// Looks through BUILD_VECTOR and SCALAR_TO_VECTOR nodes to find a scalar.
7346 static SDValue getScalarValueForVectorElement(SDValue V, int Idx,
7347                                               SelectionDAG &DAG) {
7348   MVT VT = V.getSimpleValueType();
7349   MVT EltVT = VT.getVectorElementType();
7350   while (V.getOpcode() == ISD::BITCAST)
7351     V = V.getOperand(0);
7352   // If the bitcasts shift the element size, we can't extract an equivalent
7353   // element from it.
7354   MVT NewVT = V.getSimpleValueType();
7355   if (!NewVT.isVector() || NewVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
7356     return SDValue();
7357
7358   if (V.getOpcode() == ISD::BUILD_VECTOR ||
7359       (Idx == 0 && V.getOpcode() == ISD::SCALAR_TO_VECTOR)) {
7360     // Ensure the scalar operand is the same size as the destination.
7361     // FIXME: Add support for scalar truncation where possible.
7362     SDValue S = V.getOperand(Idx);
7363     if (EltVT.getSizeInBits() == S.getSimpleValueType().getSizeInBits())
7364       return DAG.getNode(ISD::BITCAST, SDLoc(V), EltVT, S);
7365   }
7366
7367   return SDValue();
7368 }
7369
7370 /// \brief Helper to test for a load that can be folded with x86 shuffles.
7371 ///
7372 /// This is particularly important because the set of instructions varies
7373 /// significantly based on whether the operand is a load or not.
7374 static bool isShuffleFoldableLoad(SDValue V) {
7375   while (V.getOpcode() == ISD::BITCAST)
7376     V = V.getOperand(0);
7377
7378   return ISD::isNON_EXTLoad(V.getNode());
7379 }
7380
7381 /// \brief Try to lower insertion of a single element into a zero vector.
7382 ///
7383 /// This is a common pattern that we have especially efficient patterns to lower
7384 /// across all subtarget feature sets.
7385 static SDValue lowerVectorShuffleAsElementInsertion(
7386     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7387     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7388   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7389   MVT ExtVT = VT;
7390   MVT EltVT = VT.getVectorElementType();
7391
7392   int V2Index = std::find_if(Mask.begin(), Mask.end(),
7393                              [&Mask](int M) { return M >= (int)Mask.size(); }) -
7394                 Mask.begin();
7395   bool IsV1Zeroable = true;
7396   for (int i = 0, Size = Mask.size(); i < Size; ++i)
7397     if (i != V2Index && !Zeroable[i]) {
7398       IsV1Zeroable = false;
7399       break;
7400     }
7401
7402   // Check for a single input from a SCALAR_TO_VECTOR node.
7403   // FIXME: All of this should be canonicalized into INSERT_VECTOR_ELT and
7404   // all the smarts here sunk into that routine. However, the current
7405   // lowering of BUILD_VECTOR makes that nearly impossible until the old
7406   // vector shuffle lowering is dead.
7407   if (SDValue V2S = getScalarValueForVectorElement(
7408           V2, Mask[V2Index] - Mask.size(), DAG)) {
7409     // We need to zext the scalar if it is smaller than an i32.
7410     V2S = DAG.getBitcast(EltVT, V2S);
7411     if (EltVT == MVT::i8 || EltVT == MVT::i16) {
7412       // Using zext to expand a narrow element won't work for non-zero
7413       // insertions.
7414       if (!IsV1Zeroable)
7415         return SDValue();
7416
7417       // Zero-extend directly to i32.
7418       ExtVT = MVT::v4i32;
7419       V2S = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, V2S);
7420     }
7421     V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
7422   } else if (Mask[V2Index] != (int)Mask.size() || EltVT == MVT::i8 ||
7423              EltVT == MVT::i16) {
7424     // Either not inserting from the low element of the input or the input
7425     // element size is too small to use VZEXT_MOVL to clear the high bits.
7426     return SDValue();
7427   }
7428
7429   if (!IsV1Zeroable) {
7430     // If V1 can't be treated as a zero vector we have fewer options to lower
7431     // this. We can't support integer vectors or non-zero targets cheaply, and
7432     // the V1 elements can't be permuted in any way.
7433     assert(VT == ExtVT && "Cannot change extended type when non-zeroable!");
7434     if (!VT.isFloatingPoint() || V2Index != 0)
7435       return SDValue();
7436     SmallVector<int, 8> V1Mask(Mask.begin(), Mask.end());
7437     V1Mask[V2Index] = -1;
7438     if (!isNoopShuffleMask(V1Mask))
7439       return SDValue();
7440     // This is essentially a special case blend operation, but if we have
7441     // general purpose blend operations, they are always faster. Bail and let
7442     // the rest of the lowering handle these as blends.
7443     if (Subtarget->hasSSE41())
7444       return SDValue();
7445
7446     // Otherwise, use MOVSD or MOVSS.
7447     assert((EltVT == MVT::f32 || EltVT == MVT::f64) &&
7448            "Only two types of floating point element types to handle!");
7449     return DAG.getNode(EltVT == MVT::f32 ? X86ISD::MOVSS : X86ISD::MOVSD, DL,
7450                        ExtVT, V1, V2);
7451   }
7452
7453   // This lowering only works for the low element with floating point vectors.
7454   if (VT.isFloatingPoint() && V2Index != 0)
7455     return SDValue();
7456
7457   V2 = DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2);
7458   if (ExtVT != VT)
7459     V2 = DAG.getBitcast(VT, V2);
7460
7461   if (V2Index != 0) {
7462     // If we have 4 or fewer lanes we can cheaply shuffle the element into
7463     // the desired position. Otherwise it is more efficient to do a vector
7464     // shift left. We know that we can do a vector shift left because all
7465     // the inputs are zero.
7466     if (VT.isFloatingPoint() || VT.getVectorNumElements() <= 4) {
7467       SmallVector<int, 4> V2Shuffle(Mask.size(), 1);
7468       V2Shuffle[V2Index] = 0;
7469       V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Shuffle);
7470     } else {
7471       V2 = DAG.getBitcast(MVT::v2i64, V2);
7472       V2 = DAG.getNode(
7473           X86ISD::VSHLDQ, DL, MVT::v2i64, V2,
7474           DAG.getConstant(V2Index * EltVT.getSizeInBits() / 8, DL,
7475                           DAG.getTargetLoweringInfo().getScalarShiftAmountTy(
7476                               DAG.getDataLayout(), VT)));
7477       V2 = DAG.getBitcast(VT, V2);
7478     }
7479   }
7480   return V2;
7481 }
7482
7483 /// \brief Try to lower broadcast of a single element.
7484 ///
7485 /// For convenience, this code also bundles all of the subtarget feature set
7486 /// filtering. While a little annoying to re-dispatch on type here, there isn't
7487 /// a convenient way to factor it out.
7488 static SDValue lowerVectorShuffleAsBroadcast(SDLoc DL, MVT VT, SDValue V,
7489                                              ArrayRef<int> Mask,
7490                                              const X86Subtarget *Subtarget,
7491                                              SelectionDAG &DAG) {
7492   if (!Subtarget->hasAVX())
7493     return SDValue();
7494   if (VT.isInteger() && !Subtarget->hasAVX2())
7495     return SDValue();
7496
7497   // Check that the mask is a broadcast.
7498   int BroadcastIdx = -1;
7499   for (int M : Mask)
7500     if (M >= 0 && BroadcastIdx == -1)
7501       BroadcastIdx = M;
7502     else if (M >= 0 && M != BroadcastIdx)
7503       return SDValue();
7504
7505   assert(BroadcastIdx < (int)Mask.size() && "We only expect to be called with "
7506                                             "a sorted mask where the broadcast "
7507                                             "comes from V1.");
7508
7509   // Go up the chain of (vector) values to find a scalar load that we can
7510   // combine with the broadcast.
7511   for (;;) {
7512     switch (V.getOpcode()) {
7513     case ISD::CONCAT_VECTORS: {
7514       int OperandSize = Mask.size() / V.getNumOperands();
7515       V = V.getOperand(BroadcastIdx / OperandSize);
7516       BroadcastIdx %= OperandSize;
7517       continue;
7518     }
7519
7520     case ISD::INSERT_SUBVECTOR: {
7521       SDValue VOuter = V.getOperand(0), VInner = V.getOperand(1);
7522       auto ConstantIdx = dyn_cast<ConstantSDNode>(V.getOperand(2));
7523       if (!ConstantIdx)
7524         break;
7525
7526       int BeginIdx = (int)ConstantIdx->getZExtValue();
7527       int EndIdx =
7528           BeginIdx + (int)VInner.getValueType().getVectorNumElements();
7529       if (BroadcastIdx >= BeginIdx && BroadcastIdx < EndIdx) {
7530         BroadcastIdx -= BeginIdx;
7531         V = VInner;
7532       } else {
7533         V = VOuter;
7534       }
7535       continue;
7536     }
7537     }
7538     break;
7539   }
7540
7541   // Check if this is a broadcast of a scalar. We special case lowering
7542   // for scalars so that we can more effectively fold with loads.
7543   if (V.getOpcode() == ISD::BUILD_VECTOR ||
7544       (V.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)) {
7545     V = V.getOperand(BroadcastIdx);
7546
7547     // If the scalar isn't a load, we can't broadcast from it in AVX1.
7548     // Only AVX2 has register broadcasts.
7549     if (!Subtarget->hasAVX2() && !isShuffleFoldableLoad(V))
7550       return SDValue();
7551   } else if (BroadcastIdx != 0 || !Subtarget->hasAVX2()) {
7552     // We can't broadcast from a vector register without AVX2, and we can only
7553     // broadcast from the zero-element of a vector register.
7554     return SDValue();
7555   }
7556
7557   return DAG.getNode(X86ISD::VBROADCAST, DL, VT, V);
7558 }
7559
7560 // Check for whether we can use INSERTPS to perform the shuffle. We only use
7561 // INSERTPS when the V1 elements are already in the correct locations
7562 // because otherwise we can just always use two SHUFPS instructions which
7563 // are much smaller to encode than a SHUFPS and an INSERTPS. We can also
7564 // perform INSERTPS if a single V1 element is out of place and all V2
7565 // elements are zeroable.
7566 static SDValue lowerVectorShuffleAsInsertPS(SDValue Op, SDValue V1, SDValue V2,
7567                                             ArrayRef<int> Mask,
7568                                             SelectionDAG &DAG) {
7569   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7570   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7571   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7572   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7573
7574   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7575
7576   unsigned ZMask = 0;
7577   int V1DstIndex = -1;
7578   int V2DstIndex = -1;
7579   bool V1UsedInPlace = false;
7580
7581   for (int i = 0; i < 4; ++i) {
7582     // Synthesize a zero mask from the zeroable elements (includes undefs).
7583     if (Zeroable[i]) {
7584       ZMask |= 1 << i;
7585       continue;
7586     }
7587
7588     // Flag if we use any V1 inputs in place.
7589     if (i == Mask[i]) {
7590       V1UsedInPlace = true;
7591       continue;
7592     }
7593
7594     // We can only insert a single non-zeroable element.
7595     if (V1DstIndex != -1 || V2DstIndex != -1)
7596       return SDValue();
7597
7598     if (Mask[i] < 4) {
7599       // V1 input out of place for insertion.
7600       V1DstIndex = i;
7601     } else {
7602       // V2 input for insertion.
7603       V2DstIndex = i;
7604     }
7605   }
7606
7607   // Don't bother if we have no (non-zeroable) element for insertion.
7608   if (V1DstIndex == -1 && V2DstIndex == -1)
7609     return SDValue();
7610
7611   // Determine element insertion src/dst indices. The src index is from the
7612   // start of the inserted vector, not the start of the concatenated vector.
7613   unsigned V2SrcIndex = 0;
7614   if (V1DstIndex != -1) {
7615     // If we have a V1 input out of place, we use V1 as the V2 element insertion
7616     // and don't use the original V2 at all.
7617     V2SrcIndex = Mask[V1DstIndex];
7618     V2DstIndex = V1DstIndex;
7619     V2 = V1;
7620   } else {
7621     V2SrcIndex = Mask[V2DstIndex] - 4;
7622   }
7623
7624   // If no V1 inputs are used in place, then the result is created only from
7625   // the zero mask and the V2 insertion - so remove V1 dependency.
7626   if (!V1UsedInPlace)
7627     V1 = DAG.getUNDEF(MVT::v4f32);
7628
7629   unsigned InsertPSMask = V2SrcIndex << 6 | V2DstIndex << 4 | ZMask;
7630   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
7631
7632   // Insert the V2 element into the desired position.
7633   SDLoc DL(Op);
7634   return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
7635                      DAG.getConstant(InsertPSMask, DL, MVT::i8));
7636 }
7637
7638 /// \brief Try to lower a shuffle as a permute of the inputs followed by an
7639 /// UNPCK instruction.
7640 ///
7641 /// This specifically targets cases where we end up with alternating between
7642 /// the two inputs, and so can permute them into something that feeds a single
7643 /// UNPCK instruction. Note that this routine only targets integer vectors
7644 /// because for floating point vectors we have a generalized SHUFPS lowering
7645 /// strategy that handles everything that doesn't *exactly* match an unpack,
7646 /// making this clever lowering unnecessary.
7647 static SDValue lowerVectorShuffleAsUnpack(SDLoc DL, MVT VT, SDValue V1,
7648                                           SDValue V2, ArrayRef<int> Mask,
7649                                           SelectionDAG &DAG) {
7650   assert(!VT.isFloatingPoint() &&
7651          "This routine only supports integer vectors.");
7652   assert(!isSingleInputShuffleMask(Mask) &&
7653          "This routine should only be used when blending two inputs.");
7654   assert(Mask.size() >= 2 && "Single element masks are invalid.");
7655
7656   int Size = Mask.size();
7657
7658   int NumLoInputs = std::count_if(Mask.begin(), Mask.end(), [Size](int M) {
7659     return M >= 0 && M % Size < Size / 2;
7660   });
7661   int NumHiInputs = std::count_if(
7662       Mask.begin(), Mask.end(), [Size](int M) { return M % Size >= Size / 2; });
7663
7664   bool UnpackLo = NumLoInputs >= NumHiInputs;
7665
7666   auto TryUnpack = [&](MVT UnpackVT, int Scale) {
7667     SmallVector<int, 32> V1Mask(Mask.size(), -1);
7668     SmallVector<int, 32> V2Mask(Mask.size(), -1);
7669
7670     for (int i = 0; i < Size; ++i) {
7671       if (Mask[i] < 0)
7672         continue;
7673
7674       // Each element of the unpack contains Scale elements from this mask.
7675       int UnpackIdx = i / Scale;
7676
7677       // We only handle the case where V1 feeds the first slots of the unpack.
7678       // We rely on canonicalization to ensure this is the case.
7679       if ((UnpackIdx % 2 == 0) != (Mask[i] < Size))
7680         return SDValue();
7681
7682       // Setup the mask for this input. The indexing is tricky as we have to
7683       // handle the unpack stride.
7684       SmallVectorImpl<int> &VMask = (UnpackIdx % 2 == 0) ? V1Mask : V2Mask;
7685       VMask[(UnpackIdx / 2) * Scale + i % Scale + (UnpackLo ? 0 : Size / 2)] =
7686           Mask[i] % Size;
7687     }
7688
7689     // If we will have to shuffle both inputs to use the unpack, check whether
7690     // we can just unpack first and shuffle the result. If so, skip this unpack.
7691     if ((NumLoInputs == 0 || NumHiInputs == 0) && !isNoopShuffleMask(V1Mask) &&
7692         !isNoopShuffleMask(V2Mask))
7693       return SDValue();
7694
7695     // Shuffle the inputs into place.
7696     V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
7697     V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
7698
7699     // Cast the inputs to the type we will use to unpack them.
7700     V1 = DAG.getBitcast(UnpackVT, V1);
7701     V2 = DAG.getBitcast(UnpackVT, V2);
7702
7703     // Unpack the inputs and cast the result back to the desired type.
7704     return DAG.getBitcast(
7705         VT, DAG.getNode(UnpackLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
7706                         UnpackVT, V1, V2));
7707   };
7708
7709   // We try each unpack from the largest to the smallest to try and find one
7710   // that fits this mask.
7711   int OrigNumElements = VT.getVectorNumElements();
7712   int OrigScalarSize = VT.getScalarSizeInBits();
7713   for (int ScalarSize = 64; ScalarSize >= OrigScalarSize; ScalarSize /= 2) {
7714     int Scale = ScalarSize / OrigScalarSize;
7715     int NumElements = OrigNumElements / Scale;
7716     MVT UnpackVT = MVT::getVectorVT(MVT::getIntegerVT(ScalarSize), NumElements);
7717     if (SDValue Unpack = TryUnpack(UnpackVT, Scale))
7718       return Unpack;
7719   }
7720
7721   // If none of the unpack-rooted lowerings worked (or were profitable) try an
7722   // initial unpack.
7723   if (NumLoInputs == 0 || NumHiInputs == 0) {
7724     assert((NumLoInputs > 0 || NumHiInputs > 0) &&
7725            "We have to have *some* inputs!");
7726     int HalfOffset = NumLoInputs == 0 ? Size / 2 : 0;
7727
7728     // FIXME: We could consider the total complexity of the permute of each
7729     // possible unpacking. Or at the least we should consider how many
7730     // half-crossings are created.
7731     // FIXME: We could consider commuting the unpacks.
7732
7733     SmallVector<int, 32> PermMask;
7734     PermMask.assign(Size, -1);
7735     for (int i = 0; i < Size; ++i) {
7736       if (Mask[i] < 0)
7737         continue;
7738
7739       assert(Mask[i] % Size >= HalfOffset && "Found input from wrong half!");
7740
7741       PermMask[i] =
7742           2 * ((Mask[i] % Size) - HalfOffset) + (Mask[i] < Size ? 0 : 1);
7743     }
7744     return DAG.getVectorShuffle(
7745         VT, DL, DAG.getNode(NumLoInputs == 0 ? X86ISD::UNPCKH : X86ISD::UNPCKL,
7746                             DL, VT, V1, V2),
7747         DAG.getUNDEF(VT), PermMask);
7748   }
7749
7750   return SDValue();
7751 }
7752
7753 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
7754 ///
7755 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
7756 /// support for floating point shuffles but not integer shuffles. These
7757 /// instructions will incur a domain crossing penalty on some chips though so
7758 /// it is better to avoid lowering through this for integer vectors where
7759 /// possible.
7760 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7761                                        const X86Subtarget *Subtarget,
7762                                        SelectionDAG &DAG) {
7763   SDLoc DL(Op);
7764   assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
7765   assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7766   assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7767   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7768   ArrayRef<int> Mask = SVOp->getMask();
7769   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7770
7771   if (isSingleInputShuffleMask(Mask)) {
7772     // Use low duplicate instructions for masks that match their pattern.
7773     if (Subtarget->hasSSE3())
7774       if (isShuffleEquivalent(V1, V2, Mask, {0, 0}))
7775         return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v2f64, V1);
7776
7777     // Straight shuffle of a single input vector. Simulate this by using the
7778     // single input as both of the "inputs" to this instruction..
7779     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
7780
7781     if (Subtarget->hasAVX()) {
7782       // If we have AVX, we can use VPERMILPS which will allow folding a load
7783       // into the shuffle.
7784       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v2f64, V1,
7785                          DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7786     }
7787
7788     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V1,
7789                        DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7790   }
7791   assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
7792   assert(Mask[1] >= 2 && "Non-canonicalized blend!");
7793
7794   // If we have a single input, insert that into V1 if we can do so cheaply.
7795   if ((Mask[0] >= 2) + (Mask[1] >= 2) == 1) {
7796     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7797             DL, MVT::v2f64, V1, V2, Mask, Subtarget, DAG))
7798       return Insertion;
7799     // Try inverting the insertion since for v2 masks it is easy to do and we
7800     // can't reliably sort the mask one way or the other.
7801     int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
7802                           Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
7803     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7804             DL, MVT::v2f64, V2, V1, InverseMask, Subtarget, DAG))
7805       return Insertion;
7806   }
7807
7808   // Try to use one of the special instruction patterns to handle two common
7809   // blend patterns if a zero-blend above didn't work.
7810   if (isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
7811       isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7812     if (SDValue V1S = getScalarValueForVectorElement(V1, Mask[0], DAG))
7813       // We can either use a special instruction to load over the low double or
7814       // to move just the low double.
7815       return DAG.getNode(
7816           isShuffleFoldableLoad(V1S) ? X86ISD::MOVLPD : X86ISD::MOVSD,
7817           DL, MVT::v2f64, V2,
7818           DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V1S));
7819
7820   if (Subtarget->hasSSE41())
7821     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2f64, V1, V2, Mask,
7822                                                   Subtarget, DAG))
7823       return Blend;
7824
7825   // Use dedicated unpack instructions for masks that match their pattern.
7826   if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7827     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2f64, V1, V2);
7828   if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7829     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2f64, V1, V2);
7830
7831   unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
7832   return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V2,
7833                      DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7834 }
7835
7836 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
7837 ///
7838 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
7839 /// the integer unit to minimize domain crossing penalties. However, for blends
7840 /// it falls back to the floating point shuffle operation with appropriate bit
7841 /// casting.
7842 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7843                                        const X86Subtarget *Subtarget,
7844                                        SelectionDAG &DAG) {
7845   SDLoc DL(Op);
7846   assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
7847   assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7848   assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7849   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7850   ArrayRef<int> Mask = SVOp->getMask();
7851   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7852
7853   if (isSingleInputShuffleMask(Mask)) {
7854     // Check for being able to broadcast a single element.
7855     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v2i64, V1,
7856                                                           Mask, Subtarget, DAG))
7857       return Broadcast;
7858
7859     // Straight shuffle of a single input vector. For everything from SSE2
7860     // onward this has a single fast instruction with no scary immediates.
7861     // We have to map the mask as it is actually a v4i32 shuffle instruction.
7862     V1 = DAG.getBitcast(MVT::v4i32, V1);
7863     int WidenedMask[4] = {
7864         std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
7865         std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
7866     return DAG.getBitcast(
7867         MVT::v2i64,
7868         DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
7869                     getV4X86ShuffleImm8ForMask(WidenedMask, DL, DAG)));
7870   }
7871   assert(Mask[0] != -1 && "No undef lanes in multi-input v2 shuffles!");
7872   assert(Mask[1] != -1 && "No undef lanes in multi-input v2 shuffles!");
7873   assert(Mask[0] < 2 && "We sort V1 to be the first input.");
7874   assert(Mask[1] >= 2 && "We sort V2 to be the second input.");
7875
7876   // If we have a blend of two PACKUS operations an the blend aligns with the
7877   // low and half halves, we can just merge the PACKUS operations. This is
7878   // particularly important as it lets us merge shuffles that this routine itself
7879   // creates.
7880   auto GetPackNode = [](SDValue V) {
7881     while (V.getOpcode() == ISD::BITCAST)
7882       V = V.getOperand(0);
7883
7884     return V.getOpcode() == X86ISD::PACKUS ? V : SDValue();
7885   };
7886   if (SDValue V1Pack = GetPackNode(V1))
7887     if (SDValue V2Pack = GetPackNode(V2))
7888       return DAG.getBitcast(MVT::v2i64,
7889                             DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8,
7890                                         Mask[0] == 0 ? V1Pack.getOperand(0)
7891                                                      : V1Pack.getOperand(1),
7892                                         Mask[1] == 2 ? V2Pack.getOperand(0)
7893                                                      : V2Pack.getOperand(1)));
7894
7895   // Try to use shift instructions.
7896   if (SDValue Shift =
7897           lowerVectorShuffleAsShift(DL, MVT::v2i64, V1, V2, Mask, DAG))
7898     return Shift;
7899
7900   // When loading a scalar and then shuffling it into a vector we can often do
7901   // the insertion cheaply.
7902   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7903           DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
7904     return Insertion;
7905   // Try inverting the insertion since for v2 masks it is easy to do and we
7906   // can't reliably sort the mask one way or the other.
7907   int InverseMask[2] = {Mask[0] ^ 2, Mask[1] ^ 2};
7908   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7909           DL, MVT::v2i64, V2, V1, InverseMask, Subtarget, DAG))
7910     return Insertion;
7911
7912   // We have different paths for blend lowering, but they all must use the
7913   // *exact* same predicate.
7914   bool IsBlendSupported = Subtarget->hasSSE41();
7915   if (IsBlendSupported)
7916     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2i64, V1, V2, Mask,
7917                                                   Subtarget, DAG))
7918       return Blend;
7919
7920   // Use dedicated unpack instructions for masks that match their pattern.
7921   if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7922     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, V1, V2);
7923   if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7924     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2i64, V1, V2);
7925
7926   // Try to use byte rotation instructions.
7927   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
7928   if (Subtarget->hasSSSE3())
7929     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
7930             DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
7931       return Rotate;
7932
7933   // If we have direct support for blends, we should lower by decomposing into
7934   // a permute. That will be faster than the domain cross.
7935   if (IsBlendSupported)
7936     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v2i64, V1, V2,
7937                                                       Mask, DAG);
7938
7939   // We implement this with SHUFPD which is pretty lame because it will likely
7940   // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
7941   // However, all the alternatives are still more cycles and newer chips don't
7942   // have this problem. It would be really nice if x86 had better shuffles here.
7943   V1 = DAG.getBitcast(MVT::v2f64, V1);
7944   V2 = DAG.getBitcast(MVT::v2f64, V2);
7945   return DAG.getBitcast(MVT::v2i64,
7946                         DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
7947 }
7948
7949 /// \brief Test whether this can be lowered with a single SHUFPS instruction.
7950 ///
7951 /// This is used to disable more specialized lowerings when the shufps lowering
7952 /// will happen to be efficient.
7953 static bool isSingleSHUFPSMask(ArrayRef<int> Mask) {
7954   // This routine only handles 128-bit shufps.
7955   assert(Mask.size() == 4 && "Unsupported mask size!");
7956
7957   // To lower with a single SHUFPS we need to have the low half and high half
7958   // each requiring a single input.
7959   if (Mask[0] != -1 && Mask[1] != -1 && (Mask[0] < 4) != (Mask[1] < 4))
7960     return false;
7961   if (Mask[2] != -1 && Mask[3] != -1 && (Mask[2] < 4) != (Mask[3] < 4))
7962     return false;
7963
7964   return true;
7965 }
7966
7967 /// \brief Lower a vector shuffle using the SHUFPS instruction.
7968 ///
7969 /// This is a helper routine dedicated to lowering vector shuffles using SHUFPS.
7970 /// It makes no assumptions about whether this is the *best* lowering, it simply
7971 /// uses it.
7972 static SDValue lowerVectorShuffleWithSHUFPS(SDLoc DL, MVT VT,
7973                                             ArrayRef<int> Mask, SDValue V1,
7974                                             SDValue V2, SelectionDAG &DAG) {
7975   SDValue LowV = V1, HighV = V2;
7976   int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
7977
7978   int NumV2Elements =
7979       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7980
7981   if (NumV2Elements == 1) {
7982     int V2Index =
7983         std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
7984         Mask.begin();
7985
7986     // Compute the index adjacent to V2Index and in the same half by toggling
7987     // the low bit.
7988     int V2AdjIndex = V2Index ^ 1;
7989
7990     if (Mask[V2AdjIndex] == -1) {
7991       // Handles all the cases where we have a single V2 element and an undef.
7992       // This will only ever happen in the high lanes because we commute the
7993       // vector otherwise.
7994       if (V2Index < 2)
7995         std::swap(LowV, HighV);
7996       NewMask[V2Index] -= 4;
7997     } else {
7998       // Handle the case where the V2 element ends up adjacent to a V1 element.
7999       // To make this work, blend them together as the first step.
8000       int V1Index = V2AdjIndex;
8001       int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
8002       V2 = DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
8003                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
8004
8005       // Now proceed to reconstruct the final blend as we have the necessary
8006       // high or low half formed.
8007       if (V2Index < 2) {
8008         LowV = V2;
8009         HighV = V1;
8010       } else {
8011         HighV = V2;
8012       }
8013       NewMask[V1Index] = 2; // We put the V1 element in V2[2].
8014       NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
8015     }
8016   } else if (NumV2Elements == 2) {
8017     if (Mask[0] < 4 && Mask[1] < 4) {
8018       // Handle the easy case where we have V1 in the low lanes and V2 in the
8019       // high lanes.
8020       NewMask[2] -= 4;
8021       NewMask[3] -= 4;
8022     } else if (Mask[2] < 4 && Mask[3] < 4) {
8023       // We also handle the reversed case because this utility may get called
8024       // when we detect a SHUFPS pattern but can't easily commute the shuffle to
8025       // arrange things in the right direction.
8026       NewMask[0] -= 4;
8027       NewMask[1] -= 4;
8028       HighV = V1;
8029       LowV = V2;
8030     } else {
8031       // We have a mixture of V1 and V2 in both low and high lanes. Rather than
8032       // trying to place elements directly, just blend them and set up the final
8033       // shuffle to place them.
8034
8035       // The first two blend mask elements are for V1, the second two are for
8036       // V2.
8037       int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
8038                           Mask[2] < 4 ? Mask[2] : Mask[3],
8039                           (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
8040                           (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
8041       V1 = DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
8042                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
8043
8044       // Now we do a normal shuffle of V1 by giving V1 as both operands to
8045       // a blend.
8046       LowV = HighV = V1;
8047       NewMask[0] = Mask[0] < 4 ? 0 : 2;
8048       NewMask[1] = Mask[0] < 4 ? 2 : 0;
8049       NewMask[2] = Mask[2] < 4 ? 1 : 3;
8050       NewMask[3] = Mask[2] < 4 ? 3 : 1;
8051     }
8052   }
8053   return DAG.getNode(X86ISD::SHUFP, DL, VT, LowV, HighV,
8054                      getV4X86ShuffleImm8ForMask(NewMask, DL, DAG));
8055 }
8056
8057 /// \brief Lower 4-lane 32-bit floating point shuffles.
8058 ///
8059 /// Uses instructions exclusively from the floating point unit to minimize
8060 /// domain crossing penalties, as these are sufficient to implement all v4f32
8061 /// shuffles.
8062 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8063                                        const X86Subtarget *Subtarget,
8064                                        SelectionDAG &DAG) {
8065   SDLoc DL(Op);
8066   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
8067   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8068   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8069   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8070   ArrayRef<int> Mask = SVOp->getMask();
8071   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8072
8073   int NumV2Elements =
8074       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8075
8076   if (NumV2Elements == 0) {
8077     // Check for being able to broadcast a single element.
8078     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f32, V1,
8079                                                           Mask, Subtarget, DAG))
8080       return Broadcast;
8081
8082     // Use even/odd duplicate instructions for masks that match their pattern.
8083     if (Subtarget->hasSSE3()) {
8084       if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
8085         return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v4f32, V1);
8086       if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3}))
8087         return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v4f32, V1);
8088     }
8089
8090     if (Subtarget->hasAVX()) {
8091       // If we have AVX, we can use VPERMILPS which will allow folding a load
8092       // into the shuffle.
8093       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f32, V1,
8094                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8095     }
8096
8097     // Otherwise, use a straight shuffle of a single input vector. We pass the
8098     // input vector to both operands to simulate this with a SHUFPS.
8099     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
8100                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8101   }
8102
8103   // There are special ways we can lower some single-element blends. However, we
8104   // have custom ways we can lower more complex single-element blends below that
8105   // we defer to if both this and BLENDPS fail to match, so restrict this to
8106   // when the V2 input is targeting element 0 of the mask -- that is the fast
8107   // case here.
8108   if (NumV2Elements == 1 && Mask[0] >= 4)
8109     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4f32, V1, V2,
8110                                                          Mask, Subtarget, DAG))
8111       return V;
8112
8113   if (Subtarget->hasSSE41()) {
8114     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f32, V1, V2, Mask,
8115                                                   Subtarget, DAG))
8116       return Blend;
8117
8118     // Use INSERTPS if we can complete the shuffle efficiently.
8119     if (SDValue V = lowerVectorShuffleAsInsertPS(Op, V1, V2, Mask, DAG))
8120       return V;
8121
8122     if (!isSingleSHUFPSMask(Mask))
8123       if (SDValue BlendPerm = lowerVectorShuffleAsBlendAndPermute(
8124               DL, MVT::v4f32, V1, V2, Mask, DAG))
8125         return BlendPerm;
8126   }
8127
8128   // Use dedicated unpack instructions for masks that match their pattern.
8129   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
8130     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V1, V2);
8131   if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
8132     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V1, V2);
8133   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
8134     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V2, V1);
8135   if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
8136     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V2, V1);
8137
8138   // Otherwise fall back to a SHUFPS lowering strategy.
8139   return lowerVectorShuffleWithSHUFPS(DL, MVT::v4f32, Mask, V1, V2, DAG);
8140 }
8141
8142 /// \brief Lower 4-lane i32 vector shuffles.
8143 ///
8144 /// We try to handle these with integer-domain shuffles where we can, but for
8145 /// blends we use the floating point domain blend instructions.
8146 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8147                                        const X86Subtarget *Subtarget,
8148                                        SelectionDAG &DAG) {
8149   SDLoc DL(Op);
8150   assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
8151   assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8152   assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8153   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8154   ArrayRef<int> Mask = SVOp->getMask();
8155   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8156
8157   // Whenever we can lower this as a zext, that instruction is strictly faster
8158   // than any alternative. It also allows us to fold memory operands into the
8159   // shuffle in many cases.
8160   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v4i32, V1, V2,
8161                                                          Mask, Subtarget, DAG))
8162     return ZExt;
8163
8164   int NumV2Elements =
8165       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8166
8167   if (NumV2Elements == 0) {
8168     // Check for being able to broadcast a single element.
8169     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i32, V1,
8170                                                           Mask, Subtarget, DAG))
8171       return Broadcast;
8172
8173     // Straight shuffle of a single input vector. For everything from SSE2
8174     // onward this has a single fast instruction with no scary immediates.
8175     // We coerce the shuffle pattern to be compatible with UNPCK instructions
8176     // but we aren't actually going to use the UNPCK instruction because doing
8177     // so prevents folding a load into this instruction or making a copy.
8178     const int UnpackLoMask[] = {0, 0, 1, 1};
8179     const int UnpackHiMask[] = {2, 2, 3, 3};
8180     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 1, 1}))
8181       Mask = UnpackLoMask;
8182     else if (isShuffleEquivalent(V1, V2, Mask, {2, 2, 3, 3}))
8183       Mask = UnpackHiMask;
8184
8185     return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
8186                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8187   }
8188
8189   // Try to use shift instructions.
8190   if (SDValue Shift =
8191           lowerVectorShuffleAsShift(DL, MVT::v4i32, V1, V2, Mask, DAG))
8192     return Shift;
8193
8194   // There are special ways we can lower some single-element blends.
8195   if (NumV2Elements == 1)
8196     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4i32, V1, V2,
8197                                                          Mask, Subtarget, DAG))
8198       return V;
8199
8200   // We have different paths for blend lowering, but they all must use the
8201   // *exact* same predicate.
8202   bool IsBlendSupported = Subtarget->hasSSE41();
8203   if (IsBlendSupported)
8204     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i32, V1, V2, Mask,
8205                                                   Subtarget, DAG))
8206       return Blend;
8207
8208   if (SDValue Masked =
8209           lowerVectorShuffleAsBitMask(DL, MVT::v4i32, V1, V2, Mask, DAG))
8210     return Masked;
8211
8212   // Use dedicated unpack instructions for masks that match their pattern.
8213   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
8214     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V1, V2);
8215   if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
8216     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V1, V2);
8217   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
8218     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V2, V1);
8219   if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
8220     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V2, V1);
8221
8222   // Try to use byte rotation instructions.
8223   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
8224   if (Subtarget->hasSSSE3())
8225     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8226             DL, MVT::v4i32, V1, V2, Mask, Subtarget, DAG))
8227       return Rotate;
8228
8229   // If we have direct support for blends, we should lower by decomposing into
8230   // a permute. That will be faster than the domain cross.
8231   if (IsBlendSupported)
8232     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i32, V1, V2,
8233                                                       Mask, DAG);
8234
8235   // Try to lower by permuting the inputs into an unpack instruction.
8236   if (SDValue Unpack =
8237           lowerVectorShuffleAsUnpack(DL, MVT::v4i32, V1, V2, Mask, DAG))
8238     return Unpack;
8239
8240   // We implement this with SHUFPS because it can blend from two vectors.
8241   // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
8242   // up the inputs, bypassing domain shift penalties that we would encur if we
8243   // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
8244   // relevant.
8245   return DAG.getBitcast(
8246       MVT::v4i32,
8247       DAG.getVectorShuffle(MVT::v4f32, DL, DAG.getBitcast(MVT::v4f32, V1),
8248                            DAG.getBitcast(MVT::v4f32, V2), Mask));
8249 }
8250
8251 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
8252 /// shuffle lowering, and the most complex part.
8253 ///
8254 /// The lowering strategy is to try to form pairs of input lanes which are
8255 /// targeted at the same half of the final vector, and then use a dword shuffle
8256 /// to place them onto the right half, and finally unpack the paired lanes into
8257 /// their final position.
8258 ///
8259 /// The exact breakdown of how to form these dword pairs and align them on the
8260 /// correct sides is really tricky. See the comments within the function for
8261 /// more of the details.
8262 ///
8263 /// This code also handles repeated 128-bit lanes of v8i16 shuffles, but each
8264 /// lane must shuffle the *exact* same way. In fact, you must pass a v8 Mask to
8265 /// this routine for it to work correctly. To shuffle a 256-bit or 512-bit i16
8266 /// vector, form the analogous 128-bit 8-element Mask.
8267 static SDValue lowerV8I16GeneralSingleInputVectorShuffle(
8268     SDLoc DL, MVT VT, SDValue V, MutableArrayRef<int> Mask,
8269     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
8270   assert(VT.getScalarType() == MVT::i16 && "Bad input type!");
8271   MVT PSHUFDVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
8272
8273   assert(Mask.size() == 8 && "Shuffle mask length doen't match!");
8274   MutableArrayRef<int> LoMask = Mask.slice(0, 4);
8275   MutableArrayRef<int> HiMask = Mask.slice(4, 4);
8276
8277   SmallVector<int, 4> LoInputs;
8278   std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
8279                [](int M) { return M >= 0; });
8280   std::sort(LoInputs.begin(), LoInputs.end());
8281   LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
8282   SmallVector<int, 4> HiInputs;
8283   std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
8284                [](int M) { return M >= 0; });
8285   std::sort(HiInputs.begin(), HiInputs.end());
8286   HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
8287   int NumLToL =
8288       std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
8289   int NumHToL = LoInputs.size() - NumLToL;
8290   int NumLToH =
8291       std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
8292   int NumHToH = HiInputs.size() - NumLToH;
8293   MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
8294   MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
8295   MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
8296   MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
8297
8298   // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
8299   // such inputs we can swap two of the dwords across the half mark and end up
8300   // with <=2 inputs to each half in each half. Once there, we can fall through
8301   // to the generic code below. For example:
8302   //
8303   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8304   // Mask:  [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
8305   //
8306   // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
8307   // and an existing 2-into-2 on the other half. In this case we may have to
8308   // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
8309   // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
8310   // Fortunately, we don't have to handle anything but a 2-into-2 pattern
8311   // because any other situation (including a 3-into-1 or 1-into-3 in the other
8312   // half than the one we target for fixing) will be fixed when we re-enter this
8313   // path. We will also combine away any sequence of PSHUFD instructions that
8314   // result into a single instruction. Here is an example of the tricky case:
8315   //
8316   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8317   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
8318   //
8319   // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
8320   //
8321   // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
8322   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
8323   //
8324   // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
8325   // Mask:  [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
8326   //
8327   // The result is fine to be handled by the generic logic.
8328   auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
8329                           ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
8330                           int AOffset, int BOffset) {
8331     assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
8332            "Must call this with A having 3 or 1 inputs from the A half.");
8333     assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
8334            "Must call this with B having 1 or 3 inputs from the B half.");
8335     assert(AToAInputs.size() + BToAInputs.size() == 4 &&
8336            "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
8337
8338     // Compute the index of dword with only one word among the three inputs in
8339     // a half by taking the sum of the half with three inputs and subtracting
8340     // the sum of the actual three inputs. The difference is the remaining
8341     // slot.
8342     int ADWord, BDWord;
8343     int &TripleDWord = AToAInputs.size() == 3 ? ADWord : BDWord;
8344     int &OneInputDWord = AToAInputs.size() == 3 ? BDWord : ADWord;
8345     int TripleInputOffset = AToAInputs.size() == 3 ? AOffset : BOffset;
8346     ArrayRef<int> TripleInputs = AToAInputs.size() == 3 ? AToAInputs : BToAInputs;
8347     int OneInput = AToAInputs.size() == 3 ? BToAInputs[0] : AToAInputs[0];
8348     int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
8349     int TripleNonInputIdx =
8350         TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
8351     TripleDWord = TripleNonInputIdx / 2;
8352
8353     // We use xor with one to compute the adjacent DWord to whichever one the
8354     // OneInput is in.
8355     OneInputDWord = (OneInput / 2) ^ 1;
8356
8357     // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
8358     // and BToA inputs. If there is also such a problem with the BToB and AToB
8359     // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
8360     // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
8361     // is essential that we don't *create* a 3<-1 as then we might oscillate.
8362     if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
8363       // Compute how many inputs will be flipped by swapping these DWords. We
8364       // need
8365       // to balance this to ensure we don't form a 3-1 shuffle in the other
8366       // half.
8367       int NumFlippedAToBInputs =
8368           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
8369           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
8370       int NumFlippedBToBInputs =
8371           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
8372           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
8373       if ((NumFlippedAToBInputs == 1 &&
8374            (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
8375           (NumFlippedBToBInputs == 1 &&
8376            (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
8377         // We choose whether to fix the A half or B half based on whether that
8378         // half has zero flipped inputs. At zero, we may not be able to fix it
8379         // with that half. We also bias towards fixing the B half because that
8380         // will more commonly be the high half, and we have to bias one way.
8381         auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
8382                                                        ArrayRef<int> Inputs) {
8383           int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
8384           bool IsFixIdxInput = std::find(Inputs.begin(), Inputs.end(),
8385                                          PinnedIdx ^ 1) != Inputs.end();
8386           // Determine whether the free index is in the flipped dword or the
8387           // unflipped dword based on where the pinned index is. We use this bit
8388           // in an xor to conditionally select the adjacent dword.
8389           int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
8390           bool IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8391                                              FixFreeIdx) != Inputs.end();
8392           if (IsFixIdxInput == IsFixFreeIdxInput)
8393             FixFreeIdx += 1;
8394           IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8395                                         FixFreeIdx) != Inputs.end();
8396           assert(IsFixIdxInput != IsFixFreeIdxInput &&
8397                  "We need to be changing the number of flipped inputs!");
8398           int PSHUFHalfMask[] = {0, 1, 2, 3};
8399           std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
8400           V = DAG.getNode(FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
8401                           MVT::v8i16, V,
8402                           getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DL, DAG));
8403
8404           for (int &M : Mask)
8405             if (M != -1 && M == FixIdx)
8406               M = FixFreeIdx;
8407             else if (M != -1 && M == FixFreeIdx)
8408               M = FixIdx;
8409         };
8410         if (NumFlippedBToBInputs != 0) {
8411           int BPinnedIdx =
8412               BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8413           FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
8414         } else {
8415           assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
8416           int APinnedIdx =
8417               AToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8418           FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
8419         }
8420       }
8421     }
8422
8423     int PSHUFDMask[] = {0, 1, 2, 3};
8424     PSHUFDMask[ADWord] = BDWord;
8425     PSHUFDMask[BDWord] = ADWord;
8426     V = DAG.getBitcast(
8427         VT,
8428         DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
8429                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
8430
8431     // Adjust the mask to match the new locations of A and B.
8432     for (int &M : Mask)
8433       if (M != -1 && M/2 == ADWord)
8434         M = 2 * BDWord + M % 2;
8435       else if (M != -1 && M/2 == BDWord)
8436         M = 2 * ADWord + M % 2;
8437
8438     // Recurse back into this routine to re-compute state now that this isn't
8439     // a 3 and 1 problem.
8440     return lowerV8I16GeneralSingleInputVectorShuffle(DL, VT, V, Mask, Subtarget,
8441                                                      DAG);
8442   };
8443   if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
8444     return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
8445   else if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
8446     return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
8447
8448   // At this point there are at most two inputs to the low and high halves from
8449   // each half. That means the inputs can always be grouped into dwords and
8450   // those dwords can then be moved to the correct half with a dword shuffle.
8451   // We use at most one low and one high word shuffle to collect these paired
8452   // inputs into dwords, and finally a dword shuffle to place them.
8453   int PSHUFLMask[4] = {-1, -1, -1, -1};
8454   int PSHUFHMask[4] = {-1, -1, -1, -1};
8455   int PSHUFDMask[4] = {-1, -1, -1, -1};
8456
8457   // First fix the masks for all the inputs that are staying in their
8458   // original halves. This will then dictate the targets of the cross-half
8459   // shuffles.
8460   auto fixInPlaceInputs =
8461       [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
8462                     MutableArrayRef<int> SourceHalfMask,
8463                     MutableArrayRef<int> HalfMask, int HalfOffset) {
8464     if (InPlaceInputs.empty())
8465       return;
8466     if (InPlaceInputs.size() == 1) {
8467       SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8468           InPlaceInputs[0] - HalfOffset;
8469       PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
8470       return;
8471     }
8472     if (IncomingInputs.empty()) {
8473       // Just fix all of the in place inputs.
8474       for (int Input : InPlaceInputs) {
8475         SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
8476         PSHUFDMask[Input / 2] = Input / 2;
8477       }
8478       return;
8479     }
8480
8481     assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
8482     SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8483         InPlaceInputs[0] - HalfOffset;
8484     // Put the second input next to the first so that they are packed into
8485     // a dword. We find the adjacent index by toggling the low bit.
8486     int AdjIndex = InPlaceInputs[0] ^ 1;
8487     SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
8488     std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
8489     PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
8490   };
8491   fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
8492   fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
8493
8494   // Now gather the cross-half inputs and place them into a free dword of
8495   // their target half.
8496   // FIXME: This operation could almost certainly be simplified dramatically to
8497   // look more like the 3-1 fixing operation.
8498   auto moveInputsToRightHalf = [&PSHUFDMask](
8499       MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
8500       MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
8501       MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
8502       int DestOffset) {
8503     auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
8504       return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
8505     };
8506     auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
8507                                                int Word) {
8508       int LowWord = Word & ~1;
8509       int HighWord = Word | 1;
8510       return isWordClobbered(SourceHalfMask, LowWord) ||
8511              isWordClobbered(SourceHalfMask, HighWord);
8512     };
8513
8514     if (IncomingInputs.empty())
8515       return;
8516
8517     if (ExistingInputs.empty()) {
8518       // Map any dwords with inputs from them into the right half.
8519       for (int Input : IncomingInputs) {
8520         // If the source half mask maps over the inputs, turn those into
8521         // swaps and use the swapped lane.
8522         if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
8523           if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
8524             SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
8525                 Input - SourceOffset;
8526             // We have to swap the uses in our half mask in one sweep.
8527             for (int &M : HalfMask)
8528               if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
8529                 M = Input;
8530               else if (M == Input)
8531                 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8532           } else {
8533             assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
8534                        Input - SourceOffset &&
8535                    "Previous placement doesn't match!");
8536           }
8537           // Note that this correctly re-maps both when we do a swap and when
8538           // we observe the other side of the swap above. We rely on that to
8539           // avoid swapping the members of the input list directly.
8540           Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8541         }
8542
8543         // Map the input's dword into the correct half.
8544         if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
8545           PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
8546         else
8547           assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
8548                      Input / 2 &&
8549                  "Previous placement doesn't match!");
8550       }
8551
8552       // And just directly shift any other-half mask elements to be same-half
8553       // as we will have mirrored the dword containing the element into the
8554       // same position within that half.
8555       for (int &M : HalfMask)
8556         if (M >= SourceOffset && M < SourceOffset + 4) {
8557           M = M - SourceOffset + DestOffset;
8558           assert(M >= 0 && "This should never wrap below zero!");
8559         }
8560       return;
8561     }
8562
8563     // Ensure we have the input in a viable dword of its current half. This
8564     // is particularly tricky because the original position may be clobbered
8565     // by inputs being moved and *staying* in that half.
8566     if (IncomingInputs.size() == 1) {
8567       if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8568         int InputFixed = std::find(std::begin(SourceHalfMask),
8569                                    std::end(SourceHalfMask), -1) -
8570                          std::begin(SourceHalfMask) + SourceOffset;
8571         SourceHalfMask[InputFixed - SourceOffset] =
8572             IncomingInputs[0] - SourceOffset;
8573         std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
8574                      InputFixed);
8575         IncomingInputs[0] = InputFixed;
8576       }
8577     } else if (IncomingInputs.size() == 2) {
8578       if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
8579           isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8580         // We have two non-adjacent or clobbered inputs we need to extract from
8581         // the source half. To do this, we need to map them into some adjacent
8582         // dword slot in the source mask.
8583         int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
8584                               IncomingInputs[1] - SourceOffset};
8585
8586         // If there is a free slot in the source half mask adjacent to one of
8587         // the inputs, place the other input in it. We use (Index XOR 1) to
8588         // compute an adjacent index.
8589         if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
8590             SourceHalfMask[InputsFixed[0] ^ 1] == -1) {
8591           SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
8592           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8593           InputsFixed[1] = InputsFixed[0] ^ 1;
8594         } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
8595                    SourceHalfMask[InputsFixed[1] ^ 1] == -1) {
8596           SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
8597           SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
8598           InputsFixed[0] = InputsFixed[1] ^ 1;
8599         } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] == -1 &&
8600                    SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] == -1) {
8601           // The two inputs are in the same DWord but it is clobbered and the
8602           // adjacent DWord isn't used at all. Move both inputs to the free
8603           // slot.
8604           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
8605           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
8606           InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
8607           InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
8608         } else {
8609           // The only way we hit this point is if there is no clobbering
8610           // (because there are no off-half inputs to this half) and there is no
8611           // free slot adjacent to one of the inputs. In this case, we have to
8612           // swap an input with a non-input.
8613           for (int i = 0; i < 4; ++i)
8614             assert((SourceHalfMask[i] == -1 || SourceHalfMask[i] == i) &&
8615                    "We can't handle any clobbers here!");
8616           assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
8617                  "Cannot have adjacent inputs here!");
8618
8619           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8620           SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
8621
8622           // We also have to update the final source mask in this case because
8623           // it may need to undo the above swap.
8624           for (int &M : FinalSourceHalfMask)
8625             if (M == (InputsFixed[0] ^ 1) + SourceOffset)
8626               M = InputsFixed[1] + SourceOffset;
8627             else if (M == InputsFixed[1] + SourceOffset)
8628               M = (InputsFixed[0] ^ 1) + SourceOffset;
8629
8630           InputsFixed[1] = InputsFixed[0] ^ 1;
8631         }
8632
8633         // Point everything at the fixed inputs.
8634         for (int &M : HalfMask)
8635           if (M == IncomingInputs[0])
8636             M = InputsFixed[0] + SourceOffset;
8637           else if (M == IncomingInputs[1])
8638             M = InputsFixed[1] + SourceOffset;
8639
8640         IncomingInputs[0] = InputsFixed[0] + SourceOffset;
8641         IncomingInputs[1] = InputsFixed[1] + SourceOffset;
8642       }
8643     } else {
8644       llvm_unreachable("Unhandled input size!");
8645     }
8646
8647     // Now hoist the DWord down to the right half.
8648     int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
8649     assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
8650     PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
8651     for (int &M : HalfMask)
8652       for (int Input : IncomingInputs)
8653         if (M == Input)
8654           M = FreeDWord * 2 + Input % 2;
8655   };
8656   moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
8657                         /*SourceOffset*/ 4, /*DestOffset*/ 0);
8658   moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
8659                         /*SourceOffset*/ 0, /*DestOffset*/ 4);
8660
8661   // Now enact all the shuffles we've computed to move the inputs into their
8662   // target half.
8663   if (!isNoopShuffleMask(PSHUFLMask))
8664     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8665                     getV4X86ShuffleImm8ForMask(PSHUFLMask, DL, DAG));
8666   if (!isNoopShuffleMask(PSHUFHMask))
8667     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8668                     getV4X86ShuffleImm8ForMask(PSHUFHMask, DL, DAG));
8669   if (!isNoopShuffleMask(PSHUFDMask))
8670     V = DAG.getBitcast(
8671         VT,
8672         DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
8673                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
8674
8675   // At this point, each half should contain all its inputs, and we can then
8676   // just shuffle them into their final position.
8677   assert(std::count_if(LoMask.begin(), LoMask.end(),
8678                        [](int M) { return M >= 4; }) == 0 &&
8679          "Failed to lift all the high half inputs to the low mask!");
8680   assert(std::count_if(HiMask.begin(), HiMask.end(),
8681                        [](int M) { return M >= 0 && M < 4; }) == 0 &&
8682          "Failed to lift all the low half inputs to the high mask!");
8683
8684   // Do a half shuffle for the low mask.
8685   if (!isNoopShuffleMask(LoMask))
8686     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8687                     getV4X86ShuffleImm8ForMask(LoMask, DL, DAG));
8688
8689   // Do a half shuffle with the high mask after shifting its values down.
8690   for (int &M : HiMask)
8691     if (M >= 0)
8692       M -= 4;
8693   if (!isNoopShuffleMask(HiMask))
8694     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8695                     getV4X86ShuffleImm8ForMask(HiMask, DL, DAG));
8696
8697   return V;
8698 }
8699
8700 /// \brief Helper to form a PSHUFB-based shuffle+blend.
8701 static SDValue lowerVectorShuffleAsPSHUFB(SDLoc DL, MVT VT, SDValue V1,
8702                                           SDValue V2, ArrayRef<int> Mask,
8703                                           SelectionDAG &DAG, bool &V1InUse,
8704                                           bool &V2InUse) {
8705   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
8706   SDValue V1Mask[16];
8707   SDValue V2Mask[16];
8708   V1InUse = false;
8709   V2InUse = false;
8710
8711   int Size = Mask.size();
8712   int Scale = 16 / Size;
8713   for (int i = 0; i < 16; ++i) {
8714     if (Mask[i / Scale] == -1) {
8715       V1Mask[i] = V2Mask[i] = DAG.getUNDEF(MVT::i8);
8716     } else {
8717       const int ZeroMask = 0x80;
8718       int V1Idx = Mask[i / Scale] < Size ? Mask[i / Scale] * Scale + i % Scale
8719                                           : ZeroMask;
8720       int V2Idx = Mask[i / Scale] < Size
8721                       ? ZeroMask
8722                       : (Mask[i / Scale] - Size) * Scale + i % Scale;
8723       if (Zeroable[i / Scale])
8724         V1Idx = V2Idx = ZeroMask;
8725       V1Mask[i] = DAG.getConstant(V1Idx, DL, MVT::i8);
8726       V2Mask[i] = DAG.getConstant(V2Idx, DL, MVT::i8);
8727       V1InUse |= (ZeroMask != V1Idx);
8728       V2InUse |= (ZeroMask != V2Idx);
8729     }
8730   }
8731
8732   if (V1InUse)
8733     V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8734                      DAG.getBitcast(MVT::v16i8, V1),
8735                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
8736   if (V2InUse)
8737     V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8738                      DAG.getBitcast(MVT::v16i8, V2),
8739                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
8740
8741   // If we need shuffled inputs from both, blend the two.
8742   SDValue V;
8743   if (V1InUse && V2InUse)
8744     V = DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
8745   else
8746     V = V1InUse ? V1 : V2;
8747
8748   // Cast the result back to the correct type.
8749   return DAG.getBitcast(VT, V);
8750 }
8751
8752 /// \brief Generic lowering of 8-lane i16 shuffles.
8753 ///
8754 /// This handles both single-input shuffles and combined shuffle/blends with
8755 /// two inputs. The single input shuffles are immediately delegated to
8756 /// a dedicated lowering routine.
8757 ///
8758 /// The blends are lowered in one of three fundamental ways. If there are few
8759 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
8760 /// of the input is significantly cheaper when lowered as an interleaving of
8761 /// the two inputs, try to interleave them. Otherwise, blend the low and high
8762 /// halves of the inputs separately (making them have relatively few inputs)
8763 /// and then concatenate them.
8764 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8765                                        const X86Subtarget *Subtarget,
8766                                        SelectionDAG &DAG) {
8767   SDLoc DL(Op);
8768   assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
8769   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8770   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8771   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8772   ArrayRef<int> OrigMask = SVOp->getMask();
8773   int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
8774                         OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
8775   MutableArrayRef<int> Mask(MaskStorage);
8776
8777   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
8778
8779   // Whenever we can lower this as a zext, that instruction is strictly faster
8780   // than any alternative.
8781   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
8782           DL, MVT::v8i16, V1, V2, OrigMask, Subtarget, DAG))
8783     return ZExt;
8784
8785   auto isV1 = [](int M) { return M >= 0 && M < 8; };
8786   (void)isV1;
8787   auto isV2 = [](int M) { return M >= 8; };
8788
8789   int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
8790
8791   if (NumV2Inputs == 0) {
8792     // Check for being able to broadcast a single element.
8793     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i16, V1,
8794                                                           Mask, Subtarget, DAG))
8795       return Broadcast;
8796
8797     // Try to use shift instructions.
8798     if (SDValue Shift =
8799             lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V1, Mask, DAG))
8800       return Shift;
8801
8802     // Use dedicated unpack instructions for masks that match their pattern.
8803     if (isShuffleEquivalent(V1, V1, Mask, {0, 0, 1, 1, 2, 2, 3, 3}))
8804       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V1);
8805     if (isShuffleEquivalent(V1, V1, Mask, {4, 4, 5, 5, 6, 6, 7, 7}))
8806       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V1);
8807
8808     // Try to use byte rotation instructions.
8809     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(DL, MVT::v8i16, V1, V1,
8810                                                         Mask, Subtarget, DAG))
8811       return Rotate;
8812
8813     return lowerV8I16GeneralSingleInputVectorShuffle(DL, MVT::v8i16, V1, Mask,
8814                                                      Subtarget, DAG);
8815   }
8816
8817   assert(std::any_of(Mask.begin(), Mask.end(), isV1) &&
8818          "All single-input shuffles should be canonicalized to be V1-input "
8819          "shuffles.");
8820
8821   // Try to use shift instructions.
8822   if (SDValue Shift =
8823           lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V2, Mask, DAG))
8824     return Shift;
8825
8826   // See if we can use SSE4A Extraction / Insertion.
8827   if (Subtarget->hasSSE4A())
8828     if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v8i16, V1, V2, Mask, DAG))
8829       return V;
8830
8831   // There are special ways we can lower some single-element blends.
8832   if (NumV2Inputs == 1)
8833     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v8i16, V1, V2,
8834                                                          Mask, Subtarget, DAG))
8835       return V;
8836
8837   // We have different paths for blend lowering, but they all must use the
8838   // *exact* same predicate.
8839   bool IsBlendSupported = Subtarget->hasSSE41();
8840   if (IsBlendSupported)
8841     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i16, V1, V2, Mask,
8842                                                   Subtarget, DAG))
8843       return Blend;
8844
8845   if (SDValue Masked =
8846           lowerVectorShuffleAsBitMask(DL, MVT::v8i16, V1, V2, Mask, DAG))
8847     return Masked;
8848
8849   // Use dedicated unpack instructions for masks that match their pattern.
8850   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 2, 10, 3, 11}))
8851     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V2);
8852   if (isShuffleEquivalent(V1, V2, Mask, {4, 12, 5, 13, 6, 14, 7, 15}))
8853     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V2);
8854
8855   // Try to use byte rotation instructions.
8856   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8857           DL, MVT::v8i16, V1, V2, Mask, Subtarget, DAG))
8858     return Rotate;
8859
8860   if (SDValue BitBlend =
8861           lowerVectorShuffleAsBitBlend(DL, MVT::v8i16, V1, V2, Mask, DAG))
8862     return BitBlend;
8863
8864   if (SDValue Unpack =
8865           lowerVectorShuffleAsUnpack(DL, MVT::v8i16, V1, V2, Mask, DAG))
8866     return Unpack;
8867
8868   // If we can't directly blend but can use PSHUFB, that will be better as it
8869   // can both shuffle and set up the inefficient blend.
8870   if (!IsBlendSupported && Subtarget->hasSSSE3()) {
8871     bool V1InUse, V2InUse;
8872     return lowerVectorShuffleAsPSHUFB(DL, MVT::v8i16, V1, V2, Mask, DAG,
8873                                       V1InUse, V2InUse);
8874   }
8875
8876   // We can always bit-blend if we have to so the fallback strategy is to
8877   // decompose into single-input permutes and blends.
8878   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i16, V1, V2,
8879                                                       Mask, DAG);
8880 }
8881
8882 /// \brief Check whether a compaction lowering can be done by dropping even
8883 /// elements and compute how many times even elements must be dropped.
8884 ///
8885 /// This handles shuffles which take every Nth element where N is a power of
8886 /// two. Example shuffle masks:
8887 ///
8888 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14,  0,  2,  4,  6,  8, 10, 12, 14
8889 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
8890 ///  N = 2:  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12
8891 ///  N = 2:  0,  4,  8, 12, 16, 20, 24, 28,  0,  4,  8, 12, 16, 20, 24, 28
8892 ///  N = 3:  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8
8893 ///  N = 3:  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24
8894 ///
8895 /// Any of these lanes can of course be undef.
8896 ///
8897 /// This routine only supports N <= 3.
8898 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
8899 /// for larger N.
8900 ///
8901 /// \returns N above, or the number of times even elements must be dropped if
8902 /// there is such a number. Otherwise returns zero.
8903 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
8904   // Figure out whether we're looping over two inputs or just one.
8905   bool IsSingleInput = isSingleInputShuffleMask(Mask);
8906
8907   // The modulus for the shuffle vector entries is based on whether this is
8908   // a single input or not.
8909   int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
8910   assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
8911          "We should only be called with masks with a power-of-2 size!");
8912
8913   uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
8914
8915   // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
8916   // and 2^3 simultaneously. This is because we may have ambiguity with
8917   // partially undef inputs.
8918   bool ViableForN[3] = {true, true, true};
8919
8920   for (int i = 0, e = Mask.size(); i < e; ++i) {
8921     // Ignore undef lanes, we'll optimistically collapse them to the pattern we
8922     // want.
8923     if (Mask[i] == -1)
8924       continue;
8925
8926     bool IsAnyViable = false;
8927     for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8928       if (ViableForN[j]) {
8929         uint64_t N = j + 1;
8930
8931         // The shuffle mask must be equal to (i * 2^N) % M.
8932         if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
8933           IsAnyViable = true;
8934         else
8935           ViableForN[j] = false;
8936       }
8937     // Early exit if we exhaust the possible powers of two.
8938     if (!IsAnyViable)
8939       break;
8940   }
8941
8942   for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8943     if (ViableForN[j])
8944       return j + 1;
8945
8946   // Return 0 as there is no viable power of two.
8947   return 0;
8948 }
8949
8950 /// \brief Generic lowering of v16i8 shuffles.
8951 ///
8952 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
8953 /// detect any complexity reducing interleaving. If that doesn't help, it uses
8954 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
8955 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
8956 /// back together.
8957 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8958                                        const X86Subtarget *Subtarget,
8959                                        SelectionDAG &DAG) {
8960   SDLoc DL(Op);
8961   assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
8962   assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8963   assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8964   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8965   ArrayRef<int> Mask = SVOp->getMask();
8966   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
8967
8968   // Try to use shift instructions.
8969   if (SDValue Shift =
8970           lowerVectorShuffleAsShift(DL, MVT::v16i8, V1, V2, Mask, DAG))
8971     return Shift;
8972
8973   // Try to use byte rotation instructions.
8974   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8975           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
8976     return Rotate;
8977
8978   // Try to use a zext lowering.
8979   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
8980           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
8981     return ZExt;
8982
8983   // See if we can use SSE4A Extraction / Insertion.
8984   if (Subtarget->hasSSE4A())
8985     if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v16i8, V1, V2, Mask, DAG))
8986       return V;
8987
8988   int NumV2Elements =
8989       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 16; });
8990
8991   // For single-input shuffles, there are some nicer lowering tricks we can use.
8992   if (NumV2Elements == 0) {
8993     // Check for being able to broadcast a single element.
8994     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i8, V1,
8995                                                           Mask, Subtarget, DAG))
8996       return Broadcast;
8997
8998     // Check whether we can widen this to an i16 shuffle by duplicating bytes.
8999     // Notably, this handles splat and partial-splat shuffles more efficiently.
9000     // However, it only makes sense if the pre-duplication shuffle simplifies
9001     // things significantly. Currently, this means we need to be able to
9002     // express the pre-duplication shuffle as an i16 shuffle.
9003     //
9004     // FIXME: We should check for other patterns which can be widened into an
9005     // i16 shuffle as well.
9006     auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
9007       for (int i = 0; i < 16; i += 2)
9008         if (Mask[i] != -1 && Mask[i + 1] != -1 && Mask[i] != Mask[i + 1])
9009           return false;
9010
9011       return true;
9012     };
9013     auto tryToWidenViaDuplication = [&]() -> SDValue {
9014       if (!canWidenViaDuplication(Mask))
9015         return SDValue();
9016       SmallVector<int, 4> LoInputs;
9017       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
9018                    [](int M) { return M >= 0 && M < 8; });
9019       std::sort(LoInputs.begin(), LoInputs.end());
9020       LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
9021                      LoInputs.end());
9022       SmallVector<int, 4> HiInputs;
9023       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
9024                    [](int M) { return M >= 8; });
9025       std::sort(HiInputs.begin(), HiInputs.end());
9026       HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
9027                      HiInputs.end());
9028
9029       bool TargetLo = LoInputs.size() >= HiInputs.size();
9030       ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
9031       ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
9032
9033       int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
9034       SmallDenseMap<int, int, 8> LaneMap;
9035       for (int I : InPlaceInputs) {
9036         PreDupI16Shuffle[I/2] = I/2;
9037         LaneMap[I] = I;
9038       }
9039       int j = TargetLo ? 0 : 4, je = j + 4;
9040       for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
9041         // Check if j is already a shuffle of this input. This happens when
9042         // there are two adjacent bytes after we move the low one.
9043         if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
9044           // If we haven't yet mapped the input, search for a slot into which
9045           // we can map it.
9046           while (j < je && PreDupI16Shuffle[j] != -1)
9047             ++j;
9048
9049           if (j == je)
9050             // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
9051             return SDValue();
9052
9053           // Map this input with the i16 shuffle.
9054           PreDupI16Shuffle[j] = MovingInputs[i] / 2;
9055         }
9056
9057         // Update the lane map based on the mapping we ended up with.
9058         LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
9059       }
9060       V1 = DAG.getBitcast(
9061           MVT::v16i8,
9062           DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
9063                                DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
9064
9065       // Unpack the bytes to form the i16s that will be shuffled into place.
9066       V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
9067                        MVT::v16i8, V1, V1);
9068
9069       int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9070       for (int i = 0; i < 16; ++i)
9071         if (Mask[i] != -1) {
9072           int MappedMask = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
9073           assert(MappedMask < 8 && "Invalid v8 shuffle mask!");
9074           if (PostDupI16Shuffle[i / 2] == -1)
9075             PostDupI16Shuffle[i / 2] = MappedMask;
9076           else
9077             assert(PostDupI16Shuffle[i / 2] == MappedMask &&
9078                    "Conflicting entrties in the original shuffle!");
9079         }
9080       return DAG.getBitcast(
9081           MVT::v16i8,
9082           DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
9083                                DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
9084     };
9085     if (SDValue V = tryToWidenViaDuplication())
9086       return V;
9087   }
9088
9089   // Use dedicated unpack instructions for masks that match their pattern.
9090   if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
9091                                          0, 16, 1, 17, 2, 18, 3, 19,
9092                                          // High half.
9093                                          4, 20, 5, 21, 6, 22, 7, 23}))
9094     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V1, V2);
9095   if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
9096                                          8, 24, 9, 25, 10, 26, 11, 27,
9097                                          // High half.
9098                                          12, 28, 13, 29, 14, 30, 15, 31}))
9099     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V1, V2);
9100
9101   // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
9102   // with PSHUFB. It is important to do this before we attempt to generate any
9103   // blends but after all of the single-input lowerings. If the single input
9104   // lowerings can find an instruction sequence that is faster than a PSHUFB, we
9105   // want to preserve that and we can DAG combine any longer sequences into
9106   // a PSHUFB in the end. But once we start blending from multiple inputs,
9107   // the complexity of DAG combining bad patterns back into PSHUFB is too high,
9108   // and there are *very* few patterns that would actually be faster than the
9109   // PSHUFB approach because of its ability to zero lanes.
9110   //
9111   // FIXME: The only exceptions to the above are blends which are exact
9112   // interleavings with direct instructions supporting them. We currently don't
9113   // handle those well here.
9114   if (Subtarget->hasSSSE3()) {
9115     bool V1InUse = false;
9116     bool V2InUse = false;
9117
9118     SDValue PSHUFB = lowerVectorShuffleAsPSHUFB(DL, MVT::v16i8, V1, V2, Mask,
9119                                                 DAG, V1InUse, V2InUse);
9120
9121     // If both V1 and V2 are in use and we can use a direct blend or an unpack,
9122     // do so. This avoids using them to handle blends-with-zero which is
9123     // important as a single pshufb is significantly faster for that.
9124     if (V1InUse && V2InUse) {
9125       if (Subtarget->hasSSE41())
9126         if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i8, V1, V2,
9127                                                       Mask, Subtarget, DAG))
9128           return Blend;
9129
9130       // We can use an unpack to do the blending rather than an or in some
9131       // cases. Even though the or may be (very minorly) more efficient, we
9132       // preference this lowering because there are common cases where part of
9133       // the complexity of the shuffles goes away when we do the final blend as
9134       // an unpack.
9135       // FIXME: It might be worth trying to detect if the unpack-feeding
9136       // shuffles will both be pshufb, in which case we shouldn't bother with
9137       // this.
9138       if (SDValue Unpack =
9139               lowerVectorShuffleAsUnpack(DL, MVT::v16i8, V1, V2, Mask, DAG))
9140         return Unpack;
9141     }
9142
9143     return PSHUFB;
9144   }
9145
9146   // There are special ways we can lower some single-element blends.
9147   if (NumV2Elements == 1)
9148     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v16i8, V1, V2,
9149                                                          Mask, Subtarget, DAG))
9150       return V;
9151
9152   if (SDValue BitBlend =
9153           lowerVectorShuffleAsBitBlend(DL, MVT::v16i8, V1, V2, Mask, DAG))
9154     return BitBlend;
9155
9156   // Check whether a compaction lowering can be done. This handles shuffles
9157   // which take every Nth element for some even N. See the helper function for
9158   // details.
9159   //
9160   // We special case these as they can be particularly efficiently handled with
9161   // the PACKUSB instruction on x86 and they show up in common patterns of
9162   // rearranging bytes to truncate wide elements.
9163   if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
9164     // NumEvenDrops is the power of two stride of the elements. Another way of
9165     // thinking about it is that we need to drop the even elements this many
9166     // times to get the original input.
9167     bool IsSingleInput = isSingleInputShuffleMask(Mask);
9168
9169     // First we need to zero all the dropped bytes.
9170     assert(NumEvenDrops <= 3 &&
9171            "No support for dropping even elements more than 3 times.");
9172     // We use the mask type to pick which bytes are preserved based on how many
9173     // elements are dropped.
9174     MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
9175     SDValue ByteClearMask = DAG.getBitcast(
9176         MVT::v16i8, DAG.getConstant(0xFF, DL, MaskVTs[NumEvenDrops - 1]));
9177     V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
9178     if (!IsSingleInput)
9179       V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
9180
9181     // Now pack things back together.
9182     V1 = DAG.getBitcast(MVT::v8i16, V1);
9183     V2 = IsSingleInput ? V1 : DAG.getBitcast(MVT::v8i16, V2);
9184     SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
9185     for (int i = 1; i < NumEvenDrops; ++i) {
9186       Result = DAG.getBitcast(MVT::v8i16, Result);
9187       Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
9188     }
9189
9190     return Result;
9191   }
9192
9193   // Handle multi-input cases by blending single-input shuffles.
9194   if (NumV2Elements > 0)
9195     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v16i8, V1, V2,
9196                                                       Mask, DAG);
9197
9198   // The fallback path for single-input shuffles widens this into two v8i16
9199   // vectors with unpacks, shuffles those, and then pulls them back together
9200   // with a pack.
9201   SDValue V = V1;
9202
9203   int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9204   int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9205   for (int i = 0; i < 16; ++i)
9206     if (Mask[i] >= 0)
9207       (i < 8 ? LoBlendMask[i] : HiBlendMask[i % 8]) = Mask[i];
9208
9209   SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
9210
9211   SDValue VLoHalf, VHiHalf;
9212   // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
9213   // them out and avoid using UNPCK{L,H} to extract the elements of V as
9214   // i16s.
9215   if (std::none_of(std::begin(LoBlendMask), std::end(LoBlendMask),
9216                    [](int M) { return M >= 0 && M % 2 == 1; }) &&
9217       std::none_of(std::begin(HiBlendMask), std::end(HiBlendMask),
9218                    [](int M) { return M >= 0 && M % 2 == 1; })) {
9219     // Use a mask to drop the high bytes.
9220     VLoHalf = DAG.getBitcast(MVT::v8i16, V);
9221     VLoHalf = DAG.getNode(ISD::AND, DL, MVT::v8i16, VLoHalf,
9222                      DAG.getConstant(0x00FF, DL, MVT::v8i16));
9223
9224     // This will be a single vector shuffle instead of a blend so nuke VHiHalf.
9225     VHiHalf = DAG.getUNDEF(MVT::v8i16);
9226
9227     // Squash the masks to point directly into VLoHalf.
9228     for (int &M : LoBlendMask)
9229       if (M >= 0)
9230         M /= 2;
9231     for (int &M : HiBlendMask)
9232       if (M >= 0)
9233         M /= 2;
9234   } else {
9235     // Otherwise just unpack the low half of V into VLoHalf and the high half into
9236     // VHiHalf so that we can blend them as i16s.
9237     VLoHalf = DAG.getBitcast(
9238         MVT::v8i16, DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
9239     VHiHalf = DAG.getBitcast(
9240         MVT::v8i16, DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
9241   }
9242
9243   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, LoBlendMask);
9244   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, HiBlendMask);
9245
9246   return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
9247 }
9248
9249 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
9250 ///
9251 /// This routine breaks down the specific type of 128-bit shuffle and
9252 /// dispatches to the lowering routines accordingly.
9253 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9254                                         MVT VT, const X86Subtarget *Subtarget,
9255                                         SelectionDAG &DAG) {
9256   switch (VT.SimpleTy) {
9257   case MVT::v2i64:
9258     return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9259   case MVT::v2f64:
9260     return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9261   case MVT::v4i32:
9262     return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9263   case MVT::v4f32:
9264     return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9265   case MVT::v8i16:
9266     return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
9267   case MVT::v16i8:
9268     return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
9269
9270   default:
9271     llvm_unreachable("Unimplemented!");
9272   }
9273 }
9274
9275 /// \brief Helper function to test whether a shuffle mask could be
9276 /// simplified by widening the elements being shuffled.
9277 ///
9278 /// Appends the mask for wider elements in WidenedMask if valid. Otherwise
9279 /// leaves it in an unspecified state.
9280 ///
9281 /// NOTE: This must handle normal vector shuffle masks and *target* vector
9282 /// shuffle masks. The latter have the special property of a '-2' representing
9283 /// a zero-ed lane of a vector.
9284 static bool canWidenShuffleElements(ArrayRef<int> Mask,
9285                                     SmallVectorImpl<int> &WidenedMask) {
9286   for (int i = 0, Size = Mask.size(); i < Size; i += 2) {
9287     // If both elements are undef, its trivial.
9288     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] == SM_SentinelUndef) {
9289       WidenedMask.push_back(SM_SentinelUndef);
9290       continue;
9291     }
9292
9293     // Check for an undef mask and a mask value properly aligned to fit with
9294     // a pair of values. If we find such a case, use the non-undef mask's value.
9295     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] >= 0 && Mask[i + 1] % 2 == 1) {
9296       WidenedMask.push_back(Mask[i + 1] / 2);
9297       continue;
9298     }
9299     if (Mask[i + 1] == SM_SentinelUndef && Mask[i] >= 0 && Mask[i] % 2 == 0) {
9300       WidenedMask.push_back(Mask[i] / 2);
9301       continue;
9302     }
9303
9304     // When zeroing, we need to spread the zeroing across both lanes to widen.
9305     if (Mask[i] == SM_SentinelZero || Mask[i + 1] == SM_SentinelZero) {
9306       if ((Mask[i] == SM_SentinelZero || Mask[i] == SM_SentinelUndef) &&
9307           (Mask[i + 1] == SM_SentinelZero || Mask[i + 1] == SM_SentinelUndef)) {
9308         WidenedMask.push_back(SM_SentinelZero);
9309         continue;
9310       }
9311       return false;
9312     }
9313
9314     // Finally check if the two mask values are adjacent and aligned with
9315     // a pair.
9316     if (Mask[i] != SM_SentinelUndef && Mask[i] % 2 == 0 && Mask[i] + 1 == Mask[i + 1]) {
9317       WidenedMask.push_back(Mask[i] / 2);
9318       continue;
9319     }
9320
9321     // Otherwise we can't safely widen the elements used in this shuffle.
9322     return false;
9323   }
9324   assert(WidenedMask.size() == Mask.size() / 2 &&
9325          "Incorrect size of mask after widening the elements!");
9326
9327   return true;
9328 }
9329
9330 /// \brief Generic routine to split vector shuffle into half-sized shuffles.
9331 ///
9332 /// This routine just extracts two subvectors, shuffles them independently, and
9333 /// then concatenates them back together. This should work effectively with all
9334 /// AVX vector shuffle types.
9335 static SDValue splitAndLowerVectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9336                                           SDValue V2, ArrayRef<int> Mask,
9337                                           SelectionDAG &DAG) {
9338   assert(VT.getSizeInBits() >= 256 &&
9339          "Only for 256-bit or wider vector shuffles!");
9340   assert(V1.getSimpleValueType() == VT && "Bad operand type!");
9341   assert(V2.getSimpleValueType() == VT && "Bad operand type!");
9342
9343   ArrayRef<int> LoMask = Mask.slice(0, Mask.size() / 2);
9344   ArrayRef<int> HiMask = Mask.slice(Mask.size() / 2);
9345
9346   int NumElements = VT.getVectorNumElements();
9347   int SplitNumElements = NumElements / 2;
9348   MVT ScalarVT = VT.getScalarType();
9349   MVT SplitVT = MVT::getVectorVT(ScalarVT, NumElements / 2);
9350
9351   // Rather than splitting build-vectors, just build two narrower build
9352   // vectors. This helps shuffling with splats and zeros.
9353   auto SplitVector = [&](SDValue V) {
9354     while (V.getOpcode() == ISD::BITCAST)
9355       V = V->getOperand(0);
9356
9357     MVT OrigVT = V.getSimpleValueType();
9358     int OrigNumElements = OrigVT.getVectorNumElements();
9359     int OrigSplitNumElements = OrigNumElements / 2;
9360     MVT OrigScalarVT = OrigVT.getScalarType();
9361     MVT OrigSplitVT = MVT::getVectorVT(OrigScalarVT, OrigNumElements / 2);
9362
9363     SDValue LoV, HiV;
9364
9365     auto *BV = dyn_cast<BuildVectorSDNode>(V);
9366     if (!BV) {
9367       LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9368                         DAG.getIntPtrConstant(0, DL));
9369       HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9370                         DAG.getIntPtrConstant(OrigSplitNumElements, DL));
9371     } else {
9372
9373       SmallVector<SDValue, 16> LoOps, HiOps;
9374       for (int i = 0; i < OrigSplitNumElements; ++i) {
9375         LoOps.push_back(BV->getOperand(i));
9376         HiOps.push_back(BV->getOperand(i + OrigSplitNumElements));
9377       }
9378       LoV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, LoOps);
9379       HiV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, HiOps);
9380     }
9381     return std::make_pair(DAG.getBitcast(SplitVT, LoV),
9382                           DAG.getBitcast(SplitVT, HiV));
9383   };
9384
9385   SDValue LoV1, HiV1, LoV2, HiV2;
9386   std::tie(LoV1, HiV1) = SplitVector(V1);
9387   std::tie(LoV2, HiV2) = SplitVector(V2);
9388
9389   // Now create two 4-way blends of these half-width vectors.
9390   auto HalfBlend = [&](ArrayRef<int> HalfMask) {
9391     bool UseLoV1 = false, UseHiV1 = false, UseLoV2 = false, UseHiV2 = false;
9392     SmallVector<int, 32> V1BlendMask, V2BlendMask, BlendMask;
9393     for (int i = 0; i < SplitNumElements; ++i) {
9394       int M = HalfMask[i];
9395       if (M >= NumElements) {
9396         if (M >= NumElements + SplitNumElements)
9397           UseHiV2 = true;
9398         else
9399           UseLoV2 = true;
9400         V2BlendMask.push_back(M - NumElements);
9401         V1BlendMask.push_back(-1);
9402         BlendMask.push_back(SplitNumElements + i);
9403       } else if (M >= 0) {
9404         if (M >= SplitNumElements)
9405           UseHiV1 = true;
9406         else
9407           UseLoV1 = true;
9408         V2BlendMask.push_back(-1);
9409         V1BlendMask.push_back(M);
9410         BlendMask.push_back(i);
9411       } else {
9412         V2BlendMask.push_back(-1);
9413         V1BlendMask.push_back(-1);
9414         BlendMask.push_back(-1);
9415       }
9416     }
9417
9418     // Because the lowering happens after all combining takes place, we need to
9419     // manually combine these blend masks as much as possible so that we create
9420     // a minimal number of high-level vector shuffle nodes.
9421
9422     // First try just blending the halves of V1 or V2.
9423     if (!UseLoV1 && !UseHiV1 && !UseLoV2 && !UseHiV2)
9424       return DAG.getUNDEF(SplitVT);
9425     if (!UseLoV2 && !UseHiV2)
9426       return DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9427     if (!UseLoV1 && !UseHiV1)
9428       return DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9429
9430     SDValue V1Blend, V2Blend;
9431     if (UseLoV1 && UseHiV1) {
9432       V1Blend =
9433         DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9434     } else {
9435       // We only use half of V1 so map the usage down into the final blend mask.
9436       V1Blend = UseLoV1 ? LoV1 : HiV1;
9437       for (int i = 0; i < SplitNumElements; ++i)
9438         if (BlendMask[i] >= 0 && BlendMask[i] < SplitNumElements)
9439           BlendMask[i] = V1BlendMask[i] - (UseLoV1 ? 0 : SplitNumElements);
9440     }
9441     if (UseLoV2 && UseHiV2) {
9442       V2Blend =
9443         DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9444     } else {
9445       // We only use half of V2 so map the usage down into the final blend mask.
9446       V2Blend = UseLoV2 ? LoV2 : HiV2;
9447       for (int i = 0; i < SplitNumElements; ++i)
9448         if (BlendMask[i] >= SplitNumElements)
9449           BlendMask[i] = V2BlendMask[i] + (UseLoV2 ? SplitNumElements : 0);
9450     }
9451     return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
9452   };
9453   SDValue Lo = HalfBlend(LoMask);
9454   SDValue Hi = HalfBlend(HiMask);
9455   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
9456 }
9457
9458 /// \brief Either split a vector in halves or decompose the shuffles and the
9459 /// blend.
9460 ///
9461 /// This is provided as a good fallback for many lowerings of non-single-input
9462 /// shuffles with more than one 128-bit lane. In those cases, we want to select
9463 /// between splitting the shuffle into 128-bit components and stitching those
9464 /// back together vs. extracting the single-input shuffles and blending those
9465 /// results.
9466 static SDValue lowerVectorShuffleAsSplitOrBlend(SDLoc DL, MVT VT, SDValue V1,
9467                                                 SDValue V2, ArrayRef<int> Mask,
9468                                                 SelectionDAG &DAG) {
9469   assert(!isSingleInputShuffleMask(Mask) && "This routine must not be used to "
9470                                             "lower single-input shuffles as it "
9471                                             "could then recurse on itself.");
9472   int Size = Mask.size();
9473
9474   // If this can be modeled as a broadcast of two elements followed by a blend,
9475   // prefer that lowering. This is especially important because broadcasts can
9476   // often fold with memory operands.
9477   auto DoBothBroadcast = [&] {
9478     int V1BroadcastIdx = -1, V2BroadcastIdx = -1;
9479     for (int M : Mask)
9480       if (M >= Size) {
9481         if (V2BroadcastIdx == -1)
9482           V2BroadcastIdx = M - Size;
9483         else if (M - Size != V2BroadcastIdx)
9484           return false;
9485       } else if (M >= 0) {
9486         if (V1BroadcastIdx == -1)
9487           V1BroadcastIdx = M;
9488         else if (M != V1BroadcastIdx)
9489           return false;
9490       }
9491     return true;
9492   };
9493   if (DoBothBroadcast())
9494     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask,
9495                                                       DAG);
9496
9497   // If the inputs all stem from a single 128-bit lane of each input, then we
9498   // split them rather than blending because the split will decompose to
9499   // unusually few instructions.
9500   int LaneCount = VT.getSizeInBits() / 128;
9501   int LaneSize = Size / LaneCount;
9502   SmallBitVector LaneInputs[2];
9503   LaneInputs[0].resize(LaneCount, false);
9504   LaneInputs[1].resize(LaneCount, false);
9505   for (int i = 0; i < Size; ++i)
9506     if (Mask[i] >= 0)
9507       LaneInputs[Mask[i] / Size][(Mask[i] % Size) / LaneSize] = true;
9508   if (LaneInputs[0].count() <= 1 && LaneInputs[1].count() <= 1)
9509     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9510
9511   // Otherwise, just fall back to decomposed shuffles and a blend. This requires
9512   // that the decomposed single-input shuffles don't end up here.
9513   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9514 }
9515
9516 /// \brief Lower a vector shuffle crossing multiple 128-bit lanes as
9517 /// a permutation and blend of those lanes.
9518 ///
9519 /// This essentially blends the out-of-lane inputs to each lane into the lane
9520 /// from a permuted copy of the vector. This lowering strategy results in four
9521 /// instructions in the worst case for a single-input cross lane shuffle which
9522 /// is lower than any other fully general cross-lane shuffle strategy I'm aware
9523 /// of. Special cases for each particular shuffle pattern should be handled
9524 /// prior to trying this lowering.
9525 static SDValue lowerVectorShuffleAsLanePermuteAndBlend(SDLoc DL, MVT VT,
9526                                                        SDValue V1, SDValue V2,
9527                                                        ArrayRef<int> Mask,
9528                                                        SelectionDAG &DAG) {
9529   // FIXME: This should probably be generalized for 512-bit vectors as well.
9530   assert(VT.getSizeInBits() == 256 && "Only for 256-bit vector shuffles!");
9531   int LaneSize = Mask.size() / 2;
9532
9533   // If there are only inputs from one 128-bit lane, splitting will in fact be
9534   // less expensive. The flags track whether the given lane contains an element
9535   // that crosses to another lane.
9536   bool LaneCrossing[2] = {false, false};
9537   for (int i = 0, Size = Mask.size(); i < Size; ++i)
9538     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
9539       LaneCrossing[(Mask[i] % Size) / LaneSize] = true;
9540   if (!LaneCrossing[0] || !LaneCrossing[1])
9541     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9542
9543   if (isSingleInputShuffleMask(Mask)) {
9544     SmallVector<int, 32> FlippedBlendMask;
9545     for (int i = 0, Size = Mask.size(); i < Size; ++i)
9546       FlippedBlendMask.push_back(
9547           Mask[i] < 0 ? -1 : (((Mask[i] % Size) / LaneSize == i / LaneSize)
9548                                   ? Mask[i]
9549                                   : Mask[i] % LaneSize +
9550                                         (i / LaneSize) * LaneSize + Size));
9551
9552     // Flip the vector, and blend the results which should now be in-lane. The
9553     // VPERM2X128 mask uses the low 2 bits for the low source and bits 4 and
9554     // 5 for the high source. The value 3 selects the high half of source 2 and
9555     // the value 2 selects the low half of source 2. We only use source 2 to
9556     // allow folding it into a memory operand.
9557     unsigned PERMMask = 3 | 2 << 4;
9558     SDValue Flipped = DAG.getNode(X86ISD::VPERM2X128, DL, VT, DAG.getUNDEF(VT),
9559                                   V1, DAG.getConstant(PERMMask, DL, MVT::i8));
9560     return DAG.getVectorShuffle(VT, DL, V1, Flipped, FlippedBlendMask);
9561   }
9562
9563   // This now reduces to two single-input shuffles of V1 and V2 which at worst
9564   // will be handled by the above logic and a blend of the results, much like
9565   // other patterns in AVX.
9566   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9567 }
9568
9569 /// \brief Handle lowering 2-lane 128-bit shuffles.
9570 static SDValue lowerV2X128VectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9571                                         SDValue V2, ArrayRef<int> Mask,
9572                                         const X86Subtarget *Subtarget,
9573                                         SelectionDAG &DAG) {
9574   // TODO: If minimizing size and one of the inputs is a zero vector and the
9575   // the zero vector has only one use, we could use a VPERM2X128 to save the
9576   // instruction bytes needed to explicitly generate the zero vector.
9577
9578   // Blends are faster and handle all the non-lane-crossing cases.
9579   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, VT, V1, V2, Mask,
9580                                                 Subtarget, DAG))
9581     return Blend;
9582
9583   bool IsV1Zero = ISD::isBuildVectorAllZeros(V1.getNode());
9584   bool IsV2Zero = ISD::isBuildVectorAllZeros(V2.getNode());
9585
9586   // If either input operand is a zero vector, use VPERM2X128 because its mask
9587   // allows us to replace the zero input with an implicit zero.
9588   if (!IsV1Zero && !IsV2Zero) {
9589     // Check for patterns which can be matched with a single insert of a 128-bit
9590     // subvector.
9591     bool OnlyUsesV1 = isShuffleEquivalent(V1, V2, Mask, {0, 1, 0, 1});
9592     if (OnlyUsesV1 || isShuffleEquivalent(V1, V2, Mask, {0, 1, 4, 5})) {
9593       MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(),
9594                                    VT.getVectorNumElements() / 2);
9595       SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
9596                                 DAG.getIntPtrConstant(0, DL));
9597       SDValue HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT,
9598                                 OnlyUsesV1 ? V1 : V2,
9599                                 DAG.getIntPtrConstant(0, DL));
9600       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoV, HiV);
9601     }
9602   }
9603
9604   // Otherwise form a 128-bit permutation. After accounting for undefs,
9605   // convert the 64-bit shuffle mask selection values into 128-bit
9606   // selection bits by dividing the indexes by 2 and shifting into positions
9607   // defined by a vperm2*128 instruction's immediate control byte.
9608
9609   // The immediate permute control byte looks like this:
9610   //    [1:0] - select 128 bits from sources for low half of destination
9611   //    [2]   - ignore
9612   //    [3]   - zero low half of destination
9613   //    [5:4] - select 128 bits from sources for high half of destination
9614   //    [6]   - ignore
9615   //    [7]   - zero high half of destination
9616
9617   int MaskLO = Mask[0];
9618   if (MaskLO == SM_SentinelUndef)
9619     MaskLO = Mask[1] == SM_SentinelUndef ? 0 : Mask[1];
9620
9621   int MaskHI = Mask[2];
9622   if (MaskHI == SM_SentinelUndef)
9623     MaskHI = Mask[3] == SM_SentinelUndef ? 0 : Mask[3];
9624
9625   unsigned PermMask = MaskLO / 2 | (MaskHI / 2) << 4;
9626
9627   // If either input is a zero vector, replace it with an undef input.
9628   // Shuffle mask values <  4 are selecting elements of V1.
9629   // Shuffle mask values >= 4 are selecting elements of V2.
9630   // Adjust each half of the permute mask by clearing the half that was
9631   // selecting the zero vector and setting the zero mask bit.
9632   if (IsV1Zero) {
9633     V1 = DAG.getUNDEF(VT);
9634     if (MaskLO < 4)
9635       PermMask = (PermMask & 0xf0) | 0x08;
9636     if (MaskHI < 4)
9637       PermMask = (PermMask & 0x0f) | 0x80;
9638   }
9639   if (IsV2Zero) {
9640     V2 = DAG.getUNDEF(VT);
9641     if (MaskLO >= 4)
9642       PermMask = (PermMask & 0xf0) | 0x08;
9643     if (MaskHI >= 4)
9644       PermMask = (PermMask & 0x0f) | 0x80;
9645   }
9646
9647   return DAG.getNode(X86ISD::VPERM2X128, DL, VT, V1, V2,
9648                      DAG.getConstant(PermMask, DL, MVT::i8));
9649 }
9650
9651 /// \brief Lower a vector shuffle by first fixing the 128-bit lanes and then
9652 /// shuffling each lane.
9653 ///
9654 /// This will only succeed when the result of fixing the 128-bit lanes results
9655 /// in a single-input non-lane-crossing shuffle with a repeating shuffle mask in
9656 /// each 128-bit lanes. This handles many cases where we can quickly blend away
9657 /// the lane crosses early and then use simpler shuffles within each lane.
9658 ///
9659 /// FIXME: It might be worthwhile at some point to support this without
9660 /// requiring the 128-bit lane-relative shuffles to be repeating, but currently
9661 /// in x86 only floating point has interesting non-repeating shuffles, and even
9662 /// those are still *marginally* more expensive.
9663 static SDValue lowerVectorShuffleByMerging128BitLanes(
9664     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
9665     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
9666   assert(!isSingleInputShuffleMask(Mask) &&
9667          "This is only useful with multiple inputs.");
9668
9669   int Size = Mask.size();
9670   int LaneSize = 128 / VT.getScalarSizeInBits();
9671   int NumLanes = Size / LaneSize;
9672   assert(NumLanes > 1 && "Only handles 256-bit and wider shuffles.");
9673
9674   // See if we can build a hypothetical 128-bit lane-fixing shuffle mask. Also
9675   // check whether the in-128-bit lane shuffles share a repeating pattern.
9676   SmallVector<int, 4> Lanes;
9677   Lanes.resize(NumLanes, -1);
9678   SmallVector<int, 4> InLaneMask;
9679   InLaneMask.resize(LaneSize, -1);
9680   for (int i = 0; i < Size; ++i) {
9681     if (Mask[i] < 0)
9682       continue;
9683
9684     int j = i / LaneSize;
9685
9686     if (Lanes[j] < 0) {
9687       // First entry we've seen for this lane.
9688       Lanes[j] = Mask[i] / LaneSize;
9689     } else if (Lanes[j] != Mask[i] / LaneSize) {
9690       // This doesn't match the lane selected previously!
9691       return SDValue();
9692     }
9693
9694     // Check that within each lane we have a consistent shuffle mask.
9695     int k = i % LaneSize;
9696     if (InLaneMask[k] < 0) {
9697       InLaneMask[k] = Mask[i] % LaneSize;
9698     } else if (InLaneMask[k] != Mask[i] % LaneSize) {
9699       // This doesn't fit a repeating in-lane mask.
9700       return SDValue();
9701     }
9702   }
9703
9704   // First shuffle the lanes into place.
9705   MVT LaneVT = MVT::getVectorVT(VT.isFloatingPoint() ? MVT::f64 : MVT::i64,
9706                                 VT.getSizeInBits() / 64);
9707   SmallVector<int, 8> LaneMask;
9708   LaneMask.resize(NumLanes * 2, -1);
9709   for (int i = 0; i < NumLanes; ++i)
9710     if (Lanes[i] >= 0) {
9711       LaneMask[2 * i + 0] = 2*Lanes[i] + 0;
9712       LaneMask[2 * i + 1] = 2*Lanes[i] + 1;
9713     }
9714
9715   V1 = DAG.getBitcast(LaneVT, V1);
9716   V2 = DAG.getBitcast(LaneVT, V2);
9717   SDValue LaneShuffle = DAG.getVectorShuffle(LaneVT, DL, V1, V2, LaneMask);
9718
9719   // Cast it back to the type we actually want.
9720   LaneShuffle = DAG.getBitcast(VT, LaneShuffle);
9721
9722   // Now do a simple shuffle that isn't lane crossing.
9723   SmallVector<int, 8> NewMask;
9724   NewMask.resize(Size, -1);
9725   for (int i = 0; i < Size; ++i)
9726     if (Mask[i] >= 0)
9727       NewMask[i] = (i / LaneSize) * LaneSize + Mask[i] % LaneSize;
9728   assert(!is128BitLaneCrossingShuffleMask(VT, NewMask) &&
9729          "Must not introduce lane crosses at this point!");
9730
9731   return DAG.getVectorShuffle(VT, DL, LaneShuffle, DAG.getUNDEF(VT), NewMask);
9732 }
9733
9734 /// \brief Test whether the specified input (0 or 1) is in-place blended by the
9735 /// given mask.
9736 ///
9737 /// This returns true if the elements from a particular input are already in the
9738 /// slot required by the given mask and require no permutation.
9739 static bool isShuffleMaskInputInPlace(int Input, ArrayRef<int> Mask) {
9740   assert((Input == 0 || Input == 1) && "Only two inputs to shuffles.");
9741   int Size = Mask.size();
9742   for (int i = 0; i < Size; ++i)
9743     if (Mask[i] >= 0 && Mask[i] / Size == Input && Mask[i] % Size != i)
9744       return false;
9745
9746   return true;
9747 }
9748
9749 static SDValue lowerVectorShuffleWithSHUFPD(SDLoc DL, MVT VT,
9750                                             ArrayRef<int> Mask, SDValue V1,
9751                                             SDValue V2, SelectionDAG &DAG) {
9752
9753   // Mask for V8F64: 0/1,  8/9,  2/3,  10/11, 4/5, ..
9754   // Mask for V4F64; 0/1,  4/5,  2/3,  6/7..
9755   assert(VT.getScalarSizeInBits() == 64 && "Unexpected data type for VSHUFPD");
9756   int NumElts = VT.getVectorNumElements();
9757   bool ShufpdMask = true;
9758   bool CommutableMask = true;
9759   unsigned Immediate = 0;
9760   for (int i = 0; i < NumElts; ++i) {
9761     if (Mask[i] < 0)
9762       continue;
9763     int Val = (i & 6) + NumElts * (i & 1);
9764     int CommutVal = (i & 0xe) + NumElts * ((i & 1)^1);
9765     if (Mask[i] < Val ||  Mask[i] > Val + 1)
9766       ShufpdMask = false;
9767     if (Mask[i] < CommutVal ||  Mask[i] > CommutVal + 1)
9768       CommutableMask = false;
9769     Immediate |= (Mask[i] % 2) << i;
9770   }
9771   if (ShufpdMask)
9772     return DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
9773                        DAG.getConstant(Immediate, DL, MVT::i8));
9774   if (CommutableMask)
9775     return DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
9776                        DAG.getConstant(Immediate, DL, MVT::i8));
9777   return SDValue();
9778 }
9779
9780 /// \brief Handle lowering of 4-lane 64-bit floating point shuffles.
9781 ///
9782 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
9783 /// isn't available.
9784 static SDValue lowerV4F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9785                                        const X86Subtarget *Subtarget,
9786                                        SelectionDAG &DAG) {
9787   SDLoc DL(Op);
9788   assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9789   assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9790   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9791   ArrayRef<int> Mask = SVOp->getMask();
9792   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9793
9794   SmallVector<int, 4> WidenedMask;
9795   if (canWidenShuffleElements(Mask, WidenedMask))
9796     return lowerV2X128VectorShuffle(DL, MVT::v4f64, V1, V2, Mask, Subtarget,
9797                                     DAG);
9798
9799   if (isSingleInputShuffleMask(Mask)) {
9800     // Check for being able to broadcast a single element.
9801     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f64, V1,
9802                                                           Mask, Subtarget, DAG))
9803       return Broadcast;
9804
9805     // Use low duplicate instructions for masks that match their pattern.
9806     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
9807       return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v4f64, V1);
9808
9809     if (!is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask)) {
9810       // Non-half-crossing single input shuffles can be lowerid with an
9811       // interleaved permutation.
9812       unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
9813                               ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
9814       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f64, V1,
9815                          DAG.getConstant(VPERMILPMask, DL, MVT::i8));
9816     }
9817
9818     // With AVX2 we have direct support for this permutation.
9819     if (Subtarget->hasAVX2())
9820       return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4f64, V1,
9821                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
9822
9823     // Otherwise, fall back.
9824     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v4f64, V1, V2, Mask,
9825                                                    DAG);
9826   }
9827
9828   // X86 has dedicated unpack instructions that can handle specific blend
9829   // operations: UNPCKH and UNPCKL.
9830   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9831     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V1, V2);
9832   if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9833     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V1, V2);
9834   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9835     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V2, V1);
9836   if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9837     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V2, V1);
9838
9839   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f64, V1, V2, Mask,
9840                                                 Subtarget, DAG))
9841     return Blend;
9842
9843   // Check if the blend happens to exactly fit that of SHUFPD.
9844   if (SDValue Op =
9845       lowerVectorShuffleWithSHUFPD(DL, MVT::v4f64, Mask, V1, V2, DAG))
9846     return Op;
9847
9848   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9849   // shuffle. However, if we have AVX2 and either inputs are already in place,
9850   // we will be able to shuffle even across lanes the other input in a single
9851   // instruction so skip this pattern.
9852   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9853                                  isShuffleMaskInputInPlace(1, Mask))))
9854     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9855             DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
9856       return Result;
9857
9858   // If we have AVX2 then we always want to lower with a blend because an v4 we
9859   // can fully permute the elements.
9860   if (Subtarget->hasAVX2())
9861     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4f64, V1, V2,
9862                                                       Mask, DAG);
9863
9864   // Otherwise fall back on generic lowering.
9865   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v4f64, V1, V2, Mask, DAG);
9866 }
9867
9868 /// \brief Handle lowering of 4-lane 64-bit integer shuffles.
9869 ///
9870 /// This routine is only called when we have AVX2 and thus a reasonable
9871 /// instruction set for v4i64 shuffling..
9872 static SDValue lowerV4I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9873                                        const X86Subtarget *Subtarget,
9874                                        SelectionDAG &DAG) {
9875   SDLoc DL(Op);
9876   assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9877   assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9878   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9879   ArrayRef<int> Mask = SVOp->getMask();
9880   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9881   assert(Subtarget->hasAVX2() && "We can only lower v4i64 with AVX2!");
9882
9883   SmallVector<int, 4> WidenedMask;
9884   if (canWidenShuffleElements(Mask, WidenedMask))
9885     return lowerV2X128VectorShuffle(DL, MVT::v4i64, V1, V2, Mask, Subtarget,
9886                                     DAG);
9887
9888   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i64, V1, V2, Mask,
9889                                                 Subtarget, DAG))
9890     return Blend;
9891
9892   // Check for being able to broadcast a single element.
9893   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i64, V1,
9894                                                         Mask, Subtarget, DAG))
9895     return Broadcast;
9896
9897   // When the shuffle is mirrored between the 128-bit lanes of the unit, we can
9898   // use lower latency instructions that will operate on both 128-bit lanes.
9899   SmallVector<int, 2> RepeatedMask;
9900   if (is128BitLaneRepeatedShuffleMask(MVT::v4i64, Mask, RepeatedMask)) {
9901     if (isSingleInputShuffleMask(Mask)) {
9902       int PSHUFDMask[] = {-1, -1, -1, -1};
9903       for (int i = 0; i < 2; ++i)
9904         if (RepeatedMask[i] >= 0) {
9905           PSHUFDMask[2 * i] = 2 * RepeatedMask[i];
9906           PSHUFDMask[2 * i + 1] = 2 * RepeatedMask[i] + 1;
9907         }
9908       return DAG.getBitcast(
9909           MVT::v4i64,
9910           DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32,
9911                       DAG.getBitcast(MVT::v8i32, V1),
9912                       getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
9913     }
9914   }
9915
9916   // AVX2 provides a direct instruction for permuting a single input across
9917   // lanes.
9918   if (isSingleInputShuffleMask(Mask))
9919     return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4i64, V1,
9920                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
9921
9922   // Try to use shift instructions.
9923   if (SDValue Shift =
9924           lowerVectorShuffleAsShift(DL, MVT::v4i64, V1, V2, Mask, DAG))
9925     return Shift;
9926
9927   // Use dedicated unpack instructions for masks that match their pattern.
9928   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9929     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V1, V2);
9930   if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9931     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V1, V2);
9932   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9933     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V2, V1);
9934   if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9935     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V2, V1);
9936
9937   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9938   // shuffle. However, if we have AVX2 and either inputs are already in place,
9939   // we will be able to shuffle even across lanes the other input in a single
9940   // instruction so skip this pattern.
9941   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9942                                  isShuffleMaskInputInPlace(1, Mask))))
9943     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9944             DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
9945       return Result;
9946
9947   // Otherwise fall back on generic blend lowering.
9948   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i64, V1, V2,
9949                                                     Mask, DAG);
9950 }
9951
9952 /// \brief Handle lowering of 8-lane 32-bit floating point shuffles.
9953 ///
9954 /// Also ends up handling lowering of 8-lane 32-bit integer shuffles when AVX2
9955 /// isn't available.
9956 static SDValue lowerV8F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9957                                        const X86Subtarget *Subtarget,
9958                                        SelectionDAG &DAG) {
9959   SDLoc DL(Op);
9960   assert(V1.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
9961   assert(V2.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
9962   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9963   ArrayRef<int> Mask = SVOp->getMask();
9964   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9965
9966   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8f32, V1, V2, Mask,
9967                                                 Subtarget, DAG))
9968     return Blend;
9969
9970   // Check for being able to broadcast a single element.
9971   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8f32, V1,
9972                                                         Mask, Subtarget, DAG))
9973     return Broadcast;
9974
9975   // If the shuffle mask is repeated in each 128-bit lane, we have many more
9976   // options to efficiently lower the shuffle.
9977   SmallVector<int, 4> RepeatedMask;
9978   if (is128BitLaneRepeatedShuffleMask(MVT::v8f32, Mask, RepeatedMask)) {
9979     assert(RepeatedMask.size() == 4 &&
9980            "Repeated masks must be half the mask width!");
9981
9982     // Use even/odd duplicate instructions for masks that match their pattern.
9983     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2, 4, 4, 6, 6}))
9984       return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v8f32, V1);
9985     if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3, 5, 5, 7, 7}))
9986       return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v8f32, V1);
9987
9988     if (isSingleInputShuffleMask(Mask))
9989       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, V1,
9990                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
9991
9992     // Use dedicated unpack instructions for masks that match their pattern.
9993     if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
9994       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V1, V2);
9995     if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
9996       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V1, V2);
9997     if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
9998       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V2, V1);
9999     if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
10000       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V2, V1);
10001
10002     // Otherwise, fall back to a SHUFPS sequence. Here it is important that we
10003     // have already handled any direct blends. We also need to squash the
10004     // repeated mask into a simulated v4f32 mask.
10005     for (int i = 0; i < 4; ++i)
10006       if (RepeatedMask[i] >= 8)
10007         RepeatedMask[i] -= 4;
10008     return lowerVectorShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask, V1, V2, DAG);
10009   }
10010
10011   // If we have a single input shuffle with different shuffle patterns in the
10012   // two 128-bit lanes use the variable mask to VPERMILPS.
10013   if (isSingleInputShuffleMask(Mask)) {
10014     SDValue VPermMask[8];
10015     for (int i = 0; i < 8; ++i)
10016       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10017                                  : DAG.getConstant(Mask[i], DL, MVT::i32);
10018     if (!is128BitLaneCrossingShuffleMask(MVT::v8f32, Mask))
10019       return DAG.getNode(
10020           X86ISD::VPERMILPV, DL, MVT::v8f32, V1,
10021           DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask));
10022
10023     if (Subtarget->hasAVX2())
10024       return DAG.getNode(
10025           X86ISD::VPERMV, DL, MVT::v8f32,
10026           DAG.getBitcast(MVT::v8f32, DAG.getNode(ISD::BUILD_VECTOR, DL,
10027                                                  MVT::v8i32, VPermMask)),
10028           V1);
10029
10030     // Otherwise, fall back.
10031     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v8f32, V1, V2, Mask,
10032                                                    DAG);
10033   }
10034
10035   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10036   // shuffle.
10037   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10038           DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
10039     return Result;
10040
10041   // If we have AVX2 then we always want to lower with a blend because at v8 we
10042   // can fully permute the elements.
10043   if (Subtarget->hasAVX2())
10044     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8f32, V1, V2,
10045                                                       Mask, DAG);
10046
10047   // Otherwise fall back on generic lowering.
10048   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask, DAG);
10049 }
10050
10051 /// \brief Handle lowering of 8-lane 32-bit integer shuffles.
10052 ///
10053 /// This routine is only called when we have AVX2 and thus a reasonable
10054 /// instruction set for v8i32 shuffling..
10055 static SDValue lowerV8I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10056                                        const X86Subtarget *Subtarget,
10057                                        SelectionDAG &DAG) {
10058   SDLoc DL(Op);
10059   assert(V1.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10060   assert(V2.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10061   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10062   ArrayRef<int> Mask = SVOp->getMask();
10063   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10064   assert(Subtarget->hasAVX2() && "We can only lower v8i32 with AVX2!");
10065
10066   // Whenever we can lower this as a zext, that instruction is strictly faster
10067   // than any alternative. It also allows us to fold memory operands into the
10068   // shuffle in many cases.
10069   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v8i32, V1, V2,
10070                                                          Mask, Subtarget, DAG))
10071     return ZExt;
10072
10073   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i32, V1, V2, Mask,
10074                                                 Subtarget, DAG))
10075     return Blend;
10076
10077   // Check for being able to broadcast a single element.
10078   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i32, V1,
10079                                                         Mask, Subtarget, DAG))
10080     return Broadcast;
10081
10082   // If the shuffle mask is repeated in each 128-bit lane we can use more
10083   // efficient instructions that mirror the shuffles across the two 128-bit
10084   // lanes.
10085   SmallVector<int, 4> RepeatedMask;
10086   if (is128BitLaneRepeatedShuffleMask(MVT::v8i32, Mask, RepeatedMask)) {
10087     assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
10088     if (isSingleInputShuffleMask(Mask))
10089       return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32, V1,
10090                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
10091
10092     // Use dedicated unpack instructions for masks that match their pattern.
10093     if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
10094       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V1, V2);
10095     if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
10096       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V1, V2);
10097     if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
10098       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V2, V1);
10099     if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
10100       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V2, V1);
10101   }
10102
10103   // Try to use shift instructions.
10104   if (SDValue Shift =
10105           lowerVectorShuffleAsShift(DL, MVT::v8i32, V1, V2, Mask, DAG))
10106     return Shift;
10107
10108   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10109           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10110     return Rotate;
10111
10112   // If the shuffle patterns aren't repeated but it is a single input, directly
10113   // generate a cross-lane VPERMD instruction.
10114   if (isSingleInputShuffleMask(Mask)) {
10115     SDValue VPermMask[8];
10116     for (int i = 0; i < 8; ++i)
10117       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10118                                  : DAG.getConstant(Mask[i], DL, MVT::i32);
10119     return DAG.getNode(
10120         X86ISD::VPERMV, DL, MVT::v8i32,
10121         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask), V1);
10122   }
10123
10124   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10125   // shuffle.
10126   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10127           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10128     return Result;
10129
10130   // Otherwise fall back on generic blend lowering.
10131   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i32, V1, V2,
10132                                                     Mask, DAG);
10133 }
10134
10135 /// \brief Handle lowering of 16-lane 16-bit integer shuffles.
10136 ///
10137 /// This routine is only called when we have AVX2 and thus a reasonable
10138 /// instruction set for v16i16 shuffling..
10139 static SDValue lowerV16I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10140                                         const X86Subtarget *Subtarget,
10141                                         SelectionDAG &DAG) {
10142   SDLoc DL(Op);
10143   assert(V1.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10144   assert(V2.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10145   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10146   ArrayRef<int> Mask = SVOp->getMask();
10147   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10148   assert(Subtarget->hasAVX2() && "We can only lower v16i16 with AVX2!");
10149
10150   // Whenever we can lower this as a zext, that instruction is strictly faster
10151   // than any alternative. It also allows us to fold memory operands into the
10152   // shuffle in many cases.
10153   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v16i16, V1, V2,
10154                                                          Mask, Subtarget, DAG))
10155     return ZExt;
10156
10157   // Check for being able to broadcast a single element.
10158   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i16, V1,
10159                                                         Mask, Subtarget, DAG))
10160     return Broadcast;
10161
10162   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i16, V1, V2, Mask,
10163                                                 Subtarget, DAG))
10164     return Blend;
10165
10166   // Use dedicated unpack instructions for masks that match their pattern.
10167   if (isShuffleEquivalent(V1, V2, Mask,
10168                           {// First 128-bit lane:
10169                            0, 16, 1, 17, 2, 18, 3, 19,
10170                            // Second 128-bit lane:
10171                            8, 24, 9, 25, 10, 26, 11, 27}))
10172     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i16, V1, V2);
10173   if (isShuffleEquivalent(V1, V2, Mask,
10174                           {// First 128-bit lane:
10175                            4, 20, 5, 21, 6, 22, 7, 23,
10176                            // Second 128-bit lane:
10177                            12, 28, 13, 29, 14, 30, 15, 31}))
10178     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i16, V1, V2);
10179
10180   // Try to use shift instructions.
10181   if (SDValue Shift =
10182           lowerVectorShuffleAsShift(DL, MVT::v16i16, V1, V2, Mask, DAG))
10183     return Shift;
10184
10185   // Try to use byte rotation instructions.
10186   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10187           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10188     return Rotate;
10189
10190   if (isSingleInputShuffleMask(Mask)) {
10191     // There are no generalized cross-lane shuffle operations available on i16
10192     // element types.
10193     if (is128BitLaneCrossingShuffleMask(MVT::v16i16, Mask))
10194       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v16i16, V1, V2,
10195                                                      Mask, DAG);
10196
10197     SmallVector<int, 8> RepeatedMask;
10198     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
10199       // As this is a single-input shuffle, the repeated mask should be
10200       // a strictly valid v8i16 mask that we can pass through to the v8i16
10201       // lowering to handle even the v16 case.
10202       return lowerV8I16GeneralSingleInputVectorShuffle(
10203           DL, MVT::v16i16, V1, RepeatedMask, Subtarget, DAG);
10204     }
10205
10206     SDValue PSHUFBMask[32];
10207     for (int i = 0; i < 16; ++i) {
10208       if (Mask[i] == -1) {
10209         PSHUFBMask[2 * i] = PSHUFBMask[2 * i + 1] = DAG.getUNDEF(MVT::i8);
10210         continue;
10211       }
10212
10213       int M = i < 8 ? Mask[i] : Mask[i] - 8;
10214       assert(M >= 0 && M < 8 && "Invalid single-input mask!");
10215       PSHUFBMask[2 * i] = DAG.getConstant(2 * M, DL, MVT::i8);
10216       PSHUFBMask[2 * i + 1] = DAG.getConstant(2 * M + 1, DL, MVT::i8);
10217     }
10218     return DAG.getBitcast(MVT::v16i16,
10219                           DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8,
10220                                       DAG.getBitcast(MVT::v32i8, V1),
10221                                       DAG.getNode(ISD::BUILD_VECTOR, DL,
10222                                                   MVT::v32i8, PSHUFBMask)));
10223   }
10224
10225   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10226   // shuffle.
10227   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10228           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10229     return Result;
10230
10231   // Otherwise fall back on generic lowering.
10232   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v16i16, V1, V2, Mask, DAG);
10233 }
10234
10235 /// \brief Handle lowering of 32-lane 8-bit integer shuffles.
10236 ///
10237 /// This routine is only called when we have AVX2 and thus a reasonable
10238 /// instruction set for v32i8 shuffling..
10239 static SDValue lowerV32I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10240                                        const X86Subtarget *Subtarget,
10241                                        SelectionDAG &DAG) {
10242   SDLoc DL(Op);
10243   assert(V1.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10244   assert(V2.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10245   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10246   ArrayRef<int> Mask = SVOp->getMask();
10247   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10248   assert(Subtarget->hasAVX2() && "We can only lower v32i8 with AVX2!");
10249
10250   // Whenever we can lower this as a zext, that instruction is strictly faster
10251   // than any alternative. It also allows us to fold memory operands into the
10252   // shuffle in many cases.
10253   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v32i8, V1, V2,
10254                                                          Mask, Subtarget, DAG))
10255     return ZExt;
10256
10257   // Check for being able to broadcast a single element.
10258   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v32i8, V1,
10259                                                         Mask, Subtarget, DAG))
10260     return Broadcast;
10261
10262   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v32i8, V1, V2, Mask,
10263                                                 Subtarget, DAG))
10264     return Blend;
10265
10266   // Use dedicated unpack instructions for masks that match their pattern.
10267   // Note that these are repeated 128-bit lane unpacks, not unpacks across all
10268   // 256-bit lanes.
10269   if (isShuffleEquivalent(
10270           V1, V2, Mask,
10271           {// First 128-bit lane:
10272            0, 32, 1, 33, 2, 34, 3, 35, 4, 36, 5, 37, 6, 38, 7, 39,
10273            // Second 128-bit lane:
10274            16, 48, 17, 49, 18, 50, 19, 51, 20, 52, 21, 53, 22, 54, 23, 55}))
10275     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v32i8, V1, V2);
10276   if (isShuffleEquivalent(
10277           V1, V2, Mask,
10278           {// First 128-bit lane:
10279            8, 40, 9, 41, 10, 42, 11, 43, 12, 44, 13, 45, 14, 46, 15, 47,
10280            // Second 128-bit lane:
10281            24, 56, 25, 57, 26, 58, 27, 59, 28, 60, 29, 61, 30, 62, 31, 63}))
10282     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v32i8, V1, V2);
10283
10284   // Try to use shift instructions.
10285   if (SDValue Shift =
10286           lowerVectorShuffleAsShift(DL, MVT::v32i8, V1, V2, Mask, DAG))
10287     return Shift;
10288
10289   // Try to use byte rotation instructions.
10290   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10291           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
10292     return Rotate;
10293
10294   if (isSingleInputShuffleMask(Mask)) {
10295     // There are no generalized cross-lane shuffle operations available on i8
10296     // element types.
10297     if (is128BitLaneCrossingShuffleMask(MVT::v32i8, Mask))
10298       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v32i8, V1, V2,
10299                                                      Mask, DAG);
10300
10301     SDValue PSHUFBMask[32];
10302     for (int i = 0; i < 32; ++i)
10303       PSHUFBMask[i] =
10304           Mask[i] < 0
10305               ? DAG.getUNDEF(MVT::i8)
10306               : DAG.getConstant(Mask[i] < 16 ? Mask[i] : Mask[i] - 16, DL,
10307                                 MVT::i8);
10308
10309     return DAG.getNode(
10310         X86ISD::PSHUFB, DL, MVT::v32i8, V1,
10311         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask));
10312   }
10313
10314   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10315   // shuffle.
10316   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10317           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
10318     return Result;
10319
10320   // Otherwise fall back on generic lowering.
10321   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v32i8, V1, V2, Mask, DAG);
10322 }
10323
10324 /// \brief High-level routine to lower various 256-bit x86 vector shuffles.
10325 ///
10326 /// This routine either breaks down the specific type of a 256-bit x86 vector
10327 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
10328 /// together based on the available instructions.
10329 static SDValue lower256BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10330                                         MVT VT, const X86Subtarget *Subtarget,
10331                                         SelectionDAG &DAG) {
10332   SDLoc DL(Op);
10333   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10334   ArrayRef<int> Mask = SVOp->getMask();
10335
10336   // If we have a single input to the zero element, insert that into V1 if we
10337   // can do so cheaply.
10338   int NumElts = VT.getVectorNumElements();
10339   int NumV2Elements = std::count_if(Mask.begin(), Mask.end(), [NumElts](int M) {
10340     return M >= NumElts;
10341   });
10342
10343   if (NumV2Elements == 1 && Mask[0] >= NumElts)
10344     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
10345                               DL, VT, V1, V2, Mask, Subtarget, DAG))
10346       return Insertion;
10347
10348   // There is a really nice hard cut-over between AVX1 and AVX2 that means we can
10349   // check for those subtargets here and avoid much of the subtarget querying in
10350   // the per-vector-type lowering routines. With AVX1 we have essentially *zero*
10351   // ability to manipulate a 256-bit vector with integer types. Since we'll use
10352   // floating point types there eventually, just immediately cast everything to
10353   // a float and operate entirely in that domain.
10354   if (VT.isInteger() && !Subtarget->hasAVX2()) {
10355     int ElementBits = VT.getScalarSizeInBits();
10356     if (ElementBits < 32)
10357       // No floating point type available, decompose into 128-bit vectors.
10358       return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10359
10360     MVT FpVT = MVT::getVectorVT(MVT::getFloatingPointVT(ElementBits),
10361                                 VT.getVectorNumElements());
10362     V1 = DAG.getBitcast(FpVT, V1);
10363     V2 = DAG.getBitcast(FpVT, V2);
10364     return DAG.getBitcast(VT, DAG.getVectorShuffle(FpVT, DL, V1, V2, Mask));
10365   }
10366
10367   switch (VT.SimpleTy) {
10368   case MVT::v4f64:
10369     return lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10370   case MVT::v4i64:
10371     return lowerV4I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10372   case MVT::v8f32:
10373     return lowerV8F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10374   case MVT::v8i32:
10375     return lowerV8I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10376   case MVT::v16i16:
10377     return lowerV16I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10378   case MVT::v32i8:
10379     return lowerV32I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10380
10381   default:
10382     llvm_unreachable("Not a valid 256-bit x86 vector type!");
10383   }
10384 }
10385
10386 /// \brief Handle lowering of 8-lane 64-bit floating point shuffles.
10387 static SDValue lowerV8F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10388                                        const X86Subtarget *Subtarget,
10389                                        SelectionDAG &DAG) {
10390   SDLoc DL(Op);
10391   assert(V1.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10392   assert(V2.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10393   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10394   ArrayRef<int> Mask = SVOp->getMask();
10395   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10396
10397   // X86 has dedicated unpack instructions that can handle specific blend
10398   // operations: UNPCKH and UNPCKL.
10399   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
10400     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f64, V1, V2);
10401   if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
10402     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f64, V1, V2);
10403
10404   // FIXME: Implement direct support for this type!
10405   return splitAndLowerVectorShuffle(DL, MVT::v8f64, V1, V2, Mask, DAG);
10406 }
10407
10408 /// \brief Handle lowering of 16-lane 32-bit floating point shuffles.
10409 static SDValue lowerV16F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10410                                        const X86Subtarget *Subtarget,
10411                                        SelectionDAG &DAG) {
10412   SDLoc DL(Op);
10413   assert(V1.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10414   assert(V2.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10415   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10416   ArrayRef<int> Mask = SVOp->getMask();
10417   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10418
10419   // Use dedicated unpack instructions for masks that match their pattern.
10420   if (isShuffleEquivalent(V1, V2, Mask,
10421                           {// First 128-bit lane.
10422                            0, 16, 1, 17, 4, 20, 5, 21,
10423                            // Second 128-bit lane.
10424                            8, 24, 9, 25, 12, 28, 13, 29}))
10425     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16f32, V1, V2);
10426   if (isShuffleEquivalent(V1, V2, Mask,
10427                           {// First 128-bit lane.
10428                            2, 18, 3, 19, 6, 22, 7, 23,
10429                            // Second 128-bit lane.
10430                            10, 26, 11, 27, 14, 30, 15, 31}))
10431     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16f32, V1, V2);
10432
10433   // FIXME: Implement direct support for this type!
10434   return splitAndLowerVectorShuffle(DL, MVT::v16f32, V1, V2, Mask, DAG);
10435 }
10436
10437 /// \brief Handle lowering of 8-lane 64-bit integer shuffles.
10438 static SDValue lowerV8I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10439                                        const X86Subtarget *Subtarget,
10440                                        SelectionDAG &DAG) {
10441   SDLoc DL(Op);
10442   assert(V1.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10443   assert(V2.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10444   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10445   ArrayRef<int> Mask = SVOp->getMask();
10446   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10447
10448   // X86 has dedicated unpack instructions that can handle specific blend
10449   // operations: UNPCKH and UNPCKL.
10450   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
10451     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i64, V1, V2);
10452   if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
10453     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i64, V1, V2);
10454
10455   // FIXME: Implement direct support for this type!
10456   return splitAndLowerVectorShuffle(DL, MVT::v8i64, V1, V2, Mask, DAG);
10457 }
10458
10459 /// \brief Handle lowering of 16-lane 32-bit integer shuffles.
10460 static SDValue lowerV16I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10461                                        const X86Subtarget *Subtarget,
10462                                        SelectionDAG &DAG) {
10463   SDLoc DL(Op);
10464   assert(V1.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10465   assert(V2.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10466   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10467   ArrayRef<int> Mask = SVOp->getMask();
10468   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10469
10470   // Use dedicated unpack instructions for masks that match their pattern.
10471   if (isShuffleEquivalent(V1, V2, Mask,
10472                           {// First 128-bit lane.
10473                            0, 16, 1, 17, 4, 20, 5, 21,
10474                            // Second 128-bit lane.
10475                            8, 24, 9, 25, 12, 28, 13, 29}))
10476     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i32, V1, V2);
10477   if (isShuffleEquivalent(V1, V2, Mask,
10478                           {// First 128-bit lane.
10479                            2, 18, 3, 19, 6, 22, 7, 23,
10480                            // Second 128-bit lane.
10481                            10, 26, 11, 27, 14, 30, 15, 31}))
10482     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i32, V1, V2);
10483
10484   // FIXME: Implement direct support for this type!
10485   return splitAndLowerVectorShuffle(DL, MVT::v16i32, V1, V2, Mask, DAG);
10486 }
10487
10488 /// \brief Handle lowering of 32-lane 16-bit integer shuffles.
10489 static SDValue lowerV32I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10490                                         const X86Subtarget *Subtarget,
10491                                         SelectionDAG &DAG) {
10492   SDLoc DL(Op);
10493   assert(V1.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10494   assert(V2.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10495   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10496   ArrayRef<int> Mask = SVOp->getMask();
10497   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10498   assert(Subtarget->hasBWI() && "We can only lower v32i16 with AVX-512-BWI!");
10499
10500   // FIXME: Implement direct support for this type!
10501   return splitAndLowerVectorShuffle(DL, MVT::v32i16, V1, V2, Mask, DAG);
10502 }
10503
10504 /// \brief Handle lowering of 64-lane 8-bit integer shuffles.
10505 static SDValue lowerV64I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10506                                        const X86Subtarget *Subtarget,
10507                                        SelectionDAG &DAG) {
10508   SDLoc DL(Op);
10509   assert(V1.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10510   assert(V2.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10511   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10512   ArrayRef<int> Mask = SVOp->getMask();
10513   assert(Mask.size() == 64 && "Unexpected mask size for v64 shuffle!");
10514   assert(Subtarget->hasBWI() && "We can only lower v64i8 with AVX-512-BWI!");
10515
10516   // FIXME: Implement direct support for this type!
10517   return splitAndLowerVectorShuffle(DL, MVT::v64i8, V1, V2, Mask, DAG);
10518 }
10519
10520 /// \brief High-level routine to lower various 512-bit x86 vector shuffles.
10521 ///
10522 /// This routine either breaks down the specific type of a 512-bit x86 vector
10523 /// shuffle or splits it into two 256-bit shuffles and fuses the results back
10524 /// together based on the available instructions.
10525 static SDValue lower512BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10526                                         MVT VT, const X86Subtarget *Subtarget,
10527                                         SelectionDAG &DAG) {
10528   SDLoc DL(Op);
10529   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10530   ArrayRef<int> Mask = SVOp->getMask();
10531   assert(Subtarget->hasAVX512() &&
10532          "Cannot lower 512-bit vectors w/ basic ISA!");
10533
10534   // Check for being able to broadcast a single element.
10535   if (SDValue Broadcast =
10536           lowerVectorShuffleAsBroadcast(DL, VT, V1, Mask, Subtarget, DAG))
10537     return Broadcast;
10538
10539   // Dispatch to each element type for lowering. If we don't have supprot for
10540   // specific element type shuffles at 512 bits, immediately split them and
10541   // lower them. Each lowering routine of a given type is allowed to assume that
10542   // the requisite ISA extensions for that element type are available.
10543   switch (VT.SimpleTy) {
10544   case MVT::v8f64:
10545     return lowerV8F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10546   case MVT::v16f32:
10547     return lowerV16F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10548   case MVT::v8i64:
10549     return lowerV8I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10550   case MVT::v16i32:
10551     return lowerV16I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10552   case MVT::v32i16:
10553     if (Subtarget->hasBWI())
10554       return lowerV32I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10555     break;
10556   case MVT::v64i8:
10557     if (Subtarget->hasBWI())
10558       return lowerV64I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10559     break;
10560
10561   default:
10562     llvm_unreachable("Not a valid 512-bit x86 vector type!");
10563   }
10564
10565   // Otherwise fall back on splitting.
10566   return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10567 }
10568
10569 /// \brief Top-level lowering for x86 vector shuffles.
10570 ///
10571 /// This handles decomposition, canonicalization, and lowering of all x86
10572 /// vector shuffles. Most of the specific lowering strategies are encapsulated
10573 /// above in helper routines. The canonicalization attempts to widen shuffles
10574 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
10575 /// s.t. only one of the two inputs needs to be tested, etc.
10576 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
10577                                   SelectionDAG &DAG) {
10578   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10579   ArrayRef<int> Mask = SVOp->getMask();
10580   SDValue V1 = Op.getOperand(0);
10581   SDValue V2 = Op.getOperand(1);
10582   MVT VT = Op.getSimpleValueType();
10583   int NumElements = VT.getVectorNumElements();
10584   SDLoc dl(Op);
10585
10586   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
10587
10588   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
10589   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
10590   if (V1IsUndef && V2IsUndef)
10591     return DAG.getUNDEF(VT);
10592
10593   // When we create a shuffle node we put the UNDEF node to second operand,
10594   // but in some cases the first operand may be transformed to UNDEF.
10595   // In this case we should just commute the node.
10596   if (V1IsUndef)
10597     return DAG.getCommutedVectorShuffle(*SVOp);
10598
10599   // Check for non-undef masks pointing at an undef vector and make the masks
10600   // undef as well. This makes it easier to match the shuffle based solely on
10601   // the mask.
10602   if (V2IsUndef)
10603     for (int M : Mask)
10604       if (M >= NumElements) {
10605         SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
10606         for (int &M : NewMask)
10607           if (M >= NumElements)
10608             M = -1;
10609         return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
10610       }
10611
10612   // We actually see shuffles that are entirely re-arrangements of a set of
10613   // zero inputs. This mostly happens while decomposing complex shuffles into
10614   // simple ones. Directly lower these as a buildvector of zeros.
10615   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
10616   if (Zeroable.all())
10617     return getZeroVector(VT, Subtarget, DAG, dl);
10618
10619   // Try to collapse shuffles into using a vector type with fewer elements but
10620   // wider element types. We cap this to not form integers or floating point
10621   // elements wider than 64 bits, but it might be interesting to form i128
10622   // integers to handle flipping the low and high halves of AVX 256-bit vectors.
10623   SmallVector<int, 16> WidenedMask;
10624   if (VT.getScalarSizeInBits() < 64 &&
10625       canWidenShuffleElements(Mask, WidenedMask)) {
10626     MVT NewEltVT = VT.isFloatingPoint()
10627                        ? MVT::getFloatingPointVT(VT.getScalarSizeInBits() * 2)
10628                        : MVT::getIntegerVT(VT.getScalarSizeInBits() * 2);
10629     MVT NewVT = MVT::getVectorVT(NewEltVT, VT.getVectorNumElements() / 2);
10630     // Make sure that the new vector type is legal. For example, v2f64 isn't
10631     // legal on SSE1.
10632     if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
10633       V1 = DAG.getBitcast(NewVT, V1);
10634       V2 = DAG.getBitcast(NewVT, V2);
10635       return DAG.getBitcast(
10636           VT, DAG.getVectorShuffle(NewVT, dl, V1, V2, WidenedMask));
10637     }
10638   }
10639
10640   int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
10641   for (int M : SVOp->getMask())
10642     if (M < 0)
10643       ++NumUndefElements;
10644     else if (M < NumElements)
10645       ++NumV1Elements;
10646     else
10647       ++NumV2Elements;
10648
10649   // Commute the shuffle as needed such that more elements come from V1 than
10650   // V2. This allows us to match the shuffle pattern strictly on how many
10651   // elements come from V1 without handling the symmetric cases.
10652   if (NumV2Elements > NumV1Elements)
10653     return DAG.getCommutedVectorShuffle(*SVOp);
10654
10655   // When the number of V1 and V2 elements are the same, try to minimize the
10656   // number of uses of V2 in the low half of the vector. When that is tied,
10657   // ensure that the sum of indices for V1 is equal to or lower than the sum
10658   // indices for V2. When those are equal, try to ensure that the number of odd
10659   // indices for V1 is lower than the number of odd indices for V2.
10660   if (NumV1Elements == NumV2Elements) {
10661     int LowV1Elements = 0, LowV2Elements = 0;
10662     for (int M : SVOp->getMask().slice(0, NumElements / 2))
10663       if (M >= NumElements)
10664         ++LowV2Elements;
10665       else if (M >= 0)
10666         ++LowV1Elements;
10667     if (LowV2Elements > LowV1Elements) {
10668       return DAG.getCommutedVectorShuffle(*SVOp);
10669     } else if (LowV2Elements == LowV1Elements) {
10670       int SumV1Indices = 0, SumV2Indices = 0;
10671       for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10672         if (SVOp->getMask()[i] >= NumElements)
10673           SumV2Indices += i;
10674         else if (SVOp->getMask()[i] >= 0)
10675           SumV1Indices += i;
10676       if (SumV2Indices < SumV1Indices) {
10677         return DAG.getCommutedVectorShuffle(*SVOp);
10678       } else if (SumV2Indices == SumV1Indices) {
10679         int NumV1OddIndices = 0, NumV2OddIndices = 0;
10680         for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10681           if (SVOp->getMask()[i] >= NumElements)
10682             NumV2OddIndices += i % 2;
10683           else if (SVOp->getMask()[i] >= 0)
10684             NumV1OddIndices += i % 2;
10685         if (NumV2OddIndices < NumV1OddIndices)
10686           return DAG.getCommutedVectorShuffle(*SVOp);
10687       }
10688     }
10689   }
10690
10691   // For each vector width, delegate to a specialized lowering routine.
10692   if (VT.getSizeInBits() == 128)
10693     return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10694
10695   if (VT.getSizeInBits() == 256)
10696     return lower256BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10697
10698   // Force AVX-512 vectors to be scalarized for now.
10699   // FIXME: Implement AVX-512 support!
10700   if (VT.getSizeInBits() == 512)
10701     return lower512BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10702
10703   llvm_unreachable("Unimplemented!");
10704 }
10705
10706 // This function assumes its argument is a BUILD_VECTOR of constants or
10707 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
10708 // true.
10709 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
10710                                     unsigned &MaskValue) {
10711   MaskValue = 0;
10712   unsigned NumElems = BuildVector->getNumOperands();
10713   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
10714   unsigned NumLanes = (NumElems - 1) / 8 + 1;
10715   unsigned NumElemsInLane = NumElems / NumLanes;
10716
10717   // Blend for v16i16 should be symetric for the both lanes.
10718   for (unsigned i = 0; i < NumElemsInLane; ++i) {
10719     SDValue EltCond = BuildVector->getOperand(i);
10720     SDValue SndLaneEltCond =
10721         (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
10722
10723     int Lane1Cond = -1, Lane2Cond = -1;
10724     if (isa<ConstantSDNode>(EltCond))
10725       Lane1Cond = !isZero(EltCond);
10726     if (isa<ConstantSDNode>(SndLaneEltCond))
10727       Lane2Cond = !isZero(SndLaneEltCond);
10728
10729     if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
10730       // Lane1Cond != 0, means we want the first argument.
10731       // Lane1Cond == 0, means we want the second argument.
10732       // The encoding of this argument is 0 for the first argument, 1
10733       // for the second. Therefore, invert the condition.
10734       MaskValue |= !Lane1Cond << i;
10735     else if (Lane1Cond < 0)
10736       MaskValue |= !Lane2Cond << i;
10737     else
10738       return false;
10739   }
10740   return true;
10741 }
10742
10743 /// \brief Try to lower a VSELECT instruction to a vector shuffle.
10744 static SDValue lowerVSELECTtoVectorShuffle(SDValue Op,
10745                                            const X86Subtarget *Subtarget,
10746                                            SelectionDAG &DAG) {
10747   SDValue Cond = Op.getOperand(0);
10748   SDValue LHS = Op.getOperand(1);
10749   SDValue RHS = Op.getOperand(2);
10750   SDLoc dl(Op);
10751   MVT VT = Op.getSimpleValueType();
10752
10753   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
10754     return SDValue();
10755   auto *CondBV = cast<BuildVectorSDNode>(Cond);
10756
10757   // Only non-legal VSELECTs reach this lowering, convert those into generic
10758   // shuffles and re-use the shuffle lowering path for blends.
10759   SmallVector<int, 32> Mask;
10760   for (int i = 0, Size = VT.getVectorNumElements(); i < Size; ++i) {
10761     SDValue CondElt = CondBV->getOperand(i);
10762     Mask.push_back(
10763         isa<ConstantSDNode>(CondElt) ? i + (isZero(CondElt) ? Size : 0) : -1);
10764   }
10765   return DAG.getVectorShuffle(VT, dl, LHS, RHS, Mask);
10766 }
10767
10768 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
10769   // A vselect where all conditions and data are constants can be optimized into
10770   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
10771   if (ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(0).getNode()) &&
10772       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(1).getNode()) &&
10773       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(2).getNode()))
10774     return SDValue();
10775
10776   // Try to lower this to a blend-style vector shuffle. This can handle all
10777   // constant condition cases.
10778   if (SDValue BlendOp = lowerVSELECTtoVectorShuffle(Op, Subtarget, DAG))
10779     return BlendOp;
10780
10781   // Variable blends are only legal from SSE4.1 onward.
10782   if (!Subtarget->hasSSE41())
10783     return SDValue();
10784
10785   // Only some types will be legal on some subtargets. If we can emit a legal
10786   // VSELECT-matching blend, return Op, and but if we need to expand, return
10787   // a null value.
10788   switch (Op.getSimpleValueType().SimpleTy) {
10789   default:
10790     // Most of the vector types have blends past SSE4.1.
10791     return Op;
10792
10793   case MVT::v32i8:
10794     // The byte blends for AVX vectors were introduced only in AVX2.
10795     if (Subtarget->hasAVX2())
10796       return Op;
10797
10798     return SDValue();
10799
10800   case MVT::v8i16:
10801   case MVT::v16i16:
10802     // AVX-512 BWI and VLX features support VSELECT with i16 elements.
10803     if (Subtarget->hasBWI() && Subtarget->hasVLX())
10804       return Op;
10805
10806     // FIXME: We should custom lower this by fixing the condition and using i8
10807     // blends.
10808     return SDValue();
10809   }
10810 }
10811
10812 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
10813   MVT VT = Op.getSimpleValueType();
10814   SDLoc dl(Op);
10815
10816   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
10817     return SDValue();
10818
10819   if (VT.getSizeInBits() == 8) {
10820     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
10821                                   Op.getOperand(0), Op.getOperand(1));
10822     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10823                                   DAG.getValueType(VT));
10824     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10825   }
10826
10827   if (VT.getSizeInBits() == 16) {
10828     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10829     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
10830     if (Idx == 0)
10831       return DAG.getNode(
10832           ISD::TRUNCATE, dl, MVT::i16,
10833           DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10834                       DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
10835                       Op.getOperand(1)));
10836     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
10837                                   Op.getOperand(0), Op.getOperand(1));
10838     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10839                                   DAG.getValueType(VT));
10840     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10841   }
10842
10843   if (VT == MVT::f32) {
10844     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
10845     // the result back to FR32 register. It's only worth matching if the
10846     // result has a single use which is a store or a bitcast to i32.  And in
10847     // the case of a store, it's not worth it if the index is a constant 0,
10848     // because a MOVSSmr can be used instead, which is smaller and faster.
10849     if (!Op.hasOneUse())
10850       return SDValue();
10851     SDNode *User = *Op.getNode()->use_begin();
10852     if ((User->getOpcode() != ISD::STORE ||
10853          (isa<ConstantSDNode>(Op.getOperand(1)) &&
10854           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
10855         (User->getOpcode() != ISD::BITCAST ||
10856          User->getValueType(0) != MVT::i32))
10857       return SDValue();
10858     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10859                                   DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
10860                                   Op.getOperand(1));
10861     return DAG.getBitcast(MVT::f32, Extract);
10862   }
10863
10864   if (VT == MVT::i32 || VT == MVT::i64) {
10865     // ExtractPS/pextrq works with constant index.
10866     if (isa<ConstantSDNode>(Op.getOperand(1)))
10867       return Op;
10868   }
10869   return SDValue();
10870 }
10871
10872 /// Extract one bit from mask vector, like v16i1 or v8i1.
10873 /// AVX-512 feature.
10874 SDValue
10875 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
10876   SDValue Vec = Op.getOperand(0);
10877   SDLoc dl(Vec);
10878   MVT VecVT = Vec.getSimpleValueType();
10879   SDValue Idx = Op.getOperand(1);
10880   MVT EltVT = Op.getSimpleValueType();
10881
10882   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
10883   assert((VecVT.getVectorNumElements() <= 16 || Subtarget->hasBWI()) &&
10884          "Unexpected vector type in ExtractBitFromMaskVector");
10885
10886   // variable index can't be handled in mask registers,
10887   // extend vector to VR512
10888   if (!isa<ConstantSDNode>(Idx)) {
10889     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
10890     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
10891     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
10892                               ExtVT.getVectorElementType(), Ext, Idx);
10893     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
10894   }
10895
10896   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10897   const TargetRegisterClass* rc = getRegClassFor(VecVT);
10898   if (!Subtarget->hasDQI() && (VecVT.getVectorNumElements() <= 8))
10899     rc = getRegClassFor(MVT::v16i1);
10900   unsigned MaxSift = rc->getSize()*8 - 1;
10901   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
10902                     DAG.getConstant(MaxSift - IdxVal, dl, MVT::i8));
10903   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
10904                     DAG.getConstant(MaxSift, dl, MVT::i8));
10905   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
10906                        DAG.getIntPtrConstant(0, dl));
10907 }
10908
10909 SDValue
10910 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
10911                                            SelectionDAG &DAG) const {
10912   SDLoc dl(Op);
10913   SDValue Vec = Op.getOperand(0);
10914   MVT VecVT = Vec.getSimpleValueType();
10915   SDValue Idx = Op.getOperand(1);
10916
10917   if (Op.getSimpleValueType() == MVT::i1)
10918     return ExtractBitFromMaskVector(Op, DAG);
10919
10920   if (!isa<ConstantSDNode>(Idx)) {
10921     if (VecVT.is512BitVector() ||
10922         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
10923          VecVT.getVectorElementType().getSizeInBits() == 32)) {
10924
10925       MVT MaskEltVT =
10926         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
10927       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
10928                                     MaskEltVT.getSizeInBits());
10929
10930       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
10931       auto PtrVT = getPointerTy(DAG.getDataLayout());
10932       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
10933                                  getZeroVector(MaskVT, Subtarget, DAG, dl), Idx,
10934                                  DAG.getConstant(0, dl, PtrVT));
10935       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
10936       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Perm,
10937                          DAG.getConstant(0, dl, PtrVT));
10938     }
10939     return SDValue();
10940   }
10941
10942   // If this is a 256-bit vector result, first extract the 128-bit vector and
10943   // then extract the element from the 128-bit vector.
10944   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
10945
10946     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10947     // Get the 128-bit vector.
10948     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
10949     MVT EltVT = VecVT.getVectorElementType();
10950
10951     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
10952
10953     //if (IdxVal >= NumElems/2)
10954     //  IdxVal -= NumElems/2;
10955     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
10956     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
10957                        DAG.getConstant(IdxVal, dl, MVT::i32));
10958   }
10959
10960   assert(VecVT.is128BitVector() && "Unexpected vector length");
10961
10962   if (Subtarget->hasSSE41())
10963     if (SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG))
10964       return Res;
10965
10966   MVT VT = Op.getSimpleValueType();
10967   // TODO: handle v16i8.
10968   if (VT.getSizeInBits() == 16) {
10969     SDValue Vec = Op.getOperand(0);
10970     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10971     if (Idx == 0)
10972       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
10973                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10974                                      DAG.getBitcast(MVT::v4i32, Vec),
10975                                      Op.getOperand(1)));
10976     // Transform it so it match pextrw which produces a 32-bit result.
10977     MVT EltVT = MVT::i32;
10978     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
10979                                   Op.getOperand(0), Op.getOperand(1));
10980     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
10981                                   DAG.getValueType(VT));
10982     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10983   }
10984
10985   if (VT.getSizeInBits() == 32) {
10986     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10987     if (Idx == 0)
10988       return Op;
10989
10990     // SHUFPS the element to the lowest double word, then movss.
10991     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
10992     MVT VVT = Op.getOperand(0).getSimpleValueType();
10993     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10994                                        DAG.getUNDEF(VVT), Mask);
10995     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10996                        DAG.getIntPtrConstant(0, dl));
10997   }
10998
10999   if (VT.getSizeInBits() == 64) {
11000     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
11001     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
11002     //        to match extract_elt for f64.
11003     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11004     if (Idx == 0)
11005       return Op;
11006
11007     // UNPCKHPD the element to the lowest double word, then movsd.
11008     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
11009     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
11010     int Mask[2] = { 1, -1 };
11011     MVT VVT = Op.getOperand(0).getSimpleValueType();
11012     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
11013                                        DAG.getUNDEF(VVT), Mask);
11014     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
11015                        DAG.getIntPtrConstant(0, dl));
11016   }
11017
11018   return SDValue();
11019 }
11020
11021 /// Insert one bit to mask vector, like v16i1 or v8i1.
11022 /// AVX-512 feature.
11023 SDValue
11024 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
11025   SDLoc dl(Op);
11026   SDValue Vec = Op.getOperand(0);
11027   SDValue Elt = Op.getOperand(1);
11028   SDValue Idx = Op.getOperand(2);
11029   MVT VecVT = Vec.getSimpleValueType();
11030
11031   if (!isa<ConstantSDNode>(Idx)) {
11032     // Non constant index. Extend source and destination,
11033     // insert element and then truncate the result.
11034     MVT ExtVecVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
11035     MVT ExtEltVT = (VecVT == MVT::v8i1 ?  MVT::i64 : MVT::i32);
11036     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
11037       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
11038       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
11039     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
11040   }
11041
11042   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11043   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
11044   if (IdxVal)
11045     EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
11046                            DAG.getConstant(IdxVal, dl, MVT::i8));
11047   if (Vec.getOpcode() == ISD::UNDEF)
11048     return EltInVec;
11049   return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
11050 }
11051
11052 SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
11053                                                   SelectionDAG &DAG) const {
11054   MVT VT = Op.getSimpleValueType();
11055   MVT EltVT = VT.getVectorElementType();
11056
11057   if (EltVT == MVT::i1)
11058     return InsertBitToMaskVector(Op, DAG);
11059
11060   SDLoc dl(Op);
11061   SDValue N0 = Op.getOperand(0);
11062   SDValue N1 = Op.getOperand(1);
11063   SDValue N2 = Op.getOperand(2);
11064   if (!isa<ConstantSDNode>(N2))
11065     return SDValue();
11066   auto *N2C = cast<ConstantSDNode>(N2);
11067   unsigned IdxVal = N2C->getZExtValue();
11068
11069   // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
11070   // into that, and then insert the subvector back into the result.
11071   if (VT.is256BitVector() || VT.is512BitVector()) {
11072     // With a 256-bit vector, we can insert into the zero element efficiently
11073     // using a blend if we have AVX or AVX2 and the right data type.
11074     if (VT.is256BitVector() && IdxVal == 0) {
11075       // TODO: It is worthwhile to cast integer to floating point and back
11076       // and incur a domain crossing penalty if that's what we'll end up
11077       // doing anyway after extracting to a 128-bit vector.
11078       if ((Subtarget->hasAVX() && (EltVT == MVT::f64 || EltVT == MVT::f32)) ||
11079           (Subtarget->hasAVX2() && EltVT == MVT::i32)) {
11080         SDValue N1Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, N1);
11081         N2 = DAG.getIntPtrConstant(1, dl);
11082         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1Vec, N2);
11083       }
11084     }
11085
11086     // Get the desired 128-bit vector chunk.
11087     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
11088
11089     // Insert the element into the desired chunk.
11090     unsigned NumEltsIn128 = 128 / EltVT.getSizeInBits();
11091     unsigned IdxIn128 = IdxVal - (IdxVal / NumEltsIn128) * NumEltsIn128;
11092
11093     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
11094                     DAG.getConstant(IdxIn128, dl, MVT::i32));
11095
11096     // Insert the changed part back into the bigger vector
11097     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
11098   }
11099   assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
11100
11101   if (Subtarget->hasSSE41()) {
11102     if (EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) {
11103       unsigned Opc;
11104       if (VT == MVT::v8i16) {
11105         Opc = X86ISD::PINSRW;
11106       } else {
11107         assert(VT == MVT::v16i8);
11108         Opc = X86ISD::PINSRB;
11109       }
11110
11111       // Transform it so it match pinsr{b,w} which expects a GR32 as its second
11112       // argument.
11113       if (N1.getValueType() != MVT::i32)
11114         N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11115       if (N2.getValueType() != MVT::i32)
11116         N2 = DAG.getIntPtrConstant(IdxVal, dl);
11117       return DAG.getNode(Opc, dl, VT, N0, N1, N2);
11118     }
11119
11120     if (EltVT == MVT::f32) {
11121       // Bits [7:6] of the constant are the source select. This will always be
11122       //   zero here. The DAG Combiner may combine an extract_elt index into
11123       //   these bits. For example (insert (extract, 3), 2) could be matched by
11124       //   putting the '3' into bits [7:6] of X86ISD::INSERTPS.
11125       // Bits [5:4] of the constant are the destination select. This is the
11126       //   value of the incoming immediate.
11127       // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
11128       //   combine either bitwise AND or insert of float 0.0 to set these bits.
11129
11130       const Function *F = DAG.getMachineFunction().getFunction();
11131       bool MinSize = F->hasFnAttribute(Attribute::MinSize);
11132       if (IdxVal == 0 && (!MinSize || !MayFoldLoad(N1))) {
11133         // If this is an insertion of 32-bits into the low 32-bits of
11134         // a vector, we prefer to generate a blend with immediate rather
11135         // than an insertps. Blends are simpler operations in hardware and so
11136         // will always have equal or better performance than insertps.
11137         // But if optimizing for size and there's a load folding opportunity,
11138         // generate insertps because blendps does not have a 32-bit memory
11139         // operand form.
11140         N2 = DAG.getIntPtrConstant(1, dl);
11141         N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11142         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1, N2);
11143       }
11144       N2 = DAG.getIntPtrConstant(IdxVal << 4, dl);
11145       // Create this as a scalar to vector..
11146       N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11147       return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
11148     }
11149
11150     if (EltVT == MVT::i32 || EltVT == MVT::i64) {
11151       // PINSR* works with constant index.
11152       return Op;
11153     }
11154   }
11155
11156   if (EltVT == MVT::i8)
11157     return SDValue();
11158
11159   if (EltVT.getSizeInBits() == 16) {
11160     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
11161     // as its second argument.
11162     if (N1.getValueType() != MVT::i32)
11163       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11164     if (N2.getValueType() != MVT::i32)
11165       N2 = DAG.getIntPtrConstant(IdxVal, dl);
11166     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
11167   }
11168   return SDValue();
11169 }
11170
11171 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
11172   SDLoc dl(Op);
11173   MVT OpVT = Op.getSimpleValueType();
11174
11175   // If this is a 256-bit vector result, first insert into a 128-bit
11176   // vector and then insert into the 256-bit vector.
11177   if (!OpVT.is128BitVector()) {
11178     // Insert into a 128-bit vector.
11179     unsigned SizeFactor = OpVT.getSizeInBits()/128;
11180     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
11181                                  OpVT.getVectorNumElements() / SizeFactor);
11182
11183     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
11184
11185     // Insert the 128-bit vector.
11186     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
11187   }
11188
11189   if (OpVT == MVT::v1i64 &&
11190       Op.getOperand(0).getValueType() == MVT::i64)
11191     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
11192
11193   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
11194   assert(OpVT.is128BitVector() && "Expected an SSE type!");
11195   return DAG.getBitcast(
11196       OpVT, DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, AnyExt));
11197 }
11198
11199 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
11200 // a simple subregister reference or explicit instructions to grab
11201 // upper bits of a vector.
11202 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
11203                                       SelectionDAG &DAG) {
11204   SDLoc dl(Op);
11205   SDValue In =  Op.getOperand(0);
11206   SDValue Idx = Op.getOperand(1);
11207   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11208   MVT ResVT   = Op.getSimpleValueType();
11209   MVT InVT    = In.getSimpleValueType();
11210
11211   if (Subtarget->hasFp256()) {
11212     if (ResVT.is128BitVector() &&
11213         (InVT.is256BitVector() || InVT.is512BitVector()) &&
11214         isa<ConstantSDNode>(Idx)) {
11215       return Extract128BitVector(In, IdxVal, DAG, dl);
11216     }
11217     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
11218         isa<ConstantSDNode>(Idx)) {
11219       return Extract256BitVector(In, IdxVal, DAG, dl);
11220     }
11221   }
11222   return SDValue();
11223 }
11224
11225 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
11226 // simple superregister reference or explicit instructions to insert
11227 // the upper bits of a vector.
11228 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
11229                                      SelectionDAG &DAG) {
11230   if (!Subtarget->hasAVX())
11231     return SDValue();
11232
11233   SDLoc dl(Op);
11234   SDValue Vec = Op.getOperand(0);
11235   SDValue SubVec = Op.getOperand(1);
11236   SDValue Idx = Op.getOperand(2);
11237
11238   if (!isa<ConstantSDNode>(Idx))
11239     return SDValue();
11240
11241   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11242   MVT OpVT = Op.getSimpleValueType();
11243   MVT SubVecVT = SubVec.getSimpleValueType();
11244
11245   // Fold two 16-byte subvector loads into one 32-byte load:
11246   // (insert_subvector (insert_subvector undef, (load addr), 0),
11247   //                   (load addr + 16), Elts/2)
11248   // --> load32 addr
11249   if ((IdxVal == OpVT.getVectorNumElements() / 2) &&
11250       Vec.getOpcode() == ISD::INSERT_SUBVECTOR &&
11251       OpVT.is256BitVector() && SubVecVT.is128BitVector() &&
11252       !Subtarget->isUnalignedMem32Slow()) {
11253     SDValue SubVec2 = Vec.getOperand(1);
11254     if (auto *Idx2 = dyn_cast<ConstantSDNode>(Vec.getOperand(2))) {
11255       if (Idx2->getZExtValue() == 0) {
11256         SDValue Ops[] = { SubVec2, SubVec };
11257         if (SDValue Ld = EltsFromConsecutiveLoads(OpVT, Ops, dl, DAG, false))
11258           return Ld;
11259       }
11260     }
11261   }
11262
11263   if ((OpVT.is256BitVector() || OpVT.is512BitVector()) &&
11264       SubVecVT.is128BitVector())
11265     return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
11266
11267   if (OpVT.is512BitVector() && SubVecVT.is256BitVector())
11268     return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
11269
11270   if (OpVT.getVectorElementType() == MVT::i1) {
11271     if (IdxVal == 0  && Vec.getOpcode() == ISD::UNDEF) // the operation is legal
11272       return Op;
11273     SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
11274     SDValue Undef = DAG.getUNDEF(OpVT);
11275     unsigned NumElems = OpVT.getVectorNumElements();
11276     SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
11277
11278     if (IdxVal == OpVT.getVectorNumElements() / 2) {
11279       // Zero upper bits of the Vec
11280       Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
11281       Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
11282
11283       SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
11284                                  SubVec, ZeroIdx);
11285       Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
11286       return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
11287     }
11288     if (IdxVal == 0) {
11289       SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
11290                                  SubVec, ZeroIdx);
11291       // Zero upper bits of the Vec2
11292       Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
11293       Vec2 = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec2, ShiftBits);
11294       // Zero lower bits of the Vec
11295       Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
11296       Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
11297       // Merge them together
11298       return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
11299     }
11300   }
11301   return SDValue();
11302 }
11303
11304 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
11305 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
11306 // one of the above mentioned nodes. It has to be wrapped because otherwise
11307 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
11308 // be used to form addressing mode. These wrapped nodes will be selected
11309 // into MOV32ri.
11310 SDValue
11311 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
11312   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
11313
11314   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11315   // global base reg.
11316   unsigned char OpFlag = 0;
11317   unsigned WrapperKind = X86ISD::Wrapper;
11318   CodeModel::Model M = DAG.getTarget().getCodeModel();
11319
11320   if (Subtarget->isPICStyleRIPRel() &&
11321       (M == CodeModel::Small || M == CodeModel::Kernel))
11322     WrapperKind = X86ISD::WrapperRIP;
11323   else if (Subtarget->isPICStyleGOT())
11324     OpFlag = X86II::MO_GOTOFF;
11325   else if (Subtarget->isPICStyleStubPIC())
11326     OpFlag = X86II::MO_PIC_BASE_OFFSET;
11327
11328   auto PtrVT = getPointerTy(DAG.getDataLayout());
11329   SDValue Result = DAG.getTargetConstantPool(
11330       CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(), OpFlag);
11331   SDLoc DL(CP);
11332   Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11333   // With PIC, the address is actually $g + Offset.
11334   if (OpFlag) {
11335     Result =
11336         DAG.getNode(ISD::ADD, DL, PtrVT,
11337                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11338   }
11339
11340   return Result;
11341 }
11342
11343 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
11344   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
11345
11346   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11347   // global base reg.
11348   unsigned char OpFlag = 0;
11349   unsigned WrapperKind = X86ISD::Wrapper;
11350   CodeModel::Model M = DAG.getTarget().getCodeModel();
11351
11352   if (Subtarget->isPICStyleRIPRel() &&
11353       (M == CodeModel::Small || M == CodeModel::Kernel))
11354     WrapperKind = X86ISD::WrapperRIP;
11355   else if (Subtarget->isPICStyleGOT())
11356     OpFlag = X86II::MO_GOTOFF;
11357   else if (Subtarget->isPICStyleStubPIC())
11358     OpFlag = X86II::MO_PIC_BASE_OFFSET;
11359
11360   auto PtrVT = getPointerTy(DAG.getDataLayout());
11361   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, OpFlag);
11362   SDLoc DL(JT);
11363   Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11364
11365   // With PIC, the address is actually $g + Offset.
11366   if (OpFlag)
11367     Result =
11368         DAG.getNode(ISD::ADD, DL, PtrVT,
11369                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11370
11371   return Result;
11372 }
11373
11374 SDValue
11375 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
11376   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
11377
11378   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11379   // global base reg.
11380   unsigned char OpFlag = 0;
11381   unsigned WrapperKind = X86ISD::Wrapper;
11382   CodeModel::Model M = DAG.getTarget().getCodeModel();
11383
11384   if (Subtarget->isPICStyleRIPRel() &&
11385       (M == CodeModel::Small || M == CodeModel::Kernel)) {
11386     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
11387       OpFlag = X86II::MO_GOTPCREL;
11388     WrapperKind = X86ISD::WrapperRIP;
11389   } else if (Subtarget->isPICStyleGOT()) {
11390     OpFlag = X86II::MO_GOT;
11391   } else if (Subtarget->isPICStyleStubPIC()) {
11392     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
11393   } else if (Subtarget->isPICStyleStubNoDynamic()) {
11394     OpFlag = X86II::MO_DARWIN_NONLAZY;
11395   }
11396
11397   auto PtrVT = getPointerTy(DAG.getDataLayout());
11398   SDValue Result = DAG.getTargetExternalSymbol(Sym, PtrVT, OpFlag);
11399
11400   SDLoc DL(Op);
11401   Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11402
11403   // With PIC, the address is actually $g + Offset.
11404   if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
11405       !Subtarget->is64Bit()) {
11406     Result =
11407         DAG.getNode(ISD::ADD, DL, PtrVT,
11408                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11409   }
11410
11411   // For symbols that require a load from a stub to get the address, emit the
11412   // load.
11413   if (isGlobalStubReference(OpFlag))
11414     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
11415                          MachinePointerInfo::getGOT(), false, false, false, 0);
11416
11417   return Result;
11418 }
11419
11420 SDValue
11421 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
11422   // Create the TargetBlockAddressAddress node.
11423   unsigned char OpFlags =
11424     Subtarget->ClassifyBlockAddressReference();
11425   CodeModel::Model M = DAG.getTarget().getCodeModel();
11426   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
11427   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
11428   SDLoc dl(Op);
11429   auto PtrVT = getPointerTy(DAG.getDataLayout());
11430   SDValue Result = DAG.getTargetBlockAddress(BA, PtrVT, Offset, OpFlags);
11431
11432   if (Subtarget->isPICStyleRIPRel() &&
11433       (M == CodeModel::Small || M == CodeModel::Kernel))
11434     Result = DAG.getNode(X86ISD::WrapperRIP, dl, PtrVT, Result);
11435   else
11436     Result = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, Result);
11437
11438   // With PIC, the address is actually $g + Offset.
11439   if (isGlobalRelativeToPICBase(OpFlags)) {
11440     Result = DAG.getNode(ISD::ADD, dl, PtrVT,
11441                          DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
11442   }
11443
11444   return Result;
11445 }
11446
11447 SDValue
11448 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
11449                                       int64_t Offset, SelectionDAG &DAG) const {
11450   // Create the TargetGlobalAddress node, folding in the constant
11451   // offset if it is legal.
11452   unsigned char OpFlags =
11453       Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
11454   CodeModel::Model M = DAG.getTarget().getCodeModel();
11455   auto PtrVT = getPointerTy(DAG.getDataLayout());
11456   SDValue Result;
11457   if (OpFlags == X86II::MO_NO_FLAG &&
11458       X86::isOffsetSuitableForCodeModel(Offset, M)) {
11459     // A direct static reference to a global.
11460     Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, Offset);
11461     Offset = 0;
11462   } else {
11463     Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, OpFlags);
11464   }
11465
11466   if (Subtarget->isPICStyleRIPRel() &&
11467       (M == CodeModel::Small || M == CodeModel::Kernel))
11468     Result = DAG.getNode(X86ISD::WrapperRIP, dl, PtrVT, Result);
11469   else
11470     Result = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, Result);
11471
11472   // With PIC, the address is actually $g + Offset.
11473   if (isGlobalRelativeToPICBase(OpFlags)) {
11474     Result = DAG.getNode(ISD::ADD, dl, PtrVT,
11475                          DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
11476   }
11477
11478   // For globals that require a load from a stub to get the address, emit the
11479   // load.
11480   if (isGlobalStubReference(OpFlags))
11481     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
11482                          MachinePointerInfo::getGOT(), false, false, false, 0);
11483
11484   // If there was a non-zero offset that we didn't fold, create an explicit
11485   // addition for it.
11486   if (Offset != 0)
11487     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result,
11488                          DAG.getConstant(Offset, dl, PtrVT));
11489
11490   return Result;
11491 }
11492
11493 SDValue
11494 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
11495   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
11496   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
11497   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
11498 }
11499
11500 static SDValue
11501 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
11502            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
11503            unsigned char OperandFlags, bool LocalDynamic = false) {
11504   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11505   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11506   SDLoc dl(GA);
11507   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11508                                            GA->getValueType(0),
11509                                            GA->getOffset(),
11510                                            OperandFlags);
11511
11512   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
11513                                            : X86ISD::TLSADDR;
11514
11515   if (InFlag) {
11516     SDValue Ops[] = { Chain,  TGA, *InFlag };
11517     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11518   } else {
11519     SDValue Ops[]  = { Chain, TGA };
11520     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11521   }
11522
11523   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
11524   MFI->setAdjustsStack(true);
11525   MFI->setHasCalls(true);
11526
11527   SDValue Flag = Chain.getValue(1);
11528   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
11529 }
11530
11531 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
11532 static SDValue
11533 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11534                                 const EVT PtrVT) {
11535   SDValue InFlag;
11536   SDLoc dl(GA);  // ? function entry point might be better
11537   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11538                                    DAG.getNode(X86ISD::GlobalBaseReg,
11539                                                SDLoc(), PtrVT), InFlag);
11540   InFlag = Chain.getValue(1);
11541
11542   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
11543 }
11544
11545 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
11546 static SDValue
11547 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11548                                 const EVT PtrVT) {
11549   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
11550                     X86::RAX, X86II::MO_TLSGD);
11551 }
11552
11553 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
11554                                            SelectionDAG &DAG,
11555                                            const EVT PtrVT,
11556                                            bool is64Bit) {
11557   SDLoc dl(GA);
11558
11559   // Get the start address of the TLS block for this module.
11560   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
11561       .getInfo<X86MachineFunctionInfo>();
11562   MFI->incNumLocalDynamicTLSAccesses();
11563
11564   SDValue Base;
11565   if (is64Bit) {
11566     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
11567                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
11568   } else {
11569     SDValue InFlag;
11570     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11571         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
11572     InFlag = Chain.getValue(1);
11573     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
11574                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
11575   }
11576
11577   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
11578   // of Base.
11579
11580   // Build x@dtpoff.
11581   unsigned char OperandFlags = X86II::MO_DTPOFF;
11582   unsigned WrapperKind = X86ISD::Wrapper;
11583   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11584                                            GA->getValueType(0),
11585                                            GA->getOffset(), OperandFlags);
11586   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11587
11588   // Add x@dtpoff with the base.
11589   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
11590 }
11591
11592 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
11593 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11594                                    const EVT PtrVT, TLSModel::Model model,
11595                                    bool is64Bit, bool isPIC) {
11596   SDLoc dl(GA);
11597
11598   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
11599   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
11600                                                          is64Bit ? 257 : 256));
11601
11602   SDValue ThreadPointer =
11603       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0, dl),
11604                   MachinePointerInfo(Ptr), false, false, false, 0);
11605
11606   unsigned char OperandFlags = 0;
11607   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
11608   // initialexec.
11609   unsigned WrapperKind = X86ISD::Wrapper;
11610   if (model == TLSModel::LocalExec) {
11611     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
11612   } else if (model == TLSModel::InitialExec) {
11613     if (is64Bit) {
11614       OperandFlags = X86II::MO_GOTTPOFF;
11615       WrapperKind = X86ISD::WrapperRIP;
11616     } else {
11617       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
11618     }
11619   } else {
11620     llvm_unreachable("Unexpected model");
11621   }
11622
11623   // emit "addl x@ntpoff,%eax" (local exec)
11624   // or "addl x@indntpoff,%eax" (initial exec)
11625   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
11626   SDValue TGA =
11627       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
11628                                  GA->getOffset(), OperandFlags);
11629   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11630
11631   if (model == TLSModel::InitialExec) {
11632     if (isPIC && !is64Bit) {
11633       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
11634                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
11635                            Offset);
11636     }
11637
11638     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
11639                          MachinePointerInfo::getGOT(), false, false, false, 0);
11640   }
11641
11642   // The address of the thread local variable is the add of the thread
11643   // pointer with the offset of the variable.
11644   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
11645 }
11646
11647 SDValue
11648 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
11649
11650   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
11651   const GlobalValue *GV = GA->getGlobal();
11652   auto PtrVT = getPointerTy(DAG.getDataLayout());
11653
11654   if (Subtarget->isTargetELF()) {
11655     TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
11656     switch (model) {
11657       case TLSModel::GeneralDynamic:
11658         if (Subtarget->is64Bit())
11659           return LowerToTLSGeneralDynamicModel64(GA, DAG, PtrVT);
11660         return LowerToTLSGeneralDynamicModel32(GA, DAG, PtrVT);
11661       case TLSModel::LocalDynamic:
11662         return LowerToTLSLocalDynamicModel(GA, DAG, PtrVT,
11663                                            Subtarget->is64Bit());
11664       case TLSModel::InitialExec:
11665       case TLSModel::LocalExec:
11666         return LowerToTLSExecModel(GA, DAG, PtrVT, model, Subtarget->is64Bit(),
11667                                    DAG.getTarget().getRelocationModel() ==
11668                                        Reloc::PIC_);
11669     }
11670     llvm_unreachable("Unknown TLS model.");
11671   }
11672
11673   if (Subtarget->isTargetDarwin()) {
11674     // Darwin only has one model of TLS.  Lower to that.
11675     unsigned char OpFlag = 0;
11676     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
11677                            X86ISD::WrapperRIP : X86ISD::Wrapper;
11678
11679     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11680     // global base reg.
11681     bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
11682                  !Subtarget->is64Bit();
11683     if (PIC32)
11684       OpFlag = X86II::MO_TLVP_PIC_BASE;
11685     else
11686       OpFlag = X86II::MO_TLVP;
11687     SDLoc DL(Op);
11688     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
11689                                                 GA->getValueType(0),
11690                                                 GA->getOffset(), OpFlag);
11691     SDValue Offset = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11692
11693     // With PIC32, the address is actually $g + Offset.
11694     if (PIC32)
11695       Offset = DAG.getNode(ISD::ADD, DL, PtrVT,
11696                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
11697                            Offset);
11698
11699     // Lowering the machine isd will make sure everything is in the right
11700     // location.
11701     SDValue Chain = DAG.getEntryNode();
11702     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11703     SDValue Args[] = { Chain, Offset };
11704     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
11705
11706     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
11707     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11708     MFI->setAdjustsStack(true);
11709
11710     // And our return value (tls address) is in the standard call return value
11711     // location.
11712     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11713     return DAG.getCopyFromReg(Chain, DL, Reg, PtrVT, Chain.getValue(1));
11714   }
11715
11716   if (Subtarget->isTargetKnownWindowsMSVC() ||
11717       Subtarget->isTargetWindowsGNU()) {
11718     // Just use the implicit TLS architecture
11719     // Need to generate someting similar to:
11720     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
11721     //                                  ; from TEB
11722     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
11723     //   mov     rcx, qword [rdx+rcx*8]
11724     //   mov     eax, .tls$:tlsvar
11725     //   [rax+rcx] contains the address
11726     // Windows 64bit: gs:0x58
11727     // Windows 32bit: fs:__tls_array
11728
11729     SDLoc dl(GA);
11730     SDValue Chain = DAG.getEntryNode();
11731
11732     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
11733     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
11734     // use its literal value of 0x2C.
11735     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
11736                                         ? Type::getInt8PtrTy(*DAG.getContext(),
11737                                                              256)
11738                                         : Type::getInt32PtrTy(*DAG.getContext(),
11739                                                               257));
11740
11741     SDValue TlsArray = Subtarget->is64Bit()
11742                            ? DAG.getIntPtrConstant(0x58, dl)
11743                            : (Subtarget->isTargetWindowsGNU()
11744                                   ? DAG.getIntPtrConstant(0x2C, dl)
11745                                   : DAG.getExternalSymbol("_tls_array", PtrVT));
11746
11747     SDValue ThreadPointer =
11748         DAG.getLoad(PtrVT, dl, Chain, TlsArray, MachinePointerInfo(Ptr), false,
11749                     false, false, 0);
11750
11751     SDValue res;
11752     if (GV->getThreadLocalMode() == GlobalVariable::LocalExecTLSModel) {
11753       res = ThreadPointer;
11754     } else {
11755       // Load the _tls_index variable
11756       SDValue IDX = DAG.getExternalSymbol("_tls_index", PtrVT);
11757       if (Subtarget->is64Bit())
11758         IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, PtrVT, Chain, IDX,
11759                              MachinePointerInfo(), MVT::i32, false, false,
11760                              false, 0);
11761       else
11762         IDX = DAG.getLoad(PtrVT, dl, Chain, IDX, MachinePointerInfo(), false,
11763                           false, false, 0);
11764
11765       auto &DL = DAG.getDataLayout();
11766       SDValue Scale =
11767           DAG.getConstant(Log2_64_Ceil(DL.getPointerSize()), dl, PtrVT);
11768       IDX = DAG.getNode(ISD::SHL, dl, PtrVT, IDX, Scale);
11769
11770       res = DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, IDX);
11771     }
11772
11773     res = DAG.getLoad(PtrVT, dl, Chain, res, MachinePointerInfo(), false, false,
11774                       false, 0);
11775
11776     // Get the offset of start of .tls section
11777     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11778                                              GA->getValueType(0),
11779                                              GA->getOffset(), X86II::MO_SECREL);
11780     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, TGA);
11781
11782     // The address of the thread local variable is the add of the thread
11783     // pointer with the offset of the variable.
11784     return DAG.getNode(ISD::ADD, dl, PtrVT, res, Offset);
11785   }
11786
11787   llvm_unreachable("TLS not implemented for this target.");
11788 }
11789
11790 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
11791 /// and take a 2 x i32 value to shift plus a shift amount.
11792 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
11793   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
11794   MVT VT = Op.getSimpleValueType();
11795   unsigned VTBits = VT.getSizeInBits();
11796   SDLoc dl(Op);
11797   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
11798   SDValue ShOpLo = Op.getOperand(0);
11799   SDValue ShOpHi = Op.getOperand(1);
11800   SDValue ShAmt  = Op.getOperand(2);
11801   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
11802   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
11803   // during isel.
11804   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11805                                   DAG.getConstant(VTBits - 1, dl, MVT::i8));
11806   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
11807                                      DAG.getConstant(VTBits - 1, dl, MVT::i8))
11808                        : DAG.getConstant(0, dl, VT);
11809
11810   SDValue Tmp2, Tmp3;
11811   if (Op.getOpcode() == ISD::SHL_PARTS) {
11812     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
11813     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
11814   } else {
11815     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
11816     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
11817   }
11818
11819   // If the shift amount is larger or equal than the width of a part we can't
11820   // rely on the results of shld/shrd. Insert a test and select the appropriate
11821   // values for large shift amounts.
11822   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11823                                 DAG.getConstant(VTBits, dl, MVT::i8));
11824   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11825                              AndNode, DAG.getConstant(0, dl, MVT::i8));
11826
11827   SDValue Hi, Lo;
11828   SDValue CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
11829   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
11830   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
11831
11832   if (Op.getOpcode() == ISD::SHL_PARTS) {
11833     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11834     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11835   } else {
11836     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11837     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11838   }
11839
11840   SDValue Ops[2] = { Lo, Hi };
11841   return DAG.getMergeValues(Ops, dl);
11842 }
11843
11844 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
11845                                            SelectionDAG &DAG) const {
11846   SDValue Src = Op.getOperand(0);
11847   MVT SrcVT = Src.getSimpleValueType();
11848   MVT VT = Op.getSimpleValueType();
11849   SDLoc dl(Op);
11850
11851   if (SrcVT.isVector()) {
11852     if (SrcVT == MVT::v2i32 && VT == MVT::v2f64) {
11853       return DAG.getNode(X86ISD::CVTDQ2PD, dl, VT,
11854                          DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i32, Src,
11855                          DAG.getUNDEF(SrcVT)));
11856     }
11857     if (SrcVT.getVectorElementType() == MVT::i1) {
11858       MVT IntegerVT = MVT::getVectorVT(MVT::i32, SrcVT.getVectorNumElements());
11859       return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
11860                          DAG.getNode(ISD::SIGN_EXTEND, dl, IntegerVT, Src));
11861     }
11862     return SDValue();
11863   }
11864
11865   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
11866          "Unknown SINT_TO_FP to lower!");
11867
11868   // These are really Legal; return the operand so the caller accepts it as
11869   // Legal.
11870   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
11871     return Op;
11872   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
11873       Subtarget->is64Bit()) {
11874     return Op;
11875   }
11876
11877   unsigned Size = SrcVT.getSizeInBits()/8;
11878   MachineFunction &MF = DAG.getMachineFunction();
11879   auto PtrVT = getPointerTy(MF.getDataLayout());
11880   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
11881   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
11882   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11883                                StackSlot,
11884                                MachinePointerInfo::getFixedStack(SSFI),
11885                                false, false, 0);
11886   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
11887 }
11888
11889 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
11890                                      SDValue StackSlot,
11891                                      SelectionDAG &DAG) const {
11892   // Build the FILD
11893   SDLoc DL(Op);
11894   SDVTList Tys;
11895   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
11896   if (useSSE)
11897     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
11898   else
11899     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
11900
11901   unsigned ByteSize = SrcVT.getSizeInBits()/8;
11902
11903   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
11904   MachineMemOperand *MMO;
11905   if (FI) {
11906     int SSFI = FI->getIndex();
11907     MMO =
11908       DAG.getMachineFunction()
11909       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11910                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
11911   } else {
11912     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
11913     StackSlot = StackSlot.getOperand(1);
11914   }
11915   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
11916   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
11917                                            X86ISD::FILD, DL,
11918                                            Tys, Ops, SrcVT, MMO);
11919
11920   if (useSSE) {
11921     Chain = Result.getValue(1);
11922     SDValue InFlag = Result.getValue(2);
11923
11924     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
11925     // shouldn't be necessary except that RFP cannot be live across
11926     // multiple blocks. When stackifier is fixed, they can be uncoupled.
11927     MachineFunction &MF = DAG.getMachineFunction();
11928     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
11929     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
11930     auto PtrVT = getPointerTy(MF.getDataLayout());
11931     SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
11932     Tys = DAG.getVTList(MVT::Other);
11933     SDValue Ops[] = {
11934       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
11935     };
11936     MachineMemOperand *MMO =
11937       DAG.getMachineFunction()
11938       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11939                             MachineMemOperand::MOStore, SSFISize, SSFISize);
11940
11941     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
11942                                     Ops, Op.getValueType(), MMO);
11943     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
11944                          MachinePointerInfo::getFixedStack(SSFI),
11945                          false, false, false, 0);
11946   }
11947
11948   return Result;
11949 }
11950
11951 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
11952 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
11953                                                SelectionDAG &DAG) const {
11954   // This algorithm is not obvious. Here it is what we're trying to output:
11955   /*
11956      movq       %rax,  %xmm0
11957      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
11958      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
11959      #ifdef __SSE3__
11960        haddpd   %xmm0, %xmm0
11961      #else
11962        pshufd   $0x4e, %xmm0, %xmm1
11963        addpd    %xmm1, %xmm0
11964      #endif
11965   */
11966
11967   SDLoc dl(Op);
11968   LLVMContext *Context = DAG.getContext();
11969
11970   // Build some magic constants.
11971   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
11972   Constant *C0 = ConstantDataVector::get(*Context, CV0);
11973   auto PtrVT = getPointerTy(DAG.getDataLayout());
11974   SDValue CPIdx0 = DAG.getConstantPool(C0, PtrVT, 16);
11975
11976   SmallVector<Constant*,2> CV1;
11977   CV1.push_back(
11978     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11979                                       APInt(64, 0x4330000000000000ULL))));
11980   CV1.push_back(
11981     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11982                                       APInt(64, 0x4530000000000000ULL))));
11983   Constant *C1 = ConstantVector::get(CV1);
11984   SDValue CPIdx1 = DAG.getConstantPool(C1, PtrVT, 16);
11985
11986   // Load the 64-bit value into an XMM register.
11987   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
11988                             Op.getOperand(0));
11989   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
11990                               MachinePointerInfo::getConstantPool(),
11991                               false, false, false, 16);
11992   SDValue Unpck1 =
11993       getUnpackl(DAG, dl, MVT::v4i32, DAG.getBitcast(MVT::v4i32, XR1), CLod0);
11994
11995   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
11996                               MachinePointerInfo::getConstantPool(),
11997                               false, false, false, 16);
11998   SDValue XR2F = DAG.getBitcast(MVT::v2f64, Unpck1);
11999   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
12000   SDValue Result;
12001
12002   if (Subtarget->hasSSE3()) {
12003     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
12004     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
12005   } else {
12006     SDValue S2F = DAG.getBitcast(MVT::v4i32, Sub);
12007     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
12008                                            S2F, 0x4E, DAG);
12009     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
12010                          DAG.getBitcast(MVT::v2f64, Shuffle), Sub);
12011   }
12012
12013   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
12014                      DAG.getIntPtrConstant(0, dl));
12015 }
12016
12017 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
12018 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
12019                                                SelectionDAG &DAG) const {
12020   SDLoc dl(Op);
12021   // FP constant to bias correct the final result.
12022   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
12023                                    MVT::f64);
12024
12025   // Load the 32-bit value into an XMM register.
12026   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
12027                              Op.getOperand(0));
12028
12029   // Zero out the upper parts of the register.
12030   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
12031
12032   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
12033                      DAG.getBitcast(MVT::v2f64, Load),
12034                      DAG.getIntPtrConstant(0, dl));
12035
12036   // Or the load with the bias.
12037   SDValue Or = DAG.getNode(
12038       ISD::OR, dl, MVT::v2i64,
12039       DAG.getBitcast(MVT::v2i64,
12040                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Load)),
12041       DAG.getBitcast(MVT::v2i64,
12042                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Bias)));
12043   Or =
12044       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
12045                   DAG.getBitcast(MVT::v2f64, Or), DAG.getIntPtrConstant(0, dl));
12046
12047   // Subtract the bias.
12048   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
12049
12050   // Handle final rounding.
12051   EVT DestVT = Op.getValueType();
12052
12053   if (DestVT.bitsLT(MVT::f64))
12054     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
12055                        DAG.getIntPtrConstant(0, dl));
12056   if (DestVT.bitsGT(MVT::f64))
12057     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
12058
12059   // Handle final rounding.
12060   return Sub;
12061 }
12062
12063 static SDValue lowerUINT_TO_FP_vXi32(SDValue Op, SelectionDAG &DAG,
12064                                      const X86Subtarget &Subtarget) {
12065   // The algorithm is the following:
12066   // #ifdef __SSE4_1__
12067   //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
12068   //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
12069   //                                 (uint4) 0x53000000, 0xaa);
12070   // #else
12071   //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
12072   //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
12073   // #endif
12074   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
12075   //     return (float4) lo + fhi;
12076
12077   SDLoc DL(Op);
12078   SDValue V = Op->getOperand(0);
12079   EVT VecIntVT = V.getValueType();
12080   bool Is128 = VecIntVT == MVT::v4i32;
12081   EVT VecFloatVT = Is128 ? MVT::v4f32 : MVT::v8f32;
12082   // If we convert to something else than the supported type, e.g., to v4f64,
12083   // abort early.
12084   if (VecFloatVT != Op->getValueType(0))
12085     return SDValue();
12086
12087   unsigned NumElts = VecIntVT.getVectorNumElements();
12088   assert((VecIntVT == MVT::v4i32 || VecIntVT == MVT::v8i32) &&
12089          "Unsupported custom type");
12090   assert(NumElts <= 8 && "The size of the constant array must be fixed");
12091
12092   // In the #idef/#else code, we have in common:
12093   // - The vector of constants:
12094   // -- 0x4b000000
12095   // -- 0x53000000
12096   // - A shift:
12097   // -- v >> 16
12098
12099   // Create the splat vector for 0x4b000000.
12100   SDValue CstLow = DAG.getConstant(0x4b000000, DL, MVT::i32);
12101   SDValue CstLowArray[] = {CstLow, CstLow, CstLow, CstLow,
12102                            CstLow, CstLow, CstLow, CstLow};
12103   SDValue VecCstLow = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12104                                   makeArrayRef(&CstLowArray[0], NumElts));
12105   // Create the splat vector for 0x53000000.
12106   SDValue CstHigh = DAG.getConstant(0x53000000, DL, MVT::i32);
12107   SDValue CstHighArray[] = {CstHigh, CstHigh, CstHigh, CstHigh,
12108                             CstHigh, CstHigh, CstHigh, CstHigh};
12109   SDValue VecCstHigh = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12110                                    makeArrayRef(&CstHighArray[0], NumElts));
12111
12112   // Create the right shift.
12113   SDValue CstShift = DAG.getConstant(16, DL, MVT::i32);
12114   SDValue CstShiftArray[] = {CstShift, CstShift, CstShift, CstShift,
12115                              CstShift, CstShift, CstShift, CstShift};
12116   SDValue VecCstShift = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12117                                     makeArrayRef(&CstShiftArray[0], NumElts));
12118   SDValue HighShift = DAG.getNode(ISD::SRL, DL, VecIntVT, V, VecCstShift);
12119
12120   SDValue Low, High;
12121   if (Subtarget.hasSSE41()) {
12122     EVT VecI16VT = Is128 ? MVT::v8i16 : MVT::v16i16;
12123     //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
12124     SDValue VecCstLowBitcast = DAG.getBitcast(VecI16VT, VecCstLow);
12125     SDValue VecBitcast = DAG.getBitcast(VecI16VT, V);
12126     // Low will be bitcasted right away, so do not bother bitcasting back to its
12127     // original type.
12128     Low = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecBitcast,
12129                       VecCstLowBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
12130     //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
12131     //                                 (uint4) 0x53000000, 0xaa);
12132     SDValue VecCstHighBitcast = DAG.getBitcast(VecI16VT, VecCstHigh);
12133     SDValue VecShiftBitcast = DAG.getBitcast(VecI16VT, HighShift);
12134     // High will be bitcasted right away, so do not bother bitcasting back to
12135     // its original type.
12136     High = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecShiftBitcast,
12137                        VecCstHighBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
12138   } else {
12139     SDValue CstMask = DAG.getConstant(0xffff, DL, MVT::i32);
12140     SDValue VecCstMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT, CstMask,
12141                                      CstMask, CstMask, CstMask);
12142     //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
12143     SDValue LowAnd = DAG.getNode(ISD::AND, DL, VecIntVT, V, VecCstMask);
12144     Low = DAG.getNode(ISD::OR, DL, VecIntVT, LowAnd, VecCstLow);
12145
12146     //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
12147     High = DAG.getNode(ISD::OR, DL, VecIntVT, HighShift, VecCstHigh);
12148   }
12149
12150   // Create the vector constant for -(0x1.0p39f + 0x1.0p23f).
12151   SDValue CstFAdd = DAG.getConstantFP(
12152       APFloat(APFloat::IEEEsingle, APInt(32, 0xD3000080)), DL, MVT::f32);
12153   SDValue CstFAddArray[] = {CstFAdd, CstFAdd, CstFAdd, CstFAdd,
12154                             CstFAdd, CstFAdd, CstFAdd, CstFAdd};
12155   SDValue VecCstFAdd = DAG.getNode(ISD::BUILD_VECTOR, DL, VecFloatVT,
12156                                    makeArrayRef(&CstFAddArray[0], NumElts));
12157
12158   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
12159   SDValue HighBitcast = DAG.getBitcast(VecFloatVT, High);
12160   SDValue FHigh =
12161       DAG.getNode(ISD::FADD, DL, VecFloatVT, HighBitcast, VecCstFAdd);
12162   //     return (float4) lo + fhi;
12163   SDValue LowBitcast = DAG.getBitcast(VecFloatVT, Low);
12164   return DAG.getNode(ISD::FADD, DL, VecFloatVT, LowBitcast, FHigh);
12165 }
12166
12167 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
12168                                                SelectionDAG &DAG) const {
12169   SDValue N0 = Op.getOperand(0);
12170   MVT SVT = N0.getSimpleValueType();
12171   SDLoc dl(Op);
12172
12173   switch (SVT.SimpleTy) {
12174   default:
12175     llvm_unreachable("Custom UINT_TO_FP is not supported!");
12176   case MVT::v4i8:
12177   case MVT::v4i16:
12178   case MVT::v8i8:
12179   case MVT::v8i16: {
12180     MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
12181     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
12182                        DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
12183   }
12184   case MVT::v4i32:
12185   case MVT::v8i32:
12186     return lowerUINT_TO_FP_vXi32(Op, DAG, *Subtarget);
12187   case MVT::v16i8:
12188   case MVT::v16i16:
12189     if (Subtarget->hasAVX512())
12190       return DAG.getNode(ISD::UINT_TO_FP, dl, Op.getValueType(),
12191                          DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v16i32, N0));
12192   }
12193   llvm_unreachable(nullptr);
12194 }
12195
12196 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
12197                                            SelectionDAG &DAG) const {
12198   SDValue N0 = Op.getOperand(0);
12199   SDLoc dl(Op);
12200   auto PtrVT = getPointerTy(DAG.getDataLayout());
12201
12202   if (Op.getValueType().isVector())
12203     return lowerUINT_TO_FP_vec(Op, DAG);
12204
12205   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
12206   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
12207   // the optimization here.
12208   if (DAG.SignBitIsZero(N0))
12209     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
12210
12211   MVT SrcVT = N0.getSimpleValueType();
12212   MVT DstVT = Op.getSimpleValueType();
12213   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
12214     return LowerUINT_TO_FP_i64(Op, DAG);
12215   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
12216     return LowerUINT_TO_FP_i32(Op, DAG);
12217   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
12218     return SDValue();
12219
12220   // Make a 64-bit buffer, and use it to build an FILD.
12221   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
12222   if (SrcVT == MVT::i32) {
12223     SDValue WordOff = DAG.getConstant(4, dl, PtrVT);
12224     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, WordOff);
12225     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
12226                                   StackSlot, MachinePointerInfo(),
12227                                   false, false, 0);
12228     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, dl, MVT::i32),
12229                                   OffsetSlot, MachinePointerInfo(),
12230                                   false, false, 0);
12231     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
12232     return Fild;
12233   }
12234
12235   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
12236   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
12237                                StackSlot, MachinePointerInfo(),
12238                                false, false, 0);
12239   // For i64 source, we need to add the appropriate power of 2 if the input
12240   // was negative.  This is the same as the optimization in
12241   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
12242   // we must be careful to do the computation in x87 extended precision, not
12243   // in SSE. (The generic code can't know it's OK to do this, or how to.)
12244   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
12245   MachineMemOperand *MMO =
12246     DAG.getMachineFunction()
12247     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
12248                           MachineMemOperand::MOLoad, 8, 8);
12249
12250   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
12251   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
12252   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
12253                                          MVT::i64, MMO);
12254
12255   APInt FF(32, 0x5F800000ULL);
12256
12257   // Check whether the sign bit is set.
12258   SDValue SignSet = DAG.getSetCC(
12259       dl, getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64),
12260       Op.getOperand(0), DAG.getConstant(0, dl, MVT::i64), ISD::SETLT);
12261
12262   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
12263   SDValue FudgePtr = DAG.getConstantPool(
12264       ConstantInt::get(*DAG.getContext(), FF.zext(64)), PtrVT);
12265
12266   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
12267   SDValue Zero = DAG.getIntPtrConstant(0, dl);
12268   SDValue Four = DAG.getIntPtrConstant(4, dl);
12269   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
12270                                Zero, Four);
12271   FudgePtr = DAG.getNode(ISD::ADD, dl, PtrVT, FudgePtr, Offset);
12272
12273   // Load the value out, extending it from f32 to f80.
12274   // FIXME: Avoid the extend by constructing the right constant pool?
12275   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
12276                                  FudgePtr, MachinePointerInfo::getConstantPool(),
12277                                  MVT::f32, false, false, false, 4);
12278   // Extend everything to 80 bits to force it to be done on x87.
12279   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
12280   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add,
12281                      DAG.getIntPtrConstant(0, dl));
12282 }
12283
12284 std::pair<SDValue,SDValue>
12285 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
12286                                     bool IsSigned, bool IsReplace) const {
12287   SDLoc DL(Op);
12288
12289   EVT DstTy = Op.getValueType();
12290   auto PtrVT = getPointerTy(DAG.getDataLayout());
12291
12292   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
12293     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
12294     DstTy = MVT::i64;
12295   }
12296
12297   assert(DstTy.getSimpleVT() <= MVT::i64 &&
12298          DstTy.getSimpleVT() >= MVT::i16 &&
12299          "Unknown FP_TO_INT to lower!");
12300
12301   // These are really Legal.
12302   if (DstTy == MVT::i32 &&
12303       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
12304     return std::make_pair(SDValue(), SDValue());
12305   if (Subtarget->is64Bit() &&
12306       DstTy == MVT::i64 &&
12307       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
12308     return std::make_pair(SDValue(), SDValue());
12309
12310   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
12311   // stack slot, or into the FTOL runtime function.
12312   MachineFunction &MF = DAG.getMachineFunction();
12313   unsigned MemSize = DstTy.getSizeInBits()/8;
12314   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
12315   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12316
12317   unsigned Opc;
12318   if (!IsSigned && isIntegerTypeFTOL(DstTy))
12319     Opc = X86ISD::WIN_FTOL;
12320   else
12321     switch (DstTy.getSimpleVT().SimpleTy) {
12322     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
12323     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
12324     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
12325     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
12326     }
12327
12328   SDValue Chain = DAG.getEntryNode();
12329   SDValue Value = Op.getOperand(0);
12330   EVT TheVT = Op.getOperand(0).getValueType();
12331   // FIXME This causes a redundant load/store if the SSE-class value is already
12332   // in memory, such as if it is on the callstack.
12333   if (isScalarFPTypeInSSEReg(TheVT)) {
12334     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
12335     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
12336                          MachinePointerInfo::getFixedStack(SSFI),
12337                          false, false, 0);
12338     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
12339     SDValue Ops[] = {
12340       Chain, StackSlot, DAG.getValueType(TheVT)
12341     };
12342
12343     MachineMemOperand *MMO =
12344       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
12345                               MachineMemOperand::MOLoad, MemSize, MemSize);
12346     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
12347     Chain = Value.getValue(1);
12348     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
12349     StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12350   }
12351
12352   MachineMemOperand *MMO =
12353     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
12354                             MachineMemOperand::MOStore, MemSize, MemSize);
12355
12356   if (Opc != X86ISD::WIN_FTOL) {
12357     // Build the FP_TO_INT*_IN_MEM
12358     SDValue Ops[] = { Chain, Value, StackSlot };
12359     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
12360                                            Ops, DstTy, MMO);
12361     return std::make_pair(FIST, StackSlot);
12362   } else {
12363     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
12364       DAG.getVTList(MVT::Other, MVT::Glue),
12365       Chain, Value);
12366     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
12367       MVT::i32, ftol.getValue(1));
12368     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
12369       MVT::i32, eax.getValue(2));
12370     SDValue Ops[] = { eax, edx };
12371     SDValue pair = IsReplace
12372       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
12373       : DAG.getMergeValues(Ops, DL);
12374     return std::make_pair(pair, SDValue());
12375   }
12376 }
12377
12378 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
12379                               const X86Subtarget *Subtarget) {
12380   MVT VT = Op->getSimpleValueType(0);
12381   SDValue In = Op->getOperand(0);
12382   MVT InVT = In.getSimpleValueType();
12383   SDLoc dl(Op);
12384
12385   if (VT.is512BitVector() || InVT.getScalarType() == MVT::i1)
12386     return DAG.getNode(ISD::ZERO_EXTEND, dl, VT, In);
12387
12388   // Optimize vectors in AVX mode:
12389   //
12390   //   v8i16 -> v8i32
12391   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
12392   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
12393   //   Concat upper and lower parts.
12394   //
12395   //   v4i32 -> v4i64
12396   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
12397   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
12398   //   Concat upper and lower parts.
12399   //
12400
12401   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
12402       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
12403       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
12404     return SDValue();
12405
12406   if (Subtarget->hasInt256())
12407     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
12408
12409   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
12410   SDValue Undef = DAG.getUNDEF(InVT);
12411   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
12412   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12413   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12414
12415   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
12416                              VT.getVectorNumElements()/2);
12417
12418   OpLo = DAG.getBitcast(HVT, OpLo);
12419   OpHi = DAG.getBitcast(HVT, OpHi);
12420
12421   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
12422 }
12423
12424 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
12425                   const X86Subtarget *Subtarget, SelectionDAG &DAG) {
12426   MVT VT = Op->getSimpleValueType(0);
12427   SDValue In = Op->getOperand(0);
12428   MVT InVT = In.getSimpleValueType();
12429   SDLoc DL(Op);
12430   unsigned int NumElts = VT.getVectorNumElements();
12431   if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
12432     return SDValue();
12433
12434   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
12435     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
12436
12437   assert(InVT.getVectorElementType() == MVT::i1);
12438   MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
12439   SDValue One =
12440    DAG.getConstant(APInt(ExtVT.getScalarSizeInBits(), 1), DL, ExtVT);
12441   SDValue Zero =
12442    DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), DL, ExtVT);
12443
12444   SDValue V = DAG.getNode(ISD::VSELECT, DL, ExtVT, In, One, Zero);
12445   if (VT.is512BitVector())
12446     return V;
12447   return DAG.getNode(X86ISD::VTRUNC, DL, VT, V);
12448 }
12449
12450 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12451                                SelectionDAG &DAG) {
12452   if (Subtarget->hasFp256())
12453     if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
12454       return Res;
12455
12456   return SDValue();
12457 }
12458
12459 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12460                                 SelectionDAG &DAG) {
12461   SDLoc DL(Op);
12462   MVT VT = Op.getSimpleValueType();
12463   SDValue In = Op.getOperand(0);
12464   MVT SVT = In.getSimpleValueType();
12465
12466   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
12467     return LowerZERO_EXTEND_AVX512(Op, Subtarget, DAG);
12468
12469   if (Subtarget->hasFp256())
12470     if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
12471       return Res;
12472
12473   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
12474          VT.getVectorNumElements() != SVT.getVectorNumElements());
12475   return SDValue();
12476 }
12477
12478 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
12479   SDLoc DL(Op);
12480   MVT VT = Op.getSimpleValueType();
12481   SDValue In = Op.getOperand(0);
12482   MVT InVT = In.getSimpleValueType();
12483
12484   if (VT == MVT::i1) {
12485     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
12486            "Invalid scalar TRUNCATE operation");
12487     if (InVT.getSizeInBits() >= 32)
12488       return SDValue();
12489     In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
12490     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
12491   }
12492   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
12493          "Invalid TRUNCATE operation");
12494
12495   // move vector to mask - truncate solution for SKX
12496   if (VT.getVectorElementType() == MVT::i1) {
12497     if (InVT.is512BitVector() && InVT.getScalarSizeInBits() <= 16 &&
12498         Subtarget->hasBWI())
12499       return Op; // legal, will go to VPMOVB2M, VPMOVW2M
12500     if ((InVT.is256BitVector() || InVT.is128BitVector())
12501         && InVT.getScalarSizeInBits() <= 16 &&
12502         Subtarget->hasBWI() && Subtarget->hasVLX())
12503       return Op; // legal, will go to VPMOVB2M, VPMOVW2M
12504     if (InVT.is512BitVector() && InVT.getScalarSizeInBits() >= 32 &&
12505         Subtarget->hasDQI())
12506       return Op; // legal, will go to VPMOVD2M, VPMOVQ2M
12507     if ((InVT.is256BitVector() || InVT.is128BitVector())
12508         && InVT.getScalarSizeInBits() >= 32 &&
12509         Subtarget->hasDQI() && Subtarget->hasVLX())
12510       return Op; // legal, will go to VPMOVB2M, VPMOVQ2M
12511   }
12512
12513   if (VT.getVectorElementType() == MVT::i1) {
12514     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
12515     unsigned NumElts = InVT.getVectorNumElements();
12516     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
12517     if (InVT.getSizeInBits() < 512) {
12518       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
12519       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
12520       InVT = ExtVT;
12521     }
12522
12523     SDValue OneV =
12524      DAG.getConstant(APInt::getSignBit(InVT.getScalarSizeInBits()), DL, InVT);
12525     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
12526     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
12527   }
12528
12529   // vpmovqb/w/d, vpmovdb/w, vpmovwb
12530   if (((!InVT.is512BitVector() && Subtarget->hasVLX()) || InVT.is512BitVector()) &&
12531       (InVT.getVectorElementType() != MVT::i16 || Subtarget->hasBWI()))
12532     return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
12533
12534   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
12535     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
12536     if (Subtarget->hasInt256()) {
12537       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
12538       In = DAG.getBitcast(MVT::v8i32, In);
12539       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
12540                                 ShufMask);
12541       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
12542                          DAG.getIntPtrConstant(0, DL));
12543     }
12544
12545     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12546                                DAG.getIntPtrConstant(0, DL));
12547     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12548                                DAG.getIntPtrConstant(2, DL));
12549     OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
12550     OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
12551     static const int ShufMask[] = {0, 2, 4, 6};
12552     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
12553   }
12554
12555   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
12556     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
12557     if (Subtarget->hasInt256()) {
12558       In = DAG.getBitcast(MVT::v32i8, In);
12559
12560       SmallVector<SDValue,32> pshufbMask;
12561       for (unsigned i = 0; i < 2; ++i) {
12562         pshufbMask.push_back(DAG.getConstant(0x0, DL, MVT::i8));
12563         pshufbMask.push_back(DAG.getConstant(0x1, DL, MVT::i8));
12564         pshufbMask.push_back(DAG.getConstant(0x4, DL, MVT::i8));
12565         pshufbMask.push_back(DAG.getConstant(0x5, DL, MVT::i8));
12566         pshufbMask.push_back(DAG.getConstant(0x8, DL, MVT::i8));
12567         pshufbMask.push_back(DAG.getConstant(0x9, DL, MVT::i8));
12568         pshufbMask.push_back(DAG.getConstant(0xc, DL, MVT::i8));
12569         pshufbMask.push_back(DAG.getConstant(0xd, DL, MVT::i8));
12570         for (unsigned j = 0; j < 8; ++j)
12571           pshufbMask.push_back(DAG.getConstant(0x80, DL, MVT::i8));
12572       }
12573       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
12574       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
12575       In = DAG.getBitcast(MVT::v4i64, In);
12576
12577       static const int ShufMask[] = {0,  2,  -1,  -1};
12578       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
12579                                 &ShufMask[0]);
12580       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12581                        DAG.getIntPtrConstant(0, DL));
12582       return DAG.getBitcast(VT, In);
12583     }
12584
12585     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12586                                DAG.getIntPtrConstant(0, DL));
12587
12588     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12589                                DAG.getIntPtrConstant(4, DL));
12590
12591     OpLo = DAG.getBitcast(MVT::v16i8, OpLo);
12592     OpHi = DAG.getBitcast(MVT::v16i8, OpHi);
12593
12594     // The PSHUFB mask:
12595     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
12596                                    -1, -1, -1, -1, -1, -1, -1, -1};
12597
12598     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
12599     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
12600     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
12601
12602     OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
12603     OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
12604
12605     // The MOVLHPS Mask:
12606     static const int ShufMask2[] = {0, 1, 4, 5};
12607     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
12608     return DAG.getBitcast(MVT::v8i16, res);
12609   }
12610
12611   // Handle truncation of V256 to V128 using shuffles.
12612   if (!VT.is128BitVector() || !InVT.is256BitVector())
12613     return SDValue();
12614
12615   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
12616
12617   unsigned NumElems = VT.getVectorNumElements();
12618   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
12619
12620   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
12621   // Prepare truncation shuffle mask
12622   for (unsigned i = 0; i != NumElems; ++i)
12623     MaskVec[i] = i * 2;
12624   SDValue V = DAG.getVectorShuffle(NVT, DL, DAG.getBitcast(NVT, In),
12625                                    DAG.getUNDEF(NVT), &MaskVec[0]);
12626   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
12627                      DAG.getIntPtrConstant(0, DL));
12628 }
12629
12630 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
12631                                            SelectionDAG &DAG) const {
12632   assert(!Op.getSimpleValueType().isVector());
12633
12634   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12635     /*IsSigned=*/ true, /*IsReplace=*/ false);
12636   SDValue FIST = Vals.first, StackSlot = Vals.second;
12637   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
12638   if (!FIST.getNode()) return Op;
12639
12640   if (StackSlot.getNode())
12641     // Load the result.
12642     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12643                        FIST, StackSlot, MachinePointerInfo(),
12644                        false, false, false, 0);
12645
12646   // The node is the result.
12647   return FIST;
12648 }
12649
12650 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
12651                                            SelectionDAG &DAG) const {
12652   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12653     /*IsSigned=*/ false, /*IsReplace=*/ false);
12654   SDValue FIST = Vals.first, StackSlot = Vals.second;
12655   assert(FIST.getNode() && "Unexpected failure");
12656
12657   if (StackSlot.getNode())
12658     // Load the result.
12659     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12660                        FIST, StackSlot, MachinePointerInfo(),
12661                        false, false, false, 0);
12662
12663   // The node is the result.
12664   return FIST;
12665 }
12666
12667 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
12668   SDLoc DL(Op);
12669   MVT VT = Op.getSimpleValueType();
12670   SDValue In = Op.getOperand(0);
12671   MVT SVT = In.getSimpleValueType();
12672
12673   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
12674
12675   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
12676                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
12677                                  In, DAG.getUNDEF(SVT)));
12678 }
12679
12680 /// The only differences between FABS and FNEG are the mask and the logic op.
12681 /// FNEG also has a folding opportunity for FNEG(FABS(x)).
12682 static SDValue LowerFABSorFNEG(SDValue Op, SelectionDAG &DAG) {
12683   assert((Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) &&
12684          "Wrong opcode for lowering FABS or FNEG.");
12685
12686   bool IsFABS = (Op.getOpcode() == ISD::FABS);
12687
12688   // If this is a FABS and it has an FNEG user, bail out to fold the combination
12689   // into an FNABS. We'll lower the FABS after that if it is still in use.
12690   if (IsFABS)
12691     for (SDNode *User : Op->uses())
12692       if (User->getOpcode() == ISD::FNEG)
12693         return Op;
12694
12695   SDValue Op0 = Op.getOperand(0);
12696   bool IsFNABS = !IsFABS && (Op0.getOpcode() == ISD::FABS);
12697
12698   SDLoc dl(Op);
12699   MVT VT = Op.getSimpleValueType();
12700   // Assume scalar op for initialization; update for vector if needed.
12701   // Note that there are no scalar bitwise logical SSE/AVX instructions, so we
12702   // generate a 16-byte vector constant and logic op even for the scalar case.
12703   // Using a 16-byte mask allows folding the load of the mask with
12704   // the logic op, so it can save (~4 bytes) on code size.
12705   MVT EltVT = VT;
12706   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
12707   // FIXME: Use function attribute "OptimizeForSize" and/or CodeGenOpt::Level to
12708   // decide if we should generate a 16-byte constant mask when we only need 4 or
12709   // 8 bytes for the scalar case.
12710   if (VT.isVector()) {
12711     EltVT = VT.getVectorElementType();
12712     NumElts = VT.getVectorNumElements();
12713   }
12714
12715   unsigned EltBits = EltVT.getSizeInBits();
12716   LLVMContext *Context = DAG.getContext();
12717   // For FABS, mask is 0x7f...; for FNEG, mask is 0x80...
12718   APInt MaskElt =
12719     IsFABS ? APInt::getSignedMaxValue(EltBits) : APInt::getSignBit(EltBits);
12720   Constant *C = ConstantInt::get(*Context, MaskElt);
12721   C = ConstantVector::getSplat(NumElts, C);
12722   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12723   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
12724   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
12725   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
12726                              MachinePointerInfo::getConstantPool(),
12727                              false, false, false, Alignment);
12728
12729   if (VT.isVector()) {
12730     // For a vector, cast operands to a vector type, perform the logic op,
12731     // and cast the result back to the original value type.
12732     MVT VecVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
12733     SDValue MaskCasted = DAG.getBitcast(VecVT, Mask);
12734     SDValue Operand = IsFNABS ? DAG.getBitcast(VecVT, Op0.getOperand(0))
12735                               : DAG.getBitcast(VecVT, Op0);
12736     unsigned BitOp = IsFABS ? ISD::AND : IsFNABS ? ISD::OR : ISD::XOR;
12737     return DAG.getBitcast(VT,
12738                           DAG.getNode(BitOp, dl, VecVT, Operand, MaskCasted));
12739   }
12740
12741   // If not vector, then scalar.
12742   unsigned BitOp = IsFABS ? X86ISD::FAND : IsFNABS ? X86ISD::FOR : X86ISD::FXOR;
12743   SDValue Operand = IsFNABS ? Op0.getOperand(0) : Op0;
12744   return DAG.getNode(BitOp, dl, VT, Operand, Mask);
12745 }
12746
12747 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
12748   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12749   LLVMContext *Context = DAG.getContext();
12750   SDValue Op0 = Op.getOperand(0);
12751   SDValue Op1 = Op.getOperand(1);
12752   SDLoc dl(Op);
12753   MVT VT = Op.getSimpleValueType();
12754   MVT SrcVT = Op1.getSimpleValueType();
12755
12756   // If second operand is smaller, extend it first.
12757   if (SrcVT.bitsLT(VT)) {
12758     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
12759     SrcVT = VT;
12760   }
12761   // And if it is bigger, shrink it first.
12762   if (SrcVT.bitsGT(VT)) {
12763     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1, dl));
12764     SrcVT = VT;
12765   }
12766
12767   // At this point the operands and the result should have the same
12768   // type, and that won't be f80 since that is not custom lowered.
12769
12770   const fltSemantics &Sem =
12771       VT == MVT::f64 ? APFloat::IEEEdouble : APFloat::IEEEsingle;
12772   const unsigned SizeInBits = VT.getSizeInBits();
12773
12774   SmallVector<Constant *, 4> CV(
12775       VT == MVT::f64 ? 2 : 4,
12776       ConstantFP::get(*Context, APFloat(Sem, APInt(SizeInBits, 0))));
12777
12778   // First, clear all bits but the sign bit from the second operand (sign).
12779   CV[0] = ConstantFP::get(*Context,
12780                           APFloat(Sem, APInt::getHighBitsSet(SizeInBits, 1)));
12781   Constant *C = ConstantVector::get(CV);
12782   auto PtrVT = TLI.getPointerTy(DAG.getDataLayout());
12783   SDValue CPIdx = DAG.getConstantPool(C, PtrVT, 16);
12784   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
12785                               MachinePointerInfo::getConstantPool(),
12786                               false, false, false, 16);
12787   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
12788
12789   // Next, clear the sign bit from the first operand (magnitude).
12790   // If it's a constant, we can clear it here.
12791   if (ConstantFPSDNode *Op0CN = dyn_cast<ConstantFPSDNode>(Op0)) {
12792     APFloat APF = Op0CN->getValueAPF();
12793     // If the magnitude is a positive zero, the sign bit alone is enough.
12794     if (APF.isPosZero())
12795       return SignBit;
12796     APF.clearSign();
12797     CV[0] = ConstantFP::get(*Context, APF);
12798   } else {
12799     CV[0] = ConstantFP::get(
12800         *Context,
12801         APFloat(Sem, APInt::getLowBitsSet(SizeInBits, SizeInBits - 1)));
12802   }
12803   C = ConstantVector::get(CV);
12804   CPIdx = DAG.getConstantPool(C, PtrVT, 16);
12805   SDValue Val = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
12806                             MachinePointerInfo::getConstantPool(),
12807                             false, false, false, 16);
12808   // If the magnitude operand wasn't a constant, we need to AND out the sign.
12809   if (!isa<ConstantFPSDNode>(Op0))
12810     Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Val);
12811
12812   // OR the magnitude value with the sign bit.
12813   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
12814 }
12815
12816 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
12817   SDValue N0 = Op.getOperand(0);
12818   SDLoc dl(Op);
12819   MVT VT = Op.getSimpleValueType();
12820
12821   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
12822   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
12823                                   DAG.getConstant(1, dl, VT));
12824   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, dl, VT));
12825 }
12826
12827 // Check whether an OR'd tree is PTEST-able.
12828 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
12829                                       SelectionDAG &DAG) {
12830   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
12831
12832   if (!Subtarget->hasSSE41())
12833     return SDValue();
12834
12835   if (!Op->hasOneUse())
12836     return SDValue();
12837
12838   SDNode *N = Op.getNode();
12839   SDLoc DL(N);
12840
12841   SmallVector<SDValue, 8> Opnds;
12842   DenseMap<SDValue, unsigned> VecInMap;
12843   SmallVector<SDValue, 8> VecIns;
12844   EVT VT = MVT::Other;
12845
12846   // Recognize a special case where a vector is casted into wide integer to
12847   // test all 0s.
12848   Opnds.push_back(N->getOperand(0));
12849   Opnds.push_back(N->getOperand(1));
12850
12851   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
12852     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
12853     // BFS traverse all OR'd operands.
12854     if (I->getOpcode() == ISD::OR) {
12855       Opnds.push_back(I->getOperand(0));
12856       Opnds.push_back(I->getOperand(1));
12857       // Re-evaluate the number of nodes to be traversed.
12858       e += 2; // 2 more nodes (LHS and RHS) are pushed.
12859       continue;
12860     }
12861
12862     // Quit if a non-EXTRACT_VECTOR_ELT
12863     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
12864       return SDValue();
12865
12866     // Quit if without a constant index.
12867     SDValue Idx = I->getOperand(1);
12868     if (!isa<ConstantSDNode>(Idx))
12869       return SDValue();
12870
12871     SDValue ExtractedFromVec = I->getOperand(0);
12872     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
12873     if (M == VecInMap.end()) {
12874       VT = ExtractedFromVec.getValueType();
12875       // Quit if not 128/256-bit vector.
12876       if (!VT.is128BitVector() && !VT.is256BitVector())
12877         return SDValue();
12878       // Quit if not the same type.
12879       if (VecInMap.begin() != VecInMap.end() &&
12880           VT != VecInMap.begin()->first.getValueType())
12881         return SDValue();
12882       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
12883       VecIns.push_back(ExtractedFromVec);
12884     }
12885     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
12886   }
12887
12888   assert((VT.is128BitVector() || VT.is256BitVector()) &&
12889          "Not extracted from 128-/256-bit vector.");
12890
12891   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
12892
12893   for (DenseMap<SDValue, unsigned>::const_iterator
12894         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
12895     // Quit if not all elements are used.
12896     if (I->second != FullMask)
12897       return SDValue();
12898   }
12899
12900   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
12901
12902   // Cast all vectors into TestVT for PTEST.
12903   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
12904     VecIns[i] = DAG.getBitcast(TestVT, VecIns[i]);
12905
12906   // If more than one full vectors are evaluated, OR them first before PTEST.
12907   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
12908     // Each iteration will OR 2 nodes and append the result until there is only
12909     // 1 node left, i.e. the final OR'd value of all vectors.
12910     SDValue LHS = VecIns[Slot];
12911     SDValue RHS = VecIns[Slot + 1];
12912     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
12913   }
12914
12915   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
12916                      VecIns.back(), VecIns.back());
12917 }
12918
12919 /// \brief return true if \c Op has a use that doesn't just read flags.
12920 static bool hasNonFlagsUse(SDValue Op) {
12921   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
12922        ++UI) {
12923     SDNode *User = *UI;
12924     unsigned UOpNo = UI.getOperandNo();
12925     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
12926       // Look pass truncate.
12927       UOpNo = User->use_begin().getOperandNo();
12928       User = *User->use_begin();
12929     }
12930
12931     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
12932         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
12933       return true;
12934   }
12935   return false;
12936 }
12937
12938 /// Emit nodes that will be selected as "test Op0,Op0", or something
12939 /// equivalent.
12940 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
12941                                     SelectionDAG &DAG) const {
12942   if (Op.getValueType() == MVT::i1) {
12943     SDValue ExtOp = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i8, Op);
12944     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, ExtOp,
12945                        DAG.getConstant(0, dl, MVT::i8));
12946   }
12947   // CF and OF aren't always set the way we want. Determine which
12948   // of these we need.
12949   bool NeedCF = false;
12950   bool NeedOF = false;
12951   switch (X86CC) {
12952   default: break;
12953   case X86::COND_A: case X86::COND_AE:
12954   case X86::COND_B: case X86::COND_BE:
12955     NeedCF = true;
12956     break;
12957   case X86::COND_G: case X86::COND_GE:
12958   case X86::COND_L: case X86::COND_LE:
12959   case X86::COND_O: case X86::COND_NO: {
12960     // Check if we really need to set the
12961     // Overflow flag. If NoSignedWrap is present
12962     // that is not actually needed.
12963     switch (Op->getOpcode()) {
12964     case ISD::ADD:
12965     case ISD::SUB:
12966     case ISD::MUL:
12967     case ISD::SHL: {
12968       const auto *BinNode = cast<BinaryWithFlagsSDNode>(Op.getNode());
12969       if (BinNode->Flags.hasNoSignedWrap())
12970         break;
12971     }
12972     default:
12973       NeedOF = true;
12974       break;
12975     }
12976     break;
12977   }
12978   }
12979   // See if we can use the EFLAGS value from the operand instead of
12980   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
12981   // we prove that the arithmetic won't overflow, we can't use OF or CF.
12982   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
12983     // Emit a CMP with 0, which is the TEST pattern.
12984     //if (Op.getValueType() == MVT::i1)
12985     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
12986     //                     DAG.getConstant(0, MVT::i1));
12987     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12988                        DAG.getConstant(0, dl, Op.getValueType()));
12989   }
12990   unsigned Opcode = 0;
12991   unsigned NumOperands = 0;
12992
12993   // Truncate operations may prevent the merge of the SETCC instruction
12994   // and the arithmetic instruction before it. Attempt to truncate the operands
12995   // of the arithmetic instruction and use a reduced bit-width instruction.
12996   bool NeedTruncation = false;
12997   SDValue ArithOp = Op;
12998   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
12999     SDValue Arith = Op->getOperand(0);
13000     // Both the trunc and the arithmetic op need to have one user each.
13001     if (Arith->hasOneUse())
13002       switch (Arith.getOpcode()) {
13003         default: break;
13004         case ISD::ADD:
13005         case ISD::SUB:
13006         case ISD::AND:
13007         case ISD::OR:
13008         case ISD::XOR: {
13009           NeedTruncation = true;
13010           ArithOp = Arith;
13011         }
13012       }
13013   }
13014
13015   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
13016   // which may be the result of a CAST.  We use the variable 'Op', which is the
13017   // non-casted variable when we check for possible users.
13018   switch (ArithOp.getOpcode()) {
13019   case ISD::ADD:
13020     // Due to an isel shortcoming, be conservative if this add is likely to be
13021     // selected as part of a load-modify-store instruction. When the root node
13022     // in a match is a store, isel doesn't know how to remap non-chain non-flag
13023     // uses of other nodes in the match, such as the ADD in this case. This
13024     // leads to the ADD being left around and reselected, with the result being
13025     // two adds in the output.  Alas, even if none our users are stores, that
13026     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
13027     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
13028     // climbing the DAG back to the root, and it doesn't seem to be worth the
13029     // effort.
13030     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
13031          UE = Op.getNode()->use_end(); UI != UE; ++UI)
13032       if (UI->getOpcode() != ISD::CopyToReg &&
13033           UI->getOpcode() != ISD::SETCC &&
13034           UI->getOpcode() != ISD::STORE)
13035         goto default_case;
13036
13037     if (ConstantSDNode *C =
13038         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
13039       // An add of one will be selected as an INC.
13040       if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
13041         Opcode = X86ISD::INC;
13042         NumOperands = 1;
13043         break;
13044       }
13045
13046       // An add of negative one (subtract of one) will be selected as a DEC.
13047       if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
13048         Opcode = X86ISD::DEC;
13049         NumOperands = 1;
13050         break;
13051       }
13052     }
13053
13054     // Otherwise use a regular EFLAGS-setting add.
13055     Opcode = X86ISD::ADD;
13056     NumOperands = 2;
13057     break;
13058   case ISD::SHL:
13059   case ISD::SRL:
13060     // If we have a constant logical shift that's only used in a comparison
13061     // against zero turn it into an equivalent AND. This allows turning it into
13062     // a TEST instruction later.
13063     if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
13064         isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
13065       EVT VT = Op.getValueType();
13066       unsigned BitWidth = VT.getSizeInBits();
13067       unsigned ShAmt = Op->getConstantOperandVal(1);
13068       if (ShAmt >= BitWidth) // Avoid undefined shifts.
13069         break;
13070       APInt Mask = ArithOp.getOpcode() == ISD::SRL
13071                        ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
13072                        : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
13073       if (!Mask.isSignedIntN(32)) // Avoid large immediates.
13074         break;
13075       SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
13076                                 DAG.getConstant(Mask, dl, VT));
13077       DAG.ReplaceAllUsesWith(Op, New);
13078       Op = New;
13079     }
13080     break;
13081
13082   case ISD::AND:
13083     // If the primary and result isn't used, don't bother using X86ISD::AND,
13084     // because a TEST instruction will be better.
13085     if (!hasNonFlagsUse(Op))
13086       break;
13087     // FALL THROUGH
13088   case ISD::SUB:
13089   case ISD::OR:
13090   case ISD::XOR:
13091     // Due to the ISEL shortcoming noted above, be conservative if this op is
13092     // likely to be selected as part of a load-modify-store instruction.
13093     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
13094            UE = Op.getNode()->use_end(); UI != UE; ++UI)
13095       if (UI->getOpcode() == ISD::STORE)
13096         goto default_case;
13097
13098     // Otherwise use a regular EFLAGS-setting instruction.
13099     switch (ArithOp.getOpcode()) {
13100     default: llvm_unreachable("unexpected operator!");
13101     case ISD::SUB: Opcode = X86ISD::SUB; break;
13102     case ISD::XOR: Opcode = X86ISD::XOR; break;
13103     case ISD::AND: Opcode = X86ISD::AND; break;
13104     case ISD::OR: {
13105       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
13106         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
13107         if (EFLAGS.getNode())
13108           return EFLAGS;
13109       }
13110       Opcode = X86ISD::OR;
13111       break;
13112     }
13113     }
13114
13115     NumOperands = 2;
13116     break;
13117   case X86ISD::ADD:
13118   case X86ISD::SUB:
13119   case X86ISD::INC:
13120   case X86ISD::DEC:
13121   case X86ISD::OR:
13122   case X86ISD::XOR:
13123   case X86ISD::AND:
13124     return SDValue(Op.getNode(), 1);
13125   default:
13126   default_case:
13127     break;
13128   }
13129
13130   // If we found that truncation is beneficial, perform the truncation and
13131   // update 'Op'.
13132   if (NeedTruncation) {
13133     EVT VT = Op.getValueType();
13134     SDValue WideVal = Op->getOperand(0);
13135     EVT WideVT = WideVal.getValueType();
13136     unsigned ConvertedOp = 0;
13137     // Use a target machine opcode to prevent further DAGCombine
13138     // optimizations that may separate the arithmetic operations
13139     // from the setcc node.
13140     switch (WideVal.getOpcode()) {
13141       default: break;
13142       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
13143       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
13144       case ISD::AND: ConvertedOp = X86ISD::AND; break;
13145       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
13146       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
13147     }
13148
13149     if (ConvertedOp) {
13150       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13151       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
13152         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
13153         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
13154         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
13155       }
13156     }
13157   }
13158
13159   if (Opcode == 0)
13160     // Emit a CMP with 0, which is the TEST pattern.
13161     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
13162                        DAG.getConstant(0, dl, Op.getValueType()));
13163
13164   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
13165   SmallVector<SDValue, 4> Ops(Op->op_begin(), Op->op_begin() + NumOperands);
13166
13167   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
13168   DAG.ReplaceAllUsesWith(Op, New);
13169   return SDValue(New.getNode(), 1);
13170 }
13171
13172 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
13173 /// equivalent.
13174 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
13175                                    SDLoc dl, SelectionDAG &DAG) const {
13176   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
13177     if (C->getAPIntValue() == 0)
13178       return EmitTest(Op0, X86CC, dl, DAG);
13179
13180      if (Op0.getValueType() == MVT::i1)
13181        llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
13182   }
13183
13184   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
13185        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
13186     // Do the comparison at i32 if it's smaller, besides the Atom case.
13187     // This avoids subregister aliasing issues. Keep the smaller reference
13188     // if we're optimizing for size, however, as that'll allow better folding
13189     // of memory operations.
13190     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
13191         !DAG.getMachineFunction().getFunction()->hasFnAttribute(
13192             Attribute::MinSize) &&
13193         !Subtarget->isAtom()) {
13194       unsigned ExtendOp =
13195           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
13196       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
13197       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
13198     }
13199     // Use SUB instead of CMP to enable CSE between SUB and CMP.
13200     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
13201     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
13202                               Op0, Op1);
13203     return SDValue(Sub.getNode(), 1);
13204   }
13205   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
13206 }
13207
13208 /// Convert a comparison if required by the subtarget.
13209 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
13210                                                  SelectionDAG &DAG) const {
13211   // If the subtarget does not support the FUCOMI instruction, floating-point
13212   // comparisons have to be converted.
13213   if (Subtarget->hasCMov() ||
13214       Cmp.getOpcode() != X86ISD::CMP ||
13215       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
13216       !Cmp.getOperand(1).getValueType().isFloatingPoint())
13217     return Cmp;
13218
13219   // The instruction selector will select an FUCOM instruction instead of
13220   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
13221   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
13222   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
13223   SDLoc dl(Cmp);
13224   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
13225   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
13226   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
13227                             DAG.getConstant(8, dl, MVT::i8));
13228   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
13229   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
13230 }
13231
13232 /// The minimum architected relative accuracy is 2^-12. We need one
13233 /// Newton-Raphson step to have a good float result (24 bits of precision).
13234 SDValue X86TargetLowering::getRsqrtEstimate(SDValue Op,
13235                                             DAGCombinerInfo &DCI,
13236                                             unsigned &RefinementSteps,
13237                                             bool &UseOneConstNR) const {
13238   EVT VT = Op.getValueType();
13239   const char *RecipOp;
13240
13241   // SSE1 has rsqrtss and rsqrtps. AVX adds a 256-bit variant for rsqrtps.
13242   // TODO: Add support for AVX512 (v16f32).
13243   // It is likely not profitable to do this for f64 because a double-precision
13244   // rsqrt estimate with refinement on x86 prior to FMA requires at least 16
13245   // instructions: convert to single, rsqrtss, convert back to double, refine
13246   // (3 steps = at least 13 insts). If an 'rsqrtsd' variant was added to the ISA
13247   // along with FMA, this could be a throughput win.
13248   if (VT == MVT::f32 && Subtarget->hasSSE1())
13249     RecipOp = "sqrtf";
13250   else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
13251            (VT == MVT::v8f32 && Subtarget->hasAVX()))
13252     RecipOp = "vec-sqrtf";
13253   else
13254     return SDValue();
13255
13256   TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
13257   if (!Recips.isEnabled(RecipOp))
13258     return SDValue();
13259
13260   RefinementSteps = Recips.getRefinementSteps(RecipOp);
13261   UseOneConstNR = false;
13262   return DCI.DAG.getNode(X86ISD::FRSQRT, SDLoc(Op), VT, Op);
13263 }
13264
13265 /// The minimum architected relative accuracy is 2^-12. We need one
13266 /// Newton-Raphson step to have a good float result (24 bits of precision).
13267 SDValue X86TargetLowering::getRecipEstimate(SDValue Op,
13268                                             DAGCombinerInfo &DCI,
13269                                             unsigned &RefinementSteps) const {
13270   EVT VT = Op.getValueType();
13271   const char *RecipOp;
13272
13273   // SSE1 has rcpss and rcpps. AVX adds a 256-bit variant for rcpps.
13274   // TODO: Add support for AVX512 (v16f32).
13275   // It is likely not profitable to do this for f64 because a double-precision
13276   // reciprocal estimate with refinement on x86 prior to FMA requires
13277   // 15 instructions: convert to single, rcpss, convert back to double, refine
13278   // (3 steps = 12 insts). If an 'rcpsd' variant was added to the ISA
13279   // along with FMA, this could be a throughput win.
13280   if (VT == MVT::f32 && Subtarget->hasSSE1())
13281     RecipOp = "divf";
13282   else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
13283            (VT == MVT::v8f32 && Subtarget->hasAVX()))
13284     RecipOp = "vec-divf";
13285   else
13286     return SDValue();
13287
13288   TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
13289   if (!Recips.isEnabled(RecipOp))
13290     return SDValue();
13291
13292   RefinementSteps = Recips.getRefinementSteps(RecipOp);
13293   return DCI.DAG.getNode(X86ISD::FRCP, SDLoc(Op), VT, Op);
13294 }
13295
13296 /// If we have at least two divisions that use the same divisor, convert to
13297 /// multplication by a reciprocal. This may need to be adjusted for a given
13298 /// CPU if a division's cost is not at least twice the cost of a multiplication.
13299 /// This is because we still need one division to calculate the reciprocal and
13300 /// then we need two multiplies by that reciprocal as replacements for the
13301 /// original divisions.
13302 bool X86TargetLowering::combineRepeatedFPDivisors(unsigned NumUsers) const {
13303   return NumUsers > 1;
13304 }
13305
13306 static bool isAllOnes(SDValue V) {
13307   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
13308   return C && C->isAllOnesValue();
13309 }
13310
13311 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
13312 /// if it's possible.
13313 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
13314                                      SDLoc dl, SelectionDAG &DAG) const {
13315   SDValue Op0 = And.getOperand(0);
13316   SDValue Op1 = And.getOperand(1);
13317   if (Op0.getOpcode() == ISD::TRUNCATE)
13318     Op0 = Op0.getOperand(0);
13319   if (Op1.getOpcode() == ISD::TRUNCATE)
13320     Op1 = Op1.getOperand(0);
13321
13322   SDValue LHS, RHS;
13323   if (Op1.getOpcode() == ISD::SHL)
13324     std::swap(Op0, Op1);
13325   if (Op0.getOpcode() == ISD::SHL) {
13326     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
13327       if (And00C->getZExtValue() == 1) {
13328         // If we looked past a truncate, check that it's only truncating away
13329         // known zeros.
13330         unsigned BitWidth = Op0.getValueSizeInBits();
13331         unsigned AndBitWidth = And.getValueSizeInBits();
13332         if (BitWidth > AndBitWidth) {
13333           APInt Zeros, Ones;
13334           DAG.computeKnownBits(Op0, Zeros, Ones);
13335           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
13336             return SDValue();
13337         }
13338         LHS = Op1;
13339         RHS = Op0.getOperand(1);
13340       }
13341   } else if (Op1.getOpcode() == ISD::Constant) {
13342     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
13343     uint64_t AndRHSVal = AndRHS->getZExtValue();
13344     SDValue AndLHS = Op0;
13345
13346     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
13347       LHS = AndLHS.getOperand(0);
13348       RHS = AndLHS.getOperand(1);
13349     }
13350
13351     // Use BT if the immediate can't be encoded in a TEST instruction.
13352     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
13353       LHS = AndLHS;
13354       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), dl, LHS.getValueType());
13355     }
13356   }
13357
13358   if (LHS.getNode()) {
13359     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
13360     // instruction.  Since the shift amount is in-range-or-undefined, we know
13361     // that doing a bittest on the i32 value is ok.  We extend to i32 because
13362     // the encoding for the i16 version is larger than the i32 version.
13363     // Also promote i16 to i32 for performance / code size reason.
13364     if (LHS.getValueType() == MVT::i8 ||
13365         LHS.getValueType() == MVT::i16)
13366       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
13367
13368     // If the operand types disagree, extend the shift amount to match.  Since
13369     // BT ignores high bits (like shifts) we can use anyextend.
13370     if (LHS.getValueType() != RHS.getValueType())
13371       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
13372
13373     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
13374     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
13375     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13376                        DAG.getConstant(Cond, dl, MVT::i8), BT);
13377   }
13378
13379   return SDValue();
13380 }
13381
13382 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
13383 /// mask CMPs.
13384 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
13385                               SDValue &Op1) {
13386   unsigned SSECC;
13387   bool Swap = false;
13388
13389   // SSE Condition code mapping:
13390   //  0 - EQ
13391   //  1 - LT
13392   //  2 - LE
13393   //  3 - UNORD
13394   //  4 - NEQ
13395   //  5 - NLT
13396   //  6 - NLE
13397   //  7 - ORD
13398   switch (SetCCOpcode) {
13399   default: llvm_unreachable("Unexpected SETCC condition");
13400   case ISD::SETOEQ:
13401   case ISD::SETEQ:  SSECC = 0; break;
13402   case ISD::SETOGT:
13403   case ISD::SETGT:  Swap = true; // Fallthrough
13404   case ISD::SETLT:
13405   case ISD::SETOLT: SSECC = 1; break;
13406   case ISD::SETOGE:
13407   case ISD::SETGE:  Swap = true; // Fallthrough
13408   case ISD::SETLE:
13409   case ISD::SETOLE: SSECC = 2; break;
13410   case ISD::SETUO:  SSECC = 3; break;
13411   case ISD::SETUNE:
13412   case ISD::SETNE:  SSECC = 4; break;
13413   case ISD::SETULE: Swap = true; // Fallthrough
13414   case ISD::SETUGE: SSECC = 5; break;
13415   case ISD::SETULT: Swap = true; // Fallthrough
13416   case ISD::SETUGT: SSECC = 6; break;
13417   case ISD::SETO:   SSECC = 7; break;
13418   case ISD::SETUEQ:
13419   case ISD::SETONE: SSECC = 8; break;
13420   }
13421   if (Swap)
13422     std::swap(Op0, Op1);
13423
13424   return SSECC;
13425 }
13426
13427 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
13428 // ones, and then concatenate the result back.
13429 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
13430   MVT VT = Op.getSimpleValueType();
13431
13432   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
13433          "Unsupported value type for operation");
13434
13435   unsigned NumElems = VT.getVectorNumElements();
13436   SDLoc dl(Op);
13437   SDValue CC = Op.getOperand(2);
13438
13439   // Extract the LHS vectors
13440   SDValue LHS = Op.getOperand(0);
13441   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13442   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13443
13444   // Extract the RHS vectors
13445   SDValue RHS = Op.getOperand(1);
13446   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
13447   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
13448
13449   // Issue the operation on the smaller types and concatenate the result back
13450   MVT EltVT = VT.getVectorElementType();
13451   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13452   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
13453                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
13454                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
13455 }
13456
13457 static SDValue LowerBoolVSETCC_AVX512(SDValue Op, SelectionDAG &DAG) {
13458   SDValue Op0 = Op.getOperand(0);
13459   SDValue Op1 = Op.getOperand(1);
13460   SDValue CC = Op.getOperand(2);
13461   MVT VT = Op.getSimpleValueType();
13462   SDLoc dl(Op);
13463
13464   assert(Op0.getValueType().getVectorElementType() == MVT::i1 &&
13465          "Unexpected type for boolean compare operation");
13466   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13467   SDValue NotOp0 = DAG.getNode(ISD::XOR, dl, VT, Op0,
13468                                DAG.getConstant(-1, dl, VT));
13469   SDValue NotOp1 = DAG.getNode(ISD::XOR, dl, VT, Op1,
13470                                DAG.getConstant(-1, dl, VT));
13471   switch (SetCCOpcode) {
13472   default: llvm_unreachable("Unexpected SETCC condition");
13473   case ISD::SETEQ:
13474     // (x == y) -> ~(x ^ y)
13475     return DAG.getNode(ISD::XOR, dl, VT,
13476                        DAG.getNode(ISD::XOR, dl, VT, Op0, Op1),
13477                        DAG.getConstant(-1, dl, VT));
13478   case ISD::SETNE:
13479     // (x != y) -> (x ^ y)
13480     return DAG.getNode(ISD::XOR, dl, VT, Op0, Op1);
13481   case ISD::SETUGT:
13482   case ISD::SETGT:
13483     // (x > y) -> (x & ~y)
13484     return DAG.getNode(ISD::AND, dl, VT, Op0, NotOp1);
13485   case ISD::SETULT:
13486   case ISD::SETLT:
13487     // (x < y) -> (~x & y)
13488     return DAG.getNode(ISD::AND, dl, VT, NotOp0, Op1);
13489   case ISD::SETULE:
13490   case ISD::SETLE:
13491     // (x <= y) -> (~x | y)
13492     return DAG.getNode(ISD::OR, dl, VT, NotOp0, Op1);
13493   case ISD::SETUGE:
13494   case ISD::SETGE:
13495     // (x >=y) -> (x | ~y)
13496     return DAG.getNode(ISD::OR, dl, VT, Op0, NotOp1);
13497   }
13498 }
13499
13500 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
13501                                      const X86Subtarget *Subtarget) {
13502   SDValue Op0 = Op.getOperand(0);
13503   SDValue Op1 = Op.getOperand(1);
13504   SDValue CC = Op.getOperand(2);
13505   MVT VT = Op.getSimpleValueType();
13506   SDLoc dl(Op);
13507
13508   assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 8 &&
13509          Op.getValueType().getScalarType() == MVT::i1 &&
13510          "Cannot set masked compare for this operation");
13511
13512   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13513   unsigned  Opc = 0;
13514   bool Unsigned = false;
13515   bool Swap = false;
13516   unsigned SSECC;
13517   switch (SetCCOpcode) {
13518   default: llvm_unreachable("Unexpected SETCC condition");
13519   case ISD::SETNE:  SSECC = 4; break;
13520   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
13521   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
13522   case ISD::SETLT:  Swap = true; //fall-through
13523   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
13524   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
13525   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
13526   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
13527   case ISD::SETULE: Unsigned = true; //fall-through
13528   case ISD::SETLE:  SSECC = 2; break;
13529   }
13530
13531   if (Swap)
13532     std::swap(Op0, Op1);
13533   if (Opc)
13534     return DAG.getNode(Opc, dl, VT, Op0, Op1);
13535   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
13536   return DAG.getNode(Opc, dl, VT, Op0, Op1,
13537                      DAG.getConstant(SSECC, dl, MVT::i8));
13538 }
13539
13540 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
13541 /// operand \p Op1.  If non-trivial (for example because it's not constant)
13542 /// return an empty value.
13543 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
13544 {
13545   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
13546   if (!BV)
13547     return SDValue();
13548
13549   MVT VT = Op1.getSimpleValueType();
13550   MVT EVT = VT.getVectorElementType();
13551   unsigned n = VT.getVectorNumElements();
13552   SmallVector<SDValue, 8> ULTOp1;
13553
13554   for (unsigned i = 0; i < n; ++i) {
13555     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
13556     if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
13557       return SDValue();
13558
13559     // Avoid underflow.
13560     APInt Val = Elt->getAPIntValue();
13561     if (Val == 0)
13562       return SDValue();
13563
13564     ULTOp1.push_back(DAG.getConstant(Val - 1, dl, EVT));
13565   }
13566
13567   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
13568 }
13569
13570 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
13571                            SelectionDAG &DAG) {
13572   SDValue Op0 = Op.getOperand(0);
13573   SDValue Op1 = Op.getOperand(1);
13574   SDValue CC = Op.getOperand(2);
13575   MVT VT = Op.getSimpleValueType();
13576   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13577   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
13578   SDLoc dl(Op);
13579
13580   if (isFP) {
13581 #ifndef NDEBUG
13582     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
13583     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
13584 #endif
13585
13586     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
13587     unsigned Opc = X86ISD::CMPP;
13588     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
13589       assert(VT.getVectorNumElements() <= 16);
13590       Opc = X86ISD::CMPM;
13591     }
13592     // In the two special cases we can't handle, emit two comparisons.
13593     if (SSECC == 8) {
13594       unsigned CC0, CC1;
13595       unsigned CombineOpc;
13596       if (SetCCOpcode == ISD::SETUEQ) {
13597         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
13598       } else {
13599         assert(SetCCOpcode == ISD::SETONE);
13600         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
13601       }
13602
13603       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13604                                  DAG.getConstant(CC0, dl, MVT::i8));
13605       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13606                                  DAG.getConstant(CC1, dl, MVT::i8));
13607       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
13608     }
13609     // Handle all other FP comparisons here.
13610     return DAG.getNode(Opc, dl, VT, Op0, Op1,
13611                        DAG.getConstant(SSECC, dl, MVT::i8));
13612   }
13613
13614   // Break 256-bit integer vector compare into smaller ones.
13615   if (VT.is256BitVector() && !Subtarget->hasInt256())
13616     return Lower256IntVSETCC(Op, DAG);
13617
13618   EVT OpVT = Op1.getValueType();
13619   if (OpVT.getVectorElementType() == MVT::i1)
13620     return LowerBoolVSETCC_AVX512(Op, DAG);
13621
13622   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
13623   if (Subtarget->hasAVX512()) {
13624     if (Op1.getValueType().is512BitVector() ||
13625         (Subtarget->hasBWI() && Subtarget->hasVLX()) ||
13626         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
13627       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
13628
13629     // In AVX-512 architecture setcc returns mask with i1 elements,
13630     // But there is no compare instruction for i8 and i16 elements in KNL.
13631     // We are not talking about 512-bit operands in this case, these
13632     // types are illegal.
13633     if (MaskResult &&
13634         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
13635          OpVT.getVectorElementType().getSizeInBits() >= 8))
13636       return DAG.getNode(ISD::TRUNCATE, dl, VT,
13637                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
13638   }
13639
13640   // We are handling one of the integer comparisons here.  Since SSE only has
13641   // GT and EQ comparisons for integer, swapping operands and multiple
13642   // operations may be required for some comparisons.
13643   unsigned Opc;
13644   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
13645   bool Subus = false;
13646
13647   switch (SetCCOpcode) {
13648   default: llvm_unreachable("Unexpected SETCC condition");
13649   case ISD::SETNE:  Invert = true;
13650   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
13651   case ISD::SETLT:  Swap = true;
13652   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
13653   case ISD::SETGE:  Swap = true;
13654   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
13655                     Invert = true; break;
13656   case ISD::SETULT: Swap = true;
13657   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
13658                     FlipSigns = true; break;
13659   case ISD::SETUGE: Swap = true;
13660   case ISD::SETULE: Opc = X86ISD::PCMPGT;
13661                     FlipSigns = true; Invert = true; break;
13662   }
13663
13664   // Special case: Use min/max operations for SETULE/SETUGE
13665   MVT VET = VT.getVectorElementType();
13666   bool hasMinMax =
13667        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
13668     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
13669
13670   if (hasMinMax) {
13671     switch (SetCCOpcode) {
13672     default: break;
13673     case ISD::SETULE: Opc = ISD::UMIN; MinMax = true; break;
13674     case ISD::SETUGE: Opc = ISD::UMAX; MinMax = true; break;
13675     }
13676
13677     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
13678   }
13679
13680   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
13681   if (!MinMax && hasSubus) {
13682     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
13683     // Op0 u<= Op1:
13684     //   t = psubus Op0, Op1
13685     //   pcmpeq t, <0..0>
13686     switch (SetCCOpcode) {
13687     default: break;
13688     case ISD::SETULT: {
13689       // If the comparison is against a constant we can turn this into a
13690       // setule.  With psubus, setule does not require a swap.  This is
13691       // beneficial because the constant in the register is no longer
13692       // destructed as the destination so it can be hoisted out of a loop.
13693       // Only do this pre-AVX since vpcmp* is no longer destructive.
13694       if (Subtarget->hasAVX())
13695         break;
13696       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
13697       if (ULEOp1.getNode()) {
13698         Op1 = ULEOp1;
13699         Subus = true; Invert = false; Swap = false;
13700       }
13701       break;
13702     }
13703     // Psubus is better than flip-sign because it requires no inversion.
13704     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
13705     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
13706     }
13707
13708     if (Subus) {
13709       Opc = X86ISD::SUBUS;
13710       FlipSigns = false;
13711     }
13712   }
13713
13714   if (Swap)
13715     std::swap(Op0, Op1);
13716
13717   // Check that the operation in question is available (most are plain SSE2,
13718   // but PCMPGTQ and PCMPEQQ have different requirements).
13719   if (VT == MVT::v2i64) {
13720     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
13721       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
13722
13723       // First cast everything to the right type.
13724       Op0 = DAG.getBitcast(MVT::v4i32, Op0);
13725       Op1 = DAG.getBitcast(MVT::v4i32, Op1);
13726
13727       // Since SSE has no unsigned integer comparisons, we need to flip the sign
13728       // bits of the inputs before performing those operations. The lower
13729       // compare is always unsigned.
13730       SDValue SB;
13731       if (FlipSigns) {
13732         SB = DAG.getConstant(0x80000000U, dl, MVT::v4i32);
13733       } else {
13734         SDValue Sign = DAG.getConstant(0x80000000U, dl, MVT::i32);
13735         SDValue Zero = DAG.getConstant(0x00000000U, dl, MVT::i32);
13736         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
13737                          Sign, Zero, Sign, Zero);
13738       }
13739       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
13740       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
13741
13742       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
13743       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
13744       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
13745
13746       // Create masks for only the low parts/high parts of the 64 bit integers.
13747       static const int MaskHi[] = { 1, 1, 3, 3 };
13748       static const int MaskLo[] = { 0, 0, 2, 2 };
13749       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
13750       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
13751       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
13752
13753       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
13754       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
13755
13756       if (Invert)
13757         Result = DAG.getNOT(dl, Result, MVT::v4i32);
13758
13759       return DAG.getBitcast(VT, Result);
13760     }
13761
13762     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
13763       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
13764       // pcmpeqd + pshufd + pand.
13765       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
13766
13767       // First cast everything to the right type.
13768       Op0 = DAG.getBitcast(MVT::v4i32, Op0);
13769       Op1 = DAG.getBitcast(MVT::v4i32, Op1);
13770
13771       // Do the compare.
13772       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
13773
13774       // Make sure the lower and upper halves are both all-ones.
13775       static const int Mask[] = { 1, 0, 3, 2 };
13776       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
13777       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
13778
13779       if (Invert)
13780         Result = DAG.getNOT(dl, Result, MVT::v4i32);
13781
13782       return DAG.getBitcast(VT, Result);
13783     }
13784   }
13785
13786   // Since SSE has no unsigned integer comparisons, we need to flip the sign
13787   // bits of the inputs before performing those operations.
13788   if (FlipSigns) {
13789     EVT EltVT = VT.getVectorElementType();
13790     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), dl,
13791                                  VT);
13792     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
13793     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
13794   }
13795
13796   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
13797
13798   // If the logical-not of the result is required, perform that now.
13799   if (Invert)
13800     Result = DAG.getNOT(dl, Result, VT);
13801
13802   if (MinMax)
13803     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
13804
13805   if (Subus)
13806     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
13807                          getZeroVector(VT, Subtarget, DAG, dl));
13808
13809   return Result;
13810 }
13811
13812 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
13813
13814   MVT VT = Op.getSimpleValueType();
13815
13816   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
13817
13818   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
13819          && "SetCC type must be 8-bit or 1-bit integer");
13820   SDValue Op0 = Op.getOperand(0);
13821   SDValue Op1 = Op.getOperand(1);
13822   SDLoc dl(Op);
13823   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
13824
13825   // Optimize to BT if possible.
13826   // Lower (X & (1 << N)) == 0 to BT(X, N).
13827   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
13828   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
13829   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
13830       Op1.getOpcode() == ISD::Constant &&
13831       cast<ConstantSDNode>(Op1)->isNullValue() &&
13832       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13833     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
13834     if (NewSetCC.getNode()) {
13835       if (VT == MVT::i1)
13836         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewSetCC);
13837       return NewSetCC;
13838     }
13839   }
13840
13841   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
13842   // these.
13843   if (Op1.getOpcode() == ISD::Constant &&
13844       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
13845        cast<ConstantSDNode>(Op1)->isNullValue()) &&
13846       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13847
13848     // If the input is a setcc, then reuse the input setcc or use a new one with
13849     // the inverted condition.
13850     if (Op0.getOpcode() == X86ISD::SETCC) {
13851       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
13852       bool Invert = (CC == ISD::SETNE) ^
13853         cast<ConstantSDNode>(Op1)->isNullValue();
13854       if (!Invert)
13855         return Op0;
13856
13857       CCode = X86::GetOppositeBranchCondition(CCode);
13858       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13859                                   DAG.getConstant(CCode, dl, MVT::i8),
13860                                   Op0.getOperand(1));
13861       if (VT == MVT::i1)
13862         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13863       return SetCC;
13864     }
13865   }
13866   if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
13867       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
13868       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13869
13870     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
13871     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, dl, MVT::i1), NewCC);
13872   }
13873
13874   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
13875   unsigned X86CC = TranslateX86CC(CC, dl, isFP, Op0, Op1, DAG);
13876   if (X86CC == X86::COND_INVALID)
13877     return SDValue();
13878
13879   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
13880   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
13881   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13882                               DAG.getConstant(X86CC, dl, MVT::i8), EFLAGS);
13883   if (VT == MVT::i1)
13884     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13885   return SetCC;
13886 }
13887
13888 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
13889 static bool isX86LogicalCmp(SDValue Op) {
13890   unsigned Opc = Op.getNode()->getOpcode();
13891   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
13892       Opc == X86ISD::SAHF)
13893     return true;
13894   if (Op.getResNo() == 1 &&
13895       (Opc == X86ISD::ADD ||
13896        Opc == X86ISD::SUB ||
13897        Opc == X86ISD::ADC ||
13898        Opc == X86ISD::SBB ||
13899        Opc == X86ISD::SMUL ||
13900        Opc == X86ISD::UMUL ||
13901        Opc == X86ISD::INC ||
13902        Opc == X86ISD::DEC ||
13903        Opc == X86ISD::OR ||
13904        Opc == X86ISD::XOR ||
13905        Opc == X86ISD::AND))
13906     return true;
13907
13908   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
13909     return true;
13910
13911   return false;
13912 }
13913
13914 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
13915   if (V.getOpcode() != ISD::TRUNCATE)
13916     return false;
13917
13918   SDValue VOp0 = V.getOperand(0);
13919   unsigned InBits = VOp0.getValueSizeInBits();
13920   unsigned Bits = V.getValueSizeInBits();
13921   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
13922 }
13923
13924 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
13925   bool addTest = true;
13926   SDValue Cond  = Op.getOperand(0);
13927   SDValue Op1 = Op.getOperand(1);
13928   SDValue Op2 = Op.getOperand(2);
13929   SDLoc DL(Op);
13930   EVT VT = Op1.getValueType();
13931   SDValue CC;
13932
13933   // Lower FP selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
13934   // are available or VBLENDV if AVX is available.
13935   // Otherwise FP cmovs get lowered into a less efficient branch sequence later.
13936   if (Cond.getOpcode() == ISD::SETCC &&
13937       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
13938        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
13939       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
13940     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
13941     int SSECC = translateX86FSETCC(
13942         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
13943
13944     if (SSECC != 8) {
13945       if (Subtarget->hasAVX512()) {
13946         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
13947                                   DAG.getConstant(SSECC, DL, MVT::i8));
13948         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
13949       }
13950
13951       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
13952                                 DAG.getConstant(SSECC, DL, MVT::i8));
13953
13954       // If we have AVX, we can use a variable vector select (VBLENDV) instead
13955       // of 3 logic instructions for size savings and potentially speed.
13956       // Unfortunately, there is no scalar form of VBLENDV.
13957
13958       // If either operand is a constant, don't try this. We can expect to
13959       // optimize away at least one of the logic instructions later in that
13960       // case, so that sequence would be faster than a variable blend.
13961
13962       // BLENDV was introduced with SSE 4.1, but the 2 register form implicitly
13963       // uses XMM0 as the selection register. That may need just as many
13964       // instructions as the AND/ANDN/OR sequence due to register moves, so
13965       // don't bother.
13966
13967       if (Subtarget->hasAVX() &&
13968           !isa<ConstantFPSDNode>(Op1) && !isa<ConstantFPSDNode>(Op2)) {
13969
13970         // Convert to vectors, do a VSELECT, and convert back to scalar.
13971         // All of the conversions should be optimized away.
13972
13973         EVT VecVT = VT == MVT::f32 ? MVT::v4f32 : MVT::v2f64;
13974         SDValue VOp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op1);
13975         SDValue VOp2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op2);
13976         SDValue VCmp = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Cmp);
13977
13978         EVT VCmpVT = VT == MVT::f32 ? MVT::v4i32 : MVT::v2i64;
13979         VCmp = DAG.getBitcast(VCmpVT, VCmp);
13980
13981         SDValue VSel = DAG.getNode(ISD::VSELECT, DL, VecVT, VCmp, VOp1, VOp2);
13982
13983         return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
13984                            VSel, DAG.getIntPtrConstant(0, DL));
13985       }
13986       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
13987       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
13988       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
13989     }
13990   }
13991
13992   if (VT.isVector() && VT.getScalarType() == MVT::i1) {
13993     SDValue Op1Scalar;
13994     if (ISD::isBuildVectorOfConstantSDNodes(Op1.getNode()))
13995       Op1Scalar = ConvertI1VectorToInteger(Op1, DAG);
13996     else if (Op1.getOpcode() == ISD::BITCAST && Op1.getOperand(0))
13997       Op1Scalar = Op1.getOperand(0);
13998     SDValue Op2Scalar;
13999     if (ISD::isBuildVectorOfConstantSDNodes(Op2.getNode()))
14000       Op2Scalar = ConvertI1VectorToInteger(Op2, DAG);
14001     else if (Op2.getOpcode() == ISD::BITCAST && Op2.getOperand(0))
14002       Op2Scalar = Op2.getOperand(0);
14003     if (Op1Scalar.getNode() && Op2Scalar.getNode()) {
14004       SDValue newSelect = DAG.getNode(ISD::SELECT, DL,
14005                                       Op1Scalar.getValueType(),
14006                                       Cond, Op1Scalar, Op2Scalar);
14007       if (newSelect.getValueSizeInBits() == VT.getSizeInBits())
14008         return DAG.getBitcast(VT, newSelect);
14009       SDValue ExtVec = DAG.getBitcast(MVT::v8i1, newSelect);
14010       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, ExtVec,
14011                          DAG.getIntPtrConstant(0, DL));
14012     }
14013   }
14014
14015   if (VT == MVT::v4i1 || VT == MVT::v2i1) {
14016     SDValue zeroConst = DAG.getIntPtrConstant(0, DL);
14017     Op1 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
14018                       DAG.getUNDEF(MVT::v8i1), Op1, zeroConst);
14019     Op2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
14020                       DAG.getUNDEF(MVT::v8i1), Op2, zeroConst);
14021     SDValue newSelect = DAG.getNode(ISD::SELECT, DL, MVT::v8i1,
14022                                     Cond, Op1, Op2);
14023     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, newSelect, zeroConst);
14024   }
14025
14026   if (Cond.getOpcode() == ISD::SETCC) {
14027     SDValue NewCond = LowerSETCC(Cond, DAG);
14028     if (NewCond.getNode())
14029       Cond = NewCond;
14030   }
14031
14032   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
14033   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
14034   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
14035   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
14036   if (Cond.getOpcode() == X86ISD::SETCC &&
14037       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
14038       isZero(Cond.getOperand(1).getOperand(1))) {
14039     SDValue Cmp = Cond.getOperand(1);
14040
14041     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
14042
14043     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
14044         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
14045       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
14046
14047       SDValue CmpOp0 = Cmp.getOperand(0);
14048       // Apply further optimizations for special cases
14049       // (select (x != 0), -1, 0) -> neg & sbb
14050       // (select (x == 0), 0, -1) -> neg & sbb
14051       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
14052         if (YC->isNullValue() &&
14053             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
14054           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
14055           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
14056                                     DAG.getConstant(0, DL,
14057                                                     CmpOp0.getValueType()),
14058                                     CmpOp0);
14059           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14060                                     DAG.getConstant(X86::COND_B, DL, MVT::i8),
14061                                     SDValue(Neg.getNode(), 1));
14062           return Res;
14063         }
14064
14065       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
14066                         CmpOp0, DAG.getConstant(1, DL, CmpOp0.getValueType()));
14067       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14068
14069       SDValue Res =   // Res = 0 or -1.
14070         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14071                     DAG.getConstant(X86::COND_B, DL, MVT::i8), Cmp);
14072
14073       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
14074         Res = DAG.getNOT(DL, Res, Res.getValueType());
14075
14076       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
14077       if (!N2C || !N2C->isNullValue())
14078         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
14079       return Res;
14080     }
14081   }
14082
14083   // Look past (and (setcc_carry (cmp ...)), 1).
14084   if (Cond.getOpcode() == ISD::AND &&
14085       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
14086     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
14087     if (C && C->getAPIntValue() == 1)
14088       Cond = Cond.getOperand(0);
14089   }
14090
14091   // If condition flag is set by a X86ISD::CMP, then use it as the condition
14092   // setting operand in place of the X86ISD::SETCC.
14093   unsigned CondOpcode = Cond.getOpcode();
14094   if (CondOpcode == X86ISD::SETCC ||
14095       CondOpcode == X86ISD::SETCC_CARRY) {
14096     CC = Cond.getOperand(0);
14097
14098     SDValue Cmp = Cond.getOperand(1);
14099     unsigned Opc = Cmp.getOpcode();
14100     MVT VT = Op.getSimpleValueType();
14101
14102     bool IllegalFPCMov = false;
14103     if (VT.isFloatingPoint() && !VT.isVector() &&
14104         !isScalarFPTypeInSSEReg(VT))  // FPStack?
14105       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
14106
14107     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
14108         Opc == X86ISD::BT) { // FIXME
14109       Cond = Cmp;
14110       addTest = false;
14111     }
14112   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
14113              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
14114              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
14115               Cond.getOperand(0).getValueType() != MVT::i8)) {
14116     SDValue LHS = Cond.getOperand(0);
14117     SDValue RHS = Cond.getOperand(1);
14118     unsigned X86Opcode;
14119     unsigned X86Cond;
14120     SDVTList VTs;
14121     switch (CondOpcode) {
14122     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
14123     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
14124     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
14125     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
14126     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
14127     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
14128     default: llvm_unreachable("unexpected overflowing operator");
14129     }
14130     if (CondOpcode == ISD::UMULO)
14131       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
14132                           MVT::i32);
14133     else
14134       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14135
14136     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
14137
14138     if (CondOpcode == ISD::UMULO)
14139       Cond = X86Op.getValue(2);
14140     else
14141       Cond = X86Op.getValue(1);
14142
14143     CC = DAG.getConstant(X86Cond, DL, MVT::i8);
14144     addTest = false;
14145   }
14146
14147   if (addTest) {
14148     // Look pass the truncate if the high bits are known zero.
14149     if (isTruncWithZeroHighBitsInput(Cond, DAG))
14150         Cond = Cond.getOperand(0);
14151
14152     // We know the result of AND is compared against zero. Try to match
14153     // it to BT.
14154     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
14155       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
14156       if (NewSetCC.getNode()) {
14157         CC = NewSetCC.getOperand(0);
14158         Cond = NewSetCC.getOperand(1);
14159         addTest = false;
14160       }
14161     }
14162   }
14163
14164   if (addTest) {
14165     CC = DAG.getConstant(X86::COND_NE, DL, MVT::i8);
14166     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
14167   }
14168
14169   // a <  b ? -1 :  0 -> RES = ~setcc_carry
14170   // a <  b ?  0 : -1 -> RES = setcc_carry
14171   // a >= b ? -1 :  0 -> RES = setcc_carry
14172   // a >= b ?  0 : -1 -> RES = ~setcc_carry
14173   if (Cond.getOpcode() == X86ISD::SUB) {
14174     Cond = ConvertCmpIfNecessary(Cond, DAG);
14175     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
14176
14177     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
14178         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
14179       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14180                                 DAG.getConstant(X86::COND_B, DL, MVT::i8),
14181                                 Cond);
14182       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
14183         return DAG.getNOT(DL, Res, Res.getValueType());
14184       return Res;
14185     }
14186   }
14187
14188   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
14189   // widen the cmov and push the truncate through. This avoids introducing a new
14190   // branch during isel and doesn't add any extensions.
14191   if (Op.getValueType() == MVT::i8 &&
14192       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
14193     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
14194     if (T1.getValueType() == T2.getValueType() &&
14195         // Blacklist CopyFromReg to avoid partial register stalls.
14196         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
14197       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
14198       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
14199       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
14200     }
14201   }
14202
14203   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
14204   // condition is true.
14205   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
14206   SDValue Ops[] = { Op2, Op1, CC, Cond };
14207   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
14208 }
14209
14210 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op,
14211                                        const X86Subtarget *Subtarget,
14212                                        SelectionDAG &DAG) {
14213   MVT VT = Op->getSimpleValueType(0);
14214   SDValue In = Op->getOperand(0);
14215   MVT InVT = In.getSimpleValueType();
14216   MVT VTElt = VT.getVectorElementType();
14217   MVT InVTElt = InVT.getVectorElementType();
14218   SDLoc dl(Op);
14219
14220   // SKX processor
14221   if ((InVTElt == MVT::i1) &&
14222       (((Subtarget->hasBWI() && Subtarget->hasVLX() &&
14223         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() <= 16)) ||
14224
14225        ((Subtarget->hasBWI() && VT.is512BitVector() &&
14226         VTElt.getSizeInBits() <= 16)) ||
14227
14228        ((Subtarget->hasDQI() && Subtarget->hasVLX() &&
14229         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() >= 32)) ||
14230
14231        ((Subtarget->hasDQI() && VT.is512BitVector() &&
14232         VTElt.getSizeInBits() >= 32))))
14233     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14234
14235   unsigned int NumElts = VT.getVectorNumElements();
14236
14237   if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
14238     return SDValue();
14239
14240   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1) {
14241     if (In.getOpcode() == X86ISD::VSEXT || In.getOpcode() == X86ISD::VZEXT)
14242       return DAG.getNode(In.getOpcode(), dl, VT, In.getOperand(0));
14243     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14244   }
14245
14246   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
14247   MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
14248   SDValue NegOne =
14249    DAG.getConstant(APInt::getAllOnesValue(ExtVT.getScalarSizeInBits()), dl,
14250                    ExtVT);
14251   SDValue Zero =
14252    DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), dl, ExtVT);
14253
14254   SDValue V = DAG.getNode(ISD::VSELECT, dl, ExtVT, In, NegOne, Zero);
14255   if (VT.is512BitVector())
14256     return V;
14257   return DAG.getNode(X86ISD::VTRUNC, dl, VT, V);
14258 }
14259
14260 static SDValue LowerSIGN_EXTEND_VECTOR_INREG(SDValue Op,
14261                                              const X86Subtarget *Subtarget,
14262                                              SelectionDAG &DAG) {
14263   SDValue In = Op->getOperand(0);
14264   MVT VT = Op->getSimpleValueType(0);
14265   MVT InVT = In.getSimpleValueType();
14266   assert(VT.getSizeInBits() == InVT.getSizeInBits());
14267
14268   MVT InSVT = InVT.getScalarType();
14269   assert(VT.getScalarType().getScalarSizeInBits() > InSVT.getScalarSizeInBits());
14270
14271   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
14272     return SDValue();
14273   if (InSVT != MVT::i32 && InSVT != MVT::i16 && InSVT != MVT::i8)
14274     return SDValue();
14275
14276   SDLoc dl(Op);
14277
14278   // SSE41 targets can use the pmovsx* instructions directly.
14279   if (Subtarget->hasSSE41())
14280     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14281
14282   // pre-SSE41 targets unpack lower lanes and then sign-extend using SRAI.
14283   SDValue Curr = In;
14284   MVT CurrVT = InVT;
14285
14286   // As SRAI is only available on i16/i32 types, we expand only up to i32
14287   // and handle i64 separately.
14288   while (CurrVT != VT && CurrVT.getScalarType() != MVT::i32) {
14289     Curr = DAG.getNode(X86ISD::UNPCKL, dl, CurrVT, DAG.getUNDEF(CurrVT), Curr);
14290     MVT CurrSVT = MVT::getIntegerVT(CurrVT.getScalarSizeInBits() * 2);
14291     CurrVT = MVT::getVectorVT(CurrSVT, CurrVT.getVectorNumElements() / 2);
14292     Curr = DAG.getBitcast(CurrVT, Curr);
14293   }
14294
14295   SDValue SignExt = Curr;
14296   if (CurrVT != InVT) {
14297     unsigned SignExtShift =
14298         CurrVT.getScalarSizeInBits() - InSVT.getScalarSizeInBits();
14299     SignExt = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
14300                           DAG.getConstant(SignExtShift, dl, MVT::i8));
14301   }
14302
14303   if (CurrVT == VT)
14304     return SignExt;
14305
14306   if (VT == MVT::v2i64 && CurrVT == MVT::v4i32) {
14307     SDValue Sign = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
14308                                DAG.getConstant(31, dl, MVT::i8));
14309     SDValue Ext = DAG.getVectorShuffle(CurrVT, dl, SignExt, Sign, {0, 4, 1, 5});
14310     return DAG.getBitcast(VT, Ext);
14311   }
14312
14313   return SDValue();
14314 }
14315
14316 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
14317                                 SelectionDAG &DAG) {
14318   MVT VT = Op->getSimpleValueType(0);
14319   SDValue In = Op->getOperand(0);
14320   MVT InVT = In.getSimpleValueType();
14321   SDLoc dl(Op);
14322
14323   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
14324     return LowerSIGN_EXTEND_AVX512(Op, Subtarget, DAG);
14325
14326   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
14327       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
14328       (VT != MVT::v16i16 || InVT != MVT::v16i8))
14329     return SDValue();
14330
14331   if (Subtarget->hasInt256())
14332     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14333
14334   // Optimize vectors in AVX mode
14335   // Sign extend  v8i16 to v8i32 and
14336   //              v4i32 to v4i64
14337   //
14338   // Divide input vector into two parts
14339   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
14340   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
14341   // concat the vectors to original VT
14342
14343   unsigned NumElems = InVT.getVectorNumElements();
14344   SDValue Undef = DAG.getUNDEF(InVT);
14345
14346   SmallVector<int,8> ShufMask1(NumElems, -1);
14347   for (unsigned i = 0; i != NumElems/2; ++i)
14348     ShufMask1[i] = i;
14349
14350   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
14351
14352   SmallVector<int,8> ShufMask2(NumElems, -1);
14353   for (unsigned i = 0; i != NumElems/2; ++i)
14354     ShufMask2[i] = i + NumElems/2;
14355
14356   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
14357
14358   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
14359                                 VT.getVectorNumElements()/2);
14360
14361   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
14362   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
14363
14364   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
14365 }
14366
14367 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
14368 // may emit an illegal shuffle but the expansion is still better than scalar
14369 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
14370 // we'll emit a shuffle and a arithmetic shift.
14371 // FIXME: Is the expansion actually better than scalar code? It doesn't seem so.
14372 // TODO: It is possible to support ZExt by zeroing the undef values during
14373 // the shuffle phase or after the shuffle.
14374 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
14375                                  SelectionDAG &DAG) {
14376   MVT RegVT = Op.getSimpleValueType();
14377   assert(RegVT.isVector() && "We only custom lower vector sext loads.");
14378   assert(RegVT.isInteger() &&
14379          "We only custom lower integer vector sext loads.");
14380
14381   // Nothing useful we can do without SSE2 shuffles.
14382   assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
14383
14384   LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
14385   SDLoc dl(Ld);
14386   EVT MemVT = Ld->getMemoryVT();
14387   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14388   unsigned RegSz = RegVT.getSizeInBits();
14389
14390   ISD::LoadExtType Ext = Ld->getExtensionType();
14391
14392   assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
14393          && "Only anyext and sext are currently implemented.");
14394   assert(MemVT != RegVT && "Cannot extend to the same type");
14395   assert(MemVT.isVector() && "Must load a vector from memory");
14396
14397   unsigned NumElems = RegVT.getVectorNumElements();
14398   unsigned MemSz = MemVT.getSizeInBits();
14399   assert(RegSz > MemSz && "Register size must be greater than the mem size");
14400
14401   if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
14402     // The only way in which we have a legal 256-bit vector result but not the
14403     // integer 256-bit operations needed to directly lower a sextload is if we
14404     // have AVX1 but not AVX2. In that case, we can always emit a sextload to
14405     // a 128-bit vector and a normal sign_extend to 256-bits that should get
14406     // correctly legalized. We do this late to allow the canonical form of
14407     // sextload to persist throughout the rest of the DAG combiner -- it wants
14408     // to fold together any extensions it can, and so will fuse a sign_extend
14409     // of an sextload into a sextload targeting a wider value.
14410     SDValue Load;
14411     if (MemSz == 128) {
14412       // Just switch this to a normal load.
14413       assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
14414                                        "it must be a legal 128-bit vector "
14415                                        "type!");
14416       Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
14417                   Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
14418                   Ld->isInvariant(), Ld->getAlignment());
14419     } else {
14420       assert(MemSz < 128 &&
14421              "Can't extend a type wider than 128 bits to a 256 bit vector!");
14422       // Do an sext load to a 128-bit vector type. We want to use the same
14423       // number of elements, but elements half as wide. This will end up being
14424       // recursively lowered by this routine, but will succeed as we definitely
14425       // have all the necessary features if we're using AVX1.
14426       EVT HalfEltVT =
14427           EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
14428       EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
14429       Load =
14430           DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
14431                          Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
14432                          Ld->isNonTemporal(), Ld->isInvariant(),
14433                          Ld->getAlignment());
14434     }
14435
14436     // Replace chain users with the new chain.
14437     assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
14438     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
14439
14440     // Finally, do a normal sign-extend to the desired register.
14441     return DAG.getSExtOrTrunc(Load, dl, RegVT);
14442   }
14443
14444   // All sizes must be a power of two.
14445   assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
14446          "Non-power-of-two elements are not custom lowered!");
14447
14448   // Attempt to load the original value using scalar loads.
14449   // Find the largest scalar type that divides the total loaded size.
14450   MVT SclrLoadTy = MVT::i8;
14451   for (MVT Tp : MVT::integer_valuetypes()) {
14452     if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
14453       SclrLoadTy = Tp;
14454     }
14455   }
14456
14457   // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
14458   if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
14459       (64 <= MemSz))
14460     SclrLoadTy = MVT::f64;
14461
14462   // Calculate the number of scalar loads that we need to perform
14463   // in order to load our vector from memory.
14464   unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
14465
14466   assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
14467          "Can only lower sext loads with a single scalar load!");
14468
14469   unsigned loadRegZize = RegSz;
14470   if (Ext == ISD::SEXTLOAD && RegSz >= 256)
14471     loadRegZize = 128;
14472
14473   // Represent our vector as a sequence of elements which are the
14474   // largest scalar that we can load.
14475   EVT LoadUnitVecVT = EVT::getVectorVT(
14476       *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
14477
14478   // Represent the data using the same element type that is stored in
14479   // memory. In practice, we ''widen'' MemVT.
14480   EVT WideVecVT =
14481       EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
14482                        loadRegZize / MemVT.getScalarType().getSizeInBits());
14483
14484   assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
14485          "Invalid vector type");
14486
14487   // We can't shuffle using an illegal type.
14488   assert(TLI.isTypeLegal(WideVecVT) &&
14489          "We only lower types that form legal widened vector types");
14490
14491   SmallVector<SDValue, 8> Chains;
14492   SDValue Ptr = Ld->getBasePtr();
14493   SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, dl,
14494                                       TLI.getPointerTy(DAG.getDataLayout()));
14495   SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
14496
14497   for (unsigned i = 0; i < NumLoads; ++i) {
14498     // Perform a single load.
14499     SDValue ScalarLoad =
14500         DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
14501                     Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
14502                     Ld->getAlignment());
14503     Chains.push_back(ScalarLoad.getValue(1));
14504     // Create the first element type using SCALAR_TO_VECTOR in order to avoid
14505     // another round of DAGCombining.
14506     if (i == 0)
14507       Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
14508     else
14509       Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
14510                         ScalarLoad, DAG.getIntPtrConstant(i, dl));
14511
14512     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
14513   }
14514
14515   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
14516
14517   // Bitcast the loaded value to a vector of the original element type, in
14518   // the size of the target vector type.
14519   SDValue SlicedVec = DAG.getBitcast(WideVecVT, Res);
14520   unsigned SizeRatio = RegSz / MemSz;
14521
14522   if (Ext == ISD::SEXTLOAD) {
14523     // If we have SSE4.1, we can directly emit a VSEXT node.
14524     if (Subtarget->hasSSE41()) {
14525       SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
14526       DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14527       return Sext;
14528     }
14529
14530     // Otherwise we'll shuffle the small elements in the high bits of the
14531     // larger type and perform an arithmetic shift. If the shift is not legal
14532     // it's better to scalarize.
14533     assert(TLI.isOperationLegalOrCustom(ISD::SRA, RegVT) &&
14534            "We can't implement a sext load without an arithmetic right shift!");
14535
14536     // Redistribute the loaded elements into the different locations.
14537     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
14538     for (unsigned i = 0; i != NumElems; ++i)
14539       ShuffleVec[i * SizeRatio + SizeRatio - 1] = i;
14540
14541     SDValue Shuff = DAG.getVectorShuffle(
14542         WideVecVT, dl, SlicedVec, DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
14543
14544     Shuff = DAG.getBitcast(RegVT, Shuff);
14545
14546     // Build the arithmetic shift.
14547     unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
14548                    MemVT.getVectorElementType().getSizeInBits();
14549     Shuff =
14550         DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
14551                     DAG.getConstant(Amt, dl, RegVT));
14552
14553     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14554     return Shuff;
14555   }
14556
14557   // Redistribute the loaded elements into the different locations.
14558   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
14559   for (unsigned i = 0; i != NumElems; ++i)
14560     ShuffleVec[i * SizeRatio] = i;
14561
14562   SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
14563                                        DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
14564
14565   // Bitcast to the requested type.
14566   Shuff = DAG.getBitcast(RegVT, Shuff);
14567   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14568   return Shuff;
14569 }
14570
14571 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
14572 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
14573 // from the AND / OR.
14574 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
14575   Opc = Op.getOpcode();
14576   if (Opc != ISD::OR && Opc != ISD::AND)
14577     return false;
14578   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
14579           Op.getOperand(0).hasOneUse() &&
14580           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
14581           Op.getOperand(1).hasOneUse());
14582 }
14583
14584 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
14585 // 1 and that the SETCC node has a single use.
14586 static bool isXor1OfSetCC(SDValue Op) {
14587   if (Op.getOpcode() != ISD::XOR)
14588     return false;
14589   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
14590   if (N1C && N1C->getAPIntValue() == 1) {
14591     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
14592       Op.getOperand(0).hasOneUse();
14593   }
14594   return false;
14595 }
14596
14597 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
14598   bool addTest = true;
14599   SDValue Chain = Op.getOperand(0);
14600   SDValue Cond  = Op.getOperand(1);
14601   SDValue Dest  = Op.getOperand(2);
14602   SDLoc dl(Op);
14603   SDValue CC;
14604   bool Inverted = false;
14605
14606   if (Cond.getOpcode() == ISD::SETCC) {
14607     // Check for setcc([su]{add,sub,mul}o == 0).
14608     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
14609         isa<ConstantSDNode>(Cond.getOperand(1)) &&
14610         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
14611         Cond.getOperand(0).getResNo() == 1 &&
14612         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
14613          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
14614          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
14615          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
14616          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
14617          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
14618       Inverted = true;
14619       Cond = Cond.getOperand(0);
14620     } else {
14621       SDValue NewCond = LowerSETCC(Cond, DAG);
14622       if (NewCond.getNode())
14623         Cond = NewCond;
14624     }
14625   }
14626 #if 0
14627   // FIXME: LowerXALUO doesn't handle these!!
14628   else if (Cond.getOpcode() == X86ISD::ADD  ||
14629            Cond.getOpcode() == X86ISD::SUB  ||
14630            Cond.getOpcode() == X86ISD::SMUL ||
14631            Cond.getOpcode() == X86ISD::UMUL)
14632     Cond = LowerXALUO(Cond, DAG);
14633 #endif
14634
14635   // Look pass (and (setcc_carry (cmp ...)), 1).
14636   if (Cond.getOpcode() == ISD::AND &&
14637       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
14638     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
14639     if (C && C->getAPIntValue() == 1)
14640       Cond = Cond.getOperand(0);
14641   }
14642
14643   // If condition flag is set by a X86ISD::CMP, then use it as the condition
14644   // setting operand in place of the X86ISD::SETCC.
14645   unsigned CondOpcode = Cond.getOpcode();
14646   if (CondOpcode == X86ISD::SETCC ||
14647       CondOpcode == X86ISD::SETCC_CARRY) {
14648     CC = Cond.getOperand(0);
14649
14650     SDValue Cmp = Cond.getOperand(1);
14651     unsigned Opc = Cmp.getOpcode();
14652     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
14653     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
14654       Cond = Cmp;
14655       addTest = false;
14656     } else {
14657       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
14658       default: break;
14659       case X86::COND_O:
14660       case X86::COND_B:
14661         // These can only come from an arithmetic instruction with overflow,
14662         // e.g. SADDO, UADDO.
14663         Cond = Cond.getNode()->getOperand(1);
14664         addTest = false;
14665         break;
14666       }
14667     }
14668   }
14669   CondOpcode = Cond.getOpcode();
14670   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
14671       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
14672       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
14673        Cond.getOperand(0).getValueType() != MVT::i8)) {
14674     SDValue LHS = Cond.getOperand(0);
14675     SDValue RHS = Cond.getOperand(1);
14676     unsigned X86Opcode;
14677     unsigned X86Cond;
14678     SDVTList VTs;
14679     // Keep this in sync with LowerXALUO, otherwise we might create redundant
14680     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
14681     // X86ISD::INC).
14682     switch (CondOpcode) {
14683     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
14684     case ISD::SADDO:
14685       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14686         if (C->isOne()) {
14687           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
14688           break;
14689         }
14690       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
14691     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
14692     case ISD::SSUBO:
14693       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14694         if (C->isOne()) {
14695           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
14696           break;
14697         }
14698       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
14699     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
14700     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
14701     default: llvm_unreachable("unexpected overflowing operator");
14702     }
14703     if (Inverted)
14704       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
14705     if (CondOpcode == ISD::UMULO)
14706       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
14707                           MVT::i32);
14708     else
14709       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14710
14711     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
14712
14713     if (CondOpcode == ISD::UMULO)
14714       Cond = X86Op.getValue(2);
14715     else
14716       Cond = X86Op.getValue(1);
14717
14718     CC = DAG.getConstant(X86Cond, dl, MVT::i8);
14719     addTest = false;
14720   } else {
14721     unsigned CondOpc;
14722     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
14723       SDValue Cmp = Cond.getOperand(0).getOperand(1);
14724       if (CondOpc == ISD::OR) {
14725         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
14726         // two branches instead of an explicit OR instruction with a
14727         // separate test.
14728         if (Cmp == Cond.getOperand(1).getOperand(1) &&
14729             isX86LogicalCmp(Cmp)) {
14730           CC = Cond.getOperand(0).getOperand(0);
14731           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14732                               Chain, Dest, CC, Cmp);
14733           CC = Cond.getOperand(1).getOperand(0);
14734           Cond = Cmp;
14735           addTest = false;
14736         }
14737       } else { // ISD::AND
14738         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
14739         // two branches instead of an explicit AND instruction with a
14740         // separate test. However, we only do this if this block doesn't
14741         // have a fall-through edge, because this requires an explicit
14742         // jmp when the condition is false.
14743         if (Cmp == Cond.getOperand(1).getOperand(1) &&
14744             isX86LogicalCmp(Cmp) &&
14745             Op.getNode()->hasOneUse()) {
14746           X86::CondCode CCode =
14747             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
14748           CCode = X86::GetOppositeBranchCondition(CCode);
14749           CC = DAG.getConstant(CCode, dl, MVT::i8);
14750           SDNode *User = *Op.getNode()->use_begin();
14751           // Look for an unconditional branch following this conditional branch.
14752           // We need this because we need to reverse the successors in order
14753           // to implement FCMP_OEQ.
14754           if (User->getOpcode() == ISD::BR) {
14755             SDValue FalseBB = User->getOperand(1);
14756             SDNode *NewBR =
14757               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14758             assert(NewBR == User);
14759             (void)NewBR;
14760             Dest = FalseBB;
14761
14762             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14763                                 Chain, Dest, CC, Cmp);
14764             X86::CondCode CCode =
14765               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
14766             CCode = X86::GetOppositeBranchCondition(CCode);
14767             CC = DAG.getConstant(CCode, dl, MVT::i8);
14768             Cond = Cmp;
14769             addTest = false;
14770           }
14771         }
14772       }
14773     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
14774       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
14775       // It should be transformed during dag combiner except when the condition
14776       // is set by a arithmetics with overflow node.
14777       X86::CondCode CCode =
14778         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
14779       CCode = X86::GetOppositeBranchCondition(CCode);
14780       CC = DAG.getConstant(CCode, dl, MVT::i8);
14781       Cond = Cond.getOperand(0).getOperand(1);
14782       addTest = false;
14783     } else if (Cond.getOpcode() == ISD::SETCC &&
14784                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
14785       // For FCMP_OEQ, we can emit
14786       // two branches instead of an explicit AND instruction with a
14787       // separate test. However, we only do this if this block doesn't
14788       // have a fall-through edge, because this requires an explicit
14789       // jmp when the condition is false.
14790       if (Op.getNode()->hasOneUse()) {
14791         SDNode *User = *Op.getNode()->use_begin();
14792         // Look for an unconditional branch following this conditional branch.
14793         // We need this because we need to reverse the successors in order
14794         // to implement FCMP_OEQ.
14795         if (User->getOpcode() == ISD::BR) {
14796           SDValue FalseBB = User->getOperand(1);
14797           SDNode *NewBR =
14798             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14799           assert(NewBR == User);
14800           (void)NewBR;
14801           Dest = FalseBB;
14802
14803           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14804                                     Cond.getOperand(0), Cond.getOperand(1));
14805           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14806           CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
14807           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14808                               Chain, Dest, CC, Cmp);
14809           CC = DAG.getConstant(X86::COND_P, dl, MVT::i8);
14810           Cond = Cmp;
14811           addTest = false;
14812         }
14813       }
14814     } else if (Cond.getOpcode() == ISD::SETCC &&
14815                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
14816       // For FCMP_UNE, we can emit
14817       // two branches instead of an explicit AND instruction with a
14818       // separate test. However, we only do this if this block doesn't
14819       // have a fall-through edge, because this requires an explicit
14820       // jmp when the condition is false.
14821       if (Op.getNode()->hasOneUse()) {
14822         SDNode *User = *Op.getNode()->use_begin();
14823         // Look for an unconditional branch following this conditional branch.
14824         // We need this because we need to reverse the successors in order
14825         // to implement FCMP_UNE.
14826         if (User->getOpcode() == ISD::BR) {
14827           SDValue FalseBB = User->getOperand(1);
14828           SDNode *NewBR =
14829             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14830           assert(NewBR == User);
14831           (void)NewBR;
14832
14833           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14834                                     Cond.getOperand(0), Cond.getOperand(1));
14835           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14836           CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
14837           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14838                               Chain, Dest, CC, Cmp);
14839           CC = DAG.getConstant(X86::COND_NP, dl, MVT::i8);
14840           Cond = Cmp;
14841           addTest = false;
14842           Dest = FalseBB;
14843         }
14844       }
14845     }
14846   }
14847
14848   if (addTest) {
14849     // Look pass the truncate if the high bits are known zero.
14850     if (isTruncWithZeroHighBitsInput(Cond, DAG))
14851         Cond = Cond.getOperand(0);
14852
14853     // We know the result of AND is compared against zero. Try to match
14854     // it to BT.
14855     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
14856       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
14857       if (NewSetCC.getNode()) {
14858         CC = NewSetCC.getOperand(0);
14859         Cond = NewSetCC.getOperand(1);
14860         addTest = false;
14861       }
14862     }
14863   }
14864
14865   if (addTest) {
14866     X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
14867     CC = DAG.getConstant(X86Cond, dl, MVT::i8);
14868     Cond = EmitTest(Cond, X86Cond, dl, DAG);
14869   }
14870   Cond = ConvertCmpIfNecessary(Cond, DAG);
14871   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14872                      Chain, Dest, CC, Cond);
14873 }
14874
14875 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
14876 // Calls to _alloca are needed to probe the stack when allocating more than 4k
14877 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
14878 // that the guard pages used by the OS virtual memory manager are allocated in
14879 // correct sequence.
14880 SDValue
14881 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
14882                                            SelectionDAG &DAG) const {
14883   MachineFunction &MF = DAG.getMachineFunction();
14884   bool SplitStack = MF.shouldSplitStack();
14885   bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMachO()) ||
14886                SplitStack;
14887   SDLoc dl(Op);
14888
14889   if (!Lower) {
14890     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14891     SDNode* Node = Op.getNode();
14892
14893     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
14894     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
14895         " not tell us which reg is the stack pointer!");
14896     EVT VT = Node->getValueType(0);
14897     SDValue Tmp1 = SDValue(Node, 0);
14898     SDValue Tmp2 = SDValue(Node, 1);
14899     SDValue Tmp3 = Node->getOperand(2);
14900     SDValue Chain = Tmp1.getOperand(0);
14901
14902     // Chain the dynamic stack allocation so that it doesn't modify the stack
14903     // pointer when other instructions are using the stack.
14904     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, dl, true),
14905         SDLoc(Node));
14906
14907     SDValue Size = Tmp2.getOperand(1);
14908     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
14909     Chain = SP.getValue(1);
14910     unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
14911     const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
14912     unsigned StackAlign = TFI.getStackAlignment();
14913     Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
14914     if (Align > StackAlign)
14915       Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
14916           DAG.getConstant(-(uint64_t)Align, dl, VT));
14917     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
14918
14919     Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
14920         DAG.getIntPtrConstant(0, dl, true), SDValue(),
14921         SDLoc(Node));
14922
14923     SDValue Ops[2] = { Tmp1, Tmp2 };
14924     return DAG.getMergeValues(Ops, dl);
14925   }
14926
14927   // Get the inputs.
14928   SDValue Chain = Op.getOperand(0);
14929   SDValue Size  = Op.getOperand(1);
14930   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
14931   EVT VT = Op.getNode()->getValueType(0);
14932
14933   bool Is64Bit = Subtarget->is64Bit();
14934   MVT SPTy = getPointerTy(DAG.getDataLayout());
14935
14936   if (SplitStack) {
14937     MachineRegisterInfo &MRI = MF.getRegInfo();
14938
14939     if (Is64Bit) {
14940       // The 64 bit implementation of segmented stacks needs to clobber both r10
14941       // r11. This makes it impossible to use it along with nested parameters.
14942       const Function *F = MF.getFunction();
14943
14944       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
14945            I != E; ++I)
14946         if (I->hasNestAttr())
14947           report_fatal_error("Cannot use segmented stacks with functions that "
14948                              "have nested arguments.");
14949     }
14950
14951     const TargetRegisterClass *AddrRegClass = getRegClassFor(SPTy);
14952     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
14953     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
14954     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
14955                                 DAG.getRegister(Vreg, SPTy));
14956     SDValue Ops1[2] = { Value, Chain };
14957     return DAG.getMergeValues(Ops1, dl);
14958   } else {
14959     SDValue Flag;
14960     const unsigned Reg = (Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX);
14961
14962     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
14963     Flag = Chain.getValue(1);
14964     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
14965
14966     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
14967
14968     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
14969     unsigned SPReg = RegInfo->getStackRegister();
14970     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
14971     Chain = SP.getValue(1);
14972
14973     if (Align) {
14974       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
14975                        DAG.getConstant(-(uint64_t)Align, dl, VT));
14976       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
14977     }
14978
14979     SDValue Ops1[2] = { SP, Chain };
14980     return DAG.getMergeValues(Ops1, dl);
14981   }
14982 }
14983
14984 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
14985   MachineFunction &MF = DAG.getMachineFunction();
14986   auto PtrVT = getPointerTy(MF.getDataLayout());
14987   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
14988
14989   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
14990   SDLoc DL(Op);
14991
14992   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
14993     // vastart just stores the address of the VarArgsFrameIndex slot into the
14994     // memory location argument.
14995     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
14996     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
14997                         MachinePointerInfo(SV), false, false, 0);
14998   }
14999
15000   // __va_list_tag:
15001   //   gp_offset         (0 - 6 * 8)
15002   //   fp_offset         (48 - 48 + 8 * 16)
15003   //   overflow_arg_area (point to parameters coming in memory).
15004   //   reg_save_area
15005   SmallVector<SDValue, 8> MemOps;
15006   SDValue FIN = Op.getOperand(1);
15007   // Store gp_offset
15008   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
15009                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
15010                                                DL, MVT::i32),
15011                                FIN, MachinePointerInfo(SV), false, false, 0);
15012   MemOps.push_back(Store);
15013
15014   // Store fp_offset
15015   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
15016   Store = DAG.getStore(Op.getOperand(0), DL,
15017                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(), DL,
15018                                        MVT::i32),
15019                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
15020   MemOps.push_back(Store);
15021
15022   // Store ptr to overflow_arg_area
15023   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
15024   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
15025   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
15026                        MachinePointerInfo(SV, 8),
15027                        false, false, 0);
15028   MemOps.push_back(Store);
15029
15030   // Store ptr to reg_save_area.
15031   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(8, DL));
15032   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), PtrVT);
15033   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
15034                        MachinePointerInfo(SV, 16), false, false, 0);
15035   MemOps.push_back(Store);
15036   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
15037 }
15038
15039 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
15040   assert(Subtarget->is64Bit() &&
15041          "LowerVAARG only handles 64-bit va_arg!");
15042   assert((Subtarget->isTargetLinux() ||
15043           Subtarget->isTargetDarwin()) &&
15044           "Unhandled target in LowerVAARG");
15045   assert(Op.getNode()->getNumOperands() == 4);
15046   SDValue Chain = Op.getOperand(0);
15047   SDValue SrcPtr = Op.getOperand(1);
15048   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
15049   unsigned Align = Op.getConstantOperandVal(3);
15050   SDLoc dl(Op);
15051
15052   EVT ArgVT = Op.getNode()->getValueType(0);
15053   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
15054   uint32_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
15055   uint8_t ArgMode;
15056
15057   // Decide which area this value should be read from.
15058   // TODO: Implement the AMD64 ABI in its entirety. This simple
15059   // selection mechanism works only for the basic types.
15060   if (ArgVT == MVT::f80) {
15061     llvm_unreachable("va_arg for f80 not yet implemented");
15062   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
15063     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
15064   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
15065     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
15066   } else {
15067     llvm_unreachable("Unhandled argument type in LowerVAARG");
15068   }
15069
15070   if (ArgMode == 2) {
15071     // Sanity Check: Make sure using fp_offset makes sense.
15072     assert(!Subtarget->useSoftFloat() &&
15073            !(DAG.getMachineFunction().getFunction()->hasFnAttribute(
15074                Attribute::NoImplicitFloat)) &&
15075            Subtarget->hasSSE1());
15076   }
15077
15078   // Insert VAARG_64 node into the DAG
15079   // VAARG_64 returns two values: Variable Argument Address, Chain
15080   SDValue InstOps[] = {Chain, SrcPtr, DAG.getConstant(ArgSize, dl, MVT::i32),
15081                        DAG.getConstant(ArgMode, dl, MVT::i8),
15082                        DAG.getConstant(Align, dl, MVT::i32)};
15083   SDVTList VTs = DAG.getVTList(getPointerTy(DAG.getDataLayout()), MVT::Other);
15084   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
15085                                           VTs, InstOps, MVT::i64,
15086                                           MachinePointerInfo(SV),
15087                                           /*Align=*/0,
15088                                           /*Volatile=*/false,
15089                                           /*ReadMem=*/true,
15090                                           /*WriteMem=*/true);
15091   Chain = VAARG.getValue(1);
15092
15093   // Load the next argument and return it
15094   return DAG.getLoad(ArgVT, dl,
15095                      Chain,
15096                      VAARG,
15097                      MachinePointerInfo(),
15098                      false, false, false, 0);
15099 }
15100
15101 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
15102                            SelectionDAG &DAG) {
15103   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
15104   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
15105   SDValue Chain = Op.getOperand(0);
15106   SDValue DstPtr = Op.getOperand(1);
15107   SDValue SrcPtr = Op.getOperand(2);
15108   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
15109   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
15110   SDLoc DL(Op);
15111
15112   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
15113                        DAG.getIntPtrConstant(24, DL), 8, /*isVolatile*/false,
15114                        false, false,
15115                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
15116 }
15117
15118 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
15119 // amount is a constant. Takes immediate version of shift as input.
15120 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
15121                                           SDValue SrcOp, uint64_t ShiftAmt,
15122                                           SelectionDAG &DAG) {
15123   MVT ElementType = VT.getVectorElementType();
15124
15125   // Fold this packed shift into its first operand if ShiftAmt is 0.
15126   if (ShiftAmt == 0)
15127     return SrcOp;
15128
15129   // Check for ShiftAmt >= element width
15130   if (ShiftAmt >= ElementType.getSizeInBits()) {
15131     if (Opc == X86ISD::VSRAI)
15132       ShiftAmt = ElementType.getSizeInBits() - 1;
15133     else
15134       return DAG.getConstant(0, dl, VT);
15135   }
15136
15137   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
15138          && "Unknown target vector shift-by-constant node");
15139
15140   // Fold this packed vector shift into a build vector if SrcOp is a
15141   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
15142   if (VT == SrcOp.getSimpleValueType() &&
15143       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
15144     SmallVector<SDValue, 8> Elts;
15145     unsigned NumElts = SrcOp->getNumOperands();
15146     ConstantSDNode *ND;
15147
15148     switch(Opc) {
15149     default: llvm_unreachable(nullptr);
15150     case X86ISD::VSHLI:
15151       for (unsigned i=0; i!=NumElts; ++i) {
15152         SDValue CurrentOp = SrcOp->getOperand(i);
15153         if (CurrentOp->getOpcode() == ISD::UNDEF) {
15154           Elts.push_back(CurrentOp);
15155           continue;
15156         }
15157         ND = cast<ConstantSDNode>(CurrentOp);
15158         const APInt &C = ND->getAPIntValue();
15159         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), dl, ElementType));
15160       }
15161       break;
15162     case X86ISD::VSRLI:
15163       for (unsigned i=0; i!=NumElts; ++i) {
15164         SDValue CurrentOp = SrcOp->getOperand(i);
15165         if (CurrentOp->getOpcode() == ISD::UNDEF) {
15166           Elts.push_back(CurrentOp);
15167           continue;
15168         }
15169         ND = cast<ConstantSDNode>(CurrentOp);
15170         const APInt &C = ND->getAPIntValue();
15171         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), dl, ElementType));
15172       }
15173       break;
15174     case X86ISD::VSRAI:
15175       for (unsigned i=0; i!=NumElts; ++i) {
15176         SDValue CurrentOp = SrcOp->getOperand(i);
15177         if (CurrentOp->getOpcode() == ISD::UNDEF) {
15178           Elts.push_back(CurrentOp);
15179           continue;
15180         }
15181         ND = cast<ConstantSDNode>(CurrentOp);
15182         const APInt &C = ND->getAPIntValue();
15183         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), dl, ElementType));
15184       }
15185       break;
15186     }
15187
15188     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
15189   }
15190
15191   return DAG.getNode(Opc, dl, VT, SrcOp,
15192                      DAG.getConstant(ShiftAmt, dl, MVT::i8));
15193 }
15194
15195 // getTargetVShiftNode - Handle vector element shifts where the shift amount
15196 // may or may not be a constant. Takes immediate version of shift as input.
15197 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
15198                                    SDValue SrcOp, SDValue ShAmt,
15199                                    SelectionDAG &DAG) {
15200   MVT SVT = ShAmt.getSimpleValueType();
15201   assert((SVT == MVT::i32 || SVT == MVT::i64) && "Unexpected value type!");
15202
15203   // Catch shift-by-constant.
15204   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
15205     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
15206                                       CShAmt->getZExtValue(), DAG);
15207
15208   // Change opcode to non-immediate version
15209   switch (Opc) {
15210     default: llvm_unreachable("Unknown target vector shift node");
15211     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
15212     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
15213     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
15214   }
15215
15216   const X86Subtarget &Subtarget =
15217       static_cast<const X86Subtarget &>(DAG.getSubtarget());
15218   if (Subtarget.hasSSE41() && ShAmt.getOpcode() == ISD::ZERO_EXTEND &&
15219       ShAmt.getOperand(0).getSimpleValueType() == MVT::i16) {
15220     // Let the shuffle legalizer expand this shift amount node.
15221     SDValue Op0 = ShAmt.getOperand(0);
15222     Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(Op0), MVT::v8i16, Op0);
15223     ShAmt = getShuffleVectorZeroOrUndef(Op0, 0, true, &Subtarget, DAG);
15224   } else {
15225     // Need to build a vector containing shift amount.
15226     // SSE/AVX packed shifts only use the lower 64-bit of the shift count.
15227     SmallVector<SDValue, 4> ShOps;
15228     ShOps.push_back(ShAmt);
15229     if (SVT == MVT::i32) {
15230       ShOps.push_back(DAG.getConstant(0, dl, SVT));
15231       ShOps.push_back(DAG.getUNDEF(SVT));
15232     }
15233     ShOps.push_back(DAG.getUNDEF(SVT));
15234
15235     MVT BVT = SVT == MVT::i32 ? MVT::v4i32 : MVT::v2i64;
15236     ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, BVT, ShOps);
15237   }
15238
15239   // The return type has to be a 128-bit type with the same element
15240   // type as the input type.
15241   MVT EltVT = VT.getVectorElementType();
15242   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
15243
15244   ShAmt = DAG.getBitcast(ShVT, ShAmt);
15245   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
15246 }
15247
15248 /// \brief Return (and \p Op, \p Mask) for compare instructions or
15249 /// (vselect \p Mask, \p Op, \p PreservedSrc) for others along with the
15250 /// necessary casting or extending for \p Mask when lowering masking intrinsics
15251 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
15252                                     SDValue PreservedSrc,
15253                                     const X86Subtarget *Subtarget,
15254                                     SelectionDAG &DAG) {
15255     EVT VT = Op.getValueType();
15256     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
15257                                   MVT::i1, VT.getVectorNumElements());
15258     SDValue VMask = SDValue();
15259     unsigned OpcodeSelect = ISD::VSELECT;
15260     SDLoc dl(Op);
15261
15262     assert(MaskVT.isSimple() && "invalid mask type");
15263
15264     if (isAllOnes(Mask))
15265       return Op;
15266
15267     if (MaskVT.bitsGT(Mask.getValueType())) {
15268       EVT newMaskVT =  EVT::getIntegerVT(*DAG.getContext(),
15269                                          MaskVT.getSizeInBits());
15270       VMask = DAG.getBitcast(MaskVT,
15271                              DAG.getNode(ISD::ANY_EXTEND, dl, newMaskVT, Mask));
15272     } else {
15273       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15274                                        Mask.getValueType().getSizeInBits());
15275       // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
15276       // are extracted by EXTRACT_SUBVECTOR.
15277       VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15278                           DAG.getBitcast(BitcastVT, Mask),
15279                           DAG.getIntPtrConstant(0, dl));
15280     }
15281
15282     switch (Op.getOpcode()) {
15283       default: break;
15284       case X86ISD::PCMPEQM:
15285       case X86ISD::PCMPGTM:
15286       case X86ISD::CMPM:
15287       case X86ISD::CMPMU:
15288         return DAG.getNode(ISD::AND, dl, VT, Op, VMask);
15289       case X86ISD::VTRUNC:
15290       case X86ISD::VTRUNCS:
15291       case X86ISD::VTRUNCUS:
15292         // We can't use ISD::VSELECT here because it is not always "Legal"
15293         // for the destination type. For example vpmovqb require only AVX512
15294         // and vselect that can operate on byte element type require BWI
15295         OpcodeSelect = X86ISD::SELECT;
15296         break;
15297     }
15298     if (PreservedSrc.getOpcode() == ISD::UNDEF)
15299       PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
15300     return DAG.getNode(OpcodeSelect, dl, VT, VMask, Op, PreservedSrc);
15301 }
15302
15303 /// \brief Creates an SDNode for a predicated scalar operation.
15304 /// \returns (X86vselect \p Mask, \p Op, \p PreservedSrc).
15305 /// The mask is comming as MVT::i8 and it should be truncated
15306 /// to MVT::i1 while lowering masking intrinsics.
15307 /// The main difference between ScalarMaskingNode and VectorMaskingNode is using
15308 /// "X86select" instead of "vselect". We just can't create the "vselect" node for
15309 /// a scalar instruction.
15310 static SDValue getScalarMaskingNode(SDValue Op, SDValue Mask,
15311                                     SDValue PreservedSrc,
15312                                     const X86Subtarget *Subtarget,
15313                                     SelectionDAG &DAG) {
15314     if (isAllOnes(Mask))
15315       return Op;
15316
15317     EVT VT = Op.getValueType();
15318     SDLoc dl(Op);
15319     // The mask should be of type MVT::i1
15320     SDValue IMask = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Mask);
15321
15322     if (PreservedSrc.getOpcode() == ISD::UNDEF)
15323       PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
15324     return DAG.getNode(X86ISD::SELECT, dl, VT, IMask, Op, PreservedSrc);
15325 }
15326
15327 static int getSEHRegistrationNodeSize(const Function *Fn) {
15328   if (!Fn->hasPersonalityFn())
15329     report_fatal_error(
15330         "querying registration node size for function without personality");
15331   // The RegNodeSize is 6 32-bit words for SEH and 4 for C++ EH. See
15332   // WinEHStatePass for the full struct definition.
15333   switch (classifyEHPersonality(Fn->getPersonalityFn())) {
15334   case EHPersonality::MSVC_X86SEH: return 24;
15335   case EHPersonality::MSVC_CXX: return 16;
15336   default: break;
15337   }
15338   report_fatal_error("can only recover FP for MSVC EH personality functions");
15339 }
15340
15341 /// When the 32-bit MSVC runtime transfers control to us, either to an outlined
15342 /// function or when returning to a parent frame after catching an exception, we
15343 /// recover the parent frame pointer by doing arithmetic on the incoming EBP.
15344 /// Here's the math:
15345 ///   RegNodeBase = EntryEBP - RegNodeSize
15346 ///   ParentFP = RegNodeBase - RegNodeFrameOffset
15347 /// Subtracting RegNodeSize takes us to the offset of the registration node, and
15348 /// subtracting the offset (negative on x86) takes us back to the parent FP.
15349 static SDValue recoverFramePointer(SelectionDAG &DAG, const Function *Fn,
15350                                    SDValue EntryEBP) {
15351   MachineFunction &MF = DAG.getMachineFunction();
15352   SDLoc dl;
15353
15354   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15355   MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
15356
15357   // It's possible that the parent function no longer has a personality function
15358   // if the exceptional code was optimized away, in which case we just return
15359   // the incoming EBP.
15360   if (!Fn->hasPersonalityFn())
15361     return EntryEBP;
15362
15363   int RegNodeSize = getSEHRegistrationNodeSize(Fn);
15364
15365   // Get an MCSymbol that will ultimately resolve to the frame offset of the EH
15366   // registration.
15367   MCSymbol *OffsetSym =
15368       MF.getMMI().getContext().getOrCreateParentFrameOffsetSymbol(
15369           GlobalValue::getRealLinkageName(Fn->getName()));
15370   SDValue OffsetSymVal = DAG.getMCSymbol(OffsetSym, PtrVT);
15371   SDValue RegNodeFrameOffset =
15372       DAG.getNode(ISD::LOCAL_RECOVER, dl, PtrVT, OffsetSymVal);
15373
15374   // RegNodeBase = EntryEBP - RegNodeSize
15375   // ParentFP = RegNodeBase - RegNodeFrameOffset
15376   SDValue RegNodeBase = DAG.getNode(ISD::SUB, dl, PtrVT, EntryEBP,
15377                                     DAG.getConstant(RegNodeSize, dl, PtrVT));
15378   return DAG.getNode(ISD::SUB, dl, PtrVT, RegNodeBase, RegNodeFrameOffset);
15379 }
15380
15381 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
15382                                        SelectionDAG &DAG) {
15383   SDLoc dl(Op);
15384   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15385   EVT VT = Op.getValueType();
15386   const IntrinsicData* IntrData = getIntrinsicWithoutChain(IntNo);
15387   if (IntrData) {
15388     switch(IntrData->Type) {
15389     case INTR_TYPE_1OP:
15390       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1));
15391     case INTR_TYPE_2OP:
15392       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15393         Op.getOperand(2));
15394     case INTR_TYPE_3OP:
15395       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15396         Op.getOperand(2), Op.getOperand(3));
15397     case INTR_TYPE_4OP:
15398       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15399         Op.getOperand(2), Op.getOperand(3), Op.getOperand(4));
15400     case INTR_TYPE_1OP_MASK_RM: {
15401       SDValue Src = Op.getOperand(1);
15402       SDValue PassThru = Op.getOperand(2);
15403       SDValue Mask = Op.getOperand(3);
15404       SDValue RoundingMode;
15405       // We allways add rounding mode to the Node.
15406       // If the rounding mode is not specified, we add the 
15407       // "current direction" mode.
15408       if (Op.getNumOperands() == 4)
15409         RoundingMode =
15410           DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
15411       else
15412         RoundingMode = Op.getOperand(4);
15413       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15414       if (IntrWithRoundingModeOpcode != 0)
15415         if (cast<ConstantSDNode>(RoundingMode)->getZExtValue() !=
15416             X86::STATIC_ROUNDING::CUR_DIRECTION)
15417           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15418                                       dl, Op.getValueType(), Src, RoundingMode),
15419                                       Mask, PassThru, Subtarget, DAG);
15420       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src,
15421                                               RoundingMode),
15422                                   Mask, PassThru, Subtarget, DAG);
15423     }
15424     case INTR_TYPE_1OP_MASK: {
15425       SDValue Src = Op.getOperand(1);
15426       SDValue PassThru = Op.getOperand(2);
15427       SDValue Mask = Op.getOperand(3);
15428       // We add rounding mode to the Node when
15429       //   - RM Opcode is specified and
15430       //   - RM is not "current direction".
15431       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15432       if (IntrWithRoundingModeOpcode != 0) {
15433         SDValue Rnd = Op.getOperand(4);
15434         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
15435         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
15436           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15437                                       dl, Op.getValueType(),
15438                                       Src, Rnd),
15439                                       Mask, PassThru, Subtarget, DAG);
15440         }
15441       }
15442       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src),
15443                                   Mask, PassThru, Subtarget, DAG);
15444     }
15445     case INTR_TYPE_SCALAR_MASK_RM: {
15446       SDValue Src1 = Op.getOperand(1);
15447       SDValue Src2 = Op.getOperand(2);
15448       SDValue Src0 = Op.getOperand(3);
15449       SDValue Mask = Op.getOperand(4);
15450       // There are 2 kinds of intrinsics in this group:
15451       // (1) With supress-all-exceptions (sae) or rounding mode- 6 operands
15452       // (2) With rounding mode and sae - 7 operands.
15453       if (Op.getNumOperands() == 6) {
15454         SDValue Sae  = Op.getOperand(5);
15455         unsigned Opc = IntrData->Opc1 ? IntrData->Opc1 : IntrData->Opc0;
15456         return getScalarMaskingNode(DAG.getNode(Opc, dl, VT, Src1, Src2,
15457                                                 Sae),
15458                                     Mask, Src0, Subtarget, DAG);
15459       }
15460       assert(Op.getNumOperands() == 7 && "Unexpected intrinsic form");
15461       SDValue RoundingMode  = Op.getOperand(5);
15462       SDValue Sae  = Op.getOperand(6);
15463       return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
15464                                               RoundingMode, Sae),
15465                                   Mask, Src0, Subtarget, DAG);
15466     }
15467     case INTR_TYPE_2OP_MASK: {
15468       SDValue Src1 = Op.getOperand(1);
15469       SDValue Src2 = Op.getOperand(2);
15470       SDValue PassThru = Op.getOperand(3);
15471       SDValue Mask = Op.getOperand(4);
15472       // We specify 2 possible opcodes for intrinsics with rounding modes.
15473       // First, we check if the intrinsic may have non-default rounding mode,
15474       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15475       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15476       if (IntrWithRoundingModeOpcode != 0) {
15477         SDValue Rnd = Op.getOperand(5);
15478         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
15479         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
15480           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15481                                       dl, Op.getValueType(),
15482                                       Src1, Src2, Rnd),
15483                                       Mask, PassThru, Subtarget, DAG);
15484         }
15485       }
15486       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15487                                               Src1,Src2),
15488                                   Mask, PassThru, Subtarget, DAG);
15489     }
15490     case INTR_TYPE_2OP_MASK_RM: {
15491       SDValue Src1 = Op.getOperand(1);
15492       SDValue Src2 = Op.getOperand(2);
15493       SDValue PassThru = Op.getOperand(3);
15494       SDValue Mask = Op.getOperand(4);
15495       // We specify 2 possible modes for intrinsics, with/without rounding modes.
15496       // First, we check if the intrinsic have rounding mode (6 operands),
15497       // if not, we set rounding mode to "current".
15498       SDValue Rnd;
15499       if (Op.getNumOperands() == 6)
15500         Rnd = Op.getOperand(5);
15501       else
15502         Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
15503       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15504                                               Src1, Src2, Rnd),
15505                                   Mask, PassThru, Subtarget, DAG);
15506     }
15507     case INTR_TYPE_3OP_MASK_RM: {
15508       SDValue Src1 = Op.getOperand(1);
15509       SDValue Src2 = Op.getOperand(2);
15510       SDValue Imm = Op.getOperand(3);
15511       SDValue PassThru = Op.getOperand(4);
15512       SDValue Mask = Op.getOperand(5);
15513       // We specify 2 possible modes for intrinsics, with/without rounding modes.
15514       // First, we check if the intrinsic have rounding mode (7 operands),
15515       // if not, we set rounding mode to "current".
15516       SDValue Rnd;
15517       if (Op.getNumOperands() == 7)
15518         Rnd = Op.getOperand(6);
15519       else
15520         Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
15521       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15522         Src1, Src2, Imm, Rnd),
15523         Mask, PassThru, Subtarget, DAG);
15524     }
15525     case INTR_TYPE_3OP_MASK: {
15526       SDValue Src1 = Op.getOperand(1);
15527       SDValue Src2 = Op.getOperand(2);
15528       SDValue Src3 = Op.getOperand(3);
15529       SDValue PassThru = Op.getOperand(4);
15530       SDValue Mask = Op.getOperand(5);
15531       // We specify 2 possible opcodes for intrinsics with rounding modes.
15532       // First, we check if the intrinsic may have non-default rounding mode,
15533       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15534       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15535       if (IntrWithRoundingModeOpcode != 0) {
15536         SDValue Rnd = Op.getOperand(6);
15537         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
15538         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
15539           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15540                                       dl, Op.getValueType(),
15541                                       Src1, Src2, Src3, Rnd),
15542                                       Mask, PassThru, Subtarget, DAG);
15543         }
15544       }
15545       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15546                                               Src1, Src2, Src3),
15547                                   Mask, PassThru, Subtarget, DAG);
15548     }
15549     case VPERM_3OP_MASKZ:
15550     case VPERM_3OP_MASK:
15551     case FMA_OP_MASK3:
15552     case FMA_OP_MASKZ:
15553     case FMA_OP_MASK: {
15554       SDValue Src1 = Op.getOperand(1);
15555       SDValue Src2 = Op.getOperand(2);
15556       SDValue Src3 = Op.getOperand(3);
15557       SDValue Mask = Op.getOperand(4);
15558       EVT VT = Op.getValueType();
15559       SDValue PassThru = SDValue();
15560
15561       // set PassThru element
15562       if (IntrData->Type == VPERM_3OP_MASKZ || IntrData->Type == FMA_OP_MASKZ)
15563         PassThru = getZeroVector(VT, Subtarget, DAG, dl);
15564       else if (IntrData->Type == FMA_OP_MASK3)
15565         PassThru = Src3;
15566       else
15567         PassThru = Src1;
15568
15569       // We specify 2 possible opcodes for intrinsics with rounding modes.
15570       // First, we check if the intrinsic may have non-default rounding mode,
15571       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15572       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15573       if (IntrWithRoundingModeOpcode != 0) {
15574         SDValue Rnd = Op.getOperand(5);
15575         if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
15576             X86::STATIC_ROUNDING::CUR_DIRECTION)
15577           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15578                                                   dl, Op.getValueType(),
15579                                                   Src1, Src2, Src3, Rnd),
15580                                       Mask, PassThru, Subtarget, DAG);
15581       }
15582       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0,
15583                                               dl, Op.getValueType(),
15584                                               Src1, Src2, Src3),
15585                                   Mask, PassThru, Subtarget, DAG);
15586     }
15587     case CMP_MASK:
15588     case CMP_MASK_CC: {
15589       // Comparison intrinsics with masks.
15590       // Example of transformation:
15591       // (i8 (int_x86_avx512_mask_pcmpeq_q_128
15592       //             (v2i64 %a), (v2i64 %b), (i8 %mask))) ->
15593       // (i8 (bitcast
15594       //   (v8i1 (insert_subvector undef,
15595       //           (v2i1 (and (PCMPEQM %a, %b),
15596       //                      (extract_subvector
15597       //                         (v8i1 (bitcast %mask)), 0))), 0))))
15598       EVT VT = Op.getOperand(1).getValueType();
15599       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15600                                     VT.getVectorNumElements());
15601       SDValue Mask = Op.getOperand((IntrData->Type == CMP_MASK_CC) ? 4 : 3);
15602       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15603                                        Mask.getValueType().getSizeInBits());
15604       SDValue Cmp;
15605       if (IntrData->Type == CMP_MASK_CC) {
15606         SDValue CC = Op.getOperand(3);
15607         CC = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, CC);
15608         // We specify 2 possible opcodes for intrinsics with rounding modes.
15609         // First, we check if the intrinsic may have non-default rounding mode,
15610         // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15611         if (IntrData->Opc1 != 0) {
15612           SDValue Rnd = Op.getOperand(5);
15613           if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
15614               X86::STATIC_ROUNDING::CUR_DIRECTION)
15615             Cmp = DAG.getNode(IntrData->Opc1, dl, MaskVT, Op.getOperand(1),
15616                               Op.getOperand(2), CC, Rnd);
15617         }
15618         //default rounding mode
15619         if(!Cmp.getNode())
15620             Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
15621                               Op.getOperand(2), CC);
15622
15623       } else {
15624         assert(IntrData->Type == CMP_MASK && "Unexpected intrinsic type!");
15625         Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
15626                           Op.getOperand(2));
15627       }
15628       SDValue CmpMask = getVectorMaskingNode(Cmp, Mask,
15629                                              DAG.getTargetConstant(0, dl,
15630                                                                    MaskVT),
15631                                              Subtarget, DAG);
15632       SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
15633                                 DAG.getUNDEF(BitcastVT), CmpMask,
15634                                 DAG.getIntPtrConstant(0, dl));
15635       return DAG.getBitcast(Op.getValueType(), Res);
15636     }
15637     case COMI: { // Comparison intrinsics
15638       ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
15639       SDValue LHS = Op.getOperand(1);
15640       SDValue RHS = Op.getOperand(2);
15641       unsigned X86CC = TranslateX86CC(CC, dl, true, LHS, RHS, DAG);
15642       assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
15643       SDValue Cond = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
15644       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15645                                   DAG.getConstant(X86CC, dl, MVT::i8), Cond);
15646       return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15647     }
15648     case VSHIFT:
15649       return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
15650                                  Op.getOperand(1), Op.getOperand(2), DAG);
15651     case VSHIFT_MASK:
15652       return getVectorMaskingNode(getTargetVShiftNode(IntrData->Opc0, dl,
15653                                                       Op.getSimpleValueType(),
15654                                                       Op.getOperand(1),
15655                                                       Op.getOperand(2), DAG),
15656                                   Op.getOperand(4), Op.getOperand(3), Subtarget,
15657                                   DAG);
15658     case COMPRESS_EXPAND_IN_REG: {
15659       SDValue Mask = Op.getOperand(3);
15660       SDValue DataToCompress = Op.getOperand(1);
15661       SDValue PassThru = Op.getOperand(2);
15662       if (isAllOnes(Mask)) // return data as is
15663         return Op.getOperand(1);
15664
15665       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15666                                               DataToCompress),
15667                                   Mask, PassThru, Subtarget, DAG);
15668     }
15669     case BLEND: {
15670       SDValue Mask = Op.getOperand(3);
15671       EVT VT = Op.getValueType();
15672       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15673                                     VT.getVectorNumElements());
15674       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15675                                        Mask.getValueType().getSizeInBits());
15676       SDLoc dl(Op);
15677       SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15678                                   DAG.getBitcast(BitcastVT, Mask),
15679                                   DAG.getIntPtrConstant(0, dl));
15680       return DAG.getNode(IntrData->Opc0, dl, VT, VMask, Op.getOperand(1),
15681                          Op.getOperand(2));
15682     }
15683     default:
15684       break;
15685     }
15686   }
15687
15688   switch (IntNo) {
15689   default: return SDValue();    // Don't custom lower most intrinsics.
15690
15691   case Intrinsic::x86_avx2_permd:
15692   case Intrinsic::x86_avx2_permps:
15693     // Operands intentionally swapped. Mask is last operand to intrinsic,
15694     // but second operand for node/instruction.
15695     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
15696                        Op.getOperand(2), Op.getOperand(1));
15697
15698   // ptest and testp intrinsics. The intrinsic these come from are designed to
15699   // return an integer value, not just an instruction so lower it to the ptest
15700   // or testp pattern and a setcc for the result.
15701   case Intrinsic::x86_sse41_ptestz:
15702   case Intrinsic::x86_sse41_ptestc:
15703   case Intrinsic::x86_sse41_ptestnzc:
15704   case Intrinsic::x86_avx_ptestz_256:
15705   case Intrinsic::x86_avx_ptestc_256:
15706   case Intrinsic::x86_avx_ptestnzc_256:
15707   case Intrinsic::x86_avx_vtestz_ps:
15708   case Intrinsic::x86_avx_vtestc_ps:
15709   case Intrinsic::x86_avx_vtestnzc_ps:
15710   case Intrinsic::x86_avx_vtestz_pd:
15711   case Intrinsic::x86_avx_vtestc_pd:
15712   case Intrinsic::x86_avx_vtestnzc_pd:
15713   case Intrinsic::x86_avx_vtestz_ps_256:
15714   case Intrinsic::x86_avx_vtestc_ps_256:
15715   case Intrinsic::x86_avx_vtestnzc_ps_256:
15716   case Intrinsic::x86_avx_vtestz_pd_256:
15717   case Intrinsic::x86_avx_vtestc_pd_256:
15718   case Intrinsic::x86_avx_vtestnzc_pd_256: {
15719     bool IsTestPacked = false;
15720     unsigned X86CC;
15721     switch (IntNo) {
15722     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
15723     case Intrinsic::x86_avx_vtestz_ps:
15724     case Intrinsic::x86_avx_vtestz_pd:
15725     case Intrinsic::x86_avx_vtestz_ps_256:
15726     case Intrinsic::x86_avx_vtestz_pd_256:
15727       IsTestPacked = true; // Fallthrough
15728     case Intrinsic::x86_sse41_ptestz:
15729     case Intrinsic::x86_avx_ptestz_256:
15730       // ZF = 1
15731       X86CC = X86::COND_E;
15732       break;
15733     case Intrinsic::x86_avx_vtestc_ps:
15734     case Intrinsic::x86_avx_vtestc_pd:
15735     case Intrinsic::x86_avx_vtestc_ps_256:
15736     case Intrinsic::x86_avx_vtestc_pd_256:
15737       IsTestPacked = true; // Fallthrough
15738     case Intrinsic::x86_sse41_ptestc:
15739     case Intrinsic::x86_avx_ptestc_256:
15740       // CF = 1
15741       X86CC = X86::COND_B;
15742       break;
15743     case Intrinsic::x86_avx_vtestnzc_ps:
15744     case Intrinsic::x86_avx_vtestnzc_pd:
15745     case Intrinsic::x86_avx_vtestnzc_ps_256:
15746     case Intrinsic::x86_avx_vtestnzc_pd_256:
15747       IsTestPacked = true; // Fallthrough
15748     case Intrinsic::x86_sse41_ptestnzc:
15749     case Intrinsic::x86_avx_ptestnzc_256:
15750       // ZF and CF = 0
15751       X86CC = X86::COND_A;
15752       break;
15753     }
15754
15755     SDValue LHS = Op.getOperand(1);
15756     SDValue RHS = Op.getOperand(2);
15757     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
15758     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
15759     SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
15760     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
15761     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15762   }
15763   case Intrinsic::x86_avx512_kortestz_w:
15764   case Intrinsic::x86_avx512_kortestc_w: {
15765     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
15766     SDValue LHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(1));
15767     SDValue RHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(2));
15768     SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
15769     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
15770     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
15771     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15772   }
15773
15774   case Intrinsic::x86_sse42_pcmpistria128:
15775   case Intrinsic::x86_sse42_pcmpestria128:
15776   case Intrinsic::x86_sse42_pcmpistric128:
15777   case Intrinsic::x86_sse42_pcmpestric128:
15778   case Intrinsic::x86_sse42_pcmpistrio128:
15779   case Intrinsic::x86_sse42_pcmpestrio128:
15780   case Intrinsic::x86_sse42_pcmpistris128:
15781   case Intrinsic::x86_sse42_pcmpestris128:
15782   case Intrinsic::x86_sse42_pcmpistriz128:
15783   case Intrinsic::x86_sse42_pcmpestriz128: {
15784     unsigned Opcode;
15785     unsigned X86CC;
15786     switch (IntNo) {
15787     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
15788     case Intrinsic::x86_sse42_pcmpistria128:
15789       Opcode = X86ISD::PCMPISTRI;
15790       X86CC = X86::COND_A;
15791       break;
15792     case Intrinsic::x86_sse42_pcmpestria128:
15793       Opcode = X86ISD::PCMPESTRI;
15794       X86CC = X86::COND_A;
15795       break;
15796     case Intrinsic::x86_sse42_pcmpistric128:
15797       Opcode = X86ISD::PCMPISTRI;
15798       X86CC = X86::COND_B;
15799       break;
15800     case Intrinsic::x86_sse42_pcmpestric128:
15801       Opcode = X86ISD::PCMPESTRI;
15802       X86CC = X86::COND_B;
15803       break;
15804     case Intrinsic::x86_sse42_pcmpistrio128:
15805       Opcode = X86ISD::PCMPISTRI;
15806       X86CC = X86::COND_O;
15807       break;
15808     case Intrinsic::x86_sse42_pcmpestrio128:
15809       Opcode = X86ISD::PCMPESTRI;
15810       X86CC = X86::COND_O;
15811       break;
15812     case Intrinsic::x86_sse42_pcmpistris128:
15813       Opcode = X86ISD::PCMPISTRI;
15814       X86CC = X86::COND_S;
15815       break;
15816     case Intrinsic::x86_sse42_pcmpestris128:
15817       Opcode = X86ISD::PCMPESTRI;
15818       X86CC = X86::COND_S;
15819       break;
15820     case Intrinsic::x86_sse42_pcmpistriz128:
15821       Opcode = X86ISD::PCMPISTRI;
15822       X86CC = X86::COND_E;
15823       break;
15824     case Intrinsic::x86_sse42_pcmpestriz128:
15825       Opcode = X86ISD::PCMPESTRI;
15826       X86CC = X86::COND_E;
15827       break;
15828     }
15829     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
15830     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
15831     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
15832     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15833                                 DAG.getConstant(X86CC, dl, MVT::i8),
15834                                 SDValue(PCMP.getNode(), 1));
15835     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15836   }
15837
15838   case Intrinsic::x86_sse42_pcmpistri128:
15839   case Intrinsic::x86_sse42_pcmpestri128: {
15840     unsigned Opcode;
15841     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
15842       Opcode = X86ISD::PCMPISTRI;
15843     else
15844       Opcode = X86ISD::PCMPESTRI;
15845
15846     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
15847     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
15848     return DAG.getNode(Opcode, dl, VTs, NewOps);
15849   }
15850
15851   case Intrinsic::x86_seh_lsda: {
15852     // Compute the symbol for the LSDA. We know it'll get emitted later.
15853     MachineFunction &MF = DAG.getMachineFunction();
15854     SDValue Op1 = Op.getOperand(1);
15855     auto *Fn = cast<Function>(cast<GlobalAddressSDNode>(Op1)->getGlobal());
15856     MCSymbol *LSDASym = MF.getMMI().getContext().getOrCreateLSDASymbol(
15857         GlobalValue::getRealLinkageName(Fn->getName()));
15858
15859     // Generate a simple absolute symbol reference. This intrinsic is only
15860     // supported on 32-bit Windows, which isn't PIC.
15861     SDValue Result = DAG.getMCSymbol(LSDASym, VT);
15862     return DAG.getNode(X86ISD::Wrapper, dl, VT, Result);
15863   }
15864
15865   case Intrinsic::x86_seh_recoverfp: {
15866     SDValue FnOp = Op.getOperand(1);
15867     SDValue IncomingFPOp = Op.getOperand(2);
15868     GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(FnOp);
15869     auto *Fn = dyn_cast_or_null<Function>(GSD ? GSD->getGlobal() : nullptr);
15870     if (!Fn)
15871       report_fatal_error(
15872           "llvm.x86.seh.recoverfp must take a function as the first argument");
15873     return recoverFramePointer(DAG, Fn, IncomingFPOp);
15874   }
15875
15876   case Intrinsic::localaddress: {
15877     // Returns one of the stack, base, or frame pointer registers, depending on
15878     // which is used to reference local variables.
15879     MachineFunction &MF = DAG.getMachineFunction();
15880     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15881     unsigned Reg;
15882     if (RegInfo->hasBasePointer(MF))
15883       Reg = RegInfo->getBaseRegister();
15884     else // This function handles the SP or FP case.
15885       Reg = RegInfo->getPtrSizedFrameRegister(MF);
15886     return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
15887   }
15888   }
15889 }
15890
15891 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15892                               SDValue Src, SDValue Mask, SDValue Base,
15893                               SDValue Index, SDValue ScaleOp, SDValue Chain,
15894                               const X86Subtarget * Subtarget) {
15895   SDLoc dl(Op);
15896   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15897   if (!C)
15898     llvm_unreachable("Invalid scale type");
15899   unsigned ScaleVal = C->getZExtValue();
15900   if (ScaleVal > 2 && ScaleVal != 4 && ScaleVal != 8)
15901     llvm_unreachable("Valid scale values are 1, 2, 4, 8");
15902
15903   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
15904   EVT MaskVT = MVT::getVectorVT(MVT::i1,
15905                              Index.getSimpleValueType().getVectorNumElements());
15906   SDValue MaskInReg;
15907   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15908   if (MaskC)
15909     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
15910   else {
15911     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15912                                      Mask.getValueType().getSizeInBits());
15913
15914     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
15915     // are extracted by EXTRACT_SUBVECTOR.
15916     MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15917                             DAG.getBitcast(BitcastVT, Mask),
15918                             DAG.getIntPtrConstant(0, dl));
15919   }
15920   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
15921   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
15922   SDValue Segment = DAG.getRegister(0, MVT::i32);
15923   if (Src.getOpcode() == ISD::UNDEF)
15924     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
15925   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
15926   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
15927   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
15928   return DAG.getMergeValues(RetOps, dl);
15929 }
15930
15931 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15932                                SDValue Src, SDValue Mask, SDValue Base,
15933                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
15934   SDLoc dl(Op);
15935   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15936   if (!C)
15937     llvm_unreachable("Invalid scale type");
15938   unsigned ScaleVal = C->getZExtValue();
15939   if (ScaleVal > 2 && ScaleVal != 4 && ScaleVal != 8)
15940     llvm_unreachable("Valid scale values are 1, 2, 4, 8");
15941
15942   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
15943   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
15944   SDValue Segment = DAG.getRegister(0, MVT::i32);
15945   EVT MaskVT = MVT::getVectorVT(MVT::i1,
15946                              Index.getSimpleValueType().getVectorNumElements());
15947   SDValue MaskInReg;
15948   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15949   if (MaskC)
15950     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
15951   else {
15952     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15953                                      Mask.getValueType().getSizeInBits());
15954
15955     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
15956     // are extracted by EXTRACT_SUBVECTOR.
15957     MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15958                             DAG.getBitcast(BitcastVT, Mask),
15959                             DAG.getIntPtrConstant(0, dl));
15960   }
15961   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
15962   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
15963   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
15964   return SDValue(Res, 1);
15965 }
15966
15967 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15968                                SDValue Mask, SDValue Base, SDValue Index,
15969                                SDValue ScaleOp, SDValue Chain) {
15970   SDLoc dl(Op);
15971   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15972   assert(C && "Invalid scale type");
15973   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
15974   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
15975   SDValue Segment = DAG.getRegister(0, MVT::i32);
15976   EVT MaskVT =
15977     MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
15978   SDValue MaskInReg;
15979   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15980   if (MaskC)
15981     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
15982   else
15983     MaskInReg = DAG.getBitcast(MaskVT, Mask);
15984   //SDVTList VTs = DAG.getVTList(MVT::Other);
15985   SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
15986   SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
15987   return SDValue(Res, 0);
15988 }
15989
15990 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
15991 // read performance monitor counters (x86_rdpmc).
15992 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
15993                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
15994                               SmallVectorImpl<SDValue> &Results) {
15995   assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
15996   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
15997   SDValue LO, HI;
15998
15999   // The ECX register is used to select the index of the performance counter
16000   // to read.
16001   SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
16002                                    N->getOperand(2));
16003   SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
16004
16005   // Reads the content of a 64-bit performance counter and returns it in the
16006   // registers EDX:EAX.
16007   if (Subtarget->is64Bit()) {
16008     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
16009     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
16010                             LO.getValue(2));
16011   } else {
16012     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
16013     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
16014                             LO.getValue(2));
16015   }
16016   Chain = HI.getValue(1);
16017
16018   if (Subtarget->is64Bit()) {
16019     // The EAX register is loaded with the low-order 32 bits. The EDX register
16020     // is loaded with the supported high-order bits of the counter.
16021     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
16022                               DAG.getConstant(32, DL, MVT::i8));
16023     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
16024     Results.push_back(Chain);
16025     return;
16026   }
16027
16028   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
16029   SDValue Ops[] = { LO, HI };
16030   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
16031   Results.push_back(Pair);
16032   Results.push_back(Chain);
16033 }
16034
16035 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
16036 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
16037 // also used to custom lower READCYCLECOUNTER nodes.
16038 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
16039                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
16040                               SmallVectorImpl<SDValue> &Results) {
16041   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16042   SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
16043   SDValue LO, HI;
16044
16045   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
16046   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
16047   // and the EAX register is loaded with the low-order 32 bits.
16048   if (Subtarget->is64Bit()) {
16049     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
16050     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
16051                             LO.getValue(2));
16052   } else {
16053     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
16054     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
16055                             LO.getValue(2));
16056   }
16057   SDValue Chain = HI.getValue(1);
16058
16059   if (Opcode == X86ISD::RDTSCP_DAG) {
16060     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
16061
16062     // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
16063     // the ECX register. Add 'ecx' explicitly to the chain.
16064     SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
16065                                      HI.getValue(2));
16066     // Explicitly store the content of ECX at the location passed in input
16067     // to the 'rdtscp' intrinsic.
16068     Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
16069                          MachinePointerInfo(), false, false, 0);
16070   }
16071
16072   if (Subtarget->is64Bit()) {
16073     // The EDX register is loaded with the high-order 32 bits of the MSR, and
16074     // the EAX register is loaded with the low-order 32 bits.
16075     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
16076                               DAG.getConstant(32, DL, MVT::i8));
16077     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
16078     Results.push_back(Chain);
16079     return;
16080   }
16081
16082   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
16083   SDValue Ops[] = { LO, HI };
16084   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
16085   Results.push_back(Pair);
16086   Results.push_back(Chain);
16087 }
16088
16089 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
16090                                      SelectionDAG &DAG) {
16091   SmallVector<SDValue, 2> Results;
16092   SDLoc DL(Op);
16093   getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
16094                           Results);
16095   return DAG.getMergeValues(Results, DL);
16096 }
16097
16098 static SDValue LowerSEHRESTOREFRAME(SDValue Op, const X86Subtarget *Subtarget,
16099                                     SelectionDAG &DAG) {
16100   MachineFunction &MF = DAG.getMachineFunction();
16101   const Function *Fn = MF.getFunction();
16102   SDLoc dl(Op);
16103   SDValue Chain = Op.getOperand(0);
16104
16105   assert(Subtarget->getFrameLowering()->hasFP(MF) &&
16106          "using llvm.x86.seh.restoreframe requires a frame pointer");
16107
16108   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16109   MVT VT = TLI.getPointerTy(DAG.getDataLayout());
16110
16111   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16112   unsigned FrameReg =
16113       RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
16114   unsigned SPReg = RegInfo->getStackRegister();
16115   unsigned SlotSize = RegInfo->getSlotSize();
16116
16117   // Get incoming EBP.
16118   SDValue IncomingEBP =
16119       DAG.getCopyFromReg(Chain, dl, FrameReg, VT);
16120
16121   // SP is saved in the first field of every registration node, so load
16122   // [EBP-RegNodeSize] into SP.
16123   int RegNodeSize = getSEHRegistrationNodeSize(Fn);
16124   SDValue SPAddr = DAG.getNode(ISD::ADD, dl, VT, IncomingEBP,
16125                                DAG.getConstant(-RegNodeSize, dl, VT));
16126   SDValue NewSP =
16127       DAG.getLoad(VT, dl, Chain, SPAddr, MachinePointerInfo(), false, false,
16128                   false, VT.getScalarSizeInBits() / 8);
16129   Chain = DAG.getCopyToReg(Chain, dl, SPReg, NewSP);
16130
16131   if (!RegInfo->needsStackRealignment(MF)) {
16132     // Adjust EBP to point back to the original frame position.
16133     SDValue NewFP = recoverFramePointer(DAG, Fn, IncomingEBP);
16134     Chain = DAG.getCopyToReg(Chain, dl, FrameReg, NewFP);
16135   } else {
16136     assert(RegInfo->hasBasePointer(MF) &&
16137            "functions with Win32 EH must use frame or base pointer register");
16138
16139     // Reload the base pointer (ESI) with the adjusted incoming EBP.
16140     SDValue NewBP = recoverFramePointer(DAG, Fn, IncomingEBP);
16141     Chain = DAG.getCopyToReg(Chain, dl, RegInfo->getBaseRegister(), NewBP);
16142
16143     // Reload the spilled EBP value, now that the stack and base pointers are
16144     // set up.
16145     X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
16146     X86FI->setHasSEHFramePtrSave(true);
16147     int FI = MF.getFrameInfo()->CreateSpillStackObject(SlotSize, SlotSize);
16148     X86FI->setSEHFramePtrSaveIndex(FI);
16149     SDValue NewFP = DAG.getLoad(VT, dl, Chain, DAG.getFrameIndex(FI, VT),
16150                                 MachinePointerInfo(), false, false, false,
16151                                 VT.getScalarSizeInBits() / 8);
16152     Chain = DAG.getCopyToReg(NewFP, dl, FrameReg, NewFP);
16153   }
16154
16155   return Chain;
16156 }
16157
16158 /// \brief Lower intrinsics for TRUNCATE_TO_MEM case
16159 /// return truncate Store/MaskedStore Node
16160 static SDValue LowerINTRINSIC_TRUNCATE_TO_MEM(const SDValue & Op,
16161                                                SelectionDAG &DAG,
16162                                                MVT ElementType) {
16163   SDLoc dl(Op);
16164   SDValue Mask = Op.getOperand(4);
16165   SDValue DataToTruncate = Op.getOperand(3);
16166   SDValue Addr = Op.getOperand(2);
16167   SDValue Chain = Op.getOperand(0);
16168
16169   EVT VT  = DataToTruncate.getValueType();
16170   EVT SVT = EVT::getVectorVT(*DAG.getContext(),
16171                              ElementType, VT.getVectorNumElements());
16172
16173   if (isAllOnes(Mask)) // return just a truncate store
16174     return DAG.getTruncStore(Chain, dl, DataToTruncate, Addr,
16175                              MachinePointerInfo(), SVT, false, false,
16176                              SVT.getScalarSizeInBits()/8);
16177
16178   EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
16179                                 MVT::i1, VT.getVectorNumElements());
16180   EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16181                                    Mask.getValueType().getSizeInBits());
16182   // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
16183   // are extracted by EXTRACT_SUBVECTOR.
16184   SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16185                               DAG.getBitcast(BitcastVT, Mask),
16186                               DAG.getIntPtrConstant(0, dl));
16187
16188   MachineMemOperand *MMO = DAG.getMachineFunction().
16189     getMachineMemOperand(MachinePointerInfo(),
16190                          MachineMemOperand::MOStore, SVT.getStoreSize(),
16191                          SVT.getScalarSizeInBits()/8);
16192
16193   return DAG.getMaskedStore(Chain, dl, DataToTruncate, Addr,
16194                             VMask, SVT, MMO, true);
16195 }
16196
16197 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
16198                                       SelectionDAG &DAG) {
16199   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
16200
16201   const IntrinsicData* IntrData = getIntrinsicWithChain(IntNo);
16202   if (!IntrData) {
16203     if (IntNo == llvm::Intrinsic::x86_seh_restoreframe)
16204       return LowerSEHRESTOREFRAME(Op, Subtarget, DAG);
16205     return SDValue();
16206   }
16207
16208   SDLoc dl(Op);
16209   switch(IntrData->Type) {
16210   default:
16211     llvm_unreachable("Unknown Intrinsic Type");
16212     break;
16213   case RDSEED:
16214   case RDRAND: {
16215     // Emit the node with the right value type.
16216     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
16217     SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
16218
16219     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
16220     // Otherwise return the value from Rand, which is always 0, casted to i32.
16221     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
16222                       DAG.getConstant(1, dl, Op->getValueType(1)),
16223                       DAG.getConstant(X86::COND_B, dl, MVT::i32),
16224                       SDValue(Result.getNode(), 1) };
16225     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
16226                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
16227                                   Ops);
16228
16229     // Return { result, isValid, chain }.
16230     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
16231                        SDValue(Result.getNode(), 2));
16232   }
16233   case GATHER: {
16234   //gather(v1, mask, index, base, scale);
16235     SDValue Chain = Op.getOperand(0);
16236     SDValue Src   = Op.getOperand(2);
16237     SDValue Base  = Op.getOperand(3);
16238     SDValue Index = Op.getOperand(4);
16239     SDValue Mask  = Op.getOperand(5);
16240     SDValue Scale = Op.getOperand(6);
16241     return getGatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale,
16242                          Chain, Subtarget);
16243   }
16244   case SCATTER: {
16245   //scatter(base, mask, index, v1, scale);
16246     SDValue Chain = Op.getOperand(0);
16247     SDValue Base  = Op.getOperand(2);
16248     SDValue Mask  = Op.getOperand(3);
16249     SDValue Index = Op.getOperand(4);
16250     SDValue Src   = Op.getOperand(5);
16251     SDValue Scale = Op.getOperand(6);
16252     return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index,
16253                           Scale, Chain);
16254   }
16255   case PREFETCH: {
16256     SDValue Hint = Op.getOperand(6);
16257     unsigned HintVal = cast<ConstantSDNode>(Hint)->getZExtValue();
16258     assert(HintVal < 2 && "Wrong prefetch hint in intrinsic: should be 0 or 1");
16259     unsigned Opcode = (HintVal ? IntrData->Opc1 : IntrData->Opc0);
16260     SDValue Chain = Op.getOperand(0);
16261     SDValue Mask  = Op.getOperand(2);
16262     SDValue Index = Op.getOperand(3);
16263     SDValue Base  = Op.getOperand(4);
16264     SDValue Scale = Op.getOperand(5);
16265     return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
16266   }
16267   // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
16268   case RDTSC: {
16269     SmallVector<SDValue, 2> Results;
16270     getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget,
16271                             Results);
16272     return DAG.getMergeValues(Results, dl);
16273   }
16274   // Read Performance Monitoring Counters.
16275   case RDPMC: {
16276     SmallVector<SDValue, 2> Results;
16277     getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
16278     return DAG.getMergeValues(Results, dl);
16279   }
16280   // XTEST intrinsics.
16281   case XTEST: {
16282     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
16283     SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
16284     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16285                                 DAG.getConstant(X86::COND_NE, dl, MVT::i8),
16286                                 InTrans);
16287     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
16288     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
16289                        Ret, SDValue(InTrans.getNode(), 1));
16290   }
16291   // ADC/ADCX/SBB
16292   case ADX: {
16293     SmallVector<SDValue, 2> Results;
16294     SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
16295     SDVTList VTs = DAG.getVTList(Op.getOperand(3)->getValueType(0), MVT::Other);
16296     SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(2),
16297                                 DAG.getConstant(-1, dl, MVT::i8));
16298     SDValue Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(3),
16299                               Op.getOperand(4), GenCF.getValue(1));
16300     SDValue Store = DAG.getStore(Op.getOperand(0), dl, Res.getValue(0),
16301                                  Op.getOperand(5), MachinePointerInfo(),
16302                                  false, false, 0);
16303     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16304                                 DAG.getConstant(X86::COND_B, dl, MVT::i8),
16305                                 Res.getValue(1));
16306     Results.push_back(SetCC);
16307     Results.push_back(Store);
16308     return DAG.getMergeValues(Results, dl);
16309   }
16310   case COMPRESS_TO_MEM: {
16311     SDLoc dl(Op);
16312     SDValue Mask = Op.getOperand(4);
16313     SDValue DataToCompress = Op.getOperand(3);
16314     SDValue Addr = Op.getOperand(2);
16315     SDValue Chain = Op.getOperand(0);
16316
16317     EVT VT = DataToCompress.getValueType();
16318     if (isAllOnes(Mask)) // return just a store
16319       return DAG.getStore(Chain, dl, DataToCompress, Addr,
16320                           MachinePointerInfo(), false, false,
16321                           VT.getScalarSizeInBits()/8);
16322
16323     SDValue Compressed =
16324       getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToCompress),
16325                            Mask, DAG.getUNDEF(VT), Subtarget, DAG);
16326     return DAG.getStore(Chain, dl, Compressed, Addr,
16327                         MachinePointerInfo(), false, false,
16328                         VT.getScalarSizeInBits()/8);
16329   }
16330   case TRUNCATE_TO_MEM_VI8:
16331     return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i8);
16332   case TRUNCATE_TO_MEM_VI16:
16333     return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i16);
16334   case TRUNCATE_TO_MEM_VI32:
16335     return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i32);
16336   case EXPAND_FROM_MEM: {
16337     SDLoc dl(Op);
16338     SDValue Mask = Op.getOperand(4);
16339     SDValue PassThru = Op.getOperand(3);
16340     SDValue Addr = Op.getOperand(2);
16341     SDValue Chain = Op.getOperand(0);
16342     EVT VT = Op.getValueType();
16343
16344     if (isAllOnes(Mask)) // return just a load
16345       return DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(), false, false,
16346                          false, VT.getScalarSizeInBits()/8);
16347
16348     SDValue DataToExpand = DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(),
16349                                        false, false, false,
16350                                        VT.getScalarSizeInBits()/8);
16351
16352     SDValue Results[] = {
16353       getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToExpand),
16354                            Mask, PassThru, Subtarget, DAG), Chain};
16355     return DAG.getMergeValues(Results, dl);
16356   }
16357   }
16358 }
16359
16360 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
16361                                            SelectionDAG &DAG) const {
16362   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
16363   MFI->setReturnAddressIsTaken(true);
16364
16365   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
16366     return SDValue();
16367
16368   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16369   SDLoc dl(Op);
16370   EVT PtrVT = getPointerTy(DAG.getDataLayout());
16371
16372   if (Depth > 0) {
16373     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
16374     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16375     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), dl, PtrVT);
16376     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
16377                        DAG.getNode(ISD::ADD, dl, PtrVT,
16378                                    FrameAddr, Offset),
16379                        MachinePointerInfo(), false, false, false, 0);
16380   }
16381
16382   // Just load the return address.
16383   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
16384   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
16385                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
16386 }
16387
16388 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
16389   MachineFunction &MF = DAG.getMachineFunction();
16390   MachineFrameInfo *MFI = MF.getFrameInfo();
16391   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
16392   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16393   EVT VT = Op.getValueType();
16394
16395   MFI->setFrameAddressIsTaken(true);
16396
16397   if (MF.getTarget().getMCAsmInfo()->usesWindowsCFI()) {
16398     // Depth > 0 makes no sense on targets which use Windows unwind codes.  It
16399     // is not possible to crawl up the stack without looking at the unwind codes
16400     // simultaneously.
16401     int FrameAddrIndex = FuncInfo->getFAIndex();
16402     if (!FrameAddrIndex) {
16403       // Set up a frame object for the return address.
16404       unsigned SlotSize = RegInfo->getSlotSize();
16405       FrameAddrIndex = MF.getFrameInfo()->CreateFixedObject(
16406           SlotSize, /*Offset=*/0, /*IsImmutable=*/false);
16407       FuncInfo->setFAIndex(FrameAddrIndex);
16408     }
16409     return DAG.getFrameIndex(FrameAddrIndex, VT);
16410   }
16411
16412   unsigned FrameReg =
16413       RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
16414   SDLoc dl(Op);  // FIXME probably not meaningful
16415   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16416   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
16417           (FrameReg == X86::EBP && VT == MVT::i32)) &&
16418          "Invalid Frame Register!");
16419   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
16420   while (Depth--)
16421     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
16422                             MachinePointerInfo(),
16423                             false, false, false, 0);
16424   return FrameAddr;
16425 }
16426
16427 // FIXME? Maybe this could be a TableGen attribute on some registers and
16428 // this table could be generated automatically from RegInfo.
16429 unsigned X86TargetLowering::getRegisterByName(const char* RegName, EVT VT,
16430                                               SelectionDAG &DAG) const {
16431   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
16432   const MachineFunction &MF = DAG.getMachineFunction();
16433
16434   unsigned Reg = StringSwitch<unsigned>(RegName)
16435                        .Case("esp", X86::ESP)
16436                        .Case("rsp", X86::RSP)
16437                        .Case("ebp", X86::EBP)
16438                        .Case("rbp", X86::RBP)
16439                        .Default(0);
16440
16441   if (Reg == X86::EBP || Reg == X86::RBP) {
16442     if (!TFI.hasFP(MF))
16443       report_fatal_error("register " + StringRef(RegName) +
16444                          " is allocatable: function has no frame pointer");
16445 #ifndef NDEBUG
16446     else {
16447       const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16448       unsigned FrameReg =
16449           RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
16450       assert((FrameReg == X86::EBP || FrameReg == X86::RBP) &&
16451              "Invalid Frame Register!");
16452     }
16453 #endif
16454   }
16455
16456   if (Reg)
16457     return Reg;
16458
16459   report_fatal_error("Invalid register name global variable");
16460 }
16461
16462 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
16463                                                      SelectionDAG &DAG) const {
16464   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16465   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize(), SDLoc(Op));
16466 }
16467
16468 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
16469   SDValue Chain     = Op.getOperand(0);
16470   SDValue Offset    = Op.getOperand(1);
16471   SDValue Handler   = Op.getOperand(2);
16472   SDLoc dl      (Op);
16473
16474   EVT PtrVT = getPointerTy(DAG.getDataLayout());
16475   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16476   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
16477   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
16478           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
16479          "Invalid Frame Register!");
16480   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
16481   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
16482
16483   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
16484                                  DAG.getIntPtrConstant(RegInfo->getSlotSize(),
16485                                                        dl));
16486   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
16487   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
16488                        false, false, 0);
16489   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
16490
16491   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
16492                      DAG.getRegister(StoreAddrReg, PtrVT));
16493 }
16494
16495 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
16496                                                SelectionDAG &DAG) const {
16497   SDLoc DL(Op);
16498   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
16499                      DAG.getVTList(MVT::i32, MVT::Other),
16500                      Op.getOperand(0), Op.getOperand(1));
16501 }
16502
16503 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
16504                                                 SelectionDAG &DAG) const {
16505   SDLoc DL(Op);
16506   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
16507                      Op.getOperand(0), Op.getOperand(1));
16508 }
16509
16510 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
16511   return Op.getOperand(0);
16512 }
16513
16514 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
16515                                                 SelectionDAG &DAG) const {
16516   SDValue Root = Op.getOperand(0);
16517   SDValue Trmp = Op.getOperand(1); // trampoline
16518   SDValue FPtr = Op.getOperand(2); // nested function
16519   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
16520   SDLoc dl (Op);
16521
16522   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
16523   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
16524
16525   if (Subtarget->is64Bit()) {
16526     SDValue OutChains[6];
16527
16528     // Large code-model.
16529     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
16530     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
16531
16532     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
16533     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
16534
16535     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
16536
16537     // Load the pointer to the nested function into R11.
16538     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
16539     SDValue Addr = Trmp;
16540     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
16541                                 Addr, MachinePointerInfo(TrmpAddr),
16542                                 false, false, 0);
16543
16544     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16545                        DAG.getConstant(2, dl, MVT::i64));
16546     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
16547                                 MachinePointerInfo(TrmpAddr, 2),
16548                                 false, false, 2);
16549
16550     // Load the 'nest' parameter value into R10.
16551     // R10 is specified in X86CallingConv.td
16552     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
16553     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16554                        DAG.getConstant(10, dl, MVT::i64));
16555     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
16556                                 Addr, MachinePointerInfo(TrmpAddr, 10),
16557                                 false, false, 0);
16558
16559     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16560                        DAG.getConstant(12, dl, MVT::i64));
16561     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
16562                                 MachinePointerInfo(TrmpAddr, 12),
16563                                 false, false, 2);
16564
16565     // Jump to the nested function.
16566     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
16567     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16568                        DAG.getConstant(20, dl, MVT::i64));
16569     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
16570                                 Addr, MachinePointerInfo(TrmpAddr, 20),
16571                                 false, false, 0);
16572
16573     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
16574     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16575                        DAG.getConstant(22, dl, MVT::i64));
16576     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, dl, MVT::i8),
16577                                 Addr, MachinePointerInfo(TrmpAddr, 22),
16578                                 false, false, 0);
16579
16580     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
16581   } else {
16582     const Function *Func =
16583       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
16584     CallingConv::ID CC = Func->getCallingConv();
16585     unsigned NestReg;
16586
16587     switch (CC) {
16588     default:
16589       llvm_unreachable("Unsupported calling convention");
16590     case CallingConv::C:
16591     case CallingConv::X86_StdCall: {
16592       // Pass 'nest' parameter in ECX.
16593       // Must be kept in sync with X86CallingConv.td
16594       NestReg = X86::ECX;
16595
16596       // Check that ECX wasn't needed by an 'inreg' parameter.
16597       FunctionType *FTy = Func->getFunctionType();
16598       const AttributeSet &Attrs = Func->getAttributes();
16599
16600       if (!Attrs.isEmpty() && !Func->isVarArg()) {
16601         unsigned InRegCount = 0;
16602         unsigned Idx = 1;
16603
16604         for (FunctionType::param_iterator I = FTy->param_begin(),
16605              E = FTy->param_end(); I != E; ++I, ++Idx)
16606           if (Attrs.hasAttribute(Idx, Attribute::InReg))
16607             // FIXME: should only count parameters that are lowered to integers.
16608             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
16609
16610         if (InRegCount > 2) {
16611           report_fatal_error("Nest register in use - reduce number of inreg"
16612                              " parameters!");
16613         }
16614       }
16615       break;
16616     }
16617     case CallingConv::X86_FastCall:
16618     case CallingConv::X86_ThisCall:
16619     case CallingConv::Fast:
16620       // Pass 'nest' parameter in EAX.
16621       // Must be kept in sync with X86CallingConv.td
16622       NestReg = X86::EAX;
16623       break;
16624     }
16625
16626     SDValue OutChains[4];
16627     SDValue Addr, Disp;
16628
16629     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16630                        DAG.getConstant(10, dl, MVT::i32));
16631     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
16632
16633     // This is storing the opcode for MOV32ri.
16634     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
16635     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
16636     OutChains[0] = DAG.getStore(Root, dl,
16637                                 DAG.getConstant(MOV32ri|N86Reg, dl, MVT::i8),
16638                                 Trmp, MachinePointerInfo(TrmpAddr),
16639                                 false, false, 0);
16640
16641     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16642                        DAG.getConstant(1, dl, MVT::i32));
16643     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
16644                                 MachinePointerInfo(TrmpAddr, 1),
16645                                 false, false, 1);
16646
16647     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
16648     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16649                        DAG.getConstant(5, dl, MVT::i32));
16650     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, dl, MVT::i8),
16651                                 Addr, MachinePointerInfo(TrmpAddr, 5),
16652                                 false, false, 1);
16653
16654     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16655                        DAG.getConstant(6, dl, MVT::i32));
16656     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
16657                                 MachinePointerInfo(TrmpAddr, 6),
16658                                 false, false, 1);
16659
16660     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
16661   }
16662 }
16663
16664 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
16665                                             SelectionDAG &DAG) const {
16666   /*
16667    The rounding mode is in bits 11:10 of FPSR, and has the following
16668    settings:
16669      00 Round to nearest
16670      01 Round to -inf
16671      10 Round to +inf
16672      11 Round to 0
16673
16674   FLT_ROUNDS, on the other hand, expects the following:
16675     -1 Undefined
16676      0 Round to 0
16677      1 Round to nearest
16678      2 Round to +inf
16679      3 Round to -inf
16680
16681   To perform the conversion, we do:
16682     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
16683   */
16684
16685   MachineFunction &MF = DAG.getMachineFunction();
16686   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
16687   unsigned StackAlignment = TFI.getStackAlignment();
16688   MVT VT = Op.getSimpleValueType();
16689   SDLoc DL(Op);
16690
16691   // Save FP Control Word to stack slot
16692   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
16693   SDValue StackSlot =
16694       DAG.getFrameIndex(SSFI, getPointerTy(DAG.getDataLayout()));
16695
16696   MachineMemOperand *MMO =
16697    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
16698                            MachineMemOperand::MOStore, 2, 2);
16699
16700   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
16701   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
16702                                           DAG.getVTList(MVT::Other),
16703                                           Ops, MVT::i16, MMO);
16704
16705   // Load FP Control Word from stack slot
16706   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
16707                             MachinePointerInfo(), false, false, false, 0);
16708
16709   // Transform as necessary
16710   SDValue CWD1 =
16711     DAG.getNode(ISD::SRL, DL, MVT::i16,
16712                 DAG.getNode(ISD::AND, DL, MVT::i16,
16713                             CWD, DAG.getConstant(0x800, DL, MVT::i16)),
16714                 DAG.getConstant(11, DL, MVT::i8));
16715   SDValue CWD2 =
16716     DAG.getNode(ISD::SRL, DL, MVT::i16,
16717                 DAG.getNode(ISD::AND, DL, MVT::i16,
16718                             CWD, DAG.getConstant(0x400, DL, MVT::i16)),
16719                 DAG.getConstant(9, DL, MVT::i8));
16720
16721   SDValue RetVal =
16722     DAG.getNode(ISD::AND, DL, MVT::i16,
16723                 DAG.getNode(ISD::ADD, DL, MVT::i16,
16724                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
16725                             DAG.getConstant(1, DL, MVT::i16)),
16726                 DAG.getConstant(3, DL, MVT::i16));
16727
16728   return DAG.getNode((VT.getSizeInBits() < 16 ?
16729                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
16730 }
16731
16732 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
16733   MVT VT = Op.getSimpleValueType();
16734   EVT OpVT = VT;
16735   unsigned NumBits = VT.getSizeInBits();
16736   SDLoc dl(Op);
16737
16738   Op = Op.getOperand(0);
16739   if (VT == MVT::i8) {
16740     // Zero extend to i32 since there is not an i8 bsr.
16741     OpVT = MVT::i32;
16742     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
16743   }
16744
16745   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
16746   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
16747   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
16748
16749   // If src is zero (i.e. bsr sets ZF), returns NumBits.
16750   SDValue Ops[] = {
16751     Op,
16752     DAG.getConstant(NumBits + NumBits - 1, dl, OpVT),
16753     DAG.getConstant(X86::COND_E, dl, MVT::i8),
16754     Op.getValue(1)
16755   };
16756   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
16757
16758   // Finally xor with NumBits-1.
16759   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
16760                    DAG.getConstant(NumBits - 1, dl, OpVT));
16761
16762   if (VT == MVT::i8)
16763     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
16764   return Op;
16765 }
16766
16767 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
16768   MVT VT = Op.getSimpleValueType();
16769   EVT OpVT = VT;
16770   unsigned NumBits = VT.getSizeInBits();
16771   SDLoc dl(Op);
16772
16773   Op = Op.getOperand(0);
16774   if (VT == MVT::i8) {
16775     // Zero extend to i32 since there is not an i8 bsr.
16776     OpVT = MVT::i32;
16777     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
16778   }
16779
16780   // Issue a bsr (scan bits in reverse).
16781   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
16782   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
16783
16784   // And xor with NumBits-1.
16785   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
16786                    DAG.getConstant(NumBits - 1, dl, OpVT));
16787
16788   if (VT == MVT::i8)
16789     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
16790   return Op;
16791 }
16792
16793 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
16794   MVT VT = Op.getSimpleValueType();
16795   unsigned NumBits = VT.getSizeInBits();
16796   SDLoc dl(Op);
16797   Op = Op.getOperand(0);
16798
16799   // Issue a bsf (scan bits forward) which also sets EFLAGS.
16800   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
16801   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
16802
16803   // If src is zero (i.e. bsf sets ZF), returns NumBits.
16804   SDValue Ops[] = {
16805     Op,
16806     DAG.getConstant(NumBits, dl, VT),
16807     DAG.getConstant(X86::COND_E, dl, MVT::i8),
16808     Op.getValue(1)
16809   };
16810   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
16811 }
16812
16813 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
16814 // ones, and then concatenate the result back.
16815 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
16816   MVT VT = Op.getSimpleValueType();
16817
16818   assert(VT.is256BitVector() && VT.isInteger() &&
16819          "Unsupported value type for operation");
16820
16821   unsigned NumElems = VT.getVectorNumElements();
16822   SDLoc dl(Op);
16823
16824   // Extract the LHS vectors
16825   SDValue LHS = Op.getOperand(0);
16826   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
16827   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
16828
16829   // Extract the RHS vectors
16830   SDValue RHS = Op.getOperand(1);
16831   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
16832   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
16833
16834   MVT EltVT = VT.getVectorElementType();
16835   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16836
16837   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
16838                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
16839                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
16840 }
16841
16842 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
16843   if (Op.getValueType() == MVT::i1)
16844     return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
16845                        Op.getOperand(0), Op.getOperand(1));
16846   assert(Op.getSimpleValueType().is256BitVector() &&
16847          Op.getSimpleValueType().isInteger() &&
16848          "Only handle AVX 256-bit vector integer operation");
16849   return Lower256IntArith(Op, DAG);
16850 }
16851
16852 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
16853   if (Op.getValueType() == MVT::i1)
16854     return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
16855                        Op.getOperand(0), Op.getOperand(1));
16856   assert(Op.getSimpleValueType().is256BitVector() &&
16857          Op.getSimpleValueType().isInteger() &&
16858          "Only handle AVX 256-bit vector integer operation");
16859   return Lower256IntArith(Op, DAG);
16860 }
16861
16862 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
16863                         SelectionDAG &DAG) {
16864   SDLoc dl(Op);
16865   MVT VT = Op.getSimpleValueType();
16866
16867   if (VT == MVT::i1)
16868     return DAG.getNode(ISD::AND, dl, VT, Op.getOperand(0), Op.getOperand(1));
16869
16870   // Decompose 256-bit ops into smaller 128-bit ops.
16871   if (VT.is256BitVector() && !Subtarget->hasInt256())
16872     return Lower256IntArith(Op, DAG);
16873
16874   SDValue A = Op.getOperand(0);
16875   SDValue B = Op.getOperand(1);
16876
16877   // Lower v16i8/v32i8 mul as promotion to v8i16/v16i16 vector
16878   // pairs, multiply and truncate.
16879   if (VT == MVT::v16i8 || VT == MVT::v32i8) {
16880     if (Subtarget->hasInt256()) {
16881       if (VT == MVT::v32i8) {
16882         MVT SubVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() / 2);
16883         SDValue Lo = DAG.getIntPtrConstant(0, dl);
16884         SDValue Hi = DAG.getIntPtrConstant(VT.getVectorNumElements() / 2, dl);
16885         SDValue ALo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Lo);
16886         SDValue BLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Lo);
16887         SDValue AHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Hi);
16888         SDValue BHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Hi);
16889         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
16890                            DAG.getNode(ISD::MUL, dl, SubVT, ALo, BLo),
16891                            DAG.getNode(ISD::MUL, dl, SubVT, AHi, BHi));
16892       }
16893
16894       MVT ExVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements());
16895       return DAG.getNode(
16896           ISD::TRUNCATE, dl, VT,
16897           DAG.getNode(ISD::MUL, dl, ExVT,
16898                       DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, A),
16899                       DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, B)));
16900     }
16901
16902     assert(VT == MVT::v16i8 &&
16903            "Pre-AVX2 support only supports v16i8 multiplication");
16904     MVT ExVT = MVT::v8i16;
16905
16906     // Extract the lo parts and sign extend to i16
16907     SDValue ALo, BLo;
16908     if (Subtarget->hasSSE41()) {
16909       ALo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, A);
16910       BLo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, B);
16911     } else {
16912       const int ShufMask[] = {-1, 0, -1, 1, -1, 2, -1, 3,
16913                               -1, 4, -1, 5, -1, 6, -1, 7};
16914       ALo = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16915       BLo = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16916       ALo = DAG.getBitcast(ExVT, ALo);
16917       BLo = DAG.getBitcast(ExVT, BLo);
16918       ALo = DAG.getNode(ISD::SRA, dl, ExVT, ALo, DAG.getConstant(8, dl, ExVT));
16919       BLo = DAG.getNode(ISD::SRA, dl, ExVT, BLo, DAG.getConstant(8, dl, ExVT));
16920     }
16921
16922     // Extract the hi parts and sign extend to i16
16923     SDValue AHi, BHi;
16924     if (Subtarget->hasSSE41()) {
16925       const int ShufMask[] = {8,  9,  10, 11, 12, 13, 14, 15,
16926                               -1, -1, -1, -1, -1, -1, -1, -1};
16927       AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16928       BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16929       AHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, AHi);
16930       BHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, BHi);
16931     } else {
16932       const int ShufMask[] = {-1, 8,  -1, 9,  -1, 10, -1, 11,
16933                               -1, 12, -1, 13, -1, 14, -1, 15};
16934       AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16935       BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16936       AHi = DAG.getBitcast(ExVT, AHi);
16937       BHi = DAG.getBitcast(ExVT, BHi);
16938       AHi = DAG.getNode(ISD::SRA, dl, ExVT, AHi, DAG.getConstant(8, dl, ExVT));
16939       BHi = DAG.getNode(ISD::SRA, dl, ExVT, BHi, DAG.getConstant(8, dl, ExVT));
16940     }
16941
16942     // Multiply, mask the lower 8bits of the lo/hi results and pack
16943     SDValue RLo = DAG.getNode(ISD::MUL, dl, ExVT, ALo, BLo);
16944     SDValue RHi = DAG.getNode(ISD::MUL, dl, ExVT, AHi, BHi);
16945     RLo = DAG.getNode(ISD::AND, dl, ExVT, RLo, DAG.getConstant(255, dl, ExVT));
16946     RHi = DAG.getNode(ISD::AND, dl, ExVT, RHi, DAG.getConstant(255, dl, ExVT));
16947     return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
16948   }
16949
16950   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
16951   if (VT == MVT::v4i32) {
16952     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
16953            "Should not custom lower when pmuldq is available!");
16954
16955     // Extract the odd parts.
16956     static const int UnpackMask[] = { 1, -1, 3, -1 };
16957     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
16958     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
16959
16960     // Multiply the even parts.
16961     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
16962     // Now multiply odd parts.
16963     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
16964
16965     Evens = DAG.getBitcast(VT, Evens);
16966     Odds = DAG.getBitcast(VT, Odds);
16967
16968     // Merge the two vectors back together with a shuffle. This expands into 2
16969     // shuffles.
16970     static const int ShufMask[] = { 0, 4, 2, 6 };
16971     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
16972   }
16973
16974   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
16975          "Only know how to lower V2I64/V4I64/V8I64 multiply");
16976
16977   //  Ahi = psrlqi(a, 32);
16978   //  Bhi = psrlqi(b, 32);
16979   //
16980   //  AloBlo = pmuludq(a, b);
16981   //  AloBhi = pmuludq(a, Bhi);
16982   //  AhiBlo = pmuludq(Ahi, b);
16983
16984   //  AloBhi = psllqi(AloBhi, 32);
16985   //  AhiBlo = psllqi(AhiBlo, 32);
16986   //  return AloBlo + AloBhi + AhiBlo;
16987
16988   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
16989   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
16990
16991   SDValue AhiBlo = Ahi;
16992   SDValue AloBhi = Bhi;
16993   // Bit cast to 32-bit vectors for MULUDQ
16994   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
16995                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
16996   A = DAG.getBitcast(MulVT, A);
16997   B = DAG.getBitcast(MulVT, B);
16998   Ahi = DAG.getBitcast(MulVT, Ahi);
16999   Bhi = DAG.getBitcast(MulVT, Bhi);
17000
17001   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
17002   // After shifting right const values the result may be all-zero.
17003   if (!ISD::isBuildVectorAllZeros(Ahi.getNode())) {
17004     AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
17005     AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
17006   }
17007   if (!ISD::isBuildVectorAllZeros(Bhi.getNode())) {
17008     AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
17009     AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
17010   }
17011
17012   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
17013   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
17014 }
17015
17016 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
17017   assert(Subtarget->isTargetWin64() && "Unexpected target");
17018   EVT VT = Op.getValueType();
17019   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
17020          "Unexpected return type for lowering");
17021
17022   RTLIB::Libcall LC;
17023   bool isSigned;
17024   switch (Op->getOpcode()) {
17025   default: llvm_unreachable("Unexpected request for libcall!");
17026   case ISD::SDIV:      isSigned = true;  LC = RTLIB::SDIV_I128;    break;
17027   case ISD::UDIV:      isSigned = false; LC = RTLIB::UDIV_I128;    break;
17028   case ISD::SREM:      isSigned = true;  LC = RTLIB::SREM_I128;    break;
17029   case ISD::UREM:      isSigned = false; LC = RTLIB::UREM_I128;    break;
17030   case ISD::SDIVREM:   isSigned = true;  LC = RTLIB::SDIVREM_I128; break;
17031   case ISD::UDIVREM:   isSigned = false; LC = RTLIB::UDIVREM_I128; break;
17032   }
17033
17034   SDLoc dl(Op);
17035   SDValue InChain = DAG.getEntryNode();
17036
17037   TargetLowering::ArgListTy Args;
17038   TargetLowering::ArgListEntry Entry;
17039   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
17040     EVT ArgVT = Op->getOperand(i).getValueType();
17041     assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
17042            "Unexpected argument type for lowering");
17043     SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
17044     Entry.Node = StackPtr;
17045     InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
17046                            false, false, 16);
17047     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
17048     Entry.Ty = PointerType::get(ArgTy,0);
17049     Entry.isSExt = false;
17050     Entry.isZExt = false;
17051     Args.push_back(Entry);
17052   }
17053
17054   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
17055                                          getPointerTy(DAG.getDataLayout()));
17056
17057   TargetLowering::CallLoweringInfo CLI(DAG);
17058   CLI.setDebugLoc(dl).setChain(InChain)
17059     .setCallee(getLibcallCallingConv(LC),
17060                static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
17061                Callee, std::move(Args), 0)
17062     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
17063
17064   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
17065   return DAG.getBitcast(VT, CallInfo.first);
17066 }
17067
17068 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
17069                              SelectionDAG &DAG) {
17070   SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
17071   EVT VT = Op0.getValueType();
17072   SDLoc dl(Op);
17073
17074   assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
17075          (VT == MVT::v8i32 && Subtarget->hasInt256()));
17076
17077   // PMULxD operations multiply each even value (starting at 0) of LHS with
17078   // the related value of RHS and produce a widen result.
17079   // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
17080   // => <2 x i64> <ae|cg>
17081   //
17082   // In other word, to have all the results, we need to perform two PMULxD:
17083   // 1. one with the even values.
17084   // 2. one with the odd values.
17085   // To achieve #2, with need to place the odd values at an even position.
17086   //
17087   // Place the odd value at an even position (basically, shift all values 1
17088   // step to the left):
17089   const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
17090   // <a|b|c|d> => <b|undef|d|undef>
17091   SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
17092   // <e|f|g|h> => <f|undef|h|undef>
17093   SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
17094
17095   // Emit two multiplies, one for the lower 2 ints and one for the higher 2
17096   // ints.
17097   MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
17098   bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
17099   unsigned Opcode =
17100       (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
17101   // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
17102   // => <2 x i64> <ae|cg>
17103   SDValue Mul1 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
17104   // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
17105   // => <2 x i64> <bf|dh>
17106   SDValue Mul2 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
17107
17108   // Shuffle it back into the right order.
17109   SDValue Highs, Lows;
17110   if (VT == MVT::v8i32) {
17111     const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
17112     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
17113     const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
17114     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
17115   } else {
17116     const int HighMask[] = {1, 5, 3, 7};
17117     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
17118     const int LowMask[] = {0, 4, 2, 6};
17119     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
17120   }
17121
17122   // If we have a signed multiply but no PMULDQ fix up the high parts of a
17123   // unsigned multiply.
17124   if (IsSigned && !Subtarget->hasSSE41()) {
17125     SDValue ShAmt = DAG.getConstant(
17126         31, dl,
17127         DAG.getTargetLoweringInfo().getShiftAmountTy(VT, DAG.getDataLayout()));
17128     SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
17129                              DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
17130     SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
17131                              DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
17132
17133     SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
17134     Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
17135   }
17136
17137   // The first result of MUL_LOHI is actually the low value, followed by the
17138   // high value.
17139   SDValue Ops[] = {Lows, Highs};
17140   return DAG.getMergeValues(Ops, dl);
17141 }
17142
17143 // Return true if the required (according to Opcode) shift-imm form is natively
17144 // supported by the Subtarget
17145 static bool SupportedVectorShiftWithImm(MVT VT, const X86Subtarget *Subtarget,
17146                                         unsigned Opcode) {
17147   if (VT.getScalarSizeInBits() < 16)
17148     return false;
17149
17150   if (VT.is512BitVector() &&
17151       (VT.getScalarSizeInBits() > 16 || Subtarget->hasBWI()))
17152     return true;
17153
17154   bool LShift = VT.is128BitVector() ||
17155     (VT.is256BitVector() && Subtarget->hasInt256());
17156
17157   bool AShift = LShift && (Subtarget->hasVLX() ||
17158     (VT != MVT::v2i64 && VT != MVT::v4i64));
17159   return (Opcode == ISD::SRA) ? AShift : LShift;
17160 }
17161
17162 // The shift amount is a variable, but it is the same for all vector lanes.
17163 // These instructions are defined together with shift-immediate.
17164 static
17165 bool SupportedVectorShiftWithBaseAmnt(MVT VT, const X86Subtarget *Subtarget,
17166                                       unsigned Opcode) {
17167   return SupportedVectorShiftWithImm(VT, Subtarget, Opcode);
17168 }
17169
17170 // Return true if the required (according to Opcode) variable-shift form is
17171 // natively supported by the Subtarget
17172 static bool SupportedVectorVarShift(MVT VT, const X86Subtarget *Subtarget,
17173                                     unsigned Opcode) {
17174
17175   if (!Subtarget->hasInt256() || VT.getScalarSizeInBits() < 16)
17176     return false;
17177
17178   // vXi16 supported only on AVX-512, BWI
17179   if (VT.getScalarSizeInBits() == 16 && !Subtarget->hasBWI())
17180     return false;
17181
17182   if (VT.is512BitVector() || Subtarget->hasVLX())
17183     return true;
17184
17185   bool LShift = VT.is128BitVector() || VT.is256BitVector();
17186   bool AShift = LShift &&  VT != MVT::v2i64 && VT != MVT::v4i64;
17187   return (Opcode == ISD::SRA) ? AShift : LShift;
17188 }
17189
17190 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
17191                                          const X86Subtarget *Subtarget) {
17192   MVT VT = Op.getSimpleValueType();
17193   SDLoc dl(Op);
17194   SDValue R = Op.getOperand(0);
17195   SDValue Amt = Op.getOperand(1);
17196
17197   unsigned X86Opc = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
17198     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
17199
17200   auto ArithmeticShiftRight64 = [&](uint64_t ShiftAmt) {
17201     assert((VT == MVT::v2i64 || VT == MVT::v4i64) && "Unexpected SRA type");
17202     MVT ExVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() * 2);
17203     SDValue Ex = DAG.getBitcast(ExVT, R);
17204
17205     if (ShiftAmt >= 32) {
17206       // Splat sign to upper i32 dst, and SRA upper i32 src to lower i32.
17207       SDValue Upper =
17208           getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex, 31, DAG);
17209       SDValue Lower = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
17210                                                  ShiftAmt - 32, DAG);
17211       if (VT == MVT::v2i64)
17212         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {5, 1, 7, 3});
17213       if (VT == MVT::v4i64)
17214         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
17215                                   {9, 1, 11, 3, 13, 5, 15, 7});
17216     } else {
17217       // SRA upper i32, SHL whole i64 and select lower i32.
17218       SDValue Upper = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
17219                                                  ShiftAmt, DAG);
17220       SDValue Lower =
17221           getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt, DAG);
17222       Lower = DAG.getBitcast(ExVT, Lower);
17223       if (VT == MVT::v2i64)
17224         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {4, 1, 6, 3});
17225       if (VT == MVT::v4i64)
17226         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
17227                                   {8, 1, 10, 3, 12, 5, 14, 7});
17228     }
17229     return DAG.getBitcast(VT, Ex);
17230   };
17231
17232   // Optimize shl/srl/sra with constant shift amount.
17233   if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
17234     if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
17235       uint64_t ShiftAmt = ShiftConst->getZExtValue();
17236
17237       if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
17238         return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
17239
17240       // i64 SRA needs to be performed as partial shifts.
17241       if ((VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
17242           Op.getOpcode() == ISD::SRA)
17243         return ArithmeticShiftRight64(ShiftAmt);
17244
17245       if (VT == MVT::v16i8 || (Subtarget->hasInt256() && VT == MVT::v32i8)) {
17246         unsigned NumElts = VT.getVectorNumElements();
17247         MVT ShiftVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
17248
17249         if (Op.getOpcode() == ISD::SHL) {
17250           // Simple i8 add case
17251           if (ShiftAmt == 1)
17252             return DAG.getNode(ISD::ADD, dl, VT, R, R);
17253
17254           // Make a large shift.
17255           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ShiftVT,
17256                                                    R, ShiftAmt, DAG);
17257           SHL = DAG.getBitcast(VT, SHL);
17258           // Zero out the rightmost bits.
17259           SmallVector<SDValue, 32> V(
17260               NumElts, DAG.getConstant(uint8_t(-1U << ShiftAmt), dl, MVT::i8));
17261           return DAG.getNode(ISD::AND, dl, VT, SHL,
17262                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
17263         }
17264         if (Op.getOpcode() == ISD::SRL) {
17265           // Make a large shift.
17266           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ShiftVT,
17267                                                    R, ShiftAmt, DAG);
17268           SRL = DAG.getBitcast(VT, SRL);
17269           // Zero out the leftmost bits.
17270           SmallVector<SDValue, 32> V(
17271               NumElts, DAG.getConstant(uint8_t(-1U) >> ShiftAmt, dl, MVT::i8));
17272           return DAG.getNode(ISD::AND, dl, VT, SRL,
17273                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
17274         }
17275         if (Op.getOpcode() == ISD::SRA) {
17276           if (ShiftAmt == 7) {
17277             // R s>> 7  ===  R s< 0
17278             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
17279             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
17280           }
17281
17282           // R s>> a === ((R u>> a) ^ m) - m
17283           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
17284           SmallVector<SDValue, 32> V(NumElts,
17285                                      DAG.getConstant(128 >> ShiftAmt, dl,
17286                                                      MVT::i8));
17287           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
17288           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
17289           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
17290           return Res;
17291         }
17292         llvm_unreachable("Unknown shift opcode.");
17293       }
17294     }
17295   }
17296
17297   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
17298   if (!Subtarget->is64Bit() &&
17299       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
17300       Amt.getOpcode() == ISD::BITCAST &&
17301       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
17302     Amt = Amt.getOperand(0);
17303     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
17304                      VT.getVectorNumElements();
17305     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
17306     uint64_t ShiftAmt = 0;
17307     for (unsigned i = 0; i != Ratio; ++i) {
17308       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
17309       if (!C)
17310         return SDValue();
17311       // 6 == Log2(64)
17312       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
17313     }
17314     // Check remaining shift amounts.
17315     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
17316       uint64_t ShAmt = 0;
17317       for (unsigned j = 0; j != Ratio; ++j) {
17318         ConstantSDNode *C =
17319           dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
17320         if (!C)
17321           return SDValue();
17322         // 6 == Log2(64)
17323         ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
17324       }
17325       if (ShAmt != ShiftAmt)
17326         return SDValue();
17327     }
17328
17329     if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
17330       return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
17331
17332     if (Op.getOpcode() == ISD::SRA)
17333       return ArithmeticShiftRight64(ShiftAmt);
17334   }
17335
17336   return SDValue();
17337 }
17338
17339 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
17340                                         const X86Subtarget* Subtarget) {
17341   MVT VT = Op.getSimpleValueType();
17342   SDLoc dl(Op);
17343   SDValue R = Op.getOperand(0);
17344   SDValue Amt = Op.getOperand(1);
17345
17346   unsigned X86OpcI = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
17347     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
17348
17349   unsigned X86OpcV = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHL :
17350     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRL : X86ISD::VSRA;
17351
17352   if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode())) {
17353     SDValue BaseShAmt;
17354     EVT EltVT = VT.getVectorElementType();
17355
17356     if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Amt)) {
17357       // Check if this build_vector node is doing a splat.
17358       // If so, then set BaseShAmt equal to the splat value.
17359       BaseShAmt = BV->getSplatValue();
17360       if (BaseShAmt && BaseShAmt.getOpcode() == ISD::UNDEF)
17361         BaseShAmt = SDValue();
17362     } else {
17363       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
17364         Amt = Amt.getOperand(0);
17365
17366       ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt);
17367       if (SVN && SVN->isSplat()) {
17368         unsigned SplatIdx = (unsigned)SVN->getSplatIndex();
17369         SDValue InVec = Amt.getOperand(0);
17370         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
17371           assert((SplatIdx < InVec.getValueType().getVectorNumElements()) &&
17372                  "Unexpected shuffle index found!");
17373           BaseShAmt = InVec.getOperand(SplatIdx);
17374         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
17375            if (ConstantSDNode *C =
17376                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
17377              if (C->getZExtValue() == SplatIdx)
17378                BaseShAmt = InVec.getOperand(1);
17379            }
17380         }
17381
17382         if (!BaseShAmt)
17383           // Avoid introducing an extract element from a shuffle.
17384           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InVec,
17385                                   DAG.getIntPtrConstant(SplatIdx, dl));
17386       }
17387     }
17388
17389     if (BaseShAmt.getNode()) {
17390       assert(EltVT.bitsLE(MVT::i64) && "Unexpected element type!");
17391       if (EltVT != MVT::i64 && EltVT.bitsGT(MVT::i32))
17392         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, BaseShAmt);
17393       else if (EltVT.bitsLT(MVT::i32))
17394         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
17395
17396       return getTargetVShiftNode(X86OpcI, dl, VT, R, BaseShAmt, DAG);
17397     }
17398   }
17399
17400   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
17401   if (!Subtarget->is64Bit() && VT == MVT::v2i64  &&
17402       Amt.getOpcode() == ISD::BITCAST &&
17403       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
17404     Amt = Amt.getOperand(0);
17405     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
17406                      VT.getVectorNumElements();
17407     std::vector<SDValue> Vals(Ratio);
17408     for (unsigned i = 0; i != Ratio; ++i)
17409       Vals[i] = Amt.getOperand(i);
17410     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
17411       for (unsigned j = 0; j != Ratio; ++j)
17412         if (Vals[j] != Amt.getOperand(i + j))
17413           return SDValue();
17414     }
17415
17416     if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode()))
17417       return DAG.getNode(X86OpcV, dl, VT, R, Op.getOperand(1));
17418   }
17419   return SDValue();
17420 }
17421
17422 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
17423                           SelectionDAG &DAG) {
17424   MVT VT = Op.getSimpleValueType();
17425   SDLoc dl(Op);
17426   SDValue R = Op.getOperand(0);
17427   SDValue Amt = Op.getOperand(1);
17428
17429   assert(VT.isVector() && "Custom lowering only for vector shifts!");
17430   assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
17431
17432   if (SDValue V = LowerScalarImmediateShift(Op, DAG, Subtarget))
17433     return V;
17434
17435   if (SDValue V = LowerScalarVariableShift(Op, DAG, Subtarget))
17436       return V;
17437
17438   if (SupportedVectorVarShift(VT, Subtarget, Op.getOpcode()))
17439     return Op;
17440
17441   // 2i64 vector logical shifts can efficiently avoid scalarization - do the
17442   // shifts per-lane and then shuffle the partial results back together.
17443   if (VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) {
17444     // Splat the shift amounts so the scalar shifts above will catch it.
17445     SDValue Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {0, 0});
17446     SDValue Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {1, 1});
17447     SDValue R0 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt0);
17448     SDValue R1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt1);
17449     return DAG.getVectorShuffle(VT, dl, R0, R1, {0, 3});
17450   }
17451
17452   // If possible, lower this packed shift into a vector multiply instead of
17453   // expanding it into a sequence of scalar shifts.
17454   // Do this only if the vector shift count is a constant build_vector.
17455   if (Op.getOpcode() == ISD::SHL &&
17456       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
17457        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
17458       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
17459     SmallVector<SDValue, 8> Elts;
17460     EVT SVT = VT.getScalarType();
17461     unsigned SVTBits = SVT.getSizeInBits();
17462     const APInt &One = APInt(SVTBits, 1);
17463     unsigned NumElems = VT.getVectorNumElements();
17464
17465     for (unsigned i=0; i !=NumElems; ++i) {
17466       SDValue Op = Amt->getOperand(i);
17467       if (Op->getOpcode() == ISD::UNDEF) {
17468         Elts.push_back(Op);
17469         continue;
17470       }
17471
17472       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
17473       const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
17474       uint64_t ShAmt = C.getZExtValue();
17475       if (ShAmt >= SVTBits) {
17476         Elts.push_back(DAG.getUNDEF(SVT));
17477         continue;
17478       }
17479       Elts.push_back(DAG.getConstant(One.shl(ShAmt), dl, SVT));
17480     }
17481     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
17482     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
17483   }
17484
17485   // Lower SHL with variable shift amount.
17486   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
17487     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, dl, VT));
17488
17489     Op = DAG.getNode(ISD::ADD, dl, VT, Op,
17490                      DAG.getConstant(0x3f800000U, dl, VT));
17491     Op = DAG.getBitcast(MVT::v4f32, Op);
17492     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
17493     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
17494   }
17495
17496   // If possible, lower this shift as a sequence of two shifts by
17497   // constant plus a MOVSS/MOVSD instead of scalarizing it.
17498   // Example:
17499   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
17500   //
17501   // Could be rewritten as:
17502   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
17503   //
17504   // The advantage is that the two shifts from the example would be
17505   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
17506   // the vector shift into four scalar shifts plus four pairs of vector
17507   // insert/extract.
17508   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
17509       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
17510     unsigned TargetOpcode = X86ISD::MOVSS;
17511     bool CanBeSimplified;
17512     // The splat value for the first packed shift (the 'X' from the example).
17513     SDValue Amt1 = Amt->getOperand(0);
17514     // The splat value for the second packed shift (the 'Y' from the example).
17515     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
17516                                         Amt->getOperand(2);
17517
17518     // See if it is possible to replace this node with a sequence of
17519     // two shifts followed by a MOVSS/MOVSD
17520     if (VT == MVT::v4i32) {
17521       // Check if it is legal to use a MOVSS.
17522       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
17523                         Amt2 == Amt->getOperand(3);
17524       if (!CanBeSimplified) {
17525         // Otherwise, check if we can still simplify this node using a MOVSD.
17526         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
17527                           Amt->getOperand(2) == Amt->getOperand(3);
17528         TargetOpcode = X86ISD::MOVSD;
17529         Amt2 = Amt->getOperand(2);
17530       }
17531     } else {
17532       // Do similar checks for the case where the machine value type
17533       // is MVT::v8i16.
17534       CanBeSimplified = Amt1 == Amt->getOperand(1);
17535       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
17536         CanBeSimplified = Amt2 == Amt->getOperand(i);
17537
17538       if (!CanBeSimplified) {
17539         TargetOpcode = X86ISD::MOVSD;
17540         CanBeSimplified = true;
17541         Amt2 = Amt->getOperand(4);
17542         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
17543           CanBeSimplified = Amt1 == Amt->getOperand(i);
17544         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
17545           CanBeSimplified = Amt2 == Amt->getOperand(j);
17546       }
17547     }
17548
17549     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
17550         isa<ConstantSDNode>(Amt2)) {
17551       // Replace this node with two shifts followed by a MOVSS/MOVSD.
17552       EVT CastVT = MVT::v4i32;
17553       SDValue Splat1 =
17554         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), dl, VT);
17555       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
17556       SDValue Splat2 =
17557         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), dl, VT);
17558       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
17559       if (TargetOpcode == X86ISD::MOVSD)
17560         CastVT = MVT::v2i64;
17561       SDValue BitCast1 = DAG.getBitcast(CastVT, Shift1);
17562       SDValue BitCast2 = DAG.getBitcast(CastVT, Shift2);
17563       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
17564                                             BitCast1, DAG);
17565       return DAG.getBitcast(VT, Result);
17566     }
17567   }
17568
17569   // v4i32 Non Uniform Shifts.
17570   // If the shift amount is constant we can shift each lane using the SSE2
17571   // immediate shifts, else we need to zero-extend each lane to the lower i64
17572   // and shift using the SSE2 variable shifts.
17573   // The separate results can then be blended together.
17574   if (VT == MVT::v4i32) {
17575     unsigned Opc = Op.getOpcode();
17576     SDValue Amt0, Amt1, Amt2, Amt3;
17577     if (ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
17578       Amt0 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {0, 0, 0, 0});
17579       Amt1 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {1, 1, 1, 1});
17580       Amt2 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {2, 2, 2, 2});
17581       Amt3 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {3, 3, 3, 3});
17582     } else {
17583       // ISD::SHL is handled above but we include it here for completeness.
17584       switch (Opc) {
17585       default:
17586         llvm_unreachable("Unknown target vector shift node");
17587       case ISD::SHL:
17588         Opc = X86ISD::VSHL;
17589         break;
17590       case ISD::SRL:
17591         Opc = X86ISD::VSRL;
17592         break;
17593       case ISD::SRA:
17594         Opc = X86ISD::VSRA;
17595         break;
17596       }
17597       // The SSE2 shifts use the lower i64 as the same shift amount for
17598       // all lanes and the upper i64 is ignored. These shuffle masks
17599       // optimally zero-extend each lanes on SSE2/SSE41/AVX targets.
17600       SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
17601       Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Z, {0, 4, -1, -1});
17602       Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Z, {1, 5, -1, -1});
17603       Amt2 = DAG.getVectorShuffle(VT, dl, Amt, Z, {2, 6, -1, -1});
17604       Amt3 = DAG.getVectorShuffle(VT, dl, Amt, Z, {3, 7, -1, -1});
17605     }
17606
17607     SDValue R0 = DAG.getNode(Opc, dl, VT, R, Amt0);
17608     SDValue R1 = DAG.getNode(Opc, dl, VT, R, Amt1);
17609     SDValue R2 = DAG.getNode(Opc, dl, VT, R, Amt2);
17610     SDValue R3 = DAG.getNode(Opc, dl, VT, R, Amt3);
17611     SDValue R02 = DAG.getVectorShuffle(VT, dl, R0, R2, {0, -1, 6, -1});
17612     SDValue R13 = DAG.getVectorShuffle(VT, dl, R1, R3, {-1, 1, -1, 7});
17613     return DAG.getVectorShuffle(VT, dl, R02, R13, {0, 5, 2, 7});
17614   }
17615
17616   if (VT == MVT::v16i8 || (VT == MVT::v32i8 && Subtarget->hasInt256())) {
17617     MVT ExtVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements() / 2);
17618     unsigned ShiftOpcode = Op->getOpcode();
17619
17620     auto SignBitSelect = [&](MVT SelVT, SDValue Sel, SDValue V0, SDValue V1) {
17621       // On SSE41 targets we make use of the fact that VSELECT lowers
17622       // to PBLENDVB which selects bytes based just on the sign bit.
17623       if (Subtarget->hasSSE41()) {
17624         V0 = DAG.getBitcast(VT, V0);
17625         V1 = DAG.getBitcast(VT, V1);
17626         Sel = DAG.getBitcast(VT, Sel);
17627         return DAG.getBitcast(SelVT,
17628                               DAG.getNode(ISD::VSELECT, dl, VT, Sel, V0, V1));
17629       }
17630       // On pre-SSE41 targets we test for the sign bit by comparing to
17631       // zero - a negative value will set all bits of the lanes to true
17632       // and VSELECT uses that in its OR(AND(V0,C),AND(V1,~C)) lowering.
17633       SDValue Z = getZeroVector(SelVT, Subtarget, DAG, dl);
17634       SDValue C = DAG.getNode(X86ISD::PCMPGT, dl, SelVT, Z, Sel);
17635       return DAG.getNode(ISD::VSELECT, dl, SelVT, C, V0, V1);
17636     };
17637
17638     // Turn 'a' into a mask suitable for VSELECT: a = a << 5;
17639     // We can safely do this using i16 shifts as we're only interested in
17640     // the 3 lower bits of each byte.
17641     Amt = DAG.getBitcast(ExtVT, Amt);
17642     Amt = DAG.getNode(ISD::SHL, dl, ExtVT, Amt, DAG.getConstant(5, dl, ExtVT));
17643     Amt = DAG.getBitcast(VT, Amt);
17644
17645     if (Op->getOpcode() == ISD::SHL || Op->getOpcode() == ISD::SRL) {
17646       // r = VSELECT(r, shift(r, 4), a);
17647       SDValue M =
17648           DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
17649       R = SignBitSelect(VT, Amt, M, R);
17650
17651       // a += a
17652       Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17653
17654       // r = VSELECT(r, shift(r, 2), a);
17655       M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
17656       R = SignBitSelect(VT, Amt, M, R);
17657
17658       // a += a
17659       Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17660
17661       // return VSELECT(r, shift(r, 1), a);
17662       M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
17663       R = SignBitSelect(VT, Amt, M, R);
17664       return R;
17665     }
17666
17667     if (Op->getOpcode() == ISD::SRA) {
17668       // For SRA we need to unpack each byte to the higher byte of a i16 vector
17669       // so we can correctly sign extend. We don't care what happens to the
17670       // lower byte.
17671       SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), Amt);
17672       SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), Amt);
17673       SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), R);
17674       SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), R);
17675       ALo = DAG.getBitcast(ExtVT, ALo);
17676       AHi = DAG.getBitcast(ExtVT, AHi);
17677       RLo = DAG.getBitcast(ExtVT, RLo);
17678       RHi = DAG.getBitcast(ExtVT, RHi);
17679
17680       // r = VSELECT(r, shift(r, 4), a);
17681       SDValue MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
17682                                 DAG.getConstant(4, dl, ExtVT));
17683       SDValue MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
17684                                 DAG.getConstant(4, dl, ExtVT));
17685       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
17686       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
17687
17688       // a += a
17689       ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
17690       AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
17691
17692       // r = VSELECT(r, shift(r, 2), a);
17693       MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
17694                         DAG.getConstant(2, dl, ExtVT));
17695       MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
17696                         DAG.getConstant(2, dl, ExtVT));
17697       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
17698       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
17699
17700       // a += a
17701       ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
17702       AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
17703
17704       // r = VSELECT(r, shift(r, 1), a);
17705       MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
17706                         DAG.getConstant(1, dl, ExtVT));
17707       MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
17708                         DAG.getConstant(1, dl, ExtVT));
17709       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
17710       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
17711
17712       // Logical shift the result back to the lower byte, leaving a zero upper
17713       // byte
17714       // meaning that we can safely pack with PACKUSWB.
17715       RLo =
17716           DAG.getNode(ISD::SRL, dl, ExtVT, RLo, DAG.getConstant(8, dl, ExtVT));
17717       RHi =
17718           DAG.getNode(ISD::SRL, dl, ExtVT, RHi, DAG.getConstant(8, dl, ExtVT));
17719       return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
17720     }
17721   }
17722
17723   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
17724   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
17725   // solution better.
17726   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
17727     MVT ExtVT = MVT::v8i32;
17728     unsigned ExtOpc =
17729         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
17730     R = DAG.getNode(ExtOpc, dl, ExtVT, R);
17731     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, ExtVT, Amt);
17732     return DAG.getNode(ISD::TRUNCATE, dl, VT,
17733                        DAG.getNode(Op.getOpcode(), dl, ExtVT, R, Amt));
17734   }
17735
17736   if (Subtarget->hasInt256() && VT == MVT::v16i16) {
17737     MVT ExtVT = MVT::v8i32;
17738     SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
17739     SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, Amt, Z);
17740     SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, Amt, Z);
17741     SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, R, R);
17742     SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, R, R);
17743     ALo = DAG.getBitcast(ExtVT, ALo);
17744     AHi = DAG.getBitcast(ExtVT, AHi);
17745     RLo = DAG.getBitcast(ExtVT, RLo);
17746     RHi = DAG.getBitcast(ExtVT, RHi);
17747     SDValue Lo = DAG.getNode(Op.getOpcode(), dl, ExtVT, RLo, ALo);
17748     SDValue Hi = DAG.getNode(Op.getOpcode(), dl, ExtVT, RHi, AHi);
17749     Lo = DAG.getNode(ISD::SRL, dl, ExtVT, Lo, DAG.getConstant(16, dl, ExtVT));
17750     Hi = DAG.getNode(ISD::SRL, dl, ExtVT, Hi, DAG.getConstant(16, dl, ExtVT));
17751     return DAG.getNode(X86ISD::PACKUS, dl, VT, Lo, Hi);
17752   }
17753
17754   if (VT == MVT::v8i16) {
17755     unsigned ShiftOpcode = Op->getOpcode();
17756
17757     auto SignBitSelect = [&](SDValue Sel, SDValue V0, SDValue V1) {
17758       // On SSE41 targets we make use of the fact that VSELECT lowers
17759       // to PBLENDVB which selects bytes based just on the sign bit.
17760       if (Subtarget->hasSSE41()) {
17761         MVT ExtVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() * 2);
17762         V0 = DAG.getBitcast(ExtVT, V0);
17763         V1 = DAG.getBitcast(ExtVT, V1);
17764         Sel = DAG.getBitcast(ExtVT, Sel);
17765         return DAG.getBitcast(
17766             VT, DAG.getNode(ISD::VSELECT, dl, ExtVT, Sel, V0, V1));
17767       }
17768       // On pre-SSE41 targets we splat the sign bit - a negative value will
17769       // set all bits of the lanes to true and VSELECT uses that in
17770       // its OR(AND(V0,C),AND(V1,~C)) lowering.
17771       SDValue C =
17772           DAG.getNode(ISD::SRA, dl, VT, Sel, DAG.getConstant(15, dl, VT));
17773       return DAG.getNode(ISD::VSELECT, dl, VT, C, V0, V1);
17774     };
17775
17776     // Turn 'a' into a mask suitable for VSELECT: a = a << 12;
17777     if (Subtarget->hasSSE41()) {
17778       // On SSE41 targets we need to replicate the shift mask in both
17779       // bytes for PBLENDVB.
17780       Amt = DAG.getNode(
17781           ISD::OR, dl, VT,
17782           DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(4, dl, VT)),
17783           DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT)));
17784     } else {
17785       Amt = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT));
17786     }
17787
17788     // r = VSELECT(r, shift(r, 8), a);
17789     SDValue M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(8, dl, VT));
17790     R = SignBitSelect(Amt, M, R);
17791
17792     // a += a
17793     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17794
17795     // r = VSELECT(r, shift(r, 4), a);
17796     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
17797     R = SignBitSelect(Amt, M, R);
17798
17799     // a += a
17800     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17801
17802     // r = VSELECT(r, shift(r, 2), a);
17803     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
17804     R = SignBitSelect(Amt, M, R);
17805
17806     // a += a
17807     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17808
17809     // return VSELECT(r, shift(r, 1), a);
17810     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
17811     R = SignBitSelect(Amt, M, R);
17812     return R;
17813   }
17814
17815   // Decompose 256-bit shifts into smaller 128-bit shifts.
17816   if (VT.is256BitVector()) {
17817     unsigned NumElems = VT.getVectorNumElements();
17818     MVT EltVT = VT.getVectorElementType();
17819     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
17820
17821     // Extract the two vectors
17822     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
17823     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
17824
17825     // Recreate the shift amount vectors
17826     SDValue Amt1, Amt2;
17827     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
17828       // Constant shift amount
17829       SmallVector<SDValue, 8> Ops(Amt->op_begin(), Amt->op_begin() + NumElems);
17830       ArrayRef<SDValue> Amt1Csts = makeArrayRef(Ops).slice(0, NumElems / 2);
17831       ArrayRef<SDValue> Amt2Csts = makeArrayRef(Ops).slice(NumElems / 2);
17832
17833       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
17834       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
17835     } else {
17836       // Variable shift amount
17837       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
17838       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
17839     }
17840
17841     // Issue new vector shifts for the smaller types
17842     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
17843     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
17844
17845     // Concatenate the result back
17846     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
17847   }
17848
17849   return SDValue();
17850 }
17851
17852 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
17853   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
17854   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
17855   // looks for this combo and may remove the "setcc" instruction if the "setcc"
17856   // has only one use.
17857   SDNode *N = Op.getNode();
17858   SDValue LHS = N->getOperand(0);
17859   SDValue RHS = N->getOperand(1);
17860   unsigned BaseOp = 0;
17861   unsigned Cond = 0;
17862   SDLoc DL(Op);
17863   switch (Op.getOpcode()) {
17864   default: llvm_unreachable("Unknown ovf instruction!");
17865   case ISD::SADDO:
17866     // A subtract of one will be selected as a INC. Note that INC doesn't
17867     // set CF, so we can't do this for UADDO.
17868     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
17869       if (C->isOne()) {
17870         BaseOp = X86ISD::INC;
17871         Cond = X86::COND_O;
17872         break;
17873       }
17874     BaseOp = X86ISD::ADD;
17875     Cond = X86::COND_O;
17876     break;
17877   case ISD::UADDO:
17878     BaseOp = X86ISD::ADD;
17879     Cond = X86::COND_B;
17880     break;
17881   case ISD::SSUBO:
17882     // A subtract of one will be selected as a DEC. Note that DEC doesn't
17883     // set CF, so we can't do this for USUBO.
17884     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
17885       if (C->isOne()) {
17886         BaseOp = X86ISD::DEC;
17887         Cond = X86::COND_O;
17888         break;
17889       }
17890     BaseOp = X86ISD::SUB;
17891     Cond = X86::COND_O;
17892     break;
17893   case ISD::USUBO:
17894     BaseOp = X86ISD::SUB;
17895     Cond = X86::COND_B;
17896     break;
17897   case ISD::SMULO:
17898     BaseOp = N->getValueType(0) == MVT::i8 ? X86ISD::SMUL8 : X86ISD::SMUL;
17899     Cond = X86::COND_O;
17900     break;
17901   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
17902     if (N->getValueType(0) == MVT::i8) {
17903       BaseOp = X86ISD::UMUL8;
17904       Cond = X86::COND_O;
17905       break;
17906     }
17907     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
17908                                  MVT::i32);
17909     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
17910
17911     SDValue SetCC =
17912       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
17913                   DAG.getConstant(X86::COND_O, DL, MVT::i32),
17914                   SDValue(Sum.getNode(), 2));
17915
17916     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
17917   }
17918   }
17919
17920   // Also sets EFLAGS.
17921   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
17922   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
17923
17924   SDValue SetCC =
17925     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
17926                 DAG.getConstant(Cond, DL, MVT::i32),
17927                 SDValue(Sum.getNode(), 1));
17928
17929   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
17930 }
17931
17932 /// Returns true if the operand type is exactly twice the native width, and
17933 /// the corresponding cmpxchg8b or cmpxchg16b instruction is available.
17934 /// Used to know whether to use cmpxchg8/16b when expanding atomic operations
17935 /// (otherwise we leave them alone to become __sync_fetch_and_... calls).
17936 bool X86TargetLowering::needsCmpXchgNb(const Type *MemType) const {
17937   unsigned OpWidth = MemType->getPrimitiveSizeInBits();
17938
17939   if (OpWidth == 64)
17940     return !Subtarget->is64Bit(); // FIXME this should be Subtarget.hasCmpxchg8b
17941   else if (OpWidth == 128)
17942     return Subtarget->hasCmpxchg16b();
17943   else
17944     return false;
17945 }
17946
17947 bool X86TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
17948   return needsCmpXchgNb(SI->getValueOperand()->getType());
17949 }
17950
17951 // Note: this turns large loads into lock cmpxchg8b/16b.
17952 // FIXME: On 32 bits x86, fild/movq might be faster than lock cmpxchg8b.
17953 bool X86TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
17954   auto PTy = cast<PointerType>(LI->getPointerOperand()->getType());
17955   return needsCmpXchgNb(PTy->getElementType());
17956 }
17957
17958 TargetLoweringBase::AtomicRMWExpansionKind
17959 X86TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
17960   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
17961   const Type *MemType = AI->getType();
17962
17963   // If the operand is too big, we must see if cmpxchg8/16b is available
17964   // and default to library calls otherwise.
17965   if (MemType->getPrimitiveSizeInBits() > NativeWidth) {
17966     return needsCmpXchgNb(MemType) ? AtomicRMWExpansionKind::CmpXChg
17967                                    : AtomicRMWExpansionKind::None;
17968   }
17969
17970   AtomicRMWInst::BinOp Op = AI->getOperation();
17971   switch (Op) {
17972   default:
17973     llvm_unreachable("Unknown atomic operation");
17974   case AtomicRMWInst::Xchg:
17975   case AtomicRMWInst::Add:
17976   case AtomicRMWInst::Sub:
17977     // It's better to use xadd, xsub or xchg for these in all cases.
17978     return AtomicRMWExpansionKind::None;
17979   case AtomicRMWInst::Or:
17980   case AtomicRMWInst::And:
17981   case AtomicRMWInst::Xor:
17982     // If the atomicrmw's result isn't actually used, we can just add a "lock"
17983     // prefix to a normal instruction for these operations.
17984     return !AI->use_empty() ? AtomicRMWExpansionKind::CmpXChg
17985                             : AtomicRMWExpansionKind::None;
17986   case AtomicRMWInst::Nand:
17987   case AtomicRMWInst::Max:
17988   case AtomicRMWInst::Min:
17989   case AtomicRMWInst::UMax:
17990   case AtomicRMWInst::UMin:
17991     // These always require a non-trivial set of data operations on x86. We must
17992     // use a cmpxchg loop.
17993     return AtomicRMWExpansionKind::CmpXChg;
17994   }
17995 }
17996
17997 static bool hasMFENCE(const X86Subtarget& Subtarget) {
17998   // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
17999   // no-sse2). There isn't any reason to disable it if the target processor
18000   // supports it.
18001   return Subtarget.hasSSE2() || Subtarget.is64Bit();
18002 }
18003
18004 LoadInst *
18005 X86TargetLowering::lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *AI) const {
18006   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
18007   const Type *MemType = AI->getType();
18008   // Accesses larger than the native width are turned into cmpxchg/libcalls, so
18009   // there is no benefit in turning such RMWs into loads, and it is actually
18010   // harmful as it introduces a mfence.
18011   if (MemType->getPrimitiveSizeInBits() > NativeWidth)
18012     return nullptr;
18013
18014   auto Builder = IRBuilder<>(AI);
18015   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
18016   auto SynchScope = AI->getSynchScope();
18017   // We must restrict the ordering to avoid generating loads with Release or
18018   // ReleaseAcquire orderings.
18019   auto Order = AtomicCmpXchgInst::getStrongestFailureOrdering(AI->getOrdering());
18020   auto Ptr = AI->getPointerOperand();
18021
18022   // Before the load we need a fence. Here is an example lifted from
18023   // http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf showing why a fence
18024   // is required:
18025   // Thread 0:
18026   //   x.store(1, relaxed);
18027   //   r1 = y.fetch_add(0, release);
18028   // Thread 1:
18029   //   y.fetch_add(42, acquire);
18030   //   r2 = x.load(relaxed);
18031   // r1 = r2 = 0 is impossible, but becomes possible if the idempotent rmw is
18032   // lowered to just a load without a fence. A mfence flushes the store buffer,
18033   // making the optimization clearly correct.
18034   // FIXME: it is required if isAtLeastRelease(Order) but it is not clear
18035   // otherwise, we might be able to be more agressive on relaxed idempotent
18036   // rmw. In practice, they do not look useful, so we don't try to be
18037   // especially clever.
18038   if (SynchScope == SingleThread)
18039     // FIXME: we could just insert an X86ISD::MEMBARRIER here, except we are at
18040     // the IR level, so we must wrap it in an intrinsic.
18041     return nullptr;
18042
18043   if (!hasMFENCE(*Subtarget))
18044     // FIXME: it might make sense to use a locked operation here but on a
18045     // different cache-line to prevent cache-line bouncing. In practice it
18046     // is probably a small win, and x86 processors without mfence are rare
18047     // enough that we do not bother.
18048     return nullptr;
18049
18050   Function *MFence =
18051       llvm::Intrinsic::getDeclaration(M, Intrinsic::x86_sse2_mfence);
18052   Builder.CreateCall(MFence, {});
18053
18054   // Finally we can emit the atomic load.
18055   LoadInst *Loaded = Builder.CreateAlignedLoad(Ptr,
18056           AI->getType()->getPrimitiveSizeInBits());
18057   Loaded->setAtomic(Order, SynchScope);
18058   AI->replaceAllUsesWith(Loaded);
18059   AI->eraseFromParent();
18060   return Loaded;
18061 }
18062
18063 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
18064                                  SelectionDAG &DAG) {
18065   SDLoc dl(Op);
18066   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
18067     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
18068   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
18069     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
18070
18071   // The only fence that needs an instruction is a sequentially-consistent
18072   // cross-thread fence.
18073   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
18074     if (hasMFENCE(*Subtarget))
18075       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
18076
18077     SDValue Chain = Op.getOperand(0);
18078     SDValue Zero = DAG.getConstant(0, dl, MVT::i32);
18079     SDValue Ops[] = {
18080       DAG.getRegister(X86::ESP, MVT::i32),     // Base
18081       DAG.getTargetConstant(1, dl, MVT::i8),   // Scale
18082       DAG.getRegister(0, MVT::i32),            // Index
18083       DAG.getTargetConstant(0, dl, MVT::i32),  // Disp
18084       DAG.getRegister(0, MVT::i32),            // Segment.
18085       Zero,
18086       Chain
18087     };
18088     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
18089     return SDValue(Res, 0);
18090   }
18091
18092   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
18093   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
18094 }
18095
18096 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
18097                              SelectionDAG &DAG) {
18098   MVT T = Op.getSimpleValueType();
18099   SDLoc DL(Op);
18100   unsigned Reg = 0;
18101   unsigned size = 0;
18102   switch(T.SimpleTy) {
18103   default: llvm_unreachable("Invalid value type!");
18104   case MVT::i8:  Reg = X86::AL;  size = 1; break;
18105   case MVT::i16: Reg = X86::AX;  size = 2; break;
18106   case MVT::i32: Reg = X86::EAX; size = 4; break;
18107   case MVT::i64:
18108     assert(Subtarget->is64Bit() && "Node not type legal!");
18109     Reg = X86::RAX; size = 8;
18110     break;
18111   }
18112   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
18113                                   Op.getOperand(2), SDValue());
18114   SDValue Ops[] = { cpIn.getValue(0),
18115                     Op.getOperand(1),
18116                     Op.getOperand(3),
18117                     DAG.getTargetConstant(size, DL, MVT::i8),
18118                     cpIn.getValue(1) };
18119   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
18120   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
18121   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
18122                                            Ops, T, MMO);
18123
18124   SDValue cpOut =
18125     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
18126   SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
18127                                       MVT::i32, cpOut.getValue(2));
18128   SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
18129                                 DAG.getConstant(X86::COND_E, DL, MVT::i8),
18130                                 EFLAGS);
18131
18132   DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
18133   DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
18134   DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
18135   return SDValue();
18136 }
18137
18138 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
18139                             SelectionDAG &DAG) {
18140   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
18141   MVT DstVT = Op.getSimpleValueType();
18142
18143   if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
18144     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
18145     if (DstVT != MVT::f64)
18146       // This conversion needs to be expanded.
18147       return SDValue();
18148
18149     SDValue InVec = Op->getOperand(0);
18150     SDLoc dl(Op);
18151     unsigned NumElts = SrcVT.getVectorNumElements();
18152     EVT SVT = SrcVT.getVectorElementType();
18153
18154     // Widen the vector in input in the case of MVT::v2i32.
18155     // Example: from MVT::v2i32 to MVT::v4i32.
18156     SmallVector<SDValue, 16> Elts;
18157     for (unsigned i = 0, e = NumElts; i != e; ++i)
18158       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
18159                                  DAG.getIntPtrConstant(i, dl)));
18160
18161     // Explicitly mark the extra elements as Undef.
18162     Elts.append(NumElts, DAG.getUNDEF(SVT));
18163
18164     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
18165     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
18166     SDValue ToV2F64 = DAG.getBitcast(MVT::v2f64, BV);
18167     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
18168                        DAG.getIntPtrConstant(0, dl));
18169   }
18170
18171   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
18172          Subtarget->hasMMX() && "Unexpected custom BITCAST");
18173   assert((DstVT == MVT::i64 ||
18174           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
18175          "Unexpected custom BITCAST");
18176   // i64 <=> MMX conversions are Legal.
18177   if (SrcVT==MVT::i64 && DstVT.isVector())
18178     return Op;
18179   if (DstVT==MVT::i64 && SrcVT.isVector())
18180     return Op;
18181   // MMX <=> MMX conversions are Legal.
18182   if (SrcVT.isVector() && DstVT.isVector())
18183     return Op;
18184   // All other conversions need to be expanded.
18185   return SDValue();
18186 }
18187
18188 /// Compute the horizontal sum of bytes in V for the elements of VT.
18189 ///
18190 /// Requires V to be a byte vector and VT to be an integer vector type with
18191 /// wider elements than V's type. The width of the elements of VT determines
18192 /// how many bytes of V are summed horizontally to produce each element of the
18193 /// result.
18194 static SDValue LowerHorizontalByteSum(SDValue V, MVT VT,
18195                                       const X86Subtarget *Subtarget,
18196                                       SelectionDAG &DAG) {
18197   SDLoc DL(V);
18198   MVT ByteVecVT = V.getSimpleValueType();
18199   MVT EltVT = VT.getVectorElementType();
18200   int NumElts = VT.getVectorNumElements();
18201   assert(ByteVecVT.getVectorElementType() == MVT::i8 &&
18202          "Expected value to have byte element type.");
18203   assert(EltVT != MVT::i8 &&
18204          "Horizontal byte sum only makes sense for wider elements!");
18205   unsigned VecSize = VT.getSizeInBits();
18206   assert(ByteVecVT.getSizeInBits() == VecSize && "Cannot change vector size!");
18207
18208   // PSADBW instruction horizontally add all bytes and leave the result in i64
18209   // chunks, thus directly computes the pop count for v2i64 and v4i64.
18210   if (EltVT == MVT::i64) {
18211     SDValue Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
18212     V = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT, V, Zeros);
18213     return DAG.getBitcast(VT, V);
18214   }
18215
18216   if (EltVT == MVT::i32) {
18217     // We unpack the low half and high half into i32s interleaved with zeros so
18218     // that we can use PSADBW to horizontally sum them. The most useful part of
18219     // this is that it lines up the results of two PSADBW instructions to be
18220     // two v2i64 vectors which concatenated are the 4 population counts. We can
18221     // then use PACKUSWB to shrink and concatenate them into a v4i32 again.
18222     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, DL);
18223     SDValue Low = DAG.getNode(X86ISD::UNPCKL, DL, VT, V, Zeros);
18224     SDValue High = DAG.getNode(X86ISD::UNPCKH, DL, VT, V, Zeros);
18225
18226     // Do the horizontal sums into two v2i64s.
18227     Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
18228     Low = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT,
18229                       DAG.getBitcast(ByteVecVT, Low), Zeros);
18230     High = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT,
18231                        DAG.getBitcast(ByteVecVT, High), Zeros);
18232
18233     // Merge them together.
18234     MVT ShortVecVT = MVT::getVectorVT(MVT::i16, VecSize / 16);
18235     V = DAG.getNode(X86ISD::PACKUS, DL, ByteVecVT,
18236                     DAG.getBitcast(ShortVecVT, Low),
18237                     DAG.getBitcast(ShortVecVT, High));
18238
18239     return DAG.getBitcast(VT, V);
18240   }
18241
18242   // The only element type left is i16.
18243   assert(EltVT == MVT::i16 && "Unknown how to handle type");
18244
18245   // To obtain pop count for each i16 element starting from the pop count for
18246   // i8 elements, shift the i16s left by 8, sum as i8s, and then shift as i16s
18247   // right by 8. It is important to shift as i16s as i8 vector shift isn't
18248   // directly supported.
18249   SmallVector<SDValue, 16> Shifters(NumElts, DAG.getConstant(8, DL, EltVT));
18250   SDValue Shifter = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters);
18251   SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, DAG.getBitcast(VT, V), Shifter);
18252   V = DAG.getNode(ISD::ADD, DL, ByteVecVT, DAG.getBitcast(ByteVecVT, Shl),
18253                   DAG.getBitcast(ByteVecVT, V));
18254   return DAG.getNode(ISD::SRL, DL, VT, DAG.getBitcast(VT, V), Shifter);
18255 }
18256
18257 static SDValue LowerVectorCTPOPInRegLUT(SDValue Op, SDLoc DL,
18258                                         const X86Subtarget *Subtarget,
18259                                         SelectionDAG &DAG) {
18260   MVT VT = Op.getSimpleValueType();
18261   MVT EltVT = VT.getVectorElementType();
18262   unsigned VecSize = VT.getSizeInBits();
18263
18264   // Implement a lookup table in register by using an algorithm based on:
18265   // http://wm.ite.pl/articles/sse-popcount.html
18266   //
18267   // The general idea is that every lower byte nibble in the input vector is an
18268   // index into a in-register pre-computed pop count table. We then split up the
18269   // input vector in two new ones: (1) a vector with only the shifted-right
18270   // higher nibbles for each byte and (2) a vector with the lower nibbles (and
18271   // masked out higher ones) for each byte. PSHUB is used separately with both
18272   // to index the in-register table. Next, both are added and the result is a
18273   // i8 vector where each element contains the pop count for input byte.
18274   //
18275   // To obtain the pop count for elements != i8, we follow up with the same
18276   // approach and use additional tricks as described below.
18277   //
18278   const int LUT[16] = {/* 0 */ 0, /* 1 */ 1, /* 2 */ 1, /* 3 */ 2,
18279                        /* 4 */ 1, /* 5 */ 2, /* 6 */ 2, /* 7 */ 3,
18280                        /* 8 */ 1, /* 9 */ 2, /* a */ 2, /* b */ 3,
18281                        /* c */ 2, /* d */ 3, /* e */ 3, /* f */ 4};
18282
18283   int NumByteElts = VecSize / 8;
18284   MVT ByteVecVT = MVT::getVectorVT(MVT::i8, NumByteElts);
18285   SDValue In = DAG.getBitcast(ByteVecVT, Op);
18286   SmallVector<SDValue, 16> LUTVec;
18287   for (int i = 0; i < NumByteElts; ++i)
18288     LUTVec.push_back(DAG.getConstant(LUT[i % 16], DL, MVT::i8));
18289   SDValue InRegLUT = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, LUTVec);
18290   SmallVector<SDValue, 16> Mask0F(NumByteElts,
18291                                   DAG.getConstant(0x0F, DL, MVT::i8));
18292   SDValue M0F = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Mask0F);
18293
18294   // High nibbles
18295   SmallVector<SDValue, 16> Four(NumByteElts, DAG.getConstant(4, DL, MVT::i8));
18296   SDValue FourV = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Four);
18297   SDValue HighNibbles = DAG.getNode(ISD::SRL, DL, ByteVecVT, In, FourV);
18298
18299   // Low nibbles
18300   SDValue LowNibbles = DAG.getNode(ISD::AND, DL, ByteVecVT, In, M0F);
18301
18302   // The input vector is used as the shuffle mask that index elements into the
18303   // LUT. After counting low and high nibbles, add the vector to obtain the
18304   // final pop count per i8 element.
18305   SDValue HighPopCnt =
18306       DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, HighNibbles);
18307   SDValue LowPopCnt =
18308       DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, LowNibbles);
18309   SDValue PopCnt = DAG.getNode(ISD::ADD, DL, ByteVecVT, HighPopCnt, LowPopCnt);
18310
18311   if (EltVT == MVT::i8)
18312     return PopCnt;
18313
18314   return LowerHorizontalByteSum(PopCnt, VT, Subtarget, DAG);
18315 }
18316
18317 static SDValue LowerVectorCTPOPBitmath(SDValue Op, SDLoc DL,
18318                                        const X86Subtarget *Subtarget,
18319                                        SelectionDAG &DAG) {
18320   MVT VT = Op.getSimpleValueType();
18321   assert(VT.is128BitVector() &&
18322          "Only 128-bit vector bitmath lowering supported.");
18323
18324   int VecSize = VT.getSizeInBits();
18325   MVT EltVT = VT.getVectorElementType();
18326   int Len = EltVT.getSizeInBits();
18327
18328   // This is the vectorized version of the "best" algorithm from
18329   // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
18330   // with a minor tweak to use a series of adds + shifts instead of vector
18331   // multiplications. Implemented for all integer vector types. We only use
18332   // this when we don't have SSSE3 which allows a LUT-based lowering that is
18333   // much faster, even faster than using native popcnt instructions.
18334
18335   auto GetShift = [&](unsigned OpCode, SDValue V, int Shifter) {
18336     MVT VT = V.getSimpleValueType();
18337     SmallVector<SDValue, 32> Shifters(
18338         VT.getVectorNumElements(),
18339         DAG.getConstant(Shifter, DL, VT.getVectorElementType()));
18340     return DAG.getNode(OpCode, DL, VT, V,
18341                        DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters));
18342   };
18343   auto GetMask = [&](SDValue V, APInt Mask) {
18344     MVT VT = V.getSimpleValueType();
18345     SmallVector<SDValue, 32> Masks(
18346         VT.getVectorNumElements(),
18347         DAG.getConstant(Mask, DL, VT.getVectorElementType()));
18348     return DAG.getNode(ISD::AND, DL, VT, V,
18349                        DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Masks));
18350   };
18351
18352   // We don't want to incur the implicit masks required to SRL vNi8 vectors on
18353   // x86, so set the SRL type to have elements at least i16 wide. This is
18354   // correct because all of our SRLs are followed immediately by a mask anyways
18355   // that handles any bits that sneak into the high bits of the byte elements.
18356   MVT SrlVT = Len > 8 ? VT : MVT::getVectorVT(MVT::i16, VecSize / 16);
18357
18358   SDValue V = Op;
18359
18360   // v = v - ((v >> 1) & 0x55555555...)
18361   SDValue Srl =
18362       DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 1));
18363   SDValue And = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x55)));
18364   V = DAG.getNode(ISD::SUB, DL, VT, V, And);
18365
18366   // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
18367   SDValue AndLHS = GetMask(V, APInt::getSplat(Len, APInt(8, 0x33)));
18368   Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 2));
18369   SDValue AndRHS = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x33)));
18370   V = DAG.getNode(ISD::ADD, DL, VT, AndLHS, AndRHS);
18371
18372   // v = (v + (v >> 4)) & 0x0F0F0F0F...
18373   Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 4));
18374   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, V, Srl);
18375   V = GetMask(Add, APInt::getSplat(Len, APInt(8, 0x0F)));
18376
18377   // At this point, V contains the byte-wise population count, and we are
18378   // merely doing a horizontal sum if necessary to get the wider element
18379   // counts.
18380   if (EltVT == MVT::i8)
18381     return V;
18382
18383   return LowerHorizontalByteSum(
18384       DAG.getBitcast(MVT::getVectorVT(MVT::i8, VecSize / 8), V), VT, Subtarget,
18385       DAG);
18386 }
18387
18388 static SDValue LowerVectorCTPOP(SDValue Op, const X86Subtarget *Subtarget,
18389                                 SelectionDAG &DAG) {
18390   MVT VT = Op.getSimpleValueType();
18391   // FIXME: Need to add AVX-512 support here!
18392   assert((VT.is256BitVector() || VT.is128BitVector()) &&
18393          "Unknown CTPOP type to handle");
18394   SDLoc DL(Op.getNode());
18395   SDValue Op0 = Op.getOperand(0);
18396
18397   if (!Subtarget->hasSSSE3()) {
18398     // We can't use the fast LUT approach, so fall back on vectorized bitmath.
18399     assert(VT.is128BitVector() && "Only 128-bit vectors supported in SSE!");
18400     return LowerVectorCTPOPBitmath(Op0, DL, Subtarget, DAG);
18401   }
18402
18403   if (VT.is256BitVector() && !Subtarget->hasInt256()) {
18404     unsigned NumElems = VT.getVectorNumElements();
18405
18406     // Extract each 128-bit vector, compute pop count and concat the result.
18407     SDValue LHS = Extract128BitVector(Op0, 0, DAG, DL);
18408     SDValue RHS = Extract128BitVector(Op0, NumElems/2, DAG, DL);
18409
18410     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT,
18411                        LowerVectorCTPOPInRegLUT(LHS, DL, Subtarget, DAG),
18412                        LowerVectorCTPOPInRegLUT(RHS, DL, Subtarget, DAG));
18413   }
18414
18415   return LowerVectorCTPOPInRegLUT(Op0, DL, Subtarget, DAG);
18416 }
18417
18418 static SDValue LowerCTPOP(SDValue Op, const X86Subtarget *Subtarget,
18419                           SelectionDAG &DAG) {
18420   assert(Op.getValueType().isVector() &&
18421          "We only do custom lowering for vector population count.");
18422   return LowerVectorCTPOP(Op, Subtarget, DAG);
18423 }
18424
18425 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
18426   SDNode *Node = Op.getNode();
18427   SDLoc dl(Node);
18428   EVT T = Node->getValueType(0);
18429   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
18430                               DAG.getConstant(0, dl, T), Node->getOperand(2));
18431   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
18432                        cast<AtomicSDNode>(Node)->getMemoryVT(),
18433                        Node->getOperand(0),
18434                        Node->getOperand(1), negOp,
18435                        cast<AtomicSDNode>(Node)->getMemOperand(),
18436                        cast<AtomicSDNode>(Node)->getOrdering(),
18437                        cast<AtomicSDNode>(Node)->getSynchScope());
18438 }
18439
18440 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
18441   SDNode *Node = Op.getNode();
18442   SDLoc dl(Node);
18443   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
18444
18445   // Convert seq_cst store -> xchg
18446   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
18447   // FIXME: On 32-bit, store -> fist or movq would be more efficient
18448   //        (The only way to get a 16-byte store is cmpxchg16b)
18449   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
18450   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
18451       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
18452     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
18453                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
18454                                  Node->getOperand(0),
18455                                  Node->getOperand(1), Node->getOperand(2),
18456                                  cast<AtomicSDNode>(Node)->getMemOperand(),
18457                                  cast<AtomicSDNode>(Node)->getOrdering(),
18458                                  cast<AtomicSDNode>(Node)->getSynchScope());
18459     return Swap.getValue(1);
18460   }
18461   // Other atomic stores have a simple pattern.
18462   return Op;
18463 }
18464
18465 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
18466   EVT VT = Op.getNode()->getSimpleValueType(0);
18467
18468   // Let legalize expand this if it isn't a legal type yet.
18469   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
18470     return SDValue();
18471
18472   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
18473
18474   unsigned Opc;
18475   bool ExtraOp = false;
18476   switch (Op.getOpcode()) {
18477   default: llvm_unreachable("Invalid code");
18478   case ISD::ADDC: Opc = X86ISD::ADD; break;
18479   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
18480   case ISD::SUBC: Opc = X86ISD::SUB; break;
18481   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
18482   }
18483
18484   if (!ExtraOp)
18485     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
18486                        Op.getOperand(1));
18487   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
18488                      Op.getOperand(1), Op.getOperand(2));
18489 }
18490
18491 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
18492                             SelectionDAG &DAG) {
18493   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
18494
18495   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
18496   // which returns the values as { float, float } (in XMM0) or
18497   // { double, double } (which is returned in XMM0, XMM1).
18498   SDLoc dl(Op);
18499   SDValue Arg = Op.getOperand(0);
18500   EVT ArgVT = Arg.getValueType();
18501   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
18502
18503   TargetLowering::ArgListTy Args;
18504   TargetLowering::ArgListEntry Entry;
18505
18506   Entry.Node = Arg;
18507   Entry.Ty = ArgTy;
18508   Entry.isSExt = false;
18509   Entry.isZExt = false;
18510   Args.push_back(Entry);
18511
18512   bool isF64 = ArgVT == MVT::f64;
18513   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
18514   // the small struct {f32, f32} is returned in (eax, edx). For f64,
18515   // the results are returned via SRet in memory.
18516   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
18517   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18518   SDValue Callee =
18519       DAG.getExternalSymbol(LibcallName, TLI.getPointerTy(DAG.getDataLayout()));
18520
18521   Type *RetTy = isF64
18522     ? (Type*)StructType::get(ArgTy, ArgTy, nullptr)
18523     : (Type*)VectorType::get(ArgTy, 4);
18524
18525   TargetLowering::CallLoweringInfo CLI(DAG);
18526   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
18527     .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
18528
18529   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
18530
18531   if (isF64)
18532     // Returned in xmm0 and xmm1.
18533     return CallResult.first;
18534
18535   // Returned in bits 0:31 and 32:64 xmm0.
18536   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
18537                                CallResult.first, DAG.getIntPtrConstant(0, dl));
18538   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
18539                                CallResult.first, DAG.getIntPtrConstant(1, dl));
18540   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
18541   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
18542 }
18543
18544 static SDValue LowerMSCATTER(SDValue Op, const X86Subtarget *Subtarget,
18545                              SelectionDAG &DAG) {
18546   assert(Subtarget->hasAVX512() &&
18547          "MGATHER/MSCATTER are supported on AVX-512 arch only");
18548
18549   MaskedScatterSDNode *N = cast<MaskedScatterSDNode>(Op.getNode());
18550   EVT VT = N->getValue().getValueType();
18551   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported scatter op");
18552   SDLoc dl(Op);
18553
18554   // X86 scatter kills mask register, so its type should be added to
18555   // the list of return values
18556   if (N->getNumValues() == 1) {
18557     SDValue Index = N->getIndex();
18558     if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
18559         !Index.getValueType().is512BitVector())
18560       Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
18561
18562     SDVTList VTs = DAG.getVTList(N->getMask().getValueType(), MVT::Other);
18563     SDValue Ops[] = { N->getOperand(0), N->getOperand(1),  N->getOperand(2),
18564                       N->getOperand(3), Index };
18565
18566     SDValue NewScatter = DAG.getMaskedScatter(VTs, VT, dl, Ops, N->getMemOperand());
18567     DAG.ReplaceAllUsesWith(Op, SDValue(NewScatter.getNode(), 1));
18568     return SDValue(NewScatter.getNode(), 0);
18569   }
18570   return Op;
18571 }
18572
18573 static SDValue LowerMGATHER(SDValue Op, const X86Subtarget *Subtarget,
18574                             SelectionDAG &DAG) {
18575   assert(Subtarget->hasAVX512() &&
18576          "MGATHER/MSCATTER are supported on AVX-512 arch only");
18577
18578   MaskedGatherSDNode *N = cast<MaskedGatherSDNode>(Op.getNode());
18579   EVT VT = Op.getValueType();
18580   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported gather op");
18581   SDLoc dl(Op);
18582
18583   SDValue Index = N->getIndex();
18584   if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
18585       !Index.getValueType().is512BitVector()) {
18586     Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
18587     SDValue Ops[] = { N->getOperand(0), N->getOperand(1),  N->getOperand(2),
18588                       N->getOperand(3), Index };
18589     DAG.UpdateNodeOperands(N, Ops);
18590   }
18591   return Op;
18592 }
18593
18594 SDValue X86TargetLowering::LowerGC_TRANSITION_START(SDValue Op,
18595                                                     SelectionDAG &DAG) const {
18596   // TODO: Eventually, the lowering of these nodes should be informed by or
18597   // deferred to the GC strategy for the function in which they appear. For
18598   // now, however, they must be lowered to something. Since they are logically
18599   // no-ops in the case of a null GC strategy (or a GC strategy which does not
18600   // require special handling for these nodes), lower them as literal NOOPs for
18601   // the time being.
18602   SmallVector<SDValue, 2> Ops;
18603
18604   Ops.push_back(Op.getOperand(0));
18605   if (Op->getGluedNode())
18606     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
18607
18608   SDLoc OpDL(Op);
18609   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
18610   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
18611
18612   return NOOP;
18613 }
18614
18615 SDValue X86TargetLowering::LowerGC_TRANSITION_END(SDValue Op,
18616                                                   SelectionDAG &DAG) const {
18617   // TODO: Eventually, the lowering of these nodes should be informed by or
18618   // deferred to the GC strategy for the function in which they appear. For
18619   // now, however, they must be lowered to something. Since they are logically
18620   // no-ops in the case of a null GC strategy (or a GC strategy which does not
18621   // require special handling for these nodes), lower them as literal NOOPs for
18622   // the time being.
18623   SmallVector<SDValue, 2> Ops;
18624
18625   Ops.push_back(Op.getOperand(0));
18626   if (Op->getGluedNode())
18627     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
18628
18629   SDLoc OpDL(Op);
18630   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
18631   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
18632
18633   return NOOP;
18634 }
18635
18636 /// LowerOperation - Provide custom lowering hooks for some operations.
18637 ///
18638 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
18639   switch (Op.getOpcode()) {
18640   default: llvm_unreachable("Should not custom lower this!");
18641   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
18642   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
18643     return LowerCMP_SWAP(Op, Subtarget, DAG);
18644   case ISD::CTPOP:              return LowerCTPOP(Op, Subtarget, DAG);
18645   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
18646   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
18647   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
18648   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, Subtarget, DAG);
18649   case ISD::VECTOR_SHUFFLE:     return lowerVectorShuffle(Op, Subtarget, DAG);
18650   case ISD::VSELECT:            return LowerVSELECT(Op, DAG);
18651   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
18652   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
18653   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
18654   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
18655   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
18656   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
18657   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
18658   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
18659   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
18660   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
18661   case ISD::SHL_PARTS:
18662   case ISD::SRA_PARTS:
18663   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
18664   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
18665   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
18666   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
18667   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
18668   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
18669   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
18670   case ISD::SIGN_EXTEND_VECTOR_INREG:
18671     return LowerSIGN_EXTEND_VECTOR_INREG(Op, Subtarget, DAG);
18672   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
18673   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
18674   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
18675   case ISD::LOAD:               return LowerExtendedLoad(Op, Subtarget, DAG);
18676   case ISD::FABS:
18677   case ISD::FNEG:               return LowerFABSorFNEG(Op, DAG);
18678   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
18679   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
18680   case ISD::SETCC:              return LowerSETCC(Op, DAG);
18681   case ISD::SELECT:             return LowerSELECT(Op, DAG);
18682   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
18683   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
18684   case ISD::VASTART:            return LowerVASTART(Op, DAG);
18685   case ISD::VAARG:              return LowerVAARG(Op, DAG);
18686   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
18687   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, Subtarget, DAG);
18688   case ISD::INTRINSIC_VOID:
18689   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
18690   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
18691   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
18692   case ISD::FRAME_TO_ARGS_OFFSET:
18693                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
18694   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
18695   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
18696   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
18697   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
18698   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
18699   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
18700   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
18701   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
18702   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
18703   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
18704   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
18705   case ISD::UMUL_LOHI:
18706   case ISD::SMUL_LOHI:          return LowerMUL_LOHI(Op, Subtarget, DAG);
18707   case ISD::SRA:
18708   case ISD::SRL:
18709   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
18710   case ISD::SADDO:
18711   case ISD::UADDO:
18712   case ISD::SSUBO:
18713   case ISD::USUBO:
18714   case ISD::SMULO:
18715   case ISD::UMULO:              return LowerXALUO(Op, DAG);
18716   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
18717   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
18718   case ISD::ADDC:
18719   case ISD::ADDE:
18720   case ISD::SUBC:
18721   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
18722   case ISD::ADD:                return LowerADD(Op, DAG);
18723   case ISD::SUB:                return LowerSUB(Op, DAG);
18724   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
18725   case ISD::MGATHER:            return LowerMGATHER(Op, Subtarget, DAG);
18726   case ISD::MSCATTER:           return LowerMSCATTER(Op, Subtarget, DAG);
18727   case ISD::GC_TRANSITION_START:
18728                                 return LowerGC_TRANSITION_START(Op, DAG);
18729   case ISD::GC_TRANSITION_END:  return LowerGC_TRANSITION_END(Op, DAG);
18730   }
18731 }
18732
18733 /// ReplaceNodeResults - Replace a node with an illegal result type
18734 /// with a new node built out of custom code.
18735 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
18736                                            SmallVectorImpl<SDValue>&Results,
18737                                            SelectionDAG &DAG) const {
18738   SDLoc dl(N);
18739   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18740   switch (N->getOpcode()) {
18741   default:
18742     llvm_unreachable("Do not know how to custom type legalize this operation!");
18743   // We might have generated v2f32 FMIN/FMAX operations. Widen them to v4f32.
18744   case X86ISD::FMINC:
18745   case X86ISD::FMIN:
18746   case X86ISD::FMAXC:
18747   case X86ISD::FMAX: {
18748     EVT VT = N->getValueType(0);
18749     if (VT != MVT::v2f32)
18750       llvm_unreachable("Unexpected type (!= v2f32) on FMIN/FMAX.");
18751     SDValue UNDEF = DAG.getUNDEF(VT);
18752     SDValue LHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
18753                               N->getOperand(0), UNDEF);
18754     SDValue RHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
18755                               N->getOperand(1), UNDEF);
18756     Results.push_back(DAG.getNode(N->getOpcode(), dl, MVT::v4f32, LHS, RHS));
18757     return;
18758   }
18759   case ISD::SIGN_EXTEND_INREG:
18760   case ISD::ADDC:
18761   case ISD::ADDE:
18762   case ISD::SUBC:
18763   case ISD::SUBE:
18764     // We don't want to expand or promote these.
18765     return;
18766   case ISD::SDIV:
18767   case ISD::UDIV:
18768   case ISD::SREM:
18769   case ISD::UREM:
18770   case ISD::SDIVREM:
18771   case ISD::UDIVREM: {
18772     SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
18773     Results.push_back(V);
18774     return;
18775   }
18776   case ISD::FP_TO_SINT:
18777     // FP_TO_INT*_IN_MEM is not legal for f16 inputs.  Do not convert
18778     // (FP_TO_SINT (load f16)) to FP_TO_INT*.
18779     if (N->getOperand(0).getValueType() == MVT::f16)
18780       break;
18781     // fallthrough
18782   case ISD::FP_TO_UINT: {
18783     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
18784
18785     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
18786       return;
18787
18788     std::pair<SDValue,SDValue> Vals =
18789         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
18790     SDValue FIST = Vals.first, StackSlot = Vals.second;
18791     if (FIST.getNode()) {
18792       EVT VT = N->getValueType(0);
18793       // Return a load from the stack slot.
18794       if (StackSlot.getNode())
18795         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
18796                                       MachinePointerInfo(),
18797                                       false, false, false, 0));
18798       else
18799         Results.push_back(FIST);
18800     }
18801     return;
18802   }
18803   case ISD::UINT_TO_FP: {
18804     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
18805     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
18806         N->getValueType(0) != MVT::v2f32)
18807       return;
18808     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
18809                                  N->getOperand(0));
18810     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
18811                                      MVT::f64);
18812     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
18813     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
18814                              DAG.getBitcast(MVT::v2i64, VBias));
18815     Or = DAG.getBitcast(MVT::v2f64, Or);
18816     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
18817     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
18818     return;
18819   }
18820   case ISD::FP_ROUND: {
18821     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
18822         return;
18823     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
18824     Results.push_back(V);
18825     return;
18826   }
18827   case ISD::FP_EXTEND: {
18828     // Right now, only MVT::v2f32 has OperationAction for FP_EXTEND.
18829     // No other ValueType for FP_EXTEND should reach this point.
18830     assert(N->getValueType(0) == MVT::v2f32 &&
18831            "Do not know how to legalize this Node");
18832     return;
18833   }
18834   case ISD::INTRINSIC_W_CHAIN: {
18835     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
18836     switch (IntNo) {
18837     default : llvm_unreachable("Do not know how to custom type "
18838                                "legalize this intrinsic operation!");
18839     case Intrinsic::x86_rdtsc:
18840       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
18841                                      Results);
18842     case Intrinsic::x86_rdtscp:
18843       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
18844                                      Results);
18845     case Intrinsic::x86_rdpmc:
18846       return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
18847     }
18848   }
18849   case ISD::READCYCLECOUNTER: {
18850     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
18851                                    Results);
18852   }
18853   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
18854     EVT T = N->getValueType(0);
18855     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
18856     bool Regs64bit = T == MVT::i128;
18857     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
18858     SDValue cpInL, cpInH;
18859     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
18860                         DAG.getConstant(0, dl, HalfT));
18861     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
18862                         DAG.getConstant(1, dl, HalfT));
18863     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
18864                              Regs64bit ? X86::RAX : X86::EAX,
18865                              cpInL, SDValue());
18866     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
18867                              Regs64bit ? X86::RDX : X86::EDX,
18868                              cpInH, cpInL.getValue(1));
18869     SDValue swapInL, swapInH;
18870     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
18871                           DAG.getConstant(0, dl, HalfT));
18872     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
18873                           DAG.getConstant(1, dl, HalfT));
18874     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
18875                                Regs64bit ? X86::RBX : X86::EBX,
18876                                swapInL, cpInH.getValue(1));
18877     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
18878                                Regs64bit ? X86::RCX : X86::ECX,
18879                                swapInH, swapInL.getValue(1));
18880     SDValue Ops[] = { swapInH.getValue(0),
18881                       N->getOperand(1),
18882                       swapInH.getValue(1) };
18883     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
18884     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
18885     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
18886                                   X86ISD::LCMPXCHG8_DAG;
18887     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
18888     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
18889                                         Regs64bit ? X86::RAX : X86::EAX,
18890                                         HalfT, Result.getValue(1));
18891     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
18892                                         Regs64bit ? X86::RDX : X86::EDX,
18893                                         HalfT, cpOutL.getValue(2));
18894     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
18895
18896     SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
18897                                         MVT::i32, cpOutH.getValue(2));
18898     SDValue Success =
18899         DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
18900                     DAG.getConstant(X86::COND_E, dl, MVT::i8), EFLAGS);
18901     Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
18902
18903     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
18904     Results.push_back(Success);
18905     Results.push_back(EFLAGS.getValue(1));
18906     return;
18907   }
18908   case ISD::ATOMIC_SWAP:
18909   case ISD::ATOMIC_LOAD_ADD:
18910   case ISD::ATOMIC_LOAD_SUB:
18911   case ISD::ATOMIC_LOAD_AND:
18912   case ISD::ATOMIC_LOAD_OR:
18913   case ISD::ATOMIC_LOAD_XOR:
18914   case ISD::ATOMIC_LOAD_NAND:
18915   case ISD::ATOMIC_LOAD_MIN:
18916   case ISD::ATOMIC_LOAD_MAX:
18917   case ISD::ATOMIC_LOAD_UMIN:
18918   case ISD::ATOMIC_LOAD_UMAX:
18919   case ISD::ATOMIC_LOAD: {
18920     // Delegate to generic TypeLegalization. Situations we can really handle
18921     // should have already been dealt with by AtomicExpandPass.cpp.
18922     break;
18923   }
18924   case ISD::BITCAST: {
18925     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
18926     EVT DstVT = N->getValueType(0);
18927     EVT SrcVT = N->getOperand(0)->getValueType(0);
18928
18929     if (SrcVT != MVT::f64 ||
18930         (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
18931       return;
18932
18933     unsigned NumElts = DstVT.getVectorNumElements();
18934     EVT SVT = DstVT.getVectorElementType();
18935     EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
18936     SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
18937                                    MVT::v2f64, N->getOperand(0));
18938     SDValue ToVecInt = DAG.getBitcast(WiderVT, Expanded);
18939
18940     if (ExperimentalVectorWideningLegalization) {
18941       // If we are legalizing vectors by widening, we already have the desired
18942       // legal vector type, just return it.
18943       Results.push_back(ToVecInt);
18944       return;
18945     }
18946
18947     SmallVector<SDValue, 8> Elts;
18948     for (unsigned i = 0, e = NumElts; i != e; ++i)
18949       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
18950                                    ToVecInt, DAG.getIntPtrConstant(i, dl)));
18951
18952     Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
18953   }
18954   }
18955 }
18956
18957 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
18958   switch ((X86ISD::NodeType)Opcode) {
18959   case X86ISD::FIRST_NUMBER:       break;
18960   case X86ISD::BSF:                return "X86ISD::BSF";
18961   case X86ISD::BSR:                return "X86ISD::BSR";
18962   case X86ISD::SHLD:               return "X86ISD::SHLD";
18963   case X86ISD::SHRD:               return "X86ISD::SHRD";
18964   case X86ISD::FAND:               return "X86ISD::FAND";
18965   case X86ISD::FANDN:              return "X86ISD::FANDN";
18966   case X86ISD::FOR:                return "X86ISD::FOR";
18967   case X86ISD::FXOR:               return "X86ISD::FXOR";
18968   case X86ISD::FILD:               return "X86ISD::FILD";
18969   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
18970   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
18971   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
18972   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
18973   case X86ISD::FLD:                return "X86ISD::FLD";
18974   case X86ISD::FST:                return "X86ISD::FST";
18975   case X86ISD::CALL:               return "X86ISD::CALL";
18976   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
18977   case X86ISD::RDTSCP_DAG:         return "X86ISD::RDTSCP_DAG";
18978   case X86ISD::RDPMC_DAG:          return "X86ISD::RDPMC_DAG";
18979   case X86ISD::BT:                 return "X86ISD::BT";
18980   case X86ISD::CMP:                return "X86ISD::CMP";
18981   case X86ISD::COMI:               return "X86ISD::COMI";
18982   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
18983   case X86ISD::CMPM:               return "X86ISD::CMPM";
18984   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
18985   case X86ISD::CMPM_RND:           return "X86ISD::CMPM_RND";
18986   case X86ISD::SETCC:              return "X86ISD::SETCC";
18987   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
18988   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
18989   case X86ISD::FGETSIGNx86:        return "X86ISD::FGETSIGNx86";
18990   case X86ISD::CMOV:               return "X86ISD::CMOV";
18991   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
18992   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
18993   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
18994   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
18995   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
18996   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
18997   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
18998   case X86ISD::MOVDQ2Q:            return "X86ISD::MOVDQ2Q";
18999   case X86ISD::MMX_MOVD2W:         return "X86ISD::MMX_MOVD2W";
19000   case X86ISD::MMX_MOVW2D:         return "X86ISD::MMX_MOVW2D";
19001   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
19002   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
19003   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
19004   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
19005   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
19006   case X86ISD::MMX_PINSRW:         return "X86ISD::MMX_PINSRW";
19007   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
19008   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
19009   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
19010   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
19011   case X86ISD::SHRUNKBLEND:        return "X86ISD::SHRUNKBLEND";
19012   case X86ISD::ADDUS:              return "X86ISD::ADDUS";
19013   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
19014   case X86ISD::HADD:               return "X86ISD::HADD";
19015   case X86ISD::HSUB:               return "X86ISD::HSUB";
19016   case X86ISD::FHADD:              return "X86ISD::FHADD";
19017   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
19018   case X86ISD::ABS:                return "X86ISD::ABS";
19019   case X86ISD::FMAX:               return "X86ISD::FMAX";
19020   case X86ISD::FMAX_RND:           return "X86ISD::FMAX_RND";
19021   case X86ISD::FMIN:               return "X86ISD::FMIN";
19022   case X86ISD::FMIN_RND:           return "X86ISD::FMIN_RND";
19023   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
19024   case X86ISD::FMINC:              return "X86ISD::FMINC";
19025   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
19026   case X86ISD::FRCP:               return "X86ISD::FRCP";
19027   case X86ISD::EXTRQI:             return "X86ISD::EXTRQI";
19028   case X86ISD::INSERTQI:           return "X86ISD::INSERTQI";
19029   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
19030   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
19031   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
19032   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
19033   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
19034   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
19035   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
19036   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
19037   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
19038   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
19039   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
19040   case X86ISD::LCMPXCHG16_DAG:     return "X86ISD::LCMPXCHG16_DAG";
19041   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
19042   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
19043   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
19044   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
19045   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
19046   case X86ISD::VTRUNCS:            return "X86ISD::VTRUNCS";
19047   case X86ISD::VTRUNCUS:           return "X86ISD::VTRUNCUS";
19048   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
19049   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
19050   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
19051   case X86ISD::CVTDQ2PD:           return "X86ISD::CVTDQ2PD";
19052   case X86ISD::CVTUDQ2PD:          return "X86ISD::CVTUDQ2PD";
19053   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
19054   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
19055   case X86ISD::VSHL:               return "X86ISD::VSHL";
19056   case X86ISD::VSRL:               return "X86ISD::VSRL";
19057   case X86ISD::VSRA:               return "X86ISD::VSRA";
19058   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
19059   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
19060   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
19061   case X86ISD::CMPP:               return "X86ISD::CMPP";
19062   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
19063   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
19064   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
19065   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
19066   case X86ISD::ADD:                return "X86ISD::ADD";
19067   case X86ISD::SUB:                return "X86ISD::SUB";
19068   case X86ISD::ADC:                return "X86ISD::ADC";
19069   case X86ISD::SBB:                return "X86ISD::SBB";
19070   case X86ISD::SMUL:               return "X86ISD::SMUL";
19071   case X86ISD::UMUL:               return "X86ISD::UMUL";
19072   case X86ISD::SMUL8:              return "X86ISD::SMUL8";
19073   case X86ISD::UMUL8:              return "X86ISD::UMUL8";
19074   case X86ISD::SDIVREM8_SEXT_HREG: return "X86ISD::SDIVREM8_SEXT_HREG";
19075   case X86ISD::UDIVREM8_ZEXT_HREG: return "X86ISD::UDIVREM8_ZEXT_HREG";
19076   case X86ISD::INC:                return "X86ISD::INC";
19077   case X86ISD::DEC:                return "X86ISD::DEC";
19078   case X86ISD::OR:                 return "X86ISD::OR";
19079   case X86ISD::XOR:                return "X86ISD::XOR";
19080   case X86ISD::AND:                return "X86ISD::AND";
19081   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
19082   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
19083   case X86ISD::PTEST:              return "X86ISD::PTEST";
19084   case X86ISD::TESTP:              return "X86ISD::TESTP";
19085   case X86ISD::TESTM:              return "X86ISD::TESTM";
19086   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
19087   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
19088   case X86ISD::PACKSS:             return "X86ISD::PACKSS";
19089   case X86ISD::PACKUS:             return "X86ISD::PACKUS";
19090   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
19091   case X86ISD::VALIGN:             return "X86ISD::VALIGN";
19092   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
19093   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
19094   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
19095   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
19096   case X86ISD::SHUF128:            return "X86ISD::SHUF128";
19097   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
19098   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
19099   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
19100   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
19101   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
19102   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
19103   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
19104   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
19105   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
19106   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
19107   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
19108   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
19109   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
19110   case X86ISD::SUBV_BROADCAST:     return "X86ISD::SUBV_BROADCAST";
19111   case X86ISD::VEXTRACT:           return "X86ISD::VEXTRACT";
19112   case X86ISD::VPERMILPV:          return "X86ISD::VPERMILPV";
19113   case X86ISD::VPERMILPI:          return "X86ISD::VPERMILPI";
19114   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
19115   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
19116   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
19117   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
19118   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
19119   case X86ISD::VFIXUPIMM:          return "X86ISD::VFIXUPIMM";
19120   case X86ISD::VRANGE:             return "X86ISD::VRANGE";
19121   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
19122   case X86ISD::PMULDQ:             return "X86ISD::PMULDQ";
19123   case X86ISD::PSADBW:             return "X86ISD::PSADBW";
19124   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
19125   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
19126   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
19127   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
19128   case X86ISD::MFENCE:             return "X86ISD::MFENCE";
19129   case X86ISD::SFENCE:             return "X86ISD::SFENCE";
19130   case X86ISD::LFENCE:             return "X86ISD::LFENCE";
19131   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
19132   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
19133   case X86ISD::SAHF:               return "X86ISD::SAHF";
19134   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
19135   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
19136   case X86ISD::VPMADDUBSW:         return "X86ISD::VPMADDUBSW";
19137   case X86ISD::VPMADDWD:           return "X86ISD::VPMADDWD";
19138   case X86ISD::FMADD:              return "X86ISD::FMADD";
19139   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
19140   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
19141   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
19142   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
19143   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
19144   case X86ISD::FMADD_RND:          return "X86ISD::FMADD_RND";
19145   case X86ISD::FNMADD_RND:         return "X86ISD::FNMADD_RND";
19146   case X86ISD::FMSUB_RND:          return "X86ISD::FMSUB_RND";
19147   case X86ISD::FNMSUB_RND:         return "X86ISD::FNMSUB_RND";
19148   case X86ISD::FMADDSUB_RND:       return "X86ISD::FMADDSUB_RND";
19149   case X86ISD::FMSUBADD_RND:       return "X86ISD::FMSUBADD_RND";
19150   case X86ISD::VRNDSCALE:          return "X86ISD::VRNDSCALE";
19151   case X86ISD::VREDUCE:            return "X86ISD::VREDUCE";
19152   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
19153   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
19154   case X86ISD::XTEST:              return "X86ISD::XTEST";
19155   case X86ISD::COMPRESS:           return "X86ISD::COMPRESS";
19156   case X86ISD::EXPAND:             return "X86ISD::EXPAND";
19157   case X86ISD::SELECT:             return "X86ISD::SELECT";
19158   case X86ISD::ADDSUB:             return "X86ISD::ADDSUB";
19159   case X86ISD::RCP28:              return "X86ISD::RCP28";
19160   case X86ISD::EXP2:               return "X86ISD::EXP2";
19161   case X86ISD::RSQRT28:            return "X86ISD::RSQRT28";
19162   case X86ISD::FADD_RND:           return "X86ISD::FADD_RND";
19163   case X86ISD::FSUB_RND:           return "X86ISD::FSUB_RND";
19164   case X86ISD::FMUL_RND:           return "X86ISD::FMUL_RND";
19165   case X86ISD::FDIV_RND:           return "X86ISD::FDIV_RND";
19166   case X86ISD::FSQRT_RND:          return "X86ISD::FSQRT_RND";
19167   case X86ISD::FGETEXP_RND:        return "X86ISD::FGETEXP_RND";
19168   case X86ISD::SCALEF:             return "X86ISD::SCALEF";
19169   case X86ISD::ADDS:               return "X86ISD::ADDS";
19170   case X86ISD::SUBS:               return "X86ISD::SUBS";
19171   case X86ISD::AVG:                return "X86ISD::AVG";
19172   case X86ISD::MULHRS:             return "X86ISD::MULHRS";
19173   case X86ISD::SINT_TO_FP_RND:     return "X86ISD::SINT_TO_FP_RND";
19174   case X86ISD::UINT_TO_FP_RND:     return "X86ISD::UINT_TO_FP_RND";
19175   case X86ISD::FP_TO_SINT_RND:     return "X86ISD::FP_TO_SINT_RND";
19176   case X86ISD::FP_TO_UINT_RND:     return "X86ISD::FP_TO_UINT_RND";
19177   }
19178   return nullptr;
19179 }
19180
19181 // isLegalAddressingMode - Return true if the addressing mode represented
19182 // by AM is legal for this target, for a load/store of the specified type.
19183 bool X86TargetLowering::isLegalAddressingMode(const DataLayout &DL,
19184                                               const AddrMode &AM, Type *Ty,
19185                                               unsigned AS) const {
19186   // X86 supports extremely general addressing modes.
19187   CodeModel::Model M = getTargetMachine().getCodeModel();
19188   Reloc::Model R = getTargetMachine().getRelocationModel();
19189
19190   // X86 allows a sign-extended 32-bit immediate field as a displacement.
19191   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
19192     return false;
19193
19194   if (AM.BaseGV) {
19195     unsigned GVFlags =
19196       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
19197
19198     // If a reference to this global requires an extra load, we can't fold it.
19199     if (isGlobalStubReference(GVFlags))
19200       return false;
19201
19202     // If BaseGV requires a register for the PIC base, we cannot also have a
19203     // BaseReg specified.
19204     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
19205       return false;
19206
19207     // If lower 4G is not available, then we must use rip-relative addressing.
19208     if ((M != CodeModel::Small || R != Reloc::Static) &&
19209         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
19210       return false;
19211   }
19212
19213   switch (AM.Scale) {
19214   case 0:
19215   case 1:
19216   case 2:
19217   case 4:
19218   case 8:
19219     // These scales always work.
19220     break;
19221   case 3:
19222   case 5:
19223   case 9:
19224     // These scales are formed with basereg+scalereg.  Only accept if there is
19225     // no basereg yet.
19226     if (AM.HasBaseReg)
19227       return false;
19228     break;
19229   default:  // Other stuff never works.
19230     return false;
19231   }
19232
19233   return true;
19234 }
19235
19236 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
19237   unsigned Bits = Ty->getScalarSizeInBits();
19238
19239   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
19240   // particularly cheaper than those without.
19241   if (Bits == 8)
19242     return false;
19243
19244   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
19245   // variable shifts just as cheap as scalar ones.
19246   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
19247     return false;
19248
19249   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
19250   // fully general vector.
19251   return true;
19252 }
19253
19254 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
19255   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
19256     return false;
19257   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
19258   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
19259   return NumBits1 > NumBits2;
19260 }
19261
19262 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
19263   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
19264     return false;
19265
19266   if (!isTypeLegal(EVT::getEVT(Ty1)))
19267     return false;
19268
19269   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
19270
19271   // Assuming the caller doesn't have a zeroext or signext return parameter,
19272   // truncation all the way down to i1 is valid.
19273   return true;
19274 }
19275
19276 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
19277   return isInt<32>(Imm);
19278 }
19279
19280 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
19281   // Can also use sub to handle negated immediates.
19282   return isInt<32>(Imm);
19283 }
19284
19285 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
19286   if (!VT1.isInteger() || !VT2.isInteger())
19287     return false;
19288   unsigned NumBits1 = VT1.getSizeInBits();
19289   unsigned NumBits2 = VT2.getSizeInBits();
19290   return NumBits1 > NumBits2;
19291 }
19292
19293 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
19294   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
19295   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
19296 }
19297
19298 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
19299   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
19300   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
19301 }
19302
19303 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
19304   EVT VT1 = Val.getValueType();
19305   if (isZExtFree(VT1, VT2))
19306     return true;
19307
19308   if (Val.getOpcode() != ISD::LOAD)
19309     return false;
19310
19311   if (!VT1.isSimple() || !VT1.isInteger() ||
19312       !VT2.isSimple() || !VT2.isInteger())
19313     return false;
19314
19315   switch (VT1.getSimpleVT().SimpleTy) {
19316   default: break;
19317   case MVT::i8:
19318   case MVT::i16:
19319   case MVT::i32:
19320     // X86 has 8, 16, and 32-bit zero-extending loads.
19321     return true;
19322   }
19323
19324   return false;
19325 }
19326
19327 bool X86TargetLowering::isVectorLoadExtDesirable(SDValue) const { return true; }
19328
19329 bool
19330 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
19331   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4() || Subtarget->hasAVX512()))
19332     return false;
19333
19334   VT = VT.getScalarType();
19335
19336   if (!VT.isSimple())
19337     return false;
19338
19339   switch (VT.getSimpleVT().SimpleTy) {
19340   case MVT::f32:
19341   case MVT::f64:
19342     return true;
19343   default:
19344     break;
19345   }
19346
19347   return false;
19348 }
19349
19350 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
19351   // i16 instructions are longer (0x66 prefix) and potentially slower.
19352   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
19353 }
19354
19355 /// isShuffleMaskLegal - Targets can use this to indicate that they only
19356 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
19357 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
19358 /// are assumed to be legal.
19359 bool
19360 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
19361                                       EVT VT) const {
19362   if (!VT.isSimple())
19363     return false;
19364
19365   // Not for i1 vectors
19366   if (VT.getScalarType() == MVT::i1)
19367     return false;
19368
19369   // Very little shuffling can be done for 64-bit vectors right now.
19370   if (VT.getSizeInBits() == 64)
19371     return false;
19372
19373   // We only care that the types being shuffled are legal. The lowering can
19374   // handle any possible shuffle mask that results.
19375   return isTypeLegal(VT.getSimpleVT());
19376 }
19377
19378 bool
19379 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
19380                                           EVT VT) const {
19381   // Just delegate to the generic legality, clear masks aren't special.
19382   return isShuffleMaskLegal(Mask, VT);
19383 }
19384
19385 //===----------------------------------------------------------------------===//
19386 //                           X86 Scheduler Hooks
19387 //===----------------------------------------------------------------------===//
19388
19389 /// Utility function to emit xbegin specifying the start of an RTM region.
19390 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
19391                                      const TargetInstrInfo *TII) {
19392   DebugLoc DL = MI->getDebugLoc();
19393
19394   const BasicBlock *BB = MBB->getBasicBlock();
19395   MachineFunction::iterator I = MBB;
19396   ++I;
19397
19398   // For the v = xbegin(), we generate
19399   //
19400   // thisMBB:
19401   //  xbegin sinkMBB
19402   //
19403   // mainMBB:
19404   //  eax = -1
19405   //
19406   // sinkMBB:
19407   //  v = eax
19408
19409   MachineBasicBlock *thisMBB = MBB;
19410   MachineFunction *MF = MBB->getParent();
19411   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
19412   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
19413   MF->insert(I, mainMBB);
19414   MF->insert(I, sinkMBB);
19415
19416   // Transfer the remainder of BB and its successor edges to sinkMBB.
19417   sinkMBB->splice(sinkMBB->begin(), MBB,
19418                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
19419   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
19420
19421   // thisMBB:
19422   //  xbegin sinkMBB
19423   //  # fallthrough to mainMBB
19424   //  # abortion to sinkMBB
19425   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
19426   thisMBB->addSuccessor(mainMBB);
19427   thisMBB->addSuccessor(sinkMBB);
19428
19429   // mainMBB:
19430   //  EAX = -1
19431   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
19432   mainMBB->addSuccessor(sinkMBB);
19433
19434   // sinkMBB:
19435   // EAX is live into the sinkMBB
19436   sinkMBB->addLiveIn(X86::EAX);
19437   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
19438           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
19439     .addReg(X86::EAX);
19440
19441   MI->eraseFromParent();
19442   return sinkMBB;
19443 }
19444
19445 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
19446 // or XMM0_V32I8 in AVX all of this code can be replaced with that
19447 // in the .td file.
19448 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
19449                                        const TargetInstrInfo *TII) {
19450   unsigned Opc;
19451   switch (MI->getOpcode()) {
19452   default: llvm_unreachable("illegal opcode!");
19453   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
19454   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
19455   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
19456   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
19457   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
19458   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
19459   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
19460   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
19461   }
19462
19463   DebugLoc dl = MI->getDebugLoc();
19464   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
19465
19466   unsigned NumArgs = MI->getNumOperands();
19467   for (unsigned i = 1; i < NumArgs; ++i) {
19468     MachineOperand &Op = MI->getOperand(i);
19469     if (!(Op.isReg() && Op.isImplicit()))
19470       MIB.addOperand(Op);
19471   }
19472   if (MI->hasOneMemOperand())
19473     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
19474
19475   BuildMI(*BB, MI, dl,
19476     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
19477     .addReg(X86::XMM0);
19478
19479   MI->eraseFromParent();
19480   return BB;
19481 }
19482
19483 // FIXME: Custom handling because TableGen doesn't support multiple implicit
19484 // defs in an instruction pattern
19485 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
19486                                        const TargetInstrInfo *TII) {
19487   unsigned Opc;
19488   switch (MI->getOpcode()) {
19489   default: llvm_unreachable("illegal opcode!");
19490   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
19491   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
19492   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
19493   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
19494   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
19495   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
19496   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
19497   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
19498   }
19499
19500   DebugLoc dl = MI->getDebugLoc();
19501   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
19502
19503   unsigned NumArgs = MI->getNumOperands(); // remove the results
19504   for (unsigned i = 1; i < NumArgs; ++i) {
19505     MachineOperand &Op = MI->getOperand(i);
19506     if (!(Op.isReg() && Op.isImplicit()))
19507       MIB.addOperand(Op);
19508   }
19509   if (MI->hasOneMemOperand())
19510     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
19511
19512   BuildMI(*BB, MI, dl,
19513     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
19514     .addReg(X86::ECX);
19515
19516   MI->eraseFromParent();
19517   return BB;
19518 }
19519
19520 static MachineBasicBlock *EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
19521                                       const X86Subtarget *Subtarget) {
19522   DebugLoc dl = MI->getDebugLoc();
19523   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19524   // Address into RAX/EAX, other two args into ECX, EDX.
19525   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
19526   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
19527   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
19528   for (int i = 0; i < X86::AddrNumOperands; ++i)
19529     MIB.addOperand(MI->getOperand(i));
19530
19531   unsigned ValOps = X86::AddrNumOperands;
19532   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
19533     .addReg(MI->getOperand(ValOps).getReg());
19534   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
19535     .addReg(MI->getOperand(ValOps+1).getReg());
19536
19537   // The instruction doesn't actually take any operands though.
19538   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
19539
19540   MI->eraseFromParent(); // The pseudo is gone now.
19541   return BB;
19542 }
19543
19544 MachineBasicBlock *
19545 X86TargetLowering::EmitVAARG64WithCustomInserter(MachineInstr *MI,
19546                                                  MachineBasicBlock *MBB) const {
19547   // Emit va_arg instruction on X86-64.
19548
19549   // Operands to this pseudo-instruction:
19550   // 0  ) Output        : destination address (reg)
19551   // 1-5) Input         : va_list address (addr, i64mem)
19552   // 6  ) ArgSize       : Size (in bytes) of vararg type
19553   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
19554   // 8  ) Align         : Alignment of type
19555   // 9  ) EFLAGS (implicit-def)
19556
19557   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
19558   static_assert(X86::AddrNumOperands == 5,
19559                 "VAARG_64 assumes 5 address operands");
19560
19561   unsigned DestReg = MI->getOperand(0).getReg();
19562   MachineOperand &Base = MI->getOperand(1);
19563   MachineOperand &Scale = MI->getOperand(2);
19564   MachineOperand &Index = MI->getOperand(3);
19565   MachineOperand &Disp = MI->getOperand(4);
19566   MachineOperand &Segment = MI->getOperand(5);
19567   unsigned ArgSize = MI->getOperand(6).getImm();
19568   unsigned ArgMode = MI->getOperand(7).getImm();
19569   unsigned Align = MI->getOperand(8).getImm();
19570
19571   // Memory Reference
19572   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
19573   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
19574   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
19575
19576   // Machine Information
19577   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19578   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
19579   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
19580   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
19581   DebugLoc DL = MI->getDebugLoc();
19582
19583   // struct va_list {
19584   //   i32   gp_offset
19585   //   i32   fp_offset
19586   //   i64   overflow_area (address)
19587   //   i64   reg_save_area (address)
19588   // }
19589   // sizeof(va_list) = 24
19590   // alignment(va_list) = 8
19591
19592   unsigned TotalNumIntRegs = 6;
19593   unsigned TotalNumXMMRegs = 8;
19594   bool UseGPOffset = (ArgMode == 1);
19595   bool UseFPOffset = (ArgMode == 2);
19596   unsigned MaxOffset = TotalNumIntRegs * 8 +
19597                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
19598
19599   /* Align ArgSize to a multiple of 8 */
19600   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
19601   bool NeedsAlign = (Align > 8);
19602
19603   MachineBasicBlock *thisMBB = MBB;
19604   MachineBasicBlock *overflowMBB;
19605   MachineBasicBlock *offsetMBB;
19606   MachineBasicBlock *endMBB;
19607
19608   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
19609   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
19610   unsigned OffsetReg = 0;
19611
19612   if (!UseGPOffset && !UseFPOffset) {
19613     // If we only pull from the overflow region, we don't create a branch.
19614     // We don't need to alter control flow.
19615     OffsetDestReg = 0; // unused
19616     OverflowDestReg = DestReg;
19617
19618     offsetMBB = nullptr;
19619     overflowMBB = thisMBB;
19620     endMBB = thisMBB;
19621   } else {
19622     // First emit code to check if gp_offset (or fp_offset) is below the bound.
19623     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
19624     // If not, pull from overflow_area. (branch to overflowMBB)
19625     //
19626     //       thisMBB
19627     //         |     .
19628     //         |        .
19629     //     offsetMBB   overflowMBB
19630     //         |        .
19631     //         |     .
19632     //        endMBB
19633
19634     // Registers for the PHI in endMBB
19635     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
19636     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
19637
19638     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
19639     MachineFunction *MF = MBB->getParent();
19640     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19641     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19642     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19643
19644     MachineFunction::iterator MBBIter = MBB;
19645     ++MBBIter;
19646
19647     // Insert the new basic blocks
19648     MF->insert(MBBIter, offsetMBB);
19649     MF->insert(MBBIter, overflowMBB);
19650     MF->insert(MBBIter, endMBB);
19651
19652     // Transfer the remainder of MBB and its successor edges to endMBB.
19653     endMBB->splice(endMBB->begin(), thisMBB,
19654                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
19655     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
19656
19657     // Make offsetMBB and overflowMBB successors of thisMBB
19658     thisMBB->addSuccessor(offsetMBB);
19659     thisMBB->addSuccessor(overflowMBB);
19660
19661     // endMBB is a successor of both offsetMBB and overflowMBB
19662     offsetMBB->addSuccessor(endMBB);
19663     overflowMBB->addSuccessor(endMBB);
19664
19665     // Load the offset value into a register
19666     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
19667     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
19668       .addOperand(Base)
19669       .addOperand(Scale)
19670       .addOperand(Index)
19671       .addDisp(Disp, UseFPOffset ? 4 : 0)
19672       .addOperand(Segment)
19673       .setMemRefs(MMOBegin, MMOEnd);
19674
19675     // Check if there is enough room left to pull this argument.
19676     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
19677       .addReg(OffsetReg)
19678       .addImm(MaxOffset + 8 - ArgSizeA8);
19679
19680     // Branch to "overflowMBB" if offset >= max
19681     // Fall through to "offsetMBB" otherwise
19682     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
19683       .addMBB(overflowMBB);
19684   }
19685
19686   // In offsetMBB, emit code to use the reg_save_area.
19687   if (offsetMBB) {
19688     assert(OffsetReg != 0);
19689
19690     // Read the reg_save_area address.
19691     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
19692     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
19693       .addOperand(Base)
19694       .addOperand(Scale)
19695       .addOperand(Index)
19696       .addDisp(Disp, 16)
19697       .addOperand(Segment)
19698       .setMemRefs(MMOBegin, MMOEnd);
19699
19700     // Zero-extend the offset
19701     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
19702       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
19703         .addImm(0)
19704         .addReg(OffsetReg)
19705         .addImm(X86::sub_32bit);
19706
19707     // Add the offset to the reg_save_area to get the final address.
19708     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
19709       .addReg(OffsetReg64)
19710       .addReg(RegSaveReg);
19711
19712     // Compute the offset for the next argument
19713     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
19714     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
19715       .addReg(OffsetReg)
19716       .addImm(UseFPOffset ? 16 : 8);
19717
19718     // Store it back into the va_list.
19719     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
19720       .addOperand(Base)
19721       .addOperand(Scale)
19722       .addOperand(Index)
19723       .addDisp(Disp, UseFPOffset ? 4 : 0)
19724       .addOperand(Segment)
19725       .addReg(NextOffsetReg)
19726       .setMemRefs(MMOBegin, MMOEnd);
19727
19728     // Jump to endMBB
19729     BuildMI(offsetMBB, DL, TII->get(X86::JMP_1))
19730       .addMBB(endMBB);
19731   }
19732
19733   //
19734   // Emit code to use overflow area
19735   //
19736
19737   // Load the overflow_area address into a register.
19738   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
19739   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
19740     .addOperand(Base)
19741     .addOperand(Scale)
19742     .addOperand(Index)
19743     .addDisp(Disp, 8)
19744     .addOperand(Segment)
19745     .setMemRefs(MMOBegin, MMOEnd);
19746
19747   // If we need to align it, do so. Otherwise, just copy the address
19748   // to OverflowDestReg.
19749   if (NeedsAlign) {
19750     // Align the overflow address
19751     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
19752     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
19753
19754     // aligned_addr = (addr + (align-1)) & ~(align-1)
19755     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
19756       .addReg(OverflowAddrReg)
19757       .addImm(Align-1);
19758
19759     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
19760       .addReg(TmpReg)
19761       .addImm(~(uint64_t)(Align-1));
19762   } else {
19763     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
19764       .addReg(OverflowAddrReg);
19765   }
19766
19767   // Compute the next overflow address after this argument.
19768   // (the overflow address should be kept 8-byte aligned)
19769   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
19770   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
19771     .addReg(OverflowDestReg)
19772     .addImm(ArgSizeA8);
19773
19774   // Store the new overflow address.
19775   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
19776     .addOperand(Base)
19777     .addOperand(Scale)
19778     .addOperand(Index)
19779     .addDisp(Disp, 8)
19780     .addOperand(Segment)
19781     .addReg(NextAddrReg)
19782     .setMemRefs(MMOBegin, MMOEnd);
19783
19784   // If we branched, emit the PHI to the front of endMBB.
19785   if (offsetMBB) {
19786     BuildMI(*endMBB, endMBB->begin(), DL,
19787             TII->get(X86::PHI), DestReg)
19788       .addReg(OffsetDestReg).addMBB(offsetMBB)
19789       .addReg(OverflowDestReg).addMBB(overflowMBB);
19790   }
19791
19792   // Erase the pseudo instruction
19793   MI->eraseFromParent();
19794
19795   return endMBB;
19796 }
19797
19798 MachineBasicBlock *
19799 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
19800                                                  MachineInstr *MI,
19801                                                  MachineBasicBlock *MBB) const {
19802   // Emit code to save XMM registers to the stack. The ABI says that the
19803   // number of registers to save is given in %al, so it's theoretically
19804   // possible to do an indirect jump trick to avoid saving all of them,
19805   // however this code takes a simpler approach and just executes all
19806   // of the stores if %al is non-zero. It's less code, and it's probably
19807   // easier on the hardware branch predictor, and stores aren't all that
19808   // expensive anyway.
19809
19810   // Create the new basic blocks. One block contains all the XMM stores,
19811   // and one block is the final destination regardless of whether any
19812   // stores were performed.
19813   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
19814   MachineFunction *F = MBB->getParent();
19815   MachineFunction::iterator MBBIter = MBB;
19816   ++MBBIter;
19817   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
19818   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
19819   F->insert(MBBIter, XMMSaveMBB);
19820   F->insert(MBBIter, EndMBB);
19821
19822   // Transfer the remainder of MBB and its successor edges to EndMBB.
19823   EndMBB->splice(EndMBB->begin(), MBB,
19824                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
19825   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
19826
19827   // The original block will now fall through to the XMM save block.
19828   MBB->addSuccessor(XMMSaveMBB);
19829   // The XMMSaveMBB will fall through to the end block.
19830   XMMSaveMBB->addSuccessor(EndMBB);
19831
19832   // Now add the instructions.
19833   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19834   DebugLoc DL = MI->getDebugLoc();
19835
19836   unsigned CountReg = MI->getOperand(0).getReg();
19837   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
19838   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
19839
19840   if (!Subtarget->isTargetWin64()) {
19841     // If %al is 0, branch around the XMM save block.
19842     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
19843     BuildMI(MBB, DL, TII->get(X86::JE_1)).addMBB(EndMBB);
19844     MBB->addSuccessor(EndMBB);
19845   }
19846
19847   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
19848   // that was just emitted, but clearly shouldn't be "saved".
19849   assert((MI->getNumOperands() <= 3 ||
19850           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
19851           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
19852          && "Expected last argument to be EFLAGS");
19853   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
19854   // In the XMM save block, save all the XMM argument registers.
19855   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
19856     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
19857     MachineMemOperand *MMO =
19858       F->getMachineMemOperand(
19859           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
19860         MachineMemOperand::MOStore,
19861         /*Size=*/16, /*Align=*/16);
19862     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
19863       .addFrameIndex(RegSaveFrameIndex)
19864       .addImm(/*Scale=*/1)
19865       .addReg(/*IndexReg=*/0)
19866       .addImm(/*Disp=*/Offset)
19867       .addReg(/*Segment=*/0)
19868       .addReg(MI->getOperand(i).getReg())
19869       .addMemOperand(MMO);
19870   }
19871
19872   MI->eraseFromParent();   // The pseudo instruction is gone now.
19873
19874   return EndMBB;
19875 }
19876
19877 // The EFLAGS operand of SelectItr might be missing a kill marker
19878 // because there were multiple uses of EFLAGS, and ISel didn't know
19879 // which to mark. Figure out whether SelectItr should have had a
19880 // kill marker, and set it if it should. Returns the correct kill
19881 // marker value.
19882 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
19883                                      MachineBasicBlock* BB,
19884                                      const TargetRegisterInfo* TRI) {
19885   // Scan forward through BB for a use/def of EFLAGS.
19886   MachineBasicBlock::iterator miI(std::next(SelectItr));
19887   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
19888     const MachineInstr& mi = *miI;
19889     if (mi.readsRegister(X86::EFLAGS))
19890       return false;
19891     if (mi.definesRegister(X86::EFLAGS))
19892       break; // Should have kill-flag - update below.
19893   }
19894
19895   // If we hit the end of the block, check whether EFLAGS is live into a
19896   // successor.
19897   if (miI == BB->end()) {
19898     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
19899                                           sEnd = BB->succ_end();
19900          sItr != sEnd; ++sItr) {
19901       MachineBasicBlock* succ = *sItr;
19902       if (succ->isLiveIn(X86::EFLAGS))
19903         return false;
19904     }
19905   }
19906
19907   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
19908   // out. SelectMI should have a kill flag on EFLAGS.
19909   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
19910   return true;
19911 }
19912
19913 MachineBasicBlock *
19914 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
19915                                      MachineBasicBlock *BB) const {
19916   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19917   DebugLoc DL = MI->getDebugLoc();
19918
19919   // To "insert" a SELECT_CC instruction, we actually have to insert the
19920   // diamond control-flow pattern.  The incoming instruction knows the
19921   // destination vreg to set, the condition code register to branch on, the
19922   // true/false values to select between, and a branch opcode to use.
19923   const BasicBlock *LLVM_BB = BB->getBasicBlock();
19924   MachineFunction::iterator It = BB;
19925   ++It;
19926
19927   //  thisMBB:
19928   //  ...
19929   //   TrueVal = ...
19930   //   cmpTY ccX, r1, r2
19931   //   bCC copy1MBB
19932   //   fallthrough --> copy0MBB
19933   MachineBasicBlock *thisMBB = BB;
19934   MachineFunction *F = BB->getParent();
19935
19936   // We also lower double CMOVs:
19937   //   (CMOV (CMOV F, T, cc1), T, cc2)
19938   // to two successives branches.  For that, we look for another CMOV as the
19939   // following instruction.
19940   //
19941   // Without this, we would add a PHI between the two jumps, which ends up
19942   // creating a few copies all around. For instance, for
19943   //
19944   //    (sitofp (zext (fcmp une)))
19945   //
19946   // we would generate:
19947   //
19948   //         ucomiss %xmm1, %xmm0
19949   //         movss  <1.0f>, %xmm0
19950   //         movaps  %xmm0, %xmm1
19951   //         jne     .LBB5_2
19952   //         xorps   %xmm1, %xmm1
19953   // .LBB5_2:
19954   //         jp      .LBB5_4
19955   //         movaps  %xmm1, %xmm0
19956   // .LBB5_4:
19957   //         retq
19958   //
19959   // because this custom-inserter would have generated:
19960   //
19961   //   A
19962   //   | \
19963   //   |  B
19964   //   | /
19965   //   C
19966   //   | \
19967   //   |  D
19968   //   | /
19969   //   E
19970   //
19971   // A: X = ...; Y = ...
19972   // B: empty
19973   // C: Z = PHI [X, A], [Y, B]
19974   // D: empty
19975   // E: PHI [X, C], [Z, D]
19976   //
19977   // If we lower both CMOVs in a single step, we can instead generate:
19978   //
19979   //   A
19980   //   | \
19981   //   |  C
19982   //   | /|
19983   //   |/ |
19984   //   |  |
19985   //   |  D
19986   //   | /
19987   //   E
19988   //
19989   // A: X = ...; Y = ...
19990   // D: empty
19991   // E: PHI [X, A], [X, C], [Y, D]
19992   //
19993   // Which, in our sitofp/fcmp example, gives us something like:
19994   //
19995   //         ucomiss %xmm1, %xmm0
19996   //         movss  <1.0f>, %xmm0
19997   //         jne     .LBB5_4
19998   //         jp      .LBB5_4
19999   //         xorps   %xmm0, %xmm0
20000   // .LBB5_4:
20001   //         retq
20002   //
20003   MachineInstr *NextCMOV = nullptr;
20004   MachineBasicBlock::iterator NextMIIt =
20005       std::next(MachineBasicBlock::iterator(MI));
20006   if (NextMIIt != BB->end() && NextMIIt->getOpcode() == MI->getOpcode() &&
20007       NextMIIt->getOperand(2).getReg() == MI->getOperand(2).getReg() &&
20008       NextMIIt->getOperand(1).getReg() == MI->getOperand(0).getReg())
20009     NextCMOV = &*NextMIIt;
20010
20011   MachineBasicBlock *jcc1MBB = nullptr;
20012
20013   // If we have a double CMOV, we lower it to two successive branches to
20014   // the same block.  EFLAGS is used by both, so mark it as live in the second.
20015   if (NextCMOV) {
20016     jcc1MBB = F->CreateMachineBasicBlock(LLVM_BB);
20017     F->insert(It, jcc1MBB);
20018     jcc1MBB->addLiveIn(X86::EFLAGS);
20019   }
20020
20021   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
20022   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
20023   F->insert(It, copy0MBB);
20024   F->insert(It, sinkMBB);
20025
20026   // If the EFLAGS register isn't dead in the terminator, then claim that it's
20027   // live into the sink and copy blocks.
20028   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
20029
20030   MachineInstr *LastEFLAGSUser = NextCMOV ? NextCMOV : MI;
20031   if (!LastEFLAGSUser->killsRegister(X86::EFLAGS) &&
20032       !checkAndUpdateEFLAGSKill(LastEFLAGSUser, BB, TRI)) {
20033     copy0MBB->addLiveIn(X86::EFLAGS);
20034     sinkMBB->addLiveIn(X86::EFLAGS);
20035   }
20036
20037   // Transfer the remainder of BB and its successor edges to sinkMBB.
20038   sinkMBB->splice(sinkMBB->begin(), BB,
20039                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
20040   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
20041
20042   // Add the true and fallthrough blocks as its successors.
20043   if (NextCMOV) {
20044     // The fallthrough block may be jcc1MBB, if we have a double CMOV.
20045     BB->addSuccessor(jcc1MBB);
20046
20047     // In that case, jcc1MBB will itself fallthrough the copy0MBB, and
20048     // jump to the sinkMBB.
20049     jcc1MBB->addSuccessor(copy0MBB);
20050     jcc1MBB->addSuccessor(sinkMBB);
20051   } else {
20052     BB->addSuccessor(copy0MBB);
20053   }
20054
20055   // The true block target of the first (or only) branch is always sinkMBB.
20056   BB->addSuccessor(sinkMBB);
20057
20058   // Create the conditional branch instruction.
20059   unsigned Opc =
20060     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
20061   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
20062
20063   if (NextCMOV) {
20064     unsigned Opc2 = X86::GetCondBranchFromCond(
20065         (X86::CondCode)NextCMOV->getOperand(3).getImm());
20066     BuildMI(jcc1MBB, DL, TII->get(Opc2)).addMBB(sinkMBB);
20067   }
20068
20069   //  copy0MBB:
20070   //   %FalseValue = ...
20071   //   # fallthrough to sinkMBB
20072   copy0MBB->addSuccessor(sinkMBB);
20073
20074   //  sinkMBB:
20075   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
20076   //  ...
20077   MachineInstrBuilder MIB =
20078       BuildMI(*sinkMBB, sinkMBB->begin(), DL, TII->get(X86::PHI),
20079               MI->getOperand(0).getReg())
20080           .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
20081           .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
20082
20083   // If we have a double CMOV, the second Jcc provides the same incoming
20084   // value as the first Jcc (the True operand of the SELECT_CC/CMOV nodes).
20085   if (NextCMOV) {
20086     MIB.addReg(MI->getOperand(2).getReg()).addMBB(jcc1MBB);
20087     // Copy the PHI result to the register defined by the second CMOV.
20088     BuildMI(*sinkMBB, std::next(MachineBasicBlock::iterator(MIB.getInstr())),
20089             DL, TII->get(TargetOpcode::COPY), NextCMOV->getOperand(0).getReg())
20090         .addReg(MI->getOperand(0).getReg());
20091     NextCMOV->eraseFromParent();
20092   }
20093
20094   MI->eraseFromParent();   // The pseudo instruction is gone now.
20095   return sinkMBB;
20096 }
20097
20098 MachineBasicBlock *
20099 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI,
20100                                         MachineBasicBlock *BB) const {
20101   MachineFunction *MF = BB->getParent();
20102   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20103   DebugLoc DL = MI->getDebugLoc();
20104   const BasicBlock *LLVM_BB = BB->getBasicBlock();
20105
20106   assert(MF->shouldSplitStack());
20107
20108   const bool Is64Bit = Subtarget->is64Bit();
20109   const bool IsLP64 = Subtarget->isTarget64BitLP64();
20110
20111   const unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
20112   const unsigned TlsOffset = IsLP64 ? 0x70 : Is64Bit ? 0x40 : 0x30;
20113
20114   // BB:
20115   //  ... [Till the alloca]
20116   // If stacklet is not large enough, jump to mallocMBB
20117   //
20118   // bumpMBB:
20119   //  Allocate by subtracting from RSP
20120   //  Jump to continueMBB
20121   //
20122   // mallocMBB:
20123   //  Allocate by call to runtime
20124   //
20125   // continueMBB:
20126   //  ...
20127   //  [rest of original BB]
20128   //
20129
20130   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20131   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20132   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20133
20134   MachineRegisterInfo &MRI = MF->getRegInfo();
20135   const TargetRegisterClass *AddrRegClass =
20136       getRegClassFor(getPointerTy(MF->getDataLayout()));
20137
20138   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
20139     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
20140     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
20141     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
20142     sizeVReg = MI->getOperand(1).getReg(),
20143     physSPReg = IsLP64 || Subtarget->isTargetNaCl64() ? X86::RSP : X86::ESP;
20144
20145   MachineFunction::iterator MBBIter = BB;
20146   ++MBBIter;
20147
20148   MF->insert(MBBIter, bumpMBB);
20149   MF->insert(MBBIter, mallocMBB);
20150   MF->insert(MBBIter, continueMBB);
20151
20152   continueMBB->splice(continueMBB->begin(), BB,
20153                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
20154   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
20155
20156   // Add code to the main basic block to check if the stack limit has been hit,
20157   // and if so, jump to mallocMBB otherwise to bumpMBB.
20158   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
20159   BuildMI(BB, DL, TII->get(IsLP64 ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
20160     .addReg(tmpSPVReg).addReg(sizeVReg);
20161   BuildMI(BB, DL, TII->get(IsLP64 ? X86::CMP64mr:X86::CMP32mr))
20162     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
20163     .addReg(SPLimitVReg);
20164   BuildMI(BB, DL, TII->get(X86::JG_1)).addMBB(mallocMBB);
20165
20166   // bumpMBB simply decreases the stack pointer, since we know the current
20167   // stacklet has enough space.
20168   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
20169     .addReg(SPLimitVReg);
20170   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
20171     .addReg(SPLimitVReg);
20172   BuildMI(bumpMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
20173
20174   // Calls into a routine in libgcc to allocate more space from the heap.
20175   const uint32_t *RegMask =
20176       Subtarget->getRegisterInfo()->getCallPreservedMask(*MF, CallingConv::C);
20177   if (IsLP64) {
20178     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
20179       .addReg(sizeVReg);
20180     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
20181       .addExternalSymbol("__morestack_allocate_stack_space")
20182       .addRegMask(RegMask)
20183       .addReg(X86::RDI, RegState::Implicit)
20184       .addReg(X86::RAX, RegState::ImplicitDefine);
20185   } else if (Is64Bit) {
20186     BuildMI(mallocMBB, DL, TII->get(X86::MOV32rr), X86::EDI)
20187       .addReg(sizeVReg);
20188     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
20189       .addExternalSymbol("__morestack_allocate_stack_space")
20190       .addRegMask(RegMask)
20191       .addReg(X86::EDI, RegState::Implicit)
20192       .addReg(X86::EAX, RegState::ImplicitDefine);
20193   } else {
20194     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
20195       .addImm(12);
20196     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
20197     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
20198       .addExternalSymbol("__morestack_allocate_stack_space")
20199       .addRegMask(RegMask)
20200       .addReg(X86::EAX, RegState::ImplicitDefine);
20201   }
20202
20203   if (!Is64Bit)
20204     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
20205       .addImm(16);
20206
20207   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
20208     .addReg(IsLP64 ? X86::RAX : X86::EAX);
20209   BuildMI(mallocMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
20210
20211   // Set up the CFG correctly.
20212   BB->addSuccessor(bumpMBB);
20213   BB->addSuccessor(mallocMBB);
20214   mallocMBB->addSuccessor(continueMBB);
20215   bumpMBB->addSuccessor(continueMBB);
20216
20217   // Take care of the PHI nodes.
20218   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
20219           MI->getOperand(0).getReg())
20220     .addReg(mallocPtrVReg).addMBB(mallocMBB)
20221     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
20222
20223   // Delete the original pseudo instruction.
20224   MI->eraseFromParent();
20225
20226   // And we're done.
20227   return continueMBB;
20228 }
20229
20230 MachineBasicBlock *
20231 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
20232                                         MachineBasicBlock *BB) const {
20233   DebugLoc DL = MI->getDebugLoc();
20234
20235   assert(!Subtarget->isTargetMachO());
20236
20237   Subtarget->getFrameLowering()->emitStackProbeCall(*BB->getParent(), *BB, MI,
20238                                                     DL);
20239
20240   MI->eraseFromParent();   // The pseudo instruction is gone now.
20241   return BB;
20242 }
20243
20244 MachineBasicBlock *
20245 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
20246                                       MachineBasicBlock *BB) const {
20247   // This is pretty easy.  We're taking the value that we received from
20248   // our load from the relocation, sticking it in either RDI (x86-64)
20249   // or EAX and doing an indirect call.  The return value will then
20250   // be in the normal return register.
20251   MachineFunction *F = BB->getParent();
20252   const X86InstrInfo *TII = Subtarget->getInstrInfo();
20253   DebugLoc DL = MI->getDebugLoc();
20254
20255   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
20256   assert(MI->getOperand(3).isGlobal() && "This should be a global");
20257
20258   // Get a register mask for the lowered call.
20259   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
20260   // proper register mask.
20261   const uint32_t *RegMask =
20262       Subtarget->getRegisterInfo()->getCallPreservedMask(*F, CallingConv::C);
20263   if (Subtarget->is64Bit()) {
20264     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
20265                                       TII->get(X86::MOV64rm), X86::RDI)
20266     .addReg(X86::RIP)
20267     .addImm(0).addReg(0)
20268     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
20269                       MI->getOperand(3).getTargetFlags())
20270     .addReg(0);
20271     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
20272     addDirectMem(MIB, X86::RDI);
20273     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
20274   } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
20275     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
20276                                       TII->get(X86::MOV32rm), X86::EAX)
20277     .addReg(0)
20278     .addImm(0).addReg(0)
20279     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
20280                       MI->getOperand(3).getTargetFlags())
20281     .addReg(0);
20282     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
20283     addDirectMem(MIB, X86::EAX);
20284     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
20285   } else {
20286     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
20287                                       TII->get(X86::MOV32rm), X86::EAX)
20288     .addReg(TII->getGlobalBaseReg(F))
20289     .addImm(0).addReg(0)
20290     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
20291                       MI->getOperand(3).getTargetFlags())
20292     .addReg(0);
20293     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
20294     addDirectMem(MIB, X86::EAX);
20295     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
20296   }
20297
20298   MI->eraseFromParent(); // The pseudo instruction is gone now.
20299   return BB;
20300 }
20301
20302 MachineBasicBlock *
20303 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
20304                                     MachineBasicBlock *MBB) const {
20305   DebugLoc DL = MI->getDebugLoc();
20306   MachineFunction *MF = MBB->getParent();
20307   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20308   MachineRegisterInfo &MRI = MF->getRegInfo();
20309
20310   const BasicBlock *BB = MBB->getBasicBlock();
20311   MachineFunction::iterator I = MBB;
20312   ++I;
20313
20314   // Memory Reference
20315   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
20316   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
20317
20318   unsigned DstReg;
20319   unsigned MemOpndSlot = 0;
20320
20321   unsigned CurOp = 0;
20322
20323   DstReg = MI->getOperand(CurOp++).getReg();
20324   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
20325   assert(RC->hasType(MVT::i32) && "Invalid destination!");
20326   unsigned mainDstReg = MRI.createVirtualRegister(RC);
20327   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
20328
20329   MemOpndSlot = CurOp;
20330
20331   MVT PVT = getPointerTy(MF->getDataLayout());
20332   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
20333          "Invalid Pointer Size!");
20334
20335   // For v = setjmp(buf), we generate
20336   //
20337   // thisMBB:
20338   //  buf[LabelOffset] = restoreMBB
20339   //  SjLjSetup restoreMBB
20340   //
20341   // mainMBB:
20342   //  v_main = 0
20343   //
20344   // sinkMBB:
20345   //  v = phi(main, restore)
20346   //
20347   // restoreMBB:
20348   //  if base pointer being used, load it from frame
20349   //  v_restore = 1
20350
20351   MachineBasicBlock *thisMBB = MBB;
20352   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
20353   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
20354   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
20355   MF->insert(I, mainMBB);
20356   MF->insert(I, sinkMBB);
20357   MF->push_back(restoreMBB);
20358
20359   MachineInstrBuilder MIB;
20360
20361   // Transfer the remainder of BB and its successor edges to sinkMBB.
20362   sinkMBB->splice(sinkMBB->begin(), MBB,
20363                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
20364   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
20365
20366   // thisMBB:
20367   unsigned PtrStoreOpc = 0;
20368   unsigned LabelReg = 0;
20369   const int64_t LabelOffset = 1 * PVT.getStoreSize();
20370   Reloc::Model RM = MF->getTarget().getRelocationModel();
20371   bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
20372                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
20373
20374   // Prepare IP either in reg or imm.
20375   if (!UseImmLabel) {
20376     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
20377     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
20378     LabelReg = MRI.createVirtualRegister(PtrRC);
20379     if (Subtarget->is64Bit()) {
20380       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
20381               .addReg(X86::RIP)
20382               .addImm(0)
20383               .addReg(0)
20384               .addMBB(restoreMBB)
20385               .addReg(0);
20386     } else {
20387       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
20388       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
20389               .addReg(XII->getGlobalBaseReg(MF))
20390               .addImm(0)
20391               .addReg(0)
20392               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
20393               .addReg(0);
20394     }
20395   } else
20396     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
20397   // Store IP
20398   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
20399   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
20400     if (i == X86::AddrDisp)
20401       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
20402     else
20403       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
20404   }
20405   if (!UseImmLabel)
20406     MIB.addReg(LabelReg);
20407   else
20408     MIB.addMBB(restoreMBB);
20409   MIB.setMemRefs(MMOBegin, MMOEnd);
20410   // Setup
20411   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
20412           .addMBB(restoreMBB);
20413
20414   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
20415   MIB.addRegMask(RegInfo->getNoPreservedMask());
20416   thisMBB->addSuccessor(mainMBB);
20417   thisMBB->addSuccessor(restoreMBB);
20418
20419   // mainMBB:
20420   //  EAX = 0
20421   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
20422   mainMBB->addSuccessor(sinkMBB);
20423
20424   // sinkMBB:
20425   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
20426           TII->get(X86::PHI), DstReg)
20427     .addReg(mainDstReg).addMBB(mainMBB)
20428     .addReg(restoreDstReg).addMBB(restoreMBB);
20429
20430   // restoreMBB:
20431   if (RegInfo->hasBasePointer(*MF)) {
20432     const bool Uses64BitFramePtr =
20433         Subtarget->isTarget64BitLP64() || Subtarget->isTargetNaCl64();
20434     X86MachineFunctionInfo *X86FI = MF->getInfo<X86MachineFunctionInfo>();
20435     X86FI->setRestoreBasePointer(MF);
20436     unsigned FramePtr = RegInfo->getFrameRegister(*MF);
20437     unsigned BasePtr = RegInfo->getBaseRegister();
20438     unsigned Opm = Uses64BitFramePtr ? X86::MOV64rm : X86::MOV32rm;
20439     addRegOffset(BuildMI(restoreMBB, DL, TII->get(Opm), BasePtr),
20440                  FramePtr, true, X86FI->getRestoreBasePointerOffset())
20441       .setMIFlag(MachineInstr::FrameSetup);
20442   }
20443   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
20444   BuildMI(restoreMBB, DL, TII->get(X86::JMP_1)).addMBB(sinkMBB);
20445   restoreMBB->addSuccessor(sinkMBB);
20446
20447   MI->eraseFromParent();
20448   return sinkMBB;
20449 }
20450
20451 MachineBasicBlock *
20452 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
20453                                      MachineBasicBlock *MBB) const {
20454   DebugLoc DL = MI->getDebugLoc();
20455   MachineFunction *MF = MBB->getParent();
20456   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20457   MachineRegisterInfo &MRI = MF->getRegInfo();
20458
20459   // Memory Reference
20460   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
20461   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
20462
20463   MVT PVT = getPointerTy(MF->getDataLayout());
20464   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
20465          "Invalid Pointer Size!");
20466
20467   const TargetRegisterClass *RC =
20468     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
20469   unsigned Tmp = MRI.createVirtualRegister(RC);
20470   // Since FP is only updated here but NOT referenced, it's treated as GPR.
20471   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
20472   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
20473   unsigned SP = RegInfo->getStackRegister();
20474
20475   MachineInstrBuilder MIB;
20476
20477   const int64_t LabelOffset = 1 * PVT.getStoreSize();
20478   const int64_t SPOffset = 2 * PVT.getStoreSize();
20479
20480   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
20481   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
20482
20483   // Reload FP
20484   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
20485   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
20486     MIB.addOperand(MI->getOperand(i));
20487   MIB.setMemRefs(MMOBegin, MMOEnd);
20488   // Reload IP
20489   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
20490   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
20491     if (i == X86::AddrDisp)
20492       MIB.addDisp(MI->getOperand(i), LabelOffset);
20493     else
20494       MIB.addOperand(MI->getOperand(i));
20495   }
20496   MIB.setMemRefs(MMOBegin, MMOEnd);
20497   // Reload SP
20498   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
20499   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
20500     if (i == X86::AddrDisp)
20501       MIB.addDisp(MI->getOperand(i), SPOffset);
20502     else
20503       MIB.addOperand(MI->getOperand(i));
20504   }
20505   MIB.setMemRefs(MMOBegin, MMOEnd);
20506   // Jump
20507   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
20508
20509   MI->eraseFromParent();
20510   return MBB;
20511 }
20512
20513 // Replace 213-type (isel default) FMA3 instructions with 231-type for
20514 // accumulator loops. Writing back to the accumulator allows the coalescer
20515 // to remove extra copies in the loop.
20516 // FIXME: Do this on AVX512.  We don't support 231 variants yet (PR23937).
20517 MachineBasicBlock *
20518 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
20519                                  MachineBasicBlock *MBB) const {
20520   MachineOperand &AddendOp = MI->getOperand(3);
20521
20522   // Bail out early if the addend isn't a register - we can't switch these.
20523   if (!AddendOp.isReg())
20524     return MBB;
20525
20526   MachineFunction &MF = *MBB->getParent();
20527   MachineRegisterInfo &MRI = MF.getRegInfo();
20528
20529   // Check whether the addend is defined by a PHI:
20530   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
20531   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
20532   if (!AddendDef.isPHI())
20533     return MBB;
20534
20535   // Look for the following pattern:
20536   // loop:
20537   //   %addend = phi [%entry, 0], [%loop, %result]
20538   //   ...
20539   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
20540
20541   // Replace with:
20542   //   loop:
20543   //   %addend = phi [%entry, 0], [%loop, %result]
20544   //   ...
20545   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
20546
20547   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
20548     assert(AddendDef.getOperand(i).isReg());
20549     MachineOperand PHISrcOp = AddendDef.getOperand(i);
20550     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
20551     if (&PHISrcInst == MI) {
20552       // Found a matching instruction.
20553       unsigned NewFMAOpc = 0;
20554       switch (MI->getOpcode()) {
20555         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
20556         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
20557         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
20558         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
20559         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
20560         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
20561         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
20562         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
20563         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
20564         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
20565         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
20566         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
20567         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
20568         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
20569         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
20570         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
20571         case X86::VFMADDSUBPDr213r: NewFMAOpc = X86::VFMADDSUBPDr231r; break;
20572         case X86::VFMADDSUBPSr213r: NewFMAOpc = X86::VFMADDSUBPSr231r; break;
20573         case X86::VFMSUBADDPDr213r: NewFMAOpc = X86::VFMSUBADDPDr231r; break;
20574         case X86::VFMSUBADDPSr213r: NewFMAOpc = X86::VFMSUBADDPSr231r; break;
20575
20576         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
20577         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
20578         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
20579         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
20580         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
20581         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
20582         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
20583         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
20584         case X86::VFMADDSUBPDr213rY: NewFMAOpc = X86::VFMADDSUBPDr231rY; break;
20585         case X86::VFMADDSUBPSr213rY: NewFMAOpc = X86::VFMADDSUBPSr231rY; break;
20586         case X86::VFMSUBADDPDr213rY: NewFMAOpc = X86::VFMSUBADDPDr231rY; break;
20587         case X86::VFMSUBADDPSr213rY: NewFMAOpc = X86::VFMSUBADDPSr231rY; break;
20588         default: llvm_unreachable("Unrecognized FMA variant.");
20589       }
20590
20591       const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
20592       MachineInstrBuilder MIB =
20593         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
20594         .addOperand(MI->getOperand(0))
20595         .addOperand(MI->getOperand(3))
20596         .addOperand(MI->getOperand(2))
20597         .addOperand(MI->getOperand(1));
20598       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
20599       MI->eraseFromParent();
20600     }
20601   }
20602
20603   return MBB;
20604 }
20605
20606 MachineBasicBlock *
20607 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
20608                                                MachineBasicBlock *BB) const {
20609   switch (MI->getOpcode()) {
20610   default: llvm_unreachable("Unexpected instr type to insert");
20611   case X86::TAILJMPd64:
20612   case X86::TAILJMPr64:
20613   case X86::TAILJMPm64:
20614   case X86::TAILJMPd64_REX:
20615   case X86::TAILJMPr64_REX:
20616   case X86::TAILJMPm64_REX:
20617     llvm_unreachable("TAILJMP64 would not be touched here.");
20618   case X86::TCRETURNdi64:
20619   case X86::TCRETURNri64:
20620   case X86::TCRETURNmi64:
20621     return BB;
20622   case X86::WIN_ALLOCA:
20623     return EmitLoweredWinAlloca(MI, BB);
20624   case X86::SEG_ALLOCA_32:
20625   case X86::SEG_ALLOCA_64:
20626     return EmitLoweredSegAlloca(MI, BB);
20627   case X86::TLSCall_32:
20628   case X86::TLSCall_64:
20629     return EmitLoweredTLSCall(MI, BB);
20630   case X86::CMOV_GR8:
20631   case X86::CMOV_FR32:
20632   case X86::CMOV_FR64:
20633   case X86::CMOV_V4F32:
20634   case X86::CMOV_V2F64:
20635   case X86::CMOV_V2I64:
20636   case X86::CMOV_V8F32:
20637   case X86::CMOV_V4F64:
20638   case X86::CMOV_V4I64:
20639   case X86::CMOV_V16F32:
20640   case X86::CMOV_V8F64:
20641   case X86::CMOV_V8I64:
20642   case X86::CMOV_GR16:
20643   case X86::CMOV_GR32:
20644   case X86::CMOV_RFP32:
20645   case X86::CMOV_RFP64:
20646   case X86::CMOV_RFP80:
20647   case X86::CMOV_V8I1:
20648   case X86::CMOV_V16I1:
20649   case X86::CMOV_V32I1:
20650   case X86::CMOV_V64I1:
20651     return EmitLoweredSelect(MI, BB);
20652
20653   case X86::FP32_TO_INT16_IN_MEM:
20654   case X86::FP32_TO_INT32_IN_MEM:
20655   case X86::FP32_TO_INT64_IN_MEM:
20656   case X86::FP64_TO_INT16_IN_MEM:
20657   case X86::FP64_TO_INT32_IN_MEM:
20658   case X86::FP64_TO_INT64_IN_MEM:
20659   case X86::FP80_TO_INT16_IN_MEM:
20660   case X86::FP80_TO_INT32_IN_MEM:
20661   case X86::FP80_TO_INT64_IN_MEM: {
20662     MachineFunction *F = BB->getParent();
20663     const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20664     DebugLoc DL = MI->getDebugLoc();
20665
20666     // Change the floating point control register to use "round towards zero"
20667     // mode when truncating to an integer value.
20668     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
20669     addFrameReference(BuildMI(*BB, MI, DL,
20670                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
20671
20672     // Load the old value of the high byte of the control word...
20673     unsigned OldCW =
20674       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
20675     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
20676                       CWFrameIdx);
20677
20678     // Set the high part to be round to zero...
20679     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
20680       .addImm(0xC7F);
20681
20682     // Reload the modified control word now...
20683     addFrameReference(BuildMI(*BB, MI, DL,
20684                               TII->get(X86::FLDCW16m)), CWFrameIdx);
20685
20686     // Restore the memory image of control word to original value
20687     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
20688       .addReg(OldCW);
20689
20690     // Get the X86 opcode to use.
20691     unsigned Opc;
20692     switch (MI->getOpcode()) {
20693     default: llvm_unreachable("illegal opcode!");
20694     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
20695     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
20696     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
20697     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
20698     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
20699     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
20700     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
20701     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
20702     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
20703     }
20704
20705     X86AddressMode AM;
20706     MachineOperand &Op = MI->getOperand(0);
20707     if (Op.isReg()) {
20708       AM.BaseType = X86AddressMode::RegBase;
20709       AM.Base.Reg = Op.getReg();
20710     } else {
20711       AM.BaseType = X86AddressMode::FrameIndexBase;
20712       AM.Base.FrameIndex = Op.getIndex();
20713     }
20714     Op = MI->getOperand(1);
20715     if (Op.isImm())
20716       AM.Scale = Op.getImm();
20717     Op = MI->getOperand(2);
20718     if (Op.isImm())
20719       AM.IndexReg = Op.getImm();
20720     Op = MI->getOperand(3);
20721     if (Op.isGlobal()) {
20722       AM.GV = Op.getGlobal();
20723     } else {
20724       AM.Disp = Op.getImm();
20725     }
20726     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
20727                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
20728
20729     // Reload the original control word now.
20730     addFrameReference(BuildMI(*BB, MI, DL,
20731                               TII->get(X86::FLDCW16m)), CWFrameIdx);
20732
20733     MI->eraseFromParent();   // The pseudo instruction is gone now.
20734     return BB;
20735   }
20736     // String/text processing lowering.
20737   case X86::PCMPISTRM128REG:
20738   case X86::VPCMPISTRM128REG:
20739   case X86::PCMPISTRM128MEM:
20740   case X86::VPCMPISTRM128MEM:
20741   case X86::PCMPESTRM128REG:
20742   case X86::VPCMPESTRM128REG:
20743   case X86::PCMPESTRM128MEM:
20744   case X86::VPCMPESTRM128MEM:
20745     assert(Subtarget->hasSSE42() &&
20746            "Target must have SSE4.2 or AVX features enabled");
20747     return EmitPCMPSTRM(MI, BB, Subtarget->getInstrInfo());
20748
20749   // String/text processing lowering.
20750   case X86::PCMPISTRIREG:
20751   case X86::VPCMPISTRIREG:
20752   case X86::PCMPISTRIMEM:
20753   case X86::VPCMPISTRIMEM:
20754   case X86::PCMPESTRIREG:
20755   case X86::VPCMPESTRIREG:
20756   case X86::PCMPESTRIMEM:
20757   case X86::VPCMPESTRIMEM:
20758     assert(Subtarget->hasSSE42() &&
20759            "Target must have SSE4.2 or AVX features enabled");
20760     return EmitPCMPSTRI(MI, BB, Subtarget->getInstrInfo());
20761
20762   // Thread synchronization.
20763   case X86::MONITOR:
20764     return EmitMonitor(MI, BB, Subtarget);
20765
20766   // xbegin
20767   case X86::XBEGIN:
20768     return EmitXBegin(MI, BB, Subtarget->getInstrInfo());
20769
20770   case X86::VASTART_SAVE_XMM_REGS:
20771     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
20772
20773   case X86::VAARG_64:
20774     return EmitVAARG64WithCustomInserter(MI, BB);
20775
20776   case X86::EH_SjLj_SetJmp32:
20777   case X86::EH_SjLj_SetJmp64:
20778     return emitEHSjLjSetJmp(MI, BB);
20779
20780   case X86::EH_SjLj_LongJmp32:
20781   case X86::EH_SjLj_LongJmp64:
20782     return emitEHSjLjLongJmp(MI, BB);
20783
20784   case TargetOpcode::STATEPOINT:
20785     // As an implementation detail, STATEPOINT shares the STACKMAP format at
20786     // this point in the process.  We diverge later.
20787     return emitPatchPoint(MI, BB);
20788
20789   case TargetOpcode::STACKMAP:
20790   case TargetOpcode::PATCHPOINT:
20791     return emitPatchPoint(MI, BB);
20792
20793   case X86::VFMADDPDr213r:
20794   case X86::VFMADDPSr213r:
20795   case X86::VFMADDSDr213r:
20796   case X86::VFMADDSSr213r:
20797   case X86::VFMSUBPDr213r:
20798   case X86::VFMSUBPSr213r:
20799   case X86::VFMSUBSDr213r:
20800   case X86::VFMSUBSSr213r:
20801   case X86::VFNMADDPDr213r:
20802   case X86::VFNMADDPSr213r:
20803   case X86::VFNMADDSDr213r:
20804   case X86::VFNMADDSSr213r:
20805   case X86::VFNMSUBPDr213r:
20806   case X86::VFNMSUBPSr213r:
20807   case X86::VFNMSUBSDr213r:
20808   case X86::VFNMSUBSSr213r:
20809   case X86::VFMADDSUBPDr213r:
20810   case X86::VFMADDSUBPSr213r:
20811   case X86::VFMSUBADDPDr213r:
20812   case X86::VFMSUBADDPSr213r:
20813   case X86::VFMADDPDr213rY:
20814   case X86::VFMADDPSr213rY:
20815   case X86::VFMSUBPDr213rY:
20816   case X86::VFMSUBPSr213rY:
20817   case X86::VFNMADDPDr213rY:
20818   case X86::VFNMADDPSr213rY:
20819   case X86::VFNMSUBPDr213rY:
20820   case X86::VFNMSUBPSr213rY:
20821   case X86::VFMADDSUBPDr213rY:
20822   case X86::VFMADDSUBPSr213rY:
20823   case X86::VFMSUBADDPDr213rY:
20824   case X86::VFMSUBADDPSr213rY:
20825     return emitFMA3Instr(MI, BB);
20826   }
20827 }
20828
20829 //===----------------------------------------------------------------------===//
20830 //                           X86 Optimization Hooks
20831 //===----------------------------------------------------------------------===//
20832
20833 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
20834                                                       APInt &KnownZero,
20835                                                       APInt &KnownOne,
20836                                                       const SelectionDAG &DAG,
20837                                                       unsigned Depth) const {
20838   unsigned BitWidth = KnownZero.getBitWidth();
20839   unsigned Opc = Op.getOpcode();
20840   assert((Opc >= ISD::BUILTIN_OP_END ||
20841           Opc == ISD::INTRINSIC_WO_CHAIN ||
20842           Opc == ISD::INTRINSIC_W_CHAIN ||
20843           Opc == ISD::INTRINSIC_VOID) &&
20844          "Should use MaskedValueIsZero if you don't know whether Op"
20845          " is a target node!");
20846
20847   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
20848   switch (Opc) {
20849   default: break;
20850   case X86ISD::ADD:
20851   case X86ISD::SUB:
20852   case X86ISD::ADC:
20853   case X86ISD::SBB:
20854   case X86ISD::SMUL:
20855   case X86ISD::UMUL:
20856   case X86ISD::INC:
20857   case X86ISD::DEC:
20858   case X86ISD::OR:
20859   case X86ISD::XOR:
20860   case X86ISD::AND:
20861     // These nodes' second result is a boolean.
20862     if (Op.getResNo() == 0)
20863       break;
20864     // Fallthrough
20865   case X86ISD::SETCC:
20866     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
20867     break;
20868   case ISD::INTRINSIC_WO_CHAIN: {
20869     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
20870     unsigned NumLoBits = 0;
20871     switch (IntId) {
20872     default: break;
20873     case Intrinsic::x86_sse_movmsk_ps:
20874     case Intrinsic::x86_avx_movmsk_ps_256:
20875     case Intrinsic::x86_sse2_movmsk_pd:
20876     case Intrinsic::x86_avx_movmsk_pd_256:
20877     case Intrinsic::x86_mmx_pmovmskb:
20878     case Intrinsic::x86_sse2_pmovmskb_128:
20879     case Intrinsic::x86_avx2_pmovmskb: {
20880       // High bits of movmskp{s|d}, pmovmskb are known zero.
20881       switch (IntId) {
20882         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
20883         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
20884         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
20885         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
20886         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
20887         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
20888         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
20889         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
20890       }
20891       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
20892       break;
20893     }
20894     }
20895     break;
20896   }
20897   }
20898 }
20899
20900 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
20901   SDValue Op,
20902   const SelectionDAG &,
20903   unsigned Depth) const {
20904   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
20905   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
20906     return Op.getValueType().getScalarType().getSizeInBits();
20907
20908   // Fallback case.
20909   return 1;
20910 }
20911
20912 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
20913 /// node is a GlobalAddress + offset.
20914 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
20915                                        const GlobalValue* &GA,
20916                                        int64_t &Offset) const {
20917   if (N->getOpcode() == X86ISD::Wrapper) {
20918     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
20919       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
20920       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
20921       return true;
20922     }
20923   }
20924   return TargetLowering::isGAPlusOffset(N, GA, Offset);
20925 }
20926
20927 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
20928 /// same as extracting the high 128-bit part of 256-bit vector and then
20929 /// inserting the result into the low part of a new 256-bit vector
20930 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
20931   EVT VT = SVOp->getValueType(0);
20932   unsigned NumElems = VT.getVectorNumElements();
20933
20934   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
20935   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
20936     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
20937         SVOp->getMaskElt(j) >= 0)
20938       return false;
20939
20940   return true;
20941 }
20942
20943 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
20944 /// same as extracting the low 128-bit part of 256-bit vector and then
20945 /// inserting the result into the high part of a new 256-bit vector
20946 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
20947   EVT VT = SVOp->getValueType(0);
20948   unsigned NumElems = VT.getVectorNumElements();
20949
20950   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
20951   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
20952     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
20953         SVOp->getMaskElt(j) >= 0)
20954       return false;
20955
20956   return true;
20957 }
20958
20959 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
20960 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
20961                                         TargetLowering::DAGCombinerInfo &DCI,
20962                                         const X86Subtarget* Subtarget) {
20963   SDLoc dl(N);
20964   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
20965   SDValue V1 = SVOp->getOperand(0);
20966   SDValue V2 = SVOp->getOperand(1);
20967   EVT VT = SVOp->getValueType(0);
20968   unsigned NumElems = VT.getVectorNumElements();
20969
20970   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
20971       V2.getOpcode() == ISD::CONCAT_VECTORS) {
20972     //
20973     //                   0,0,0,...
20974     //                      |
20975     //    V      UNDEF    BUILD_VECTOR    UNDEF
20976     //     \      /           \           /
20977     //  CONCAT_VECTOR         CONCAT_VECTOR
20978     //         \                  /
20979     //          \                /
20980     //          RESULT: V + zero extended
20981     //
20982     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
20983         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
20984         V1.getOperand(1).getOpcode() != ISD::UNDEF)
20985       return SDValue();
20986
20987     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
20988       return SDValue();
20989
20990     // To match the shuffle mask, the first half of the mask should
20991     // be exactly the first vector, and all the rest a splat with the
20992     // first element of the second one.
20993     for (unsigned i = 0; i != NumElems/2; ++i)
20994       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
20995           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
20996         return SDValue();
20997
20998     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
20999     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
21000       if (Ld->hasNUsesOfValue(1, 0)) {
21001         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
21002         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
21003         SDValue ResNode =
21004           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
21005                                   Ld->getMemoryVT(),
21006                                   Ld->getPointerInfo(),
21007                                   Ld->getAlignment(),
21008                                   false/*isVolatile*/, true/*ReadMem*/,
21009                                   false/*WriteMem*/);
21010
21011         // Make sure the newly-created LOAD is in the same position as Ld in
21012         // terms of dependency. We create a TokenFactor for Ld and ResNode,
21013         // and update uses of Ld's output chain to use the TokenFactor.
21014         if (Ld->hasAnyUseOfValue(1)) {
21015           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
21016                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
21017           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
21018           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
21019                                  SDValue(ResNode.getNode(), 1));
21020         }
21021
21022         return DAG.getBitcast(VT, ResNode);
21023       }
21024     }
21025
21026     // Emit a zeroed vector and insert the desired subvector on its
21027     // first half.
21028     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
21029     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
21030     return DCI.CombineTo(N, InsV);
21031   }
21032
21033   //===--------------------------------------------------------------------===//
21034   // Combine some shuffles into subvector extracts and inserts:
21035   //
21036
21037   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
21038   if (isShuffleHigh128VectorInsertLow(SVOp)) {
21039     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
21040     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
21041     return DCI.CombineTo(N, InsV);
21042   }
21043
21044   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
21045   if (isShuffleLow128VectorInsertHigh(SVOp)) {
21046     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
21047     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
21048     return DCI.CombineTo(N, InsV);
21049   }
21050
21051   return SDValue();
21052 }
21053
21054 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
21055 /// possible.
21056 ///
21057 /// This is the leaf of the recursive combinine below. When we have found some
21058 /// chain of single-use x86 shuffle instructions and accumulated the combined
21059 /// shuffle mask represented by them, this will try to pattern match that mask
21060 /// into either a single instruction if there is a special purpose instruction
21061 /// for this operation, or into a PSHUFB instruction which is a fully general
21062 /// instruction but should only be used to replace chains over a certain depth.
21063 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
21064                                    int Depth, bool HasPSHUFB, SelectionDAG &DAG,
21065                                    TargetLowering::DAGCombinerInfo &DCI,
21066                                    const X86Subtarget *Subtarget) {
21067   assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
21068
21069   // Find the operand that enters the chain. Note that multiple uses are OK
21070   // here, we're not going to remove the operand we find.
21071   SDValue Input = Op.getOperand(0);
21072   while (Input.getOpcode() == ISD::BITCAST)
21073     Input = Input.getOperand(0);
21074
21075   MVT VT = Input.getSimpleValueType();
21076   MVT RootVT = Root.getSimpleValueType();
21077   SDLoc DL(Root);
21078
21079   // Just remove no-op shuffle masks.
21080   if (Mask.size() == 1) {
21081     DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Input),
21082                   /*AddTo*/ true);
21083     return true;
21084   }
21085
21086   // Use the float domain if the operand type is a floating point type.
21087   bool FloatDomain = VT.isFloatingPoint();
21088
21089   // For floating point shuffles, we don't have free copies in the shuffle
21090   // instructions or the ability to load as part of the instruction, so
21091   // canonicalize their shuffles to UNPCK or MOV variants.
21092   //
21093   // Note that even with AVX we prefer the PSHUFD form of shuffle for integer
21094   // vectors because it can have a load folded into it that UNPCK cannot. This
21095   // doesn't preclude something switching to the shorter encoding post-RA.
21096   //
21097   // FIXME: Should teach these routines about AVX vector widths.
21098   if (FloatDomain && VT.getSizeInBits() == 128) {
21099     if (Mask.equals({0, 0}) || Mask.equals({1, 1})) {
21100       bool Lo = Mask.equals({0, 0});
21101       unsigned Shuffle;
21102       MVT ShuffleVT;
21103       // Check if we have SSE3 which will let us use MOVDDUP. That instruction
21104       // is no slower than UNPCKLPD but has the option to fold the input operand
21105       // into even an unaligned memory load.
21106       if (Lo && Subtarget->hasSSE3()) {
21107         Shuffle = X86ISD::MOVDDUP;
21108         ShuffleVT = MVT::v2f64;
21109       } else {
21110         // We have MOVLHPS and MOVHLPS throughout SSE and they encode smaller
21111         // than the UNPCK variants.
21112         Shuffle = Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS;
21113         ShuffleVT = MVT::v4f32;
21114       }
21115       if (Depth == 1 && Root->getOpcode() == Shuffle)
21116         return false; // Nothing to do!
21117       Op = DAG.getBitcast(ShuffleVT, Input);
21118       DCI.AddToWorklist(Op.getNode());
21119       if (Shuffle == X86ISD::MOVDDUP)
21120         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
21121       else
21122         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
21123       DCI.AddToWorklist(Op.getNode());
21124       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21125                     /*AddTo*/ true);
21126       return true;
21127     }
21128     if (Subtarget->hasSSE3() &&
21129         (Mask.equals({0, 0, 2, 2}) || Mask.equals({1, 1, 3, 3}))) {
21130       bool Lo = Mask.equals({0, 0, 2, 2});
21131       unsigned Shuffle = Lo ? X86ISD::MOVSLDUP : X86ISD::MOVSHDUP;
21132       MVT ShuffleVT = MVT::v4f32;
21133       if (Depth == 1 && Root->getOpcode() == Shuffle)
21134         return false; // Nothing to do!
21135       Op = DAG.getBitcast(ShuffleVT, Input);
21136       DCI.AddToWorklist(Op.getNode());
21137       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
21138       DCI.AddToWorklist(Op.getNode());
21139       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21140                     /*AddTo*/ true);
21141       return true;
21142     }
21143     if (Mask.equals({0, 0, 1, 1}) || Mask.equals({2, 2, 3, 3})) {
21144       bool Lo = Mask.equals({0, 0, 1, 1});
21145       unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
21146       MVT ShuffleVT = MVT::v4f32;
21147       if (Depth == 1 && Root->getOpcode() == Shuffle)
21148         return false; // Nothing to do!
21149       Op = DAG.getBitcast(ShuffleVT, Input);
21150       DCI.AddToWorklist(Op.getNode());
21151       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
21152       DCI.AddToWorklist(Op.getNode());
21153       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21154                     /*AddTo*/ true);
21155       return true;
21156     }
21157   }
21158
21159   // We always canonicalize the 8 x i16 and 16 x i8 shuffles into their UNPCK
21160   // variants as none of these have single-instruction variants that are
21161   // superior to the UNPCK formulation.
21162   if (!FloatDomain && VT.getSizeInBits() == 128 &&
21163       (Mask.equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
21164        Mask.equals({4, 4, 5, 5, 6, 6, 7, 7}) ||
21165        Mask.equals({0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7}) ||
21166        Mask.equals(
21167            {8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15}))) {
21168     bool Lo = Mask[0] == 0;
21169     unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
21170     if (Depth == 1 && Root->getOpcode() == Shuffle)
21171       return false; // Nothing to do!
21172     MVT ShuffleVT;
21173     switch (Mask.size()) {
21174     case 8:
21175       ShuffleVT = MVT::v8i16;
21176       break;
21177     case 16:
21178       ShuffleVT = MVT::v16i8;
21179       break;
21180     default:
21181       llvm_unreachable("Impossible mask size!");
21182     };
21183     Op = DAG.getBitcast(ShuffleVT, Input);
21184     DCI.AddToWorklist(Op.getNode());
21185     Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
21186     DCI.AddToWorklist(Op.getNode());
21187     DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21188                   /*AddTo*/ true);
21189     return true;
21190   }
21191
21192   // Don't try to re-form single instruction chains under any circumstances now
21193   // that we've done encoding canonicalization for them.
21194   if (Depth < 2)
21195     return false;
21196
21197   // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
21198   // can replace them with a single PSHUFB instruction profitably. Intel's
21199   // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
21200   // in practice PSHUFB tends to be *very* fast so we're more aggressive.
21201   if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
21202     SmallVector<SDValue, 16> PSHUFBMask;
21203     int NumBytes = VT.getSizeInBits() / 8;
21204     int Ratio = NumBytes / Mask.size();
21205     for (int i = 0; i < NumBytes; ++i) {
21206       if (Mask[i / Ratio] == SM_SentinelUndef) {
21207         PSHUFBMask.push_back(DAG.getUNDEF(MVT::i8));
21208         continue;
21209       }
21210       int M = Mask[i / Ratio] != SM_SentinelZero
21211                   ? Ratio * Mask[i / Ratio] + i % Ratio
21212                   : 255;
21213       PSHUFBMask.push_back(DAG.getConstant(M, DL, MVT::i8));
21214     }
21215     MVT ByteVT = MVT::getVectorVT(MVT::i8, NumBytes);
21216     Op = DAG.getBitcast(ByteVT, Input);
21217     DCI.AddToWorklist(Op.getNode());
21218     SDValue PSHUFBMaskOp =
21219         DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVT, PSHUFBMask);
21220     DCI.AddToWorklist(PSHUFBMaskOp.getNode());
21221     Op = DAG.getNode(X86ISD::PSHUFB, DL, ByteVT, Op, PSHUFBMaskOp);
21222     DCI.AddToWorklist(Op.getNode());
21223     DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21224                   /*AddTo*/ true);
21225     return true;
21226   }
21227
21228   // Failed to find any combines.
21229   return false;
21230 }
21231
21232 /// \brief Fully generic combining of x86 shuffle instructions.
21233 ///
21234 /// This should be the last combine run over the x86 shuffle instructions. Once
21235 /// they have been fully optimized, this will recursively consider all chains
21236 /// of single-use shuffle instructions, build a generic model of the cumulative
21237 /// shuffle operation, and check for simpler instructions which implement this
21238 /// operation. We use this primarily for two purposes:
21239 ///
21240 /// 1) Collapse generic shuffles to specialized single instructions when
21241 ///    equivalent. In most cases, this is just an encoding size win, but
21242 ///    sometimes we will collapse multiple generic shuffles into a single
21243 ///    special-purpose shuffle.
21244 /// 2) Look for sequences of shuffle instructions with 3 or more total
21245 ///    instructions, and replace them with the slightly more expensive SSSE3
21246 ///    PSHUFB instruction if available. We do this as the last combining step
21247 ///    to ensure we avoid using PSHUFB if we can implement the shuffle with
21248 ///    a suitable short sequence of other instructions. The PHUFB will either
21249 ///    use a register or have to read from memory and so is slightly (but only
21250 ///    slightly) more expensive than the other shuffle instructions.
21251 ///
21252 /// Because this is inherently a quadratic operation (for each shuffle in
21253 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
21254 /// This should never be an issue in practice as the shuffle lowering doesn't
21255 /// produce sequences of more than 8 instructions.
21256 ///
21257 /// FIXME: We will currently miss some cases where the redundant shuffling
21258 /// would simplify under the threshold for PSHUFB formation because of
21259 /// combine-ordering. To fix this, we should do the redundant instruction
21260 /// combining in this recursive walk.
21261 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
21262                                           ArrayRef<int> RootMask,
21263                                           int Depth, bool HasPSHUFB,
21264                                           SelectionDAG &DAG,
21265                                           TargetLowering::DAGCombinerInfo &DCI,
21266                                           const X86Subtarget *Subtarget) {
21267   // Bound the depth of our recursive combine because this is ultimately
21268   // quadratic in nature.
21269   if (Depth > 8)
21270     return false;
21271
21272   // Directly rip through bitcasts to find the underlying operand.
21273   while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
21274     Op = Op.getOperand(0);
21275
21276   MVT VT = Op.getSimpleValueType();
21277   if (!VT.isVector())
21278     return false; // Bail if we hit a non-vector.
21279
21280   assert(Root.getSimpleValueType().isVector() &&
21281          "Shuffles operate on vector types!");
21282   assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
21283          "Can only combine shuffles of the same vector register size.");
21284
21285   if (!isTargetShuffle(Op.getOpcode()))
21286     return false;
21287   SmallVector<int, 16> OpMask;
21288   bool IsUnary;
21289   bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, OpMask, IsUnary);
21290   // We only can combine unary shuffles which we can decode the mask for.
21291   if (!HaveMask || !IsUnary)
21292     return false;
21293
21294   assert(VT.getVectorNumElements() == OpMask.size() &&
21295          "Different mask size from vector size!");
21296   assert(((RootMask.size() > OpMask.size() &&
21297            RootMask.size() % OpMask.size() == 0) ||
21298           (OpMask.size() > RootMask.size() &&
21299            OpMask.size() % RootMask.size() == 0) ||
21300           OpMask.size() == RootMask.size()) &&
21301          "The smaller number of elements must divide the larger.");
21302   int RootRatio = std::max<int>(1, OpMask.size() / RootMask.size());
21303   int OpRatio = std::max<int>(1, RootMask.size() / OpMask.size());
21304   assert(((RootRatio == 1 && OpRatio == 1) ||
21305           (RootRatio == 1) != (OpRatio == 1)) &&
21306          "Must not have a ratio for both incoming and op masks!");
21307
21308   SmallVector<int, 16> Mask;
21309   Mask.reserve(std::max(OpMask.size(), RootMask.size()));
21310
21311   // Merge this shuffle operation's mask into our accumulated mask. Note that
21312   // this shuffle's mask will be the first applied to the input, followed by the
21313   // root mask to get us all the way to the root value arrangement. The reason
21314   // for this order is that we are recursing up the operation chain.
21315   for (int i = 0, e = std::max(OpMask.size(), RootMask.size()); i < e; ++i) {
21316     int RootIdx = i / RootRatio;
21317     if (RootMask[RootIdx] < 0) {
21318       // This is a zero or undef lane, we're done.
21319       Mask.push_back(RootMask[RootIdx]);
21320       continue;
21321     }
21322
21323     int RootMaskedIdx = RootMask[RootIdx] * RootRatio + i % RootRatio;
21324     int OpIdx = RootMaskedIdx / OpRatio;
21325     if (OpMask[OpIdx] < 0) {
21326       // The incoming lanes are zero or undef, it doesn't matter which ones we
21327       // are using.
21328       Mask.push_back(OpMask[OpIdx]);
21329       continue;
21330     }
21331
21332     // Ok, we have non-zero lanes, map them through.
21333     Mask.push_back(OpMask[OpIdx] * OpRatio +
21334                    RootMaskedIdx % OpRatio);
21335   }
21336
21337   // See if we can recurse into the operand to combine more things.
21338   switch (Op.getOpcode()) {
21339     case X86ISD::PSHUFB:
21340       HasPSHUFB = true;
21341     case X86ISD::PSHUFD:
21342     case X86ISD::PSHUFHW:
21343     case X86ISD::PSHUFLW:
21344       if (Op.getOperand(0).hasOneUse() &&
21345           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
21346                                         HasPSHUFB, DAG, DCI, Subtarget))
21347         return true;
21348       break;
21349
21350     case X86ISD::UNPCKL:
21351     case X86ISD::UNPCKH:
21352       assert(Op.getOperand(0) == Op.getOperand(1) && "We only combine unary shuffles!");
21353       // We can't check for single use, we have to check that this shuffle is the only user.
21354       if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
21355           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
21356                                         HasPSHUFB, DAG, DCI, Subtarget))
21357           return true;
21358       break;
21359   }
21360
21361   // Minor canonicalization of the accumulated shuffle mask to make it easier
21362   // to match below. All this does is detect masks with squential pairs of
21363   // elements, and shrink them to the half-width mask. It does this in a loop
21364   // so it will reduce the size of the mask to the minimal width mask which
21365   // performs an equivalent shuffle.
21366   SmallVector<int, 16> WidenedMask;
21367   while (Mask.size() > 1 && canWidenShuffleElements(Mask, WidenedMask)) {
21368     Mask = std::move(WidenedMask);
21369     WidenedMask.clear();
21370   }
21371
21372   return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
21373                                 Subtarget);
21374 }
21375
21376 /// \brief Get the PSHUF-style mask from PSHUF node.
21377 ///
21378 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
21379 /// PSHUF-style masks that can be reused with such instructions.
21380 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
21381   MVT VT = N.getSimpleValueType();
21382   SmallVector<int, 4> Mask;
21383   bool IsUnary;
21384   bool HaveMask = getTargetShuffleMask(N.getNode(), VT, Mask, IsUnary);
21385   (void)HaveMask;
21386   assert(HaveMask);
21387
21388   // If we have more than 128-bits, only the low 128-bits of shuffle mask
21389   // matter. Check that the upper masks are repeats and remove them.
21390   if (VT.getSizeInBits() > 128) {
21391     int LaneElts = 128 / VT.getScalarSizeInBits();
21392 #ifndef NDEBUG
21393     for (int i = 1, NumLanes = VT.getSizeInBits() / 128; i < NumLanes; ++i)
21394       for (int j = 0; j < LaneElts; ++j)
21395         assert(Mask[j] == Mask[i * LaneElts + j] - (LaneElts * i) &&
21396                "Mask doesn't repeat in high 128-bit lanes!");
21397 #endif
21398     Mask.resize(LaneElts);
21399   }
21400
21401   switch (N.getOpcode()) {
21402   case X86ISD::PSHUFD:
21403     return Mask;
21404   case X86ISD::PSHUFLW:
21405     Mask.resize(4);
21406     return Mask;
21407   case X86ISD::PSHUFHW:
21408     Mask.erase(Mask.begin(), Mask.begin() + 4);
21409     for (int &M : Mask)
21410       M -= 4;
21411     return Mask;
21412   default:
21413     llvm_unreachable("No valid shuffle instruction found!");
21414   }
21415 }
21416
21417 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
21418 ///
21419 /// We walk up the chain and look for a combinable shuffle, skipping over
21420 /// shuffles that we could hoist this shuffle's transformation past without
21421 /// altering anything.
21422 static SDValue
21423 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
21424                              SelectionDAG &DAG,
21425                              TargetLowering::DAGCombinerInfo &DCI) {
21426   assert(N.getOpcode() == X86ISD::PSHUFD &&
21427          "Called with something other than an x86 128-bit half shuffle!");
21428   SDLoc DL(N);
21429
21430   // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
21431   // of the shuffles in the chain so that we can form a fresh chain to replace
21432   // this one.
21433   SmallVector<SDValue, 8> Chain;
21434   SDValue V = N.getOperand(0);
21435   for (; V.hasOneUse(); V = V.getOperand(0)) {
21436     switch (V.getOpcode()) {
21437     default:
21438       return SDValue(); // Nothing combined!
21439
21440     case ISD::BITCAST:
21441       // Skip bitcasts as we always know the type for the target specific
21442       // instructions.
21443       continue;
21444
21445     case X86ISD::PSHUFD:
21446       // Found another dword shuffle.
21447       break;
21448
21449     case X86ISD::PSHUFLW:
21450       // Check that the low words (being shuffled) are the identity in the
21451       // dword shuffle, and the high words are self-contained.
21452       if (Mask[0] != 0 || Mask[1] != 1 ||
21453           !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
21454         return SDValue();
21455
21456       Chain.push_back(V);
21457       continue;
21458
21459     case X86ISD::PSHUFHW:
21460       // Check that the high words (being shuffled) are the identity in the
21461       // dword shuffle, and the low words are self-contained.
21462       if (Mask[2] != 2 || Mask[3] != 3 ||
21463           !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
21464         return SDValue();
21465
21466       Chain.push_back(V);
21467       continue;
21468
21469     case X86ISD::UNPCKL:
21470     case X86ISD::UNPCKH:
21471       // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
21472       // shuffle into a preceding word shuffle.
21473       if (V.getSimpleValueType().getScalarType() != MVT::i8 &&
21474           V.getSimpleValueType().getScalarType() != MVT::i16)
21475         return SDValue();
21476
21477       // Search for a half-shuffle which we can combine with.
21478       unsigned CombineOp =
21479           V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
21480       if (V.getOperand(0) != V.getOperand(1) ||
21481           !V->isOnlyUserOf(V.getOperand(0).getNode()))
21482         return SDValue();
21483       Chain.push_back(V);
21484       V = V.getOperand(0);
21485       do {
21486         switch (V.getOpcode()) {
21487         default:
21488           return SDValue(); // Nothing to combine.
21489
21490         case X86ISD::PSHUFLW:
21491         case X86ISD::PSHUFHW:
21492           if (V.getOpcode() == CombineOp)
21493             break;
21494
21495           Chain.push_back(V);
21496
21497           // Fallthrough!
21498         case ISD::BITCAST:
21499           V = V.getOperand(0);
21500           continue;
21501         }
21502         break;
21503       } while (V.hasOneUse());
21504       break;
21505     }
21506     // Break out of the loop if we break out of the switch.
21507     break;
21508   }
21509
21510   if (!V.hasOneUse())
21511     // We fell out of the loop without finding a viable combining instruction.
21512     return SDValue();
21513
21514   // Merge this node's mask and our incoming mask.
21515   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
21516   for (int &M : Mask)
21517     M = VMask[M];
21518   V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
21519                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
21520
21521   // Rebuild the chain around this new shuffle.
21522   while (!Chain.empty()) {
21523     SDValue W = Chain.pop_back_val();
21524
21525     if (V.getValueType() != W.getOperand(0).getValueType())
21526       V = DAG.getBitcast(W.getOperand(0).getValueType(), V);
21527
21528     switch (W.getOpcode()) {
21529     default:
21530       llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
21531
21532     case X86ISD::UNPCKL:
21533     case X86ISD::UNPCKH:
21534       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
21535       break;
21536
21537     case X86ISD::PSHUFD:
21538     case X86ISD::PSHUFLW:
21539     case X86ISD::PSHUFHW:
21540       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
21541       break;
21542     }
21543   }
21544   if (V.getValueType() != N.getValueType())
21545     V = DAG.getBitcast(N.getValueType(), V);
21546
21547   // Return the new chain to replace N.
21548   return V;
21549 }
21550
21551 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or pshufhw.
21552 ///
21553 /// We walk up the chain, skipping shuffles of the other half and looking
21554 /// through shuffles which switch halves trying to find a shuffle of the same
21555 /// pair of dwords.
21556 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
21557                                         SelectionDAG &DAG,
21558                                         TargetLowering::DAGCombinerInfo &DCI) {
21559   assert(
21560       (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
21561       "Called with something other than an x86 128-bit half shuffle!");
21562   SDLoc DL(N);
21563   unsigned CombineOpcode = N.getOpcode();
21564
21565   // Walk up a single-use chain looking for a combinable shuffle.
21566   SDValue V = N.getOperand(0);
21567   for (; V.hasOneUse(); V = V.getOperand(0)) {
21568     switch (V.getOpcode()) {
21569     default:
21570       return false; // Nothing combined!
21571
21572     case ISD::BITCAST:
21573       // Skip bitcasts as we always know the type for the target specific
21574       // instructions.
21575       continue;
21576
21577     case X86ISD::PSHUFLW:
21578     case X86ISD::PSHUFHW:
21579       if (V.getOpcode() == CombineOpcode)
21580         break;
21581
21582       // Other-half shuffles are no-ops.
21583       continue;
21584     }
21585     // Break out of the loop if we break out of the switch.
21586     break;
21587   }
21588
21589   if (!V.hasOneUse())
21590     // We fell out of the loop without finding a viable combining instruction.
21591     return false;
21592
21593   // Combine away the bottom node as its shuffle will be accumulated into
21594   // a preceding shuffle.
21595   DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
21596
21597   // Record the old value.
21598   SDValue Old = V;
21599
21600   // Merge this node's mask and our incoming mask (adjusted to account for all
21601   // the pshufd instructions encountered).
21602   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
21603   for (int &M : Mask)
21604     M = VMask[M];
21605   V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
21606                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
21607
21608   // Check that the shuffles didn't cancel each other out. If not, we need to
21609   // combine to the new one.
21610   if (Old != V)
21611     // Replace the combinable shuffle with the combined one, updating all users
21612     // so that we re-evaluate the chain here.
21613     DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
21614
21615   return true;
21616 }
21617
21618 /// \brief Try to combine x86 target specific shuffles.
21619 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
21620                                            TargetLowering::DAGCombinerInfo &DCI,
21621                                            const X86Subtarget *Subtarget) {
21622   SDLoc DL(N);
21623   MVT VT = N.getSimpleValueType();
21624   SmallVector<int, 4> Mask;
21625
21626   switch (N.getOpcode()) {
21627   case X86ISD::PSHUFD:
21628   case X86ISD::PSHUFLW:
21629   case X86ISD::PSHUFHW:
21630     Mask = getPSHUFShuffleMask(N);
21631     assert(Mask.size() == 4);
21632     break;
21633   default:
21634     return SDValue();
21635   }
21636
21637   // Nuke no-op shuffles that show up after combining.
21638   if (isNoopShuffleMask(Mask))
21639     return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
21640
21641   // Look for simplifications involving one or two shuffle instructions.
21642   SDValue V = N.getOperand(0);
21643   switch (N.getOpcode()) {
21644   default:
21645     break;
21646   case X86ISD::PSHUFLW:
21647   case X86ISD::PSHUFHW:
21648     assert(VT.getScalarType() == MVT::i16 && "Bad word shuffle type!");
21649
21650     if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
21651       return SDValue(); // We combined away this shuffle, so we're done.
21652
21653     // See if this reduces to a PSHUFD which is no more expensive and can
21654     // combine with more operations. Note that it has to at least flip the
21655     // dwords as otherwise it would have been removed as a no-op.
21656     if (makeArrayRef(Mask).equals({2, 3, 0, 1})) {
21657       int DMask[] = {0, 1, 2, 3};
21658       int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
21659       DMask[DOffset + 0] = DOffset + 1;
21660       DMask[DOffset + 1] = DOffset + 0;
21661       MVT DVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
21662       V = DAG.getBitcast(DVT, V);
21663       DCI.AddToWorklist(V.getNode());
21664       V = DAG.getNode(X86ISD::PSHUFD, DL, DVT, V,
21665                       getV4X86ShuffleImm8ForMask(DMask, DL, DAG));
21666       DCI.AddToWorklist(V.getNode());
21667       return DAG.getBitcast(VT, V);
21668     }
21669
21670     // Look for shuffle patterns which can be implemented as a single unpack.
21671     // FIXME: This doesn't handle the location of the PSHUFD generically, and
21672     // only works when we have a PSHUFD followed by two half-shuffles.
21673     if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
21674         (V.getOpcode() == X86ISD::PSHUFLW ||
21675          V.getOpcode() == X86ISD::PSHUFHW) &&
21676         V.getOpcode() != N.getOpcode() &&
21677         V.hasOneUse()) {
21678       SDValue D = V.getOperand(0);
21679       while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
21680         D = D.getOperand(0);
21681       if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
21682         SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
21683         SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
21684         int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
21685         int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
21686         int WordMask[8];
21687         for (int i = 0; i < 4; ++i) {
21688           WordMask[i + NOffset] = Mask[i] + NOffset;
21689           WordMask[i + VOffset] = VMask[i] + VOffset;
21690         }
21691         // Map the word mask through the DWord mask.
21692         int MappedMask[8];
21693         for (int i = 0; i < 8; ++i)
21694           MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
21695         if (makeArrayRef(MappedMask).equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
21696             makeArrayRef(MappedMask).equals({4, 4, 5, 5, 6, 6, 7, 7})) {
21697           // We can replace all three shuffles with an unpack.
21698           V = DAG.getBitcast(VT, D.getOperand(0));
21699           DCI.AddToWorklist(V.getNode());
21700           return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
21701                                                 : X86ISD::UNPCKH,
21702                              DL, VT, V, V);
21703         }
21704       }
21705     }
21706
21707     break;
21708
21709   case X86ISD::PSHUFD:
21710     if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG, DCI))
21711       return NewN;
21712
21713     break;
21714   }
21715
21716   return SDValue();
21717 }
21718
21719 /// \brief Try to combine a shuffle into a target-specific add-sub node.
21720 ///
21721 /// We combine this directly on the abstract vector shuffle nodes so it is
21722 /// easier to generically match. We also insert dummy vector shuffle nodes for
21723 /// the operands which explicitly discard the lanes which are unused by this
21724 /// operation to try to flow through the rest of the combiner the fact that
21725 /// they're unused.
21726 static SDValue combineShuffleToAddSub(SDNode *N, SelectionDAG &DAG) {
21727   SDLoc DL(N);
21728   EVT VT = N->getValueType(0);
21729
21730   // We only handle target-independent shuffles.
21731   // FIXME: It would be easy and harmless to use the target shuffle mask
21732   // extraction tool to support more.
21733   if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
21734     return SDValue();
21735
21736   auto *SVN = cast<ShuffleVectorSDNode>(N);
21737   ArrayRef<int> Mask = SVN->getMask();
21738   SDValue V1 = N->getOperand(0);
21739   SDValue V2 = N->getOperand(1);
21740
21741   // We require the first shuffle operand to be the SUB node, and the second to
21742   // be the ADD node.
21743   // FIXME: We should support the commuted patterns.
21744   if (V1->getOpcode() != ISD::FSUB || V2->getOpcode() != ISD::FADD)
21745     return SDValue();
21746
21747   // If there are other uses of these operations we can't fold them.
21748   if (!V1->hasOneUse() || !V2->hasOneUse())
21749     return SDValue();
21750
21751   // Ensure that both operations have the same operands. Note that we can
21752   // commute the FADD operands.
21753   SDValue LHS = V1->getOperand(0), RHS = V1->getOperand(1);
21754   if ((V2->getOperand(0) != LHS || V2->getOperand(1) != RHS) &&
21755       (V2->getOperand(0) != RHS || V2->getOperand(1) != LHS))
21756     return SDValue();
21757
21758   // We're looking for blends between FADD and FSUB nodes. We insist on these
21759   // nodes being lined up in a specific expected pattern.
21760   if (!(isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
21761         isShuffleEquivalent(V1, V2, Mask, {0, 5, 2, 7}) ||
21762         isShuffleEquivalent(V1, V2, Mask, {0, 9, 2, 11, 4, 13, 6, 15})))
21763     return SDValue();
21764
21765   // Only specific types are legal at this point, assert so we notice if and
21766   // when these change.
21767   assert((VT == MVT::v4f32 || VT == MVT::v2f64 || VT == MVT::v8f32 ||
21768           VT == MVT::v4f64) &&
21769          "Unknown vector type encountered!");
21770
21771   return DAG.getNode(X86ISD::ADDSUB, DL, VT, LHS, RHS);
21772 }
21773
21774 /// PerformShuffleCombine - Performs several different shuffle combines.
21775 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
21776                                      TargetLowering::DAGCombinerInfo &DCI,
21777                                      const X86Subtarget *Subtarget) {
21778   SDLoc dl(N);
21779   SDValue N0 = N->getOperand(0);
21780   SDValue N1 = N->getOperand(1);
21781   EVT VT = N->getValueType(0);
21782
21783   // Don't create instructions with illegal types after legalize types has run.
21784   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21785   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
21786     return SDValue();
21787
21788   // If we have legalized the vector types, look for blends of FADD and FSUB
21789   // nodes that we can fuse into an ADDSUB node.
21790   if (TLI.isTypeLegal(VT) && Subtarget->hasSSE3())
21791     if (SDValue AddSub = combineShuffleToAddSub(N, DAG))
21792       return AddSub;
21793
21794   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
21795   if (Subtarget->hasFp256() && VT.is256BitVector() &&
21796       N->getOpcode() == ISD::VECTOR_SHUFFLE)
21797     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
21798
21799   // During Type Legalization, when promoting illegal vector types,
21800   // the backend might introduce new shuffle dag nodes and bitcasts.
21801   //
21802   // This code performs the following transformation:
21803   // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
21804   //       (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
21805   //
21806   // We do this only if both the bitcast and the BINOP dag nodes have
21807   // one use. Also, perform this transformation only if the new binary
21808   // operation is legal. This is to avoid introducing dag nodes that
21809   // potentially need to be further expanded (or custom lowered) into a
21810   // less optimal sequence of dag nodes.
21811   if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
21812       N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
21813       N0.getOpcode() == ISD::BITCAST) {
21814     SDValue BC0 = N0.getOperand(0);
21815     EVT SVT = BC0.getValueType();
21816     unsigned Opcode = BC0.getOpcode();
21817     unsigned NumElts = VT.getVectorNumElements();
21818
21819     if (BC0.hasOneUse() && SVT.isVector() &&
21820         SVT.getVectorNumElements() * 2 == NumElts &&
21821         TLI.isOperationLegal(Opcode, VT)) {
21822       bool CanFold = false;
21823       switch (Opcode) {
21824       default : break;
21825       case ISD::ADD :
21826       case ISD::FADD :
21827       case ISD::SUB :
21828       case ISD::FSUB :
21829       case ISD::MUL :
21830       case ISD::FMUL :
21831         CanFold = true;
21832       }
21833
21834       unsigned SVTNumElts = SVT.getVectorNumElements();
21835       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
21836       for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
21837         CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
21838       for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
21839         CanFold = SVOp->getMaskElt(i) < 0;
21840
21841       if (CanFold) {
21842         SDValue BC00 = DAG.getBitcast(VT, BC0.getOperand(0));
21843         SDValue BC01 = DAG.getBitcast(VT, BC0.getOperand(1));
21844         SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
21845         return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
21846       }
21847     }
21848   }
21849
21850   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
21851   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
21852   // consecutive, non-overlapping, and in the right order.
21853   SmallVector<SDValue, 16> Elts;
21854   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
21855     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
21856
21857   if (SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true))
21858     return LD;
21859
21860   if (isTargetShuffle(N->getOpcode())) {
21861     SDValue Shuffle =
21862         PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
21863     if (Shuffle.getNode())
21864       return Shuffle;
21865
21866     // Try recursively combining arbitrary sequences of x86 shuffle
21867     // instructions into higher-order shuffles. We do this after combining
21868     // specific PSHUF instruction sequences into their minimal form so that we
21869     // can evaluate how many specialized shuffle instructions are involved in
21870     // a particular chain.
21871     SmallVector<int, 1> NonceMask; // Just a placeholder.
21872     NonceMask.push_back(0);
21873     if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
21874                                       /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
21875                                       DCI, Subtarget))
21876       return SDValue(); // This routine will use CombineTo to replace N.
21877   }
21878
21879   return SDValue();
21880 }
21881
21882 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
21883 /// specific shuffle of a load can be folded into a single element load.
21884 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
21885 /// shuffles have been custom lowered so we need to handle those here.
21886 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
21887                                          TargetLowering::DAGCombinerInfo &DCI) {
21888   if (DCI.isBeforeLegalizeOps())
21889     return SDValue();
21890
21891   SDValue InVec = N->getOperand(0);
21892   SDValue EltNo = N->getOperand(1);
21893
21894   if (!isa<ConstantSDNode>(EltNo))
21895     return SDValue();
21896
21897   EVT OriginalVT = InVec.getValueType();
21898
21899   if (InVec.getOpcode() == ISD::BITCAST) {
21900     // Don't duplicate a load with other uses.
21901     if (!InVec.hasOneUse())
21902       return SDValue();
21903     EVT BCVT = InVec.getOperand(0).getValueType();
21904     if (!BCVT.isVector() ||
21905         BCVT.getVectorNumElements() != OriginalVT.getVectorNumElements())
21906       return SDValue();
21907     InVec = InVec.getOperand(0);
21908   }
21909
21910   EVT CurrentVT = InVec.getValueType();
21911
21912   if (!isTargetShuffle(InVec.getOpcode()))
21913     return SDValue();
21914
21915   // Don't duplicate a load with other uses.
21916   if (!InVec.hasOneUse())
21917     return SDValue();
21918
21919   SmallVector<int, 16> ShuffleMask;
21920   bool UnaryShuffle;
21921   if (!getTargetShuffleMask(InVec.getNode(), CurrentVT.getSimpleVT(),
21922                             ShuffleMask, UnaryShuffle))
21923     return SDValue();
21924
21925   // Select the input vector, guarding against out of range extract vector.
21926   unsigned NumElems = CurrentVT.getVectorNumElements();
21927   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
21928   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
21929   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
21930                                          : InVec.getOperand(1);
21931
21932   // If inputs to shuffle are the same for both ops, then allow 2 uses
21933   unsigned AllowedUses = InVec.getNumOperands() > 1 &&
21934                          InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
21935
21936   if (LdNode.getOpcode() == ISD::BITCAST) {
21937     // Don't duplicate a load with other uses.
21938     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
21939       return SDValue();
21940
21941     AllowedUses = 1; // only allow 1 load use if we have a bitcast
21942     LdNode = LdNode.getOperand(0);
21943   }
21944
21945   if (!ISD::isNormalLoad(LdNode.getNode()))
21946     return SDValue();
21947
21948   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
21949
21950   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
21951     return SDValue();
21952
21953   EVT EltVT = N->getValueType(0);
21954   // If there's a bitcast before the shuffle, check if the load type and
21955   // alignment is valid.
21956   unsigned Align = LN0->getAlignment();
21957   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21958   unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
21959       EltVT.getTypeForEVT(*DAG.getContext()));
21960
21961   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, EltVT))
21962     return SDValue();
21963
21964   // All checks match so transform back to vector_shuffle so that DAG combiner
21965   // can finish the job
21966   SDLoc dl(N);
21967
21968   // Create shuffle node taking into account the case that its a unary shuffle
21969   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(CurrentVT)
21970                                    : InVec.getOperand(1);
21971   Shuffle = DAG.getVectorShuffle(CurrentVT, dl,
21972                                  InVec.getOperand(0), Shuffle,
21973                                  &ShuffleMask[0]);
21974   Shuffle = DAG.getBitcast(OriginalVT, Shuffle);
21975   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
21976                      EltNo);
21977 }
21978
21979 /// \brief Detect bitcasts between i32 to x86mmx low word. Since MMX types are
21980 /// special and don't usually play with other vector types, it's better to
21981 /// handle them early to be sure we emit efficient code by avoiding
21982 /// store-load conversions.
21983 static SDValue PerformBITCASTCombine(SDNode *N, SelectionDAG &DAG) {
21984   if (N->getValueType(0) != MVT::x86mmx ||
21985       N->getOperand(0)->getOpcode() != ISD::BUILD_VECTOR ||
21986       N->getOperand(0)->getValueType(0) != MVT::v2i32)
21987     return SDValue();
21988
21989   SDValue V = N->getOperand(0);
21990   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V.getOperand(1));
21991   if (C && C->getZExtValue() == 0 && V.getOperand(0).getValueType() == MVT::i32)
21992     return DAG.getNode(X86ISD::MMX_MOVW2D, SDLoc(V.getOperand(0)),
21993                        N->getValueType(0), V.getOperand(0));
21994
21995   return SDValue();
21996 }
21997
21998 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
21999 /// generation and convert it from being a bunch of shuffles and extracts
22000 /// into a somewhat faster sequence. For i686, the best sequence is apparently
22001 /// storing the value and loading scalars back, while for x64 we should
22002 /// use 64-bit extracts and shifts.
22003 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
22004                                          TargetLowering::DAGCombinerInfo &DCI) {
22005   if (SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI))
22006     return NewOp;
22007
22008   SDValue InputVector = N->getOperand(0);
22009   SDLoc dl(InputVector);
22010   // Detect mmx to i32 conversion through a v2i32 elt extract.
22011   if (InputVector.getOpcode() == ISD::BITCAST && InputVector.hasOneUse() &&
22012       N->getValueType(0) == MVT::i32 &&
22013       InputVector.getValueType() == MVT::v2i32) {
22014
22015     // The bitcast source is a direct mmx result.
22016     SDValue MMXSrc = InputVector.getNode()->getOperand(0);
22017     if (MMXSrc.getValueType() == MVT::x86mmx)
22018       return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
22019                          N->getValueType(0),
22020                          InputVector.getNode()->getOperand(0));
22021
22022     // The mmx is indirect: (i64 extract_elt (v1i64 bitcast (x86mmx ...))).
22023     SDValue MMXSrcOp = MMXSrc.getOperand(0);
22024     if (MMXSrc.getOpcode() == ISD::EXTRACT_VECTOR_ELT && MMXSrc.hasOneUse() &&
22025         MMXSrc.getValueType() == MVT::i64 && MMXSrcOp.hasOneUse() &&
22026         MMXSrcOp.getOpcode() == ISD::BITCAST &&
22027         MMXSrcOp.getValueType() == MVT::v1i64 &&
22028         MMXSrcOp.getOperand(0).getValueType() == MVT::x86mmx)
22029       return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
22030                          N->getValueType(0),
22031                          MMXSrcOp.getOperand(0));
22032   }
22033
22034   EVT VT = N->getValueType(0);
22035
22036   if (VT == MVT::i1 && dyn_cast<ConstantSDNode>(N->getOperand(1)) &&
22037       InputVector.getOpcode() == ISD::BITCAST &&
22038       dyn_cast<ConstantSDNode>(InputVector.getOperand(0))) {
22039     uint64_t ExtractedElt =
22040           cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
22041     uint64_t InputValue =
22042           cast<ConstantSDNode>(InputVector.getOperand(0))->getZExtValue();
22043     uint64_t Res = (InputValue >> ExtractedElt) & 1;
22044     return DAG.getConstant(Res, dl, MVT::i1);
22045   }
22046   // Only operate on vectors of 4 elements, where the alternative shuffling
22047   // gets to be more expensive.
22048   if (InputVector.getValueType() != MVT::v4i32)
22049     return SDValue();
22050
22051   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
22052   // single use which is a sign-extend or zero-extend, and all elements are
22053   // used.
22054   SmallVector<SDNode *, 4> Uses;
22055   unsigned ExtractedElements = 0;
22056   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
22057        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
22058     if (UI.getUse().getResNo() != InputVector.getResNo())
22059       return SDValue();
22060
22061     SDNode *Extract = *UI;
22062     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
22063       return SDValue();
22064
22065     if (Extract->getValueType(0) != MVT::i32)
22066       return SDValue();
22067     if (!Extract->hasOneUse())
22068       return SDValue();
22069     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
22070         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
22071       return SDValue();
22072     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
22073       return SDValue();
22074
22075     // Record which element was extracted.
22076     ExtractedElements |=
22077       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
22078
22079     Uses.push_back(Extract);
22080   }
22081
22082   // If not all the elements were used, this may not be worthwhile.
22083   if (ExtractedElements != 15)
22084     return SDValue();
22085
22086   // Ok, we've now decided to do the transformation.
22087   // If 64-bit shifts are legal, use the extract-shift sequence,
22088   // otherwise bounce the vector off the cache.
22089   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22090   SDValue Vals[4];
22091
22092   if (TLI.isOperationLegal(ISD::SRA, MVT::i64)) {
22093     SDValue Cst = DAG.getBitcast(MVT::v2i64, InputVector);
22094     auto &DL = DAG.getDataLayout();
22095     EVT VecIdxTy = DAG.getTargetLoweringInfo().getVectorIdxTy(DL);
22096     SDValue BottomHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
22097       DAG.getConstant(0, dl, VecIdxTy));
22098     SDValue TopHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
22099       DAG.getConstant(1, dl, VecIdxTy));
22100
22101     SDValue ShAmt = DAG.getConstant(
22102         32, dl, DAG.getTargetLoweringInfo().getShiftAmountTy(MVT::i64, DL));
22103     Vals[0] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BottomHalf);
22104     Vals[1] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
22105       DAG.getNode(ISD::SRA, dl, MVT::i64, BottomHalf, ShAmt));
22106     Vals[2] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, TopHalf);
22107     Vals[3] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
22108       DAG.getNode(ISD::SRA, dl, MVT::i64, TopHalf, ShAmt));
22109   } else {
22110     // Store the value to a temporary stack slot.
22111     SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
22112     SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
22113       MachinePointerInfo(), false, false, 0);
22114
22115     EVT ElementType = InputVector.getValueType().getVectorElementType();
22116     unsigned EltSize = ElementType.getSizeInBits() / 8;
22117
22118     // Replace each use (extract) with a load of the appropriate element.
22119     for (unsigned i = 0; i < 4; ++i) {
22120       uint64_t Offset = EltSize * i;
22121       auto PtrVT = TLI.getPointerTy(DAG.getDataLayout());
22122       SDValue OffsetVal = DAG.getConstant(Offset, dl, PtrVT);
22123
22124       SDValue ScalarAddr =
22125           DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, OffsetVal);
22126
22127       // Load the scalar.
22128       Vals[i] = DAG.getLoad(ElementType, dl, Ch,
22129                             ScalarAddr, MachinePointerInfo(),
22130                             false, false, false, 0);
22131
22132     }
22133   }
22134
22135   // Replace the extracts
22136   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
22137     UE = Uses.end(); UI != UE; ++UI) {
22138     SDNode *Extract = *UI;
22139
22140     SDValue Idx = Extract->getOperand(1);
22141     uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
22142     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), Vals[IdxVal]);
22143   }
22144
22145   // The replacement was made in place; don't return anything.
22146   return SDValue();
22147 }
22148
22149 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
22150 static std::pair<unsigned, bool>
22151 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
22152                    SelectionDAG &DAG, const X86Subtarget *Subtarget) {
22153   if (!VT.isVector())
22154     return std::make_pair(0, false);
22155
22156   bool NeedSplit = false;
22157   switch (VT.getSimpleVT().SimpleTy) {
22158   default: return std::make_pair(0, false);
22159   case MVT::v4i64:
22160   case MVT::v2i64:
22161     if (!Subtarget->hasVLX())
22162       return std::make_pair(0, false);
22163     break;
22164   case MVT::v64i8:
22165   case MVT::v32i16:
22166     if (!Subtarget->hasBWI())
22167       return std::make_pair(0, false);
22168     break;
22169   case MVT::v16i32:
22170   case MVT::v8i64:
22171     if (!Subtarget->hasAVX512())
22172       return std::make_pair(0, false);
22173     break;
22174   case MVT::v32i8:
22175   case MVT::v16i16:
22176   case MVT::v8i32:
22177     if (!Subtarget->hasAVX2())
22178       NeedSplit = true;
22179     if (!Subtarget->hasAVX())
22180       return std::make_pair(0, false);
22181     break;
22182   case MVT::v16i8:
22183   case MVT::v8i16:
22184   case MVT::v4i32:
22185     if (!Subtarget->hasSSE2())
22186       return std::make_pair(0, false);
22187   }
22188
22189   // SSE2 has only a small subset of the operations.
22190   bool hasUnsigned = Subtarget->hasSSE41() ||
22191                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
22192   bool hasSigned = Subtarget->hasSSE41() ||
22193                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
22194
22195   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22196
22197   unsigned Opc = 0;
22198   // Check for x CC y ? x : y.
22199   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
22200       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
22201     switch (CC) {
22202     default: break;
22203     case ISD::SETULT:
22204     case ISD::SETULE:
22205       Opc = hasUnsigned ? ISD::UMIN : 0; break;
22206     case ISD::SETUGT:
22207     case ISD::SETUGE:
22208       Opc = hasUnsigned ? ISD::UMAX : 0; break;
22209     case ISD::SETLT:
22210     case ISD::SETLE:
22211       Opc = hasSigned ? ISD::SMIN : 0; break;
22212     case ISD::SETGT:
22213     case ISD::SETGE:
22214       Opc = hasSigned ? ISD::SMAX : 0; break;
22215     }
22216   // Check for x CC y ? y : x -- a min/max with reversed arms.
22217   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
22218              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
22219     switch (CC) {
22220     default: break;
22221     case ISD::SETULT:
22222     case ISD::SETULE:
22223       Opc = hasUnsigned ? ISD::UMAX : 0; break;
22224     case ISD::SETUGT:
22225     case ISD::SETUGE:
22226       Opc = hasUnsigned ? ISD::UMIN : 0; break;
22227     case ISD::SETLT:
22228     case ISD::SETLE:
22229       Opc = hasSigned ? ISD::SMAX : 0; break;
22230     case ISD::SETGT:
22231     case ISD::SETGE:
22232       Opc = hasSigned ? ISD::SMIN : 0; break;
22233     }
22234   }
22235
22236   return std::make_pair(Opc, NeedSplit);
22237 }
22238
22239 static SDValue
22240 transformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
22241                                       const X86Subtarget *Subtarget) {
22242   SDLoc dl(N);
22243   SDValue Cond = N->getOperand(0);
22244   SDValue LHS = N->getOperand(1);
22245   SDValue RHS = N->getOperand(2);
22246
22247   if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
22248     SDValue CondSrc = Cond->getOperand(0);
22249     if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
22250       Cond = CondSrc->getOperand(0);
22251   }
22252
22253   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
22254     return SDValue();
22255
22256   // A vselect where all conditions and data are constants can be optimized into
22257   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
22258   if (ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
22259       ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
22260     return SDValue();
22261
22262   unsigned MaskValue = 0;
22263   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
22264     return SDValue();
22265
22266   MVT VT = N->getSimpleValueType(0);
22267   unsigned NumElems = VT.getVectorNumElements();
22268   SmallVector<int, 8> ShuffleMask(NumElems, -1);
22269   for (unsigned i = 0; i < NumElems; ++i) {
22270     // Be sure we emit undef where we can.
22271     if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
22272       ShuffleMask[i] = -1;
22273     else
22274       ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
22275   }
22276
22277   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22278   if (!TLI.isShuffleMaskLegal(ShuffleMask, VT))
22279     return SDValue();
22280   return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
22281 }
22282
22283 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
22284 /// nodes.
22285 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
22286                                     TargetLowering::DAGCombinerInfo &DCI,
22287                                     const X86Subtarget *Subtarget) {
22288   SDLoc DL(N);
22289   SDValue Cond = N->getOperand(0);
22290   // Get the LHS/RHS of the select.
22291   SDValue LHS = N->getOperand(1);
22292   SDValue RHS = N->getOperand(2);
22293   EVT VT = LHS.getValueType();
22294   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22295
22296   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
22297   // instructions match the semantics of the common C idiom x<y?x:y but not
22298   // x<=y?x:y, because of how they handle negative zero (which can be
22299   // ignored in unsafe-math mode).
22300   // We also try to create v2f32 min/max nodes, which we later widen to v4f32.
22301   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
22302       VT != MVT::f80 && (TLI.isTypeLegal(VT) || VT == MVT::v2f32) &&
22303       (Subtarget->hasSSE2() ||
22304        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
22305     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22306
22307     unsigned Opcode = 0;
22308     // Check for x CC y ? x : y.
22309     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
22310         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
22311       switch (CC) {
22312       default: break;
22313       case ISD::SETULT:
22314         // Converting this to a min would handle NaNs incorrectly, and swapping
22315         // the operands would cause it to handle comparisons between positive
22316         // and negative zero incorrectly.
22317         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
22318           if (!DAG.getTarget().Options.UnsafeFPMath &&
22319               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
22320             break;
22321           std::swap(LHS, RHS);
22322         }
22323         Opcode = X86ISD::FMIN;
22324         break;
22325       case ISD::SETOLE:
22326         // Converting this to a min would handle comparisons between positive
22327         // and negative zero incorrectly.
22328         if (!DAG.getTarget().Options.UnsafeFPMath &&
22329             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
22330           break;
22331         Opcode = X86ISD::FMIN;
22332         break;
22333       case ISD::SETULE:
22334         // Converting this to a min would handle both negative zeros and NaNs
22335         // incorrectly, but we can swap the operands to fix both.
22336         std::swap(LHS, RHS);
22337       case ISD::SETOLT:
22338       case ISD::SETLT:
22339       case ISD::SETLE:
22340         Opcode = X86ISD::FMIN;
22341         break;
22342
22343       case ISD::SETOGE:
22344         // Converting this to a max would handle comparisons between positive
22345         // and negative zero incorrectly.
22346         if (!DAG.getTarget().Options.UnsafeFPMath &&
22347             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
22348           break;
22349         Opcode = X86ISD::FMAX;
22350         break;
22351       case ISD::SETUGT:
22352         // Converting this to a max would handle NaNs incorrectly, and swapping
22353         // the operands would cause it to handle comparisons between positive
22354         // and negative zero incorrectly.
22355         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
22356           if (!DAG.getTarget().Options.UnsafeFPMath &&
22357               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
22358             break;
22359           std::swap(LHS, RHS);
22360         }
22361         Opcode = X86ISD::FMAX;
22362         break;
22363       case ISD::SETUGE:
22364         // Converting this to a max would handle both negative zeros and NaNs
22365         // incorrectly, but we can swap the operands to fix both.
22366         std::swap(LHS, RHS);
22367       case ISD::SETOGT:
22368       case ISD::SETGT:
22369       case ISD::SETGE:
22370         Opcode = X86ISD::FMAX;
22371         break;
22372       }
22373     // Check for x CC y ? y : x -- a min/max with reversed arms.
22374     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
22375                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
22376       switch (CC) {
22377       default: break;
22378       case ISD::SETOGE:
22379         // Converting this to a min would handle comparisons between positive
22380         // and negative zero incorrectly, and swapping the operands would
22381         // cause it to handle NaNs incorrectly.
22382         if (!DAG.getTarget().Options.UnsafeFPMath &&
22383             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
22384           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
22385             break;
22386           std::swap(LHS, RHS);
22387         }
22388         Opcode = X86ISD::FMIN;
22389         break;
22390       case ISD::SETUGT:
22391         // Converting this to a min would handle NaNs incorrectly.
22392         if (!DAG.getTarget().Options.UnsafeFPMath &&
22393             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
22394           break;
22395         Opcode = X86ISD::FMIN;
22396         break;
22397       case ISD::SETUGE:
22398         // Converting this to a min would handle both negative zeros and NaNs
22399         // incorrectly, but we can swap the operands to fix both.
22400         std::swap(LHS, RHS);
22401       case ISD::SETOGT:
22402       case ISD::SETGT:
22403       case ISD::SETGE:
22404         Opcode = X86ISD::FMIN;
22405         break;
22406
22407       case ISD::SETULT:
22408         // Converting this to a max would handle NaNs incorrectly.
22409         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
22410           break;
22411         Opcode = X86ISD::FMAX;
22412         break;
22413       case ISD::SETOLE:
22414         // Converting this to a max would handle comparisons between positive
22415         // and negative zero incorrectly, and swapping the operands would
22416         // cause it to handle NaNs incorrectly.
22417         if (!DAG.getTarget().Options.UnsafeFPMath &&
22418             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
22419           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
22420             break;
22421           std::swap(LHS, RHS);
22422         }
22423         Opcode = X86ISD::FMAX;
22424         break;
22425       case ISD::SETULE:
22426         // Converting this to a max would handle both negative zeros and NaNs
22427         // incorrectly, but we can swap the operands to fix both.
22428         std::swap(LHS, RHS);
22429       case ISD::SETOLT:
22430       case ISD::SETLT:
22431       case ISD::SETLE:
22432         Opcode = X86ISD::FMAX;
22433         break;
22434       }
22435     }
22436
22437     if (Opcode)
22438       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
22439   }
22440
22441   EVT CondVT = Cond.getValueType();
22442   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
22443       CondVT.getVectorElementType() == MVT::i1) {
22444     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
22445     // lowering on KNL. In this case we convert it to
22446     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
22447     // The same situation for all 128 and 256-bit vectors of i8 and i16.
22448     // Since SKX these selects have a proper lowering.
22449     EVT OpVT = LHS.getValueType();
22450     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
22451         (OpVT.getVectorElementType() == MVT::i8 ||
22452          OpVT.getVectorElementType() == MVT::i16) &&
22453         !(Subtarget->hasBWI() && Subtarget->hasVLX())) {
22454       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
22455       DCI.AddToWorklist(Cond.getNode());
22456       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
22457     }
22458   }
22459   // If this is a select between two integer constants, try to do some
22460   // optimizations.
22461   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
22462     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
22463       // Don't do this for crazy integer types.
22464       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
22465         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
22466         // so that TrueC (the true value) is larger than FalseC.
22467         bool NeedsCondInvert = false;
22468
22469         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
22470             // Efficiently invertible.
22471             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
22472              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
22473               isa<ConstantSDNode>(Cond.getOperand(1))))) {
22474           NeedsCondInvert = true;
22475           std::swap(TrueC, FalseC);
22476         }
22477
22478         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
22479         if (FalseC->getAPIntValue() == 0 &&
22480             TrueC->getAPIntValue().isPowerOf2()) {
22481           if (NeedsCondInvert) // Invert the condition if needed.
22482             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
22483                                DAG.getConstant(1, DL, Cond.getValueType()));
22484
22485           // Zero extend the condition if needed.
22486           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
22487
22488           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
22489           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
22490                              DAG.getConstant(ShAmt, DL, MVT::i8));
22491         }
22492
22493         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
22494         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
22495           if (NeedsCondInvert) // Invert the condition if needed.
22496             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
22497                                DAG.getConstant(1, DL, Cond.getValueType()));
22498
22499           // Zero extend the condition if needed.
22500           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
22501                              FalseC->getValueType(0), Cond);
22502           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
22503                              SDValue(FalseC, 0));
22504         }
22505
22506         // Optimize cases that will turn into an LEA instruction.  This requires
22507         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
22508         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
22509           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
22510           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
22511
22512           bool isFastMultiplier = false;
22513           if (Diff < 10) {
22514             switch ((unsigned char)Diff) {
22515               default: break;
22516               case 1:  // result = add base, cond
22517               case 2:  // result = lea base(    , cond*2)
22518               case 3:  // result = lea base(cond, cond*2)
22519               case 4:  // result = lea base(    , cond*4)
22520               case 5:  // result = lea base(cond, cond*4)
22521               case 8:  // result = lea base(    , cond*8)
22522               case 9:  // result = lea base(cond, cond*8)
22523                 isFastMultiplier = true;
22524                 break;
22525             }
22526           }
22527
22528           if (isFastMultiplier) {
22529             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
22530             if (NeedsCondInvert) // Invert the condition if needed.
22531               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
22532                                  DAG.getConstant(1, DL, Cond.getValueType()));
22533
22534             // Zero extend the condition if needed.
22535             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
22536                                Cond);
22537             // Scale the condition by the difference.
22538             if (Diff != 1)
22539               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
22540                                  DAG.getConstant(Diff, DL,
22541                                                  Cond.getValueType()));
22542
22543             // Add the base if non-zero.
22544             if (FalseC->getAPIntValue() != 0)
22545               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
22546                                  SDValue(FalseC, 0));
22547             return Cond;
22548           }
22549         }
22550       }
22551   }
22552
22553   // Canonicalize max and min:
22554   // (x > y) ? x : y -> (x >= y) ? x : y
22555   // (x < y) ? x : y -> (x <= y) ? x : y
22556   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
22557   // the need for an extra compare
22558   // against zero. e.g.
22559   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
22560   // subl   %esi, %edi
22561   // testl  %edi, %edi
22562   // movl   $0, %eax
22563   // cmovgl %edi, %eax
22564   // =>
22565   // xorl   %eax, %eax
22566   // subl   %esi, $edi
22567   // cmovsl %eax, %edi
22568   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
22569       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
22570       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
22571     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22572     switch (CC) {
22573     default: break;
22574     case ISD::SETLT:
22575     case ISD::SETGT: {
22576       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
22577       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
22578                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
22579       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
22580     }
22581     }
22582   }
22583
22584   // Early exit check
22585   if (!TLI.isTypeLegal(VT))
22586     return SDValue();
22587
22588   // Match VSELECTs into subs with unsigned saturation.
22589   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
22590       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
22591       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
22592        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
22593     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22594
22595     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
22596     // left side invert the predicate to simplify logic below.
22597     SDValue Other;
22598     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
22599       Other = RHS;
22600       CC = ISD::getSetCCInverse(CC, true);
22601     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
22602       Other = LHS;
22603     }
22604
22605     if (Other.getNode() && Other->getNumOperands() == 2 &&
22606         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
22607       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
22608       SDValue CondRHS = Cond->getOperand(1);
22609
22610       // Look for a general sub with unsigned saturation first.
22611       // x >= y ? x-y : 0 --> subus x, y
22612       // x >  y ? x-y : 0 --> subus x, y
22613       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
22614           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
22615         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
22616
22617       if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
22618         if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
22619           if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
22620             if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
22621               // If the RHS is a constant we have to reverse the const
22622               // canonicalization.
22623               // x > C-1 ? x+-C : 0 --> subus x, C
22624               if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
22625                   CondRHSConst->getAPIntValue() ==
22626                       (-OpRHSConst->getAPIntValue() - 1))
22627                 return DAG.getNode(
22628                     X86ISD::SUBUS, DL, VT, OpLHS,
22629                     DAG.getConstant(-OpRHSConst->getAPIntValue(), DL, VT));
22630
22631           // Another special case: If C was a sign bit, the sub has been
22632           // canonicalized into a xor.
22633           // FIXME: Would it be better to use computeKnownBits to determine
22634           //        whether it's safe to decanonicalize the xor?
22635           // x s< 0 ? x^C : 0 --> subus x, C
22636           if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
22637               ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
22638               OpRHSConst->getAPIntValue().isSignBit())
22639             // Note that we have to rebuild the RHS constant here to ensure we
22640             // don't rely on particular values of undef lanes.
22641             return DAG.getNode(
22642                 X86ISD::SUBUS, DL, VT, OpLHS,
22643                 DAG.getConstant(OpRHSConst->getAPIntValue(), DL, VT));
22644         }
22645     }
22646   }
22647
22648   // Try to match a min/max vector operation.
22649   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
22650     std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
22651     unsigned Opc = ret.first;
22652     bool NeedSplit = ret.second;
22653
22654     if (Opc && NeedSplit) {
22655       unsigned NumElems = VT.getVectorNumElements();
22656       // Extract the LHS vectors
22657       SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
22658       SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
22659
22660       // Extract the RHS vectors
22661       SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
22662       SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
22663
22664       // Create min/max for each subvector
22665       LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
22666       RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
22667
22668       // Merge the result
22669       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
22670     } else if (Opc)
22671       return DAG.getNode(Opc, DL, VT, LHS, RHS);
22672   }
22673
22674   // Simplify vector selection if condition value type matches vselect
22675   // operand type
22676   if (N->getOpcode() == ISD::VSELECT && CondVT == VT) {
22677     assert(Cond.getValueType().isVector() &&
22678            "vector select expects a vector selector!");
22679
22680     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
22681     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
22682
22683     // Try invert the condition if true value is not all 1s and false value
22684     // is not all 0s.
22685     if (!TValIsAllOnes && !FValIsAllZeros &&
22686         // Check if the selector will be produced by CMPP*/PCMP*
22687         Cond.getOpcode() == ISD::SETCC &&
22688         // Check if SETCC has already been promoted
22689         TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT) ==
22690             CondVT) {
22691       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
22692       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
22693
22694       if (TValIsAllZeros || FValIsAllOnes) {
22695         SDValue CC = Cond.getOperand(2);
22696         ISD::CondCode NewCC =
22697           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
22698                                Cond.getOperand(0).getValueType().isInteger());
22699         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
22700         std::swap(LHS, RHS);
22701         TValIsAllOnes = FValIsAllOnes;
22702         FValIsAllZeros = TValIsAllZeros;
22703       }
22704     }
22705
22706     if (TValIsAllOnes || FValIsAllZeros) {
22707       SDValue Ret;
22708
22709       if (TValIsAllOnes && FValIsAllZeros)
22710         Ret = Cond;
22711       else if (TValIsAllOnes)
22712         Ret =
22713             DAG.getNode(ISD::OR, DL, CondVT, Cond, DAG.getBitcast(CondVT, RHS));
22714       else if (FValIsAllZeros)
22715         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
22716                           DAG.getBitcast(CondVT, LHS));
22717
22718       return DAG.getBitcast(VT, Ret);
22719     }
22720   }
22721
22722   // We should generate an X86ISD::BLENDI from a vselect if its argument
22723   // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
22724   // constants. This specific pattern gets generated when we split a
22725   // selector for a 512 bit vector in a machine without AVX512 (but with
22726   // 256-bit vectors), during legalization:
22727   //
22728   // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
22729   //
22730   // Iff we find this pattern and the build_vectors are built from
22731   // constants, we translate the vselect into a shuffle_vector that we
22732   // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
22733   if ((N->getOpcode() == ISD::VSELECT ||
22734        N->getOpcode() == X86ISD::SHRUNKBLEND) &&
22735       !DCI.isBeforeLegalize() && !VT.is512BitVector()) {
22736     SDValue Shuffle = transformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
22737     if (Shuffle.getNode())
22738       return Shuffle;
22739   }
22740
22741   // If this is a *dynamic* select (non-constant condition) and we can match
22742   // this node with one of the variable blend instructions, restructure the
22743   // condition so that the blends can use the high bit of each element and use
22744   // SimplifyDemandedBits to simplify the condition operand.
22745   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
22746       !DCI.isBeforeLegalize() &&
22747       !ISD::isBuildVectorOfConstantSDNodes(Cond.getNode())) {
22748     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
22749
22750     // Don't optimize vector selects that map to mask-registers.
22751     if (BitWidth == 1)
22752       return SDValue();
22753
22754     // We can only handle the cases where VSELECT is directly legal on the
22755     // subtarget. We custom lower VSELECT nodes with constant conditions and
22756     // this makes it hard to see whether a dynamic VSELECT will correctly
22757     // lower, so we both check the operation's status and explicitly handle the
22758     // cases where a *dynamic* blend will fail even though a constant-condition
22759     // blend could be custom lowered.
22760     // FIXME: We should find a better way to handle this class of problems.
22761     // Potentially, we should combine constant-condition vselect nodes
22762     // pre-legalization into shuffles and not mark as many types as custom
22763     // lowered.
22764     if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
22765       return SDValue();
22766     // FIXME: We don't support i16-element blends currently. We could and
22767     // should support them by making *all* the bits in the condition be set
22768     // rather than just the high bit and using an i8-element blend.
22769     if (VT.getScalarType() == MVT::i16)
22770       return SDValue();
22771     // Dynamic blending was only available from SSE4.1 onward.
22772     if (VT.getSizeInBits() == 128 && !Subtarget->hasSSE41())
22773       return SDValue();
22774     // Byte blends are only available in AVX2
22775     if (VT.getSizeInBits() == 256 && VT.getScalarType() == MVT::i8 &&
22776         !Subtarget->hasAVX2())
22777       return SDValue();
22778
22779     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
22780     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
22781
22782     APInt KnownZero, KnownOne;
22783     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
22784                                           DCI.isBeforeLegalizeOps());
22785     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
22786         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne,
22787                                  TLO)) {
22788       // If we changed the computation somewhere in the DAG, this change
22789       // will affect all users of Cond.
22790       // Make sure it is fine and update all the nodes so that we do not
22791       // use the generic VSELECT anymore. Otherwise, we may perform
22792       // wrong optimizations as we messed up with the actual expectation
22793       // for the vector boolean values.
22794       if (Cond != TLO.Old) {
22795         // Check all uses of that condition operand to check whether it will be
22796         // consumed by non-BLEND instructions, which may depend on all bits are
22797         // set properly.
22798         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
22799              I != E; ++I)
22800           if (I->getOpcode() != ISD::VSELECT)
22801             // TODO: Add other opcodes eventually lowered into BLEND.
22802             return SDValue();
22803
22804         // Update all the users of the condition, before committing the change,
22805         // so that the VSELECT optimizations that expect the correct vector
22806         // boolean value will not be triggered.
22807         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
22808              I != E; ++I)
22809           DAG.ReplaceAllUsesOfValueWith(
22810               SDValue(*I, 0),
22811               DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(*I), I->getValueType(0),
22812                           Cond, I->getOperand(1), I->getOperand(2)));
22813         DCI.CommitTargetLoweringOpt(TLO);
22814         return SDValue();
22815       }
22816       // At this point, only Cond is changed. Change the condition
22817       // just for N to keep the opportunity to optimize all other
22818       // users their own way.
22819       DAG.ReplaceAllUsesOfValueWith(
22820           SDValue(N, 0),
22821           DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(N), N->getValueType(0),
22822                       TLO.New, N->getOperand(1), N->getOperand(2)));
22823       return SDValue();
22824     }
22825   }
22826
22827   return SDValue();
22828 }
22829
22830 // Check whether a boolean test is testing a boolean value generated by
22831 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
22832 // code.
22833 //
22834 // Simplify the following patterns:
22835 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
22836 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
22837 // to (Op EFLAGS Cond)
22838 //
22839 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
22840 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
22841 // to (Op EFLAGS !Cond)
22842 //
22843 // where Op could be BRCOND or CMOV.
22844 //
22845 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
22846   // Quit if not CMP and SUB with its value result used.
22847   if (Cmp.getOpcode() != X86ISD::CMP &&
22848       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
22849       return SDValue();
22850
22851   // Quit if not used as a boolean value.
22852   if (CC != X86::COND_E && CC != X86::COND_NE)
22853     return SDValue();
22854
22855   // Check CMP operands. One of them should be 0 or 1 and the other should be
22856   // an SetCC or extended from it.
22857   SDValue Op1 = Cmp.getOperand(0);
22858   SDValue Op2 = Cmp.getOperand(1);
22859
22860   SDValue SetCC;
22861   const ConstantSDNode* C = nullptr;
22862   bool needOppositeCond = (CC == X86::COND_E);
22863   bool checkAgainstTrue = false; // Is it a comparison against 1?
22864
22865   if ((C = dyn_cast<ConstantSDNode>(Op1)))
22866     SetCC = Op2;
22867   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
22868     SetCC = Op1;
22869   else // Quit if all operands are not constants.
22870     return SDValue();
22871
22872   if (C->getZExtValue() == 1) {
22873     needOppositeCond = !needOppositeCond;
22874     checkAgainstTrue = true;
22875   } else if (C->getZExtValue() != 0)
22876     // Quit if the constant is neither 0 or 1.
22877     return SDValue();
22878
22879   bool truncatedToBoolWithAnd = false;
22880   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
22881   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
22882          SetCC.getOpcode() == ISD::TRUNCATE ||
22883          SetCC.getOpcode() == ISD::AND) {
22884     if (SetCC.getOpcode() == ISD::AND) {
22885       int OpIdx = -1;
22886       ConstantSDNode *CS;
22887       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
22888           CS->getZExtValue() == 1)
22889         OpIdx = 1;
22890       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
22891           CS->getZExtValue() == 1)
22892         OpIdx = 0;
22893       if (OpIdx == -1)
22894         break;
22895       SetCC = SetCC.getOperand(OpIdx);
22896       truncatedToBoolWithAnd = true;
22897     } else
22898       SetCC = SetCC.getOperand(0);
22899   }
22900
22901   switch (SetCC.getOpcode()) {
22902   case X86ISD::SETCC_CARRY:
22903     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
22904     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
22905     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
22906     // truncated to i1 using 'and'.
22907     if (checkAgainstTrue && !truncatedToBoolWithAnd)
22908       break;
22909     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
22910            "Invalid use of SETCC_CARRY!");
22911     // FALL THROUGH
22912   case X86ISD::SETCC:
22913     // Set the condition code or opposite one if necessary.
22914     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
22915     if (needOppositeCond)
22916       CC = X86::GetOppositeBranchCondition(CC);
22917     return SetCC.getOperand(1);
22918   case X86ISD::CMOV: {
22919     // Check whether false/true value has canonical one, i.e. 0 or 1.
22920     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
22921     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
22922     // Quit if true value is not a constant.
22923     if (!TVal)
22924       return SDValue();
22925     // Quit if false value is not a constant.
22926     if (!FVal) {
22927       SDValue Op = SetCC.getOperand(0);
22928       // Skip 'zext' or 'trunc' node.
22929       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
22930           Op.getOpcode() == ISD::TRUNCATE)
22931         Op = Op.getOperand(0);
22932       // A special case for rdrand/rdseed, where 0 is set if false cond is
22933       // found.
22934       if ((Op.getOpcode() != X86ISD::RDRAND &&
22935            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
22936         return SDValue();
22937     }
22938     // Quit if false value is not the constant 0 or 1.
22939     bool FValIsFalse = true;
22940     if (FVal && FVal->getZExtValue() != 0) {
22941       if (FVal->getZExtValue() != 1)
22942         return SDValue();
22943       // If FVal is 1, opposite cond is needed.
22944       needOppositeCond = !needOppositeCond;
22945       FValIsFalse = false;
22946     }
22947     // Quit if TVal is not the constant opposite of FVal.
22948     if (FValIsFalse && TVal->getZExtValue() != 1)
22949       return SDValue();
22950     if (!FValIsFalse && TVal->getZExtValue() != 0)
22951       return SDValue();
22952     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
22953     if (needOppositeCond)
22954       CC = X86::GetOppositeBranchCondition(CC);
22955     return SetCC.getOperand(3);
22956   }
22957   }
22958
22959   return SDValue();
22960 }
22961
22962 /// Check whether Cond is an AND/OR of SETCCs off of the same EFLAGS.
22963 /// Match:
22964 ///   (X86or (X86setcc) (X86setcc))
22965 ///   (X86cmp (and (X86setcc) (X86setcc)), 0)
22966 static bool checkBoolTestAndOrSetCCCombine(SDValue Cond, X86::CondCode &CC0,
22967                                            X86::CondCode &CC1, SDValue &Flags,
22968                                            bool &isAnd) {
22969   if (Cond->getOpcode() == X86ISD::CMP) {
22970     ConstantSDNode *CondOp1C = dyn_cast<ConstantSDNode>(Cond->getOperand(1));
22971     if (!CondOp1C || !CondOp1C->isNullValue())
22972       return false;
22973
22974     Cond = Cond->getOperand(0);
22975   }
22976
22977   isAnd = false;
22978
22979   SDValue SetCC0, SetCC1;
22980   switch (Cond->getOpcode()) {
22981   default: return false;
22982   case ISD::AND:
22983   case X86ISD::AND:
22984     isAnd = true;
22985     // fallthru
22986   case ISD::OR:
22987   case X86ISD::OR:
22988     SetCC0 = Cond->getOperand(0);
22989     SetCC1 = Cond->getOperand(1);
22990     break;
22991   };
22992
22993   // Make sure we have SETCC nodes, using the same flags value.
22994   if (SetCC0.getOpcode() != X86ISD::SETCC ||
22995       SetCC1.getOpcode() != X86ISD::SETCC ||
22996       SetCC0->getOperand(1) != SetCC1->getOperand(1))
22997     return false;
22998
22999   CC0 = (X86::CondCode)SetCC0->getConstantOperandVal(0);
23000   CC1 = (X86::CondCode)SetCC1->getConstantOperandVal(0);
23001   Flags = SetCC0->getOperand(1);
23002   return true;
23003 }
23004
23005 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
23006 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
23007                                   TargetLowering::DAGCombinerInfo &DCI,
23008                                   const X86Subtarget *Subtarget) {
23009   SDLoc DL(N);
23010
23011   // If the flag operand isn't dead, don't touch this CMOV.
23012   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
23013     return SDValue();
23014
23015   SDValue FalseOp = N->getOperand(0);
23016   SDValue TrueOp = N->getOperand(1);
23017   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
23018   SDValue Cond = N->getOperand(3);
23019
23020   if (CC == X86::COND_E || CC == X86::COND_NE) {
23021     switch (Cond.getOpcode()) {
23022     default: break;
23023     case X86ISD::BSR:
23024     case X86ISD::BSF:
23025       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
23026       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
23027         return (CC == X86::COND_E) ? FalseOp : TrueOp;
23028     }
23029   }
23030
23031   SDValue Flags;
23032
23033   Flags = checkBoolTestSetCCCombine(Cond, CC);
23034   if (Flags.getNode() &&
23035       // Extra check as FCMOV only supports a subset of X86 cond.
23036       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
23037     SDValue Ops[] = { FalseOp, TrueOp,
23038                       DAG.getConstant(CC, DL, MVT::i8), Flags };
23039     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
23040   }
23041
23042   // If this is a select between two integer constants, try to do some
23043   // optimizations.  Note that the operands are ordered the opposite of SELECT
23044   // operands.
23045   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
23046     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
23047       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
23048       // larger than FalseC (the false value).
23049       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
23050         CC = X86::GetOppositeBranchCondition(CC);
23051         std::swap(TrueC, FalseC);
23052         std::swap(TrueOp, FalseOp);
23053       }
23054
23055       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
23056       // This is efficient for any integer data type (including i8/i16) and
23057       // shift amount.
23058       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
23059         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
23060                            DAG.getConstant(CC, DL, MVT::i8), Cond);
23061
23062         // Zero extend the condition if needed.
23063         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
23064
23065         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
23066         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
23067                            DAG.getConstant(ShAmt, DL, MVT::i8));
23068         if (N->getNumValues() == 2)  // Dead flag value?
23069           return DCI.CombineTo(N, Cond, SDValue());
23070         return Cond;
23071       }
23072
23073       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
23074       // for any integer data type, including i8/i16.
23075       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
23076         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
23077                            DAG.getConstant(CC, DL, MVT::i8), Cond);
23078
23079         // Zero extend the condition if needed.
23080         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
23081                            FalseC->getValueType(0), Cond);
23082         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23083                            SDValue(FalseC, 0));
23084
23085         if (N->getNumValues() == 2)  // Dead flag value?
23086           return DCI.CombineTo(N, Cond, SDValue());
23087         return Cond;
23088       }
23089
23090       // Optimize cases that will turn into an LEA instruction.  This requires
23091       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
23092       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
23093         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
23094         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
23095
23096         bool isFastMultiplier = false;
23097         if (Diff < 10) {
23098           switch ((unsigned char)Diff) {
23099           default: break;
23100           case 1:  // result = add base, cond
23101           case 2:  // result = lea base(    , cond*2)
23102           case 3:  // result = lea base(cond, cond*2)
23103           case 4:  // result = lea base(    , cond*4)
23104           case 5:  // result = lea base(cond, cond*4)
23105           case 8:  // result = lea base(    , cond*8)
23106           case 9:  // result = lea base(cond, cond*8)
23107             isFastMultiplier = true;
23108             break;
23109           }
23110         }
23111
23112         if (isFastMultiplier) {
23113           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
23114           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
23115                              DAG.getConstant(CC, DL, MVT::i8), Cond);
23116           // Zero extend the condition if needed.
23117           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
23118                              Cond);
23119           // Scale the condition by the difference.
23120           if (Diff != 1)
23121             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
23122                                DAG.getConstant(Diff, DL, Cond.getValueType()));
23123
23124           // Add the base if non-zero.
23125           if (FalseC->getAPIntValue() != 0)
23126             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23127                                SDValue(FalseC, 0));
23128           if (N->getNumValues() == 2)  // Dead flag value?
23129             return DCI.CombineTo(N, Cond, SDValue());
23130           return Cond;
23131         }
23132       }
23133     }
23134   }
23135
23136   // Handle these cases:
23137   //   (select (x != c), e, c) -> select (x != c), e, x),
23138   //   (select (x == c), c, e) -> select (x == c), x, e)
23139   // where the c is an integer constant, and the "select" is the combination
23140   // of CMOV and CMP.
23141   //
23142   // The rationale for this change is that the conditional-move from a constant
23143   // needs two instructions, however, conditional-move from a register needs
23144   // only one instruction.
23145   //
23146   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
23147   //  some instruction-combining opportunities. This opt needs to be
23148   //  postponed as late as possible.
23149   //
23150   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
23151     // the DCI.xxxx conditions are provided to postpone the optimization as
23152     // late as possible.
23153
23154     ConstantSDNode *CmpAgainst = nullptr;
23155     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
23156         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
23157         !isa<ConstantSDNode>(Cond.getOperand(0))) {
23158
23159       if (CC == X86::COND_NE &&
23160           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
23161         CC = X86::GetOppositeBranchCondition(CC);
23162         std::swap(TrueOp, FalseOp);
23163       }
23164
23165       if (CC == X86::COND_E &&
23166           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
23167         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
23168                           DAG.getConstant(CC, DL, MVT::i8), Cond };
23169         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
23170       }
23171     }
23172   }
23173
23174   // Fold and/or of setcc's to double CMOV:
23175   //   (CMOV F, T, ((cc1 | cc2) != 0)) -> (CMOV (CMOV F, T, cc1), T, cc2)
23176   //   (CMOV F, T, ((cc1 & cc2) != 0)) -> (CMOV (CMOV T, F, !cc1), F, !cc2)
23177   //
23178   // This combine lets us generate:
23179   //   cmovcc1 (jcc1 if we don't have CMOV)
23180   //   cmovcc2 (same)
23181   // instead of:
23182   //   setcc1
23183   //   setcc2
23184   //   and/or
23185   //   cmovne (jne if we don't have CMOV)
23186   // When we can't use the CMOV instruction, it might increase branch
23187   // mispredicts.
23188   // When we can use CMOV, or when there is no mispredict, this improves
23189   // throughput and reduces register pressure.
23190   //
23191   if (CC == X86::COND_NE) {
23192     SDValue Flags;
23193     X86::CondCode CC0, CC1;
23194     bool isAndSetCC;
23195     if (checkBoolTestAndOrSetCCCombine(Cond, CC0, CC1, Flags, isAndSetCC)) {
23196       if (isAndSetCC) {
23197         std::swap(FalseOp, TrueOp);
23198         CC0 = X86::GetOppositeBranchCondition(CC0);
23199         CC1 = X86::GetOppositeBranchCondition(CC1);
23200       }
23201
23202       SDValue LOps[] = {FalseOp, TrueOp, DAG.getConstant(CC0, DL, MVT::i8),
23203         Flags};
23204       SDValue LCMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), LOps);
23205       SDValue Ops[] = {LCMOV, TrueOp, DAG.getConstant(CC1, DL, MVT::i8), Flags};
23206       SDValue CMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
23207       DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SDValue(CMOV.getNode(), 1));
23208       return CMOV;
23209     }
23210   }
23211
23212   return SDValue();
23213 }
23214
23215 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
23216                                                 const X86Subtarget *Subtarget) {
23217   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
23218   switch (IntNo) {
23219   default: return SDValue();
23220   // SSE/AVX/AVX2 blend intrinsics.
23221   case Intrinsic::x86_avx2_pblendvb:
23222     // Don't try to simplify this intrinsic if we don't have AVX2.
23223     if (!Subtarget->hasAVX2())
23224       return SDValue();
23225     // FALL-THROUGH
23226   case Intrinsic::x86_avx_blendv_pd_256:
23227   case Intrinsic::x86_avx_blendv_ps_256:
23228     // Don't try to simplify this intrinsic if we don't have AVX.
23229     if (!Subtarget->hasAVX())
23230       return SDValue();
23231     // FALL-THROUGH
23232   case Intrinsic::x86_sse41_blendvps:
23233   case Intrinsic::x86_sse41_blendvpd:
23234   case Intrinsic::x86_sse41_pblendvb: {
23235     SDValue Op0 = N->getOperand(1);
23236     SDValue Op1 = N->getOperand(2);
23237     SDValue Mask = N->getOperand(3);
23238
23239     // Don't try to simplify this intrinsic if we don't have SSE4.1.
23240     if (!Subtarget->hasSSE41())
23241       return SDValue();
23242
23243     // fold (blend A, A, Mask) -> A
23244     if (Op0 == Op1)
23245       return Op0;
23246     // fold (blend A, B, allZeros) -> A
23247     if (ISD::isBuildVectorAllZeros(Mask.getNode()))
23248       return Op0;
23249     // fold (blend A, B, allOnes) -> B
23250     if (ISD::isBuildVectorAllOnes(Mask.getNode()))
23251       return Op1;
23252
23253     // Simplify the case where the mask is a constant i32 value.
23254     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
23255       if (C->isNullValue())
23256         return Op0;
23257       if (C->isAllOnesValue())
23258         return Op1;
23259     }
23260
23261     return SDValue();
23262   }
23263
23264   // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
23265   case Intrinsic::x86_sse2_psrai_w:
23266   case Intrinsic::x86_sse2_psrai_d:
23267   case Intrinsic::x86_avx2_psrai_w:
23268   case Intrinsic::x86_avx2_psrai_d:
23269   case Intrinsic::x86_sse2_psra_w:
23270   case Intrinsic::x86_sse2_psra_d:
23271   case Intrinsic::x86_avx2_psra_w:
23272   case Intrinsic::x86_avx2_psra_d: {
23273     SDValue Op0 = N->getOperand(1);
23274     SDValue Op1 = N->getOperand(2);
23275     EVT VT = Op0.getValueType();
23276     assert(VT.isVector() && "Expected a vector type!");
23277
23278     if (isa<BuildVectorSDNode>(Op1))
23279       Op1 = Op1.getOperand(0);
23280
23281     if (!isa<ConstantSDNode>(Op1))
23282       return SDValue();
23283
23284     EVT SVT = VT.getVectorElementType();
23285     unsigned SVTBits = SVT.getSizeInBits();
23286
23287     ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
23288     const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
23289     uint64_t ShAmt = C.getZExtValue();
23290
23291     // Don't try to convert this shift into a ISD::SRA if the shift
23292     // count is bigger than or equal to the element size.
23293     if (ShAmt >= SVTBits)
23294       return SDValue();
23295
23296     // Trivial case: if the shift count is zero, then fold this
23297     // into the first operand.
23298     if (ShAmt == 0)
23299       return Op0;
23300
23301     // Replace this packed shift intrinsic with a target independent
23302     // shift dag node.
23303     SDLoc DL(N);
23304     SDValue Splat = DAG.getConstant(C, DL, VT);
23305     return DAG.getNode(ISD::SRA, DL, VT, Op0, Splat);
23306   }
23307   }
23308 }
23309
23310 /// PerformMulCombine - Optimize a single multiply with constant into two
23311 /// in order to implement it with two cheaper instructions, e.g.
23312 /// LEA + SHL, LEA + LEA.
23313 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
23314                                  TargetLowering::DAGCombinerInfo &DCI) {
23315   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
23316     return SDValue();
23317
23318   EVT VT = N->getValueType(0);
23319   if (VT != MVT::i64 && VT != MVT::i32)
23320     return SDValue();
23321
23322   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
23323   if (!C)
23324     return SDValue();
23325   uint64_t MulAmt = C->getZExtValue();
23326   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
23327     return SDValue();
23328
23329   uint64_t MulAmt1 = 0;
23330   uint64_t MulAmt2 = 0;
23331   if ((MulAmt % 9) == 0) {
23332     MulAmt1 = 9;
23333     MulAmt2 = MulAmt / 9;
23334   } else if ((MulAmt % 5) == 0) {
23335     MulAmt1 = 5;
23336     MulAmt2 = MulAmt / 5;
23337   } else if ((MulAmt % 3) == 0) {
23338     MulAmt1 = 3;
23339     MulAmt2 = MulAmt / 3;
23340   }
23341   if (MulAmt2 &&
23342       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
23343     SDLoc DL(N);
23344
23345     if (isPowerOf2_64(MulAmt2) &&
23346         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
23347       // If second multiplifer is pow2, issue it first. We want the multiply by
23348       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
23349       // is an add.
23350       std::swap(MulAmt1, MulAmt2);
23351
23352     SDValue NewMul;
23353     if (isPowerOf2_64(MulAmt1))
23354       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
23355                            DAG.getConstant(Log2_64(MulAmt1), DL, MVT::i8));
23356     else
23357       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
23358                            DAG.getConstant(MulAmt1, DL, VT));
23359
23360     if (isPowerOf2_64(MulAmt2))
23361       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
23362                            DAG.getConstant(Log2_64(MulAmt2), DL, MVT::i8));
23363     else
23364       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
23365                            DAG.getConstant(MulAmt2, DL, VT));
23366
23367     // Do not add new nodes to DAG combiner worklist.
23368     DCI.CombineTo(N, NewMul, false);
23369   }
23370   return SDValue();
23371 }
23372
23373 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
23374   SDValue N0 = N->getOperand(0);
23375   SDValue N1 = N->getOperand(1);
23376   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
23377   EVT VT = N0.getValueType();
23378
23379   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
23380   // since the result of setcc_c is all zero's or all ones.
23381   if (VT.isInteger() && !VT.isVector() &&
23382       N1C && N0.getOpcode() == ISD::AND &&
23383       N0.getOperand(1).getOpcode() == ISD::Constant) {
23384     SDValue N00 = N0.getOperand(0);
23385     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
23386         ((N00.getOpcode() == ISD::ANY_EXTEND ||
23387           N00.getOpcode() == ISD::ZERO_EXTEND) &&
23388          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
23389       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
23390       APInt ShAmt = N1C->getAPIntValue();
23391       Mask = Mask.shl(ShAmt);
23392       if (Mask != 0) {
23393         SDLoc DL(N);
23394         return DAG.getNode(ISD::AND, DL, VT,
23395                            N00, DAG.getConstant(Mask, DL, VT));
23396       }
23397     }
23398   }
23399
23400   // Hardware support for vector shifts is sparse which makes us scalarize the
23401   // vector operations in many cases. Also, on sandybridge ADD is faster than
23402   // shl.
23403   // (shl V, 1) -> add V,V
23404   if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
23405     if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
23406       assert(N0.getValueType().isVector() && "Invalid vector shift type");
23407       // We shift all of the values by one. In many cases we do not have
23408       // hardware support for this operation. This is better expressed as an ADD
23409       // of two values.
23410       if (N1SplatC->getAPIntValue() == 1)
23411         return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
23412     }
23413
23414   return SDValue();
23415 }
23416
23417 /// \brief Returns a vector of 0s if the node in input is a vector logical
23418 /// shift by a constant amount which is known to be bigger than or equal
23419 /// to the vector element size in bits.
23420 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
23421                                       const X86Subtarget *Subtarget) {
23422   EVT VT = N->getValueType(0);
23423
23424   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
23425       (!Subtarget->hasInt256() ||
23426        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
23427     return SDValue();
23428
23429   SDValue Amt = N->getOperand(1);
23430   SDLoc DL(N);
23431   if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
23432     if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
23433       APInt ShiftAmt = AmtSplat->getAPIntValue();
23434       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
23435
23436       // SSE2/AVX2 logical shifts always return a vector of 0s
23437       // if the shift amount is bigger than or equal to
23438       // the element size. The constant shift amount will be
23439       // encoded as a 8-bit immediate.
23440       if (ShiftAmt.trunc(8).uge(MaxAmount))
23441         return getZeroVector(VT, Subtarget, DAG, DL);
23442     }
23443
23444   return SDValue();
23445 }
23446
23447 /// PerformShiftCombine - Combine shifts.
23448 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
23449                                    TargetLowering::DAGCombinerInfo &DCI,
23450                                    const X86Subtarget *Subtarget) {
23451   if (N->getOpcode() == ISD::SHL)
23452     if (SDValue V = PerformSHLCombine(N, DAG))
23453       return V;
23454
23455   // Try to fold this logical shift into a zero vector.
23456   if (N->getOpcode() != ISD::SRA)
23457     if (SDValue V = performShiftToAllZeros(N, DAG, Subtarget))
23458       return V;
23459
23460   return SDValue();
23461 }
23462
23463 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
23464 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
23465 // and friends.  Likewise for OR -> CMPNEQSS.
23466 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
23467                             TargetLowering::DAGCombinerInfo &DCI,
23468                             const X86Subtarget *Subtarget) {
23469   unsigned opcode;
23470
23471   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
23472   // we're requiring SSE2 for both.
23473   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
23474     SDValue N0 = N->getOperand(0);
23475     SDValue N1 = N->getOperand(1);
23476     SDValue CMP0 = N0->getOperand(1);
23477     SDValue CMP1 = N1->getOperand(1);
23478     SDLoc DL(N);
23479
23480     // The SETCCs should both refer to the same CMP.
23481     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
23482       return SDValue();
23483
23484     SDValue CMP00 = CMP0->getOperand(0);
23485     SDValue CMP01 = CMP0->getOperand(1);
23486     EVT     VT    = CMP00.getValueType();
23487
23488     if (VT == MVT::f32 || VT == MVT::f64) {
23489       bool ExpectingFlags = false;
23490       // Check for any users that want flags:
23491       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
23492            !ExpectingFlags && UI != UE; ++UI)
23493         switch (UI->getOpcode()) {
23494         default:
23495         case ISD::BR_CC:
23496         case ISD::BRCOND:
23497         case ISD::SELECT:
23498           ExpectingFlags = true;
23499           break;
23500         case ISD::CopyToReg:
23501         case ISD::SIGN_EXTEND:
23502         case ISD::ZERO_EXTEND:
23503         case ISD::ANY_EXTEND:
23504           break;
23505         }
23506
23507       if (!ExpectingFlags) {
23508         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
23509         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
23510
23511         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
23512           X86::CondCode tmp = cc0;
23513           cc0 = cc1;
23514           cc1 = tmp;
23515         }
23516
23517         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
23518             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
23519           // FIXME: need symbolic constants for these magic numbers.
23520           // See X86ATTInstPrinter.cpp:printSSECC().
23521           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
23522           if (Subtarget->hasAVX512()) {
23523             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
23524                                          CMP01,
23525                                          DAG.getConstant(x86cc, DL, MVT::i8));
23526             if (N->getValueType(0) != MVT::i1)
23527               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
23528                                  FSetCC);
23529             return FSetCC;
23530           }
23531           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
23532                                               CMP00.getValueType(), CMP00, CMP01,
23533                                               DAG.getConstant(x86cc, DL,
23534                                                               MVT::i8));
23535
23536           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
23537           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
23538
23539           if (is64BitFP && !Subtarget->is64Bit()) {
23540             // On a 32-bit target, we cannot bitcast the 64-bit float to a
23541             // 64-bit integer, since that's not a legal type. Since
23542             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
23543             // bits, but can do this little dance to extract the lowest 32 bits
23544             // and work with those going forward.
23545             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
23546                                            OnesOrZeroesF);
23547             SDValue Vector32 = DAG.getBitcast(MVT::v4f32, Vector64);
23548             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
23549                                         Vector32, DAG.getIntPtrConstant(0, DL));
23550             IntVT = MVT::i32;
23551           }
23552
23553           SDValue OnesOrZeroesI = DAG.getBitcast(IntVT, OnesOrZeroesF);
23554           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
23555                                       DAG.getConstant(1, DL, IntVT));
23556           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8,
23557                                               ANDed);
23558           return OneBitOfTruth;
23559         }
23560       }
23561     }
23562   }
23563   return SDValue();
23564 }
23565
23566 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
23567 /// so it can be folded inside ANDNP.
23568 static bool CanFoldXORWithAllOnes(const SDNode *N) {
23569   EVT VT = N->getValueType(0);
23570
23571   // Match direct AllOnes for 128 and 256-bit vectors
23572   if (ISD::isBuildVectorAllOnes(N))
23573     return true;
23574
23575   // Look through a bit convert.
23576   if (N->getOpcode() == ISD::BITCAST)
23577     N = N->getOperand(0).getNode();
23578
23579   // Sometimes the operand may come from a insert_subvector building a 256-bit
23580   // allones vector
23581   if (VT.is256BitVector() &&
23582       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
23583     SDValue V1 = N->getOperand(0);
23584     SDValue V2 = N->getOperand(1);
23585
23586     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
23587         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
23588         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
23589         ISD::isBuildVectorAllOnes(V2.getNode()))
23590       return true;
23591   }
23592
23593   return false;
23594 }
23595
23596 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
23597 // register. In most cases we actually compare or select YMM-sized registers
23598 // and mixing the two types creates horrible code. This method optimizes
23599 // some of the transition sequences.
23600 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
23601                                  TargetLowering::DAGCombinerInfo &DCI,
23602                                  const X86Subtarget *Subtarget) {
23603   EVT VT = N->getValueType(0);
23604   if (!VT.is256BitVector())
23605     return SDValue();
23606
23607   assert((N->getOpcode() == ISD::ANY_EXTEND ||
23608           N->getOpcode() == ISD::ZERO_EXTEND ||
23609           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
23610
23611   SDValue Narrow = N->getOperand(0);
23612   EVT NarrowVT = Narrow->getValueType(0);
23613   if (!NarrowVT.is128BitVector())
23614     return SDValue();
23615
23616   if (Narrow->getOpcode() != ISD::XOR &&
23617       Narrow->getOpcode() != ISD::AND &&
23618       Narrow->getOpcode() != ISD::OR)
23619     return SDValue();
23620
23621   SDValue N0  = Narrow->getOperand(0);
23622   SDValue N1  = Narrow->getOperand(1);
23623   SDLoc DL(Narrow);
23624
23625   // The Left side has to be a trunc.
23626   if (N0.getOpcode() != ISD::TRUNCATE)
23627     return SDValue();
23628
23629   // The type of the truncated inputs.
23630   EVT WideVT = N0->getOperand(0)->getValueType(0);
23631   if (WideVT != VT)
23632     return SDValue();
23633
23634   // The right side has to be a 'trunc' or a constant vector.
23635   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
23636   ConstantSDNode *RHSConstSplat = nullptr;
23637   if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
23638     RHSConstSplat = RHSBV->getConstantSplatNode();
23639   if (!RHSTrunc && !RHSConstSplat)
23640     return SDValue();
23641
23642   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23643
23644   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
23645     return SDValue();
23646
23647   // Set N0 and N1 to hold the inputs to the new wide operation.
23648   N0 = N0->getOperand(0);
23649   if (RHSConstSplat) {
23650     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
23651                      SDValue(RHSConstSplat, 0));
23652     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
23653     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
23654   } else if (RHSTrunc) {
23655     N1 = N1->getOperand(0);
23656   }
23657
23658   // Generate the wide operation.
23659   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
23660   unsigned Opcode = N->getOpcode();
23661   switch (Opcode) {
23662   case ISD::ANY_EXTEND:
23663     return Op;
23664   case ISD::ZERO_EXTEND: {
23665     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
23666     APInt Mask = APInt::getAllOnesValue(InBits);
23667     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
23668     return DAG.getNode(ISD::AND, DL, VT,
23669                        Op, DAG.getConstant(Mask, DL, VT));
23670   }
23671   case ISD::SIGN_EXTEND:
23672     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
23673                        Op, DAG.getValueType(NarrowVT));
23674   default:
23675     llvm_unreachable("Unexpected opcode");
23676   }
23677 }
23678
23679 static SDValue VectorZextCombine(SDNode *N, SelectionDAG &DAG,
23680                                  TargetLowering::DAGCombinerInfo &DCI,
23681                                  const X86Subtarget *Subtarget) {
23682   SDValue N0 = N->getOperand(0);
23683   SDValue N1 = N->getOperand(1);
23684   SDLoc DL(N);
23685
23686   // A vector zext_in_reg may be represented as a shuffle,
23687   // feeding into a bitcast (this represents anyext) feeding into
23688   // an and with a mask.
23689   // We'd like to try to combine that into a shuffle with zero
23690   // plus a bitcast, removing the and.
23691   if (N0.getOpcode() != ISD::BITCAST ||
23692       N0.getOperand(0).getOpcode() != ISD::VECTOR_SHUFFLE)
23693     return SDValue();
23694
23695   // The other side of the AND should be a splat of 2^C, where C
23696   // is the number of bits in the source type.
23697   if (N1.getOpcode() == ISD::BITCAST)
23698     N1 = N1.getOperand(0);
23699   if (N1.getOpcode() != ISD::BUILD_VECTOR)
23700     return SDValue();
23701   BuildVectorSDNode *Vector = cast<BuildVectorSDNode>(N1);
23702
23703   ShuffleVectorSDNode *Shuffle = cast<ShuffleVectorSDNode>(N0.getOperand(0));
23704   EVT SrcType = Shuffle->getValueType(0);
23705
23706   // We expect a single-source shuffle
23707   if (Shuffle->getOperand(1)->getOpcode() != ISD::UNDEF)
23708     return SDValue();
23709
23710   unsigned SrcSize = SrcType.getScalarSizeInBits();
23711
23712   APInt SplatValue, SplatUndef;
23713   unsigned SplatBitSize;
23714   bool HasAnyUndefs;
23715   if (!Vector->isConstantSplat(SplatValue, SplatUndef,
23716                                 SplatBitSize, HasAnyUndefs))
23717     return SDValue();
23718
23719   unsigned ResSize = N1.getValueType().getScalarSizeInBits();
23720   // Make sure the splat matches the mask we expect
23721   if (SplatBitSize > ResSize ||
23722       (SplatValue + 1).exactLogBase2() != (int)SrcSize)
23723     return SDValue();
23724
23725   // Make sure the input and output size make sense
23726   if (SrcSize >= ResSize || ResSize % SrcSize)
23727     return SDValue();
23728
23729   // We expect a shuffle of the form <0, u, u, u, 1, u, u, u...>
23730   // The number of u's between each two values depends on the ratio between
23731   // the source and dest type.
23732   unsigned ZextRatio = ResSize / SrcSize;
23733   bool IsZext = true;
23734   for (unsigned i = 0; i < SrcType.getVectorNumElements(); ++i) {
23735     if (i % ZextRatio) {
23736       if (Shuffle->getMaskElt(i) > 0) {
23737         // Expected undef
23738         IsZext = false;
23739         break;
23740       }
23741     } else {
23742       if (Shuffle->getMaskElt(i) != (int)(i / ZextRatio)) {
23743         // Expected element number
23744         IsZext = false;
23745         break;
23746       }
23747     }
23748   }
23749
23750   if (!IsZext)
23751     return SDValue();
23752
23753   // Ok, perform the transformation - replace the shuffle with
23754   // a shuffle of the form <0, k, k, k, 1, k, k, k> with zero
23755   // (instead of undef) where the k elements come from the zero vector.
23756   SmallVector<int, 8> Mask;
23757   unsigned NumElems = SrcType.getVectorNumElements();
23758   for (unsigned i = 0; i < NumElems; ++i)
23759     if (i % ZextRatio)
23760       Mask.push_back(NumElems);
23761     else
23762       Mask.push_back(i / ZextRatio);
23763
23764   SDValue NewShuffle = DAG.getVectorShuffle(Shuffle->getValueType(0), DL,
23765     Shuffle->getOperand(0), DAG.getConstant(0, DL, SrcType), Mask);
23766   return DAG.getBitcast(N0.getValueType(), NewShuffle);
23767 }
23768
23769 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
23770                                  TargetLowering::DAGCombinerInfo &DCI,
23771                                  const X86Subtarget *Subtarget) {
23772   if (DCI.isBeforeLegalizeOps())
23773     return SDValue();
23774
23775   if (SDValue Zext = VectorZextCombine(N, DAG, DCI, Subtarget))
23776     return Zext;
23777
23778   if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
23779     return R;
23780
23781   EVT VT = N->getValueType(0);
23782   SDValue N0 = N->getOperand(0);
23783   SDValue N1 = N->getOperand(1);
23784   SDLoc DL(N);
23785
23786   // Create BEXTR instructions
23787   // BEXTR is ((X >> imm) & (2**size-1))
23788   if (VT == MVT::i32 || VT == MVT::i64) {
23789     // Check for BEXTR.
23790     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
23791         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
23792       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
23793       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
23794       if (MaskNode && ShiftNode) {
23795         uint64_t Mask = MaskNode->getZExtValue();
23796         uint64_t Shift = ShiftNode->getZExtValue();
23797         if (isMask_64(Mask)) {
23798           uint64_t MaskSize = countPopulation(Mask);
23799           if (Shift + MaskSize <= VT.getSizeInBits())
23800             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
23801                                DAG.getConstant(Shift | (MaskSize << 8), DL,
23802                                                VT));
23803         }
23804       }
23805     } // BEXTR
23806
23807     return SDValue();
23808   }
23809
23810   // Want to form ANDNP nodes:
23811   // 1) In the hopes of then easily combining them with OR and AND nodes
23812   //    to form PBLEND/PSIGN.
23813   // 2) To match ANDN packed intrinsics
23814   if (VT != MVT::v2i64 && VT != MVT::v4i64)
23815     return SDValue();
23816
23817   // Check LHS for vnot
23818   if (N0.getOpcode() == ISD::XOR &&
23819       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
23820       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
23821     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
23822
23823   // Check RHS for vnot
23824   if (N1.getOpcode() == ISD::XOR &&
23825       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
23826       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
23827     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
23828
23829   return SDValue();
23830 }
23831
23832 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
23833                                 TargetLowering::DAGCombinerInfo &DCI,
23834                                 const X86Subtarget *Subtarget) {
23835   if (DCI.isBeforeLegalizeOps())
23836     return SDValue();
23837
23838   if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
23839     return R;
23840
23841   SDValue N0 = N->getOperand(0);
23842   SDValue N1 = N->getOperand(1);
23843   EVT VT = N->getValueType(0);
23844
23845   // look for psign/blend
23846   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
23847     if (!Subtarget->hasSSSE3() ||
23848         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
23849       return SDValue();
23850
23851     // Canonicalize pandn to RHS
23852     if (N0.getOpcode() == X86ISD::ANDNP)
23853       std::swap(N0, N1);
23854     // or (and (m, y), (pandn m, x))
23855     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
23856       SDValue Mask = N1.getOperand(0);
23857       SDValue X    = N1.getOperand(1);
23858       SDValue Y;
23859       if (N0.getOperand(0) == Mask)
23860         Y = N0.getOperand(1);
23861       if (N0.getOperand(1) == Mask)
23862         Y = N0.getOperand(0);
23863
23864       // Check to see if the mask appeared in both the AND and ANDNP and
23865       if (!Y.getNode())
23866         return SDValue();
23867
23868       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
23869       // Look through mask bitcast.
23870       if (Mask.getOpcode() == ISD::BITCAST)
23871         Mask = Mask.getOperand(0);
23872       if (X.getOpcode() == ISD::BITCAST)
23873         X = X.getOperand(0);
23874       if (Y.getOpcode() == ISD::BITCAST)
23875         Y = Y.getOperand(0);
23876
23877       EVT MaskVT = Mask.getValueType();
23878
23879       // Validate that the Mask operand is a vector sra node.
23880       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
23881       // there is no psrai.b
23882       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
23883       unsigned SraAmt = ~0;
23884       if (Mask.getOpcode() == ISD::SRA) {
23885         if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
23886           if (auto *AmtConst = AmtBV->getConstantSplatNode())
23887             SraAmt = AmtConst->getZExtValue();
23888       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
23889         SDValue SraC = Mask.getOperand(1);
23890         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
23891       }
23892       if ((SraAmt + 1) != EltBits)
23893         return SDValue();
23894
23895       SDLoc DL(N);
23896
23897       // Now we know we at least have a plendvb with the mask val.  See if
23898       // we can form a psignb/w/d.
23899       // psign = x.type == y.type == mask.type && y = sub(0, x);
23900       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
23901           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
23902           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
23903         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
23904                "Unsupported VT for PSIGN");
23905         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
23906         return DAG.getBitcast(VT, Mask);
23907       }
23908       // PBLENDVB only available on SSE 4.1
23909       if (!Subtarget->hasSSE41())
23910         return SDValue();
23911
23912       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
23913
23914       X = DAG.getBitcast(BlendVT, X);
23915       Y = DAG.getBitcast(BlendVT, Y);
23916       Mask = DAG.getBitcast(BlendVT, Mask);
23917       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
23918       return DAG.getBitcast(VT, Mask);
23919     }
23920   }
23921
23922   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
23923     return SDValue();
23924
23925   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
23926   MachineFunction &MF = DAG.getMachineFunction();
23927   bool OptForSize =
23928       MF.getFunction()->hasFnAttribute(Attribute::OptimizeForSize);
23929
23930   // SHLD/SHRD instructions have lower register pressure, but on some
23931   // platforms they have higher latency than the equivalent
23932   // series of shifts/or that would otherwise be generated.
23933   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
23934   // have higher latencies and we are not optimizing for size.
23935   if (!OptForSize && Subtarget->isSHLDSlow())
23936     return SDValue();
23937
23938   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
23939     std::swap(N0, N1);
23940   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
23941     return SDValue();
23942   if (!N0.hasOneUse() || !N1.hasOneUse())
23943     return SDValue();
23944
23945   SDValue ShAmt0 = N0.getOperand(1);
23946   if (ShAmt0.getValueType() != MVT::i8)
23947     return SDValue();
23948   SDValue ShAmt1 = N1.getOperand(1);
23949   if (ShAmt1.getValueType() != MVT::i8)
23950     return SDValue();
23951   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
23952     ShAmt0 = ShAmt0.getOperand(0);
23953   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
23954     ShAmt1 = ShAmt1.getOperand(0);
23955
23956   SDLoc DL(N);
23957   unsigned Opc = X86ISD::SHLD;
23958   SDValue Op0 = N0.getOperand(0);
23959   SDValue Op1 = N1.getOperand(0);
23960   if (ShAmt0.getOpcode() == ISD::SUB) {
23961     Opc = X86ISD::SHRD;
23962     std::swap(Op0, Op1);
23963     std::swap(ShAmt0, ShAmt1);
23964   }
23965
23966   unsigned Bits = VT.getSizeInBits();
23967   if (ShAmt1.getOpcode() == ISD::SUB) {
23968     SDValue Sum = ShAmt1.getOperand(0);
23969     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
23970       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
23971       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
23972         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
23973       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
23974         return DAG.getNode(Opc, DL, VT,
23975                            Op0, Op1,
23976                            DAG.getNode(ISD::TRUNCATE, DL,
23977                                        MVT::i8, ShAmt0));
23978     }
23979   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
23980     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
23981     if (ShAmt0C &&
23982         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
23983       return DAG.getNode(Opc, DL, VT,
23984                          N0.getOperand(0), N1.getOperand(0),
23985                          DAG.getNode(ISD::TRUNCATE, DL,
23986                                        MVT::i8, ShAmt0));
23987   }
23988
23989   return SDValue();
23990 }
23991
23992 // Generate NEG and CMOV for integer abs.
23993 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
23994   EVT VT = N->getValueType(0);
23995
23996   // Since X86 does not have CMOV for 8-bit integer, we don't convert
23997   // 8-bit integer abs to NEG and CMOV.
23998   if (VT.isInteger() && VT.getSizeInBits() == 8)
23999     return SDValue();
24000
24001   SDValue N0 = N->getOperand(0);
24002   SDValue N1 = N->getOperand(1);
24003   SDLoc DL(N);
24004
24005   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
24006   // and change it to SUB and CMOV.
24007   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
24008       N0.getOpcode() == ISD::ADD &&
24009       N0.getOperand(1) == N1 &&
24010       N1.getOpcode() == ISD::SRA &&
24011       N1.getOperand(0) == N0.getOperand(0))
24012     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
24013       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
24014         // Generate SUB & CMOV.
24015         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
24016                                   DAG.getConstant(0, DL, VT), N0.getOperand(0));
24017
24018         SDValue Ops[] = { N0.getOperand(0), Neg,
24019                           DAG.getConstant(X86::COND_GE, DL, MVT::i8),
24020                           SDValue(Neg.getNode(), 1) };
24021         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
24022       }
24023   return SDValue();
24024 }
24025
24026 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
24027 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
24028                                  TargetLowering::DAGCombinerInfo &DCI,
24029                                  const X86Subtarget *Subtarget) {
24030   if (DCI.isBeforeLegalizeOps())
24031     return SDValue();
24032
24033   if (Subtarget->hasCMov())
24034     if (SDValue RV = performIntegerAbsCombine(N, DAG))
24035       return RV;
24036
24037   return SDValue();
24038 }
24039
24040 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
24041 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
24042                                   TargetLowering::DAGCombinerInfo &DCI,
24043                                   const X86Subtarget *Subtarget) {
24044   LoadSDNode *Ld = cast<LoadSDNode>(N);
24045   EVT RegVT = Ld->getValueType(0);
24046   EVT MemVT = Ld->getMemoryVT();
24047   SDLoc dl(Ld);
24048   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24049
24050   // For chips with slow 32-byte unaligned loads, break the 32-byte operation
24051   // into two 16-byte operations.
24052   ISD::LoadExtType Ext = Ld->getExtensionType();
24053   unsigned Alignment = Ld->getAlignment();
24054   bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
24055   if (RegVT.is256BitVector() && Subtarget->isUnalignedMem32Slow() &&
24056       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
24057     unsigned NumElems = RegVT.getVectorNumElements();
24058     if (NumElems < 2)
24059       return SDValue();
24060
24061     SDValue Ptr = Ld->getBasePtr();
24062     SDValue Increment =
24063         DAG.getConstant(16, dl, TLI.getPointerTy(DAG.getDataLayout()));
24064
24065     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
24066                                   NumElems/2);
24067     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
24068                                 Ld->getPointerInfo(), Ld->isVolatile(),
24069                                 Ld->isNonTemporal(), Ld->isInvariant(),
24070                                 Alignment);
24071     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
24072     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
24073                                 Ld->getPointerInfo(), Ld->isVolatile(),
24074                                 Ld->isNonTemporal(), Ld->isInvariant(),
24075                                 std::min(16U, Alignment));
24076     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
24077                              Load1.getValue(1),
24078                              Load2.getValue(1));
24079
24080     SDValue NewVec = DAG.getUNDEF(RegVT);
24081     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
24082     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
24083     return DCI.CombineTo(N, NewVec, TF, true);
24084   }
24085
24086   return SDValue();
24087 }
24088
24089 /// PerformMLOADCombine - Resolve extending loads
24090 static SDValue PerformMLOADCombine(SDNode *N, SelectionDAG &DAG,
24091                                    TargetLowering::DAGCombinerInfo &DCI,
24092                                    const X86Subtarget *Subtarget) {
24093   MaskedLoadSDNode *Mld = cast<MaskedLoadSDNode>(N);
24094   if (Mld->getExtensionType() != ISD::SEXTLOAD)
24095     return SDValue();
24096
24097   EVT VT = Mld->getValueType(0);
24098   unsigned NumElems = VT.getVectorNumElements();
24099   EVT LdVT = Mld->getMemoryVT();
24100   SDLoc dl(Mld);
24101
24102   assert(LdVT != VT && "Cannot extend to the same type");
24103   unsigned ToSz = VT.getVectorElementType().getSizeInBits();
24104   unsigned FromSz = LdVT.getVectorElementType().getSizeInBits();
24105   // From, To sizes and ElemCount must be pow of two
24106   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
24107     "Unexpected size for extending masked load");
24108
24109   unsigned SizeRatio  = ToSz / FromSz;
24110   assert(SizeRatio * NumElems * FromSz == VT.getSizeInBits());
24111
24112   // Create a type on which we perform the shuffle
24113   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
24114           LdVT.getScalarType(), NumElems*SizeRatio);
24115   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
24116
24117   // Convert Src0 value
24118   SDValue WideSrc0 = DAG.getBitcast(WideVecVT, Mld->getSrc0());
24119   if (Mld->getSrc0().getOpcode() != ISD::UNDEF) {
24120     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
24121     for (unsigned i = 0; i != NumElems; ++i)
24122       ShuffleVec[i] = i * SizeRatio;
24123
24124     // Can't shuffle using an illegal type.
24125     assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
24126             && "WideVecVT should be legal");
24127     WideSrc0 = DAG.getVectorShuffle(WideVecVT, dl, WideSrc0,
24128                                     DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
24129   }
24130   // Prepare the new mask
24131   SDValue NewMask;
24132   SDValue Mask = Mld->getMask();
24133   if (Mask.getValueType() == VT) {
24134     // Mask and original value have the same type
24135     NewMask = DAG.getBitcast(WideVecVT, Mask);
24136     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
24137     for (unsigned i = 0; i != NumElems; ++i)
24138       ShuffleVec[i] = i * SizeRatio;
24139     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
24140       ShuffleVec[i] = NumElems*SizeRatio;
24141     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
24142                                    DAG.getConstant(0, dl, WideVecVT),
24143                                    &ShuffleVec[0]);
24144   }
24145   else {
24146     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
24147     unsigned WidenNumElts = NumElems*SizeRatio;
24148     unsigned MaskNumElts = VT.getVectorNumElements();
24149     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
24150                                      WidenNumElts);
24151
24152     unsigned NumConcat = WidenNumElts / MaskNumElts;
24153     SmallVector<SDValue, 16> Ops(NumConcat);
24154     SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
24155     Ops[0] = Mask;
24156     for (unsigned i = 1; i != NumConcat; ++i)
24157       Ops[i] = ZeroVal;
24158
24159     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
24160   }
24161
24162   SDValue WideLd = DAG.getMaskedLoad(WideVecVT, dl, Mld->getChain(),
24163                                      Mld->getBasePtr(), NewMask, WideSrc0,
24164                                      Mld->getMemoryVT(), Mld->getMemOperand(),
24165                                      ISD::NON_EXTLOAD);
24166   SDValue NewVec = DAG.getNode(X86ISD::VSEXT, dl, VT, WideLd);
24167   return DCI.CombineTo(N, NewVec, WideLd.getValue(1), true);
24168
24169 }
24170 /// PerformMSTORECombine - Resolve truncating stores
24171 static SDValue PerformMSTORECombine(SDNode *N, SelectionDAG &DAG,
24172                                     const X86Subtarget *Subtarget) {
24173   MaskedStoreSDNode *Mst = cast<MaskedStoreSDNode>(N);
24174   if (!Mst->isTruncatingStore())
24175     return SDValue();
24176
24177   EVT VT = Mst->getValue().getValueType();
24178   unsigned NumElems = VT.getVectorNumElements();
24179   EVT StVT = Mst->getMemoryVT();
24180   SDLoc dl(Mst);
24181
24182   assert(StVT != VT && "Cannot truncate to the same type");
24183   unsigned FromSz = VT.getVectorElementType().getSizeInBits();
24184   unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
24185
24186   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24187
24188   // The truncating store is legal in some cases. For example
24189   // vpmovqb, vpmovqw, vpmovqd, vpmovdb, vpmovdw
24190   // are designated for truncate store.
24191   // In this case we don't need any further transformations.
24192   if (TLI.isTruncStoreLegal(VT, StVT))
24193     return SDValue();
24194
24195   // From, To sizes and ElemCount must be pow of two
24196   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
24197     "Unexpected size for truncating masked store");
24198   // We are going to use the original vector elt for storing.
24199   // Accumulated smaller vector elements must be a multiple of the store size.
24200   assert (((NumElems * FromSz) % ToSz) == 0 &&
24201           "Unexpected ratio for truncating masked store");
24202
24203   unsigned SizeRatio  = FromSz / ToSz;
24204   assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
24205
24206   // Create a type on which we perform the shuffle
24207   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
24208           StVT.getScalarType(), NumElems*SizeRatio);
24209
24210   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
24211
24212   SDValue WideVec = DAG.getBitcast(WideVecVT, Mst->getValue());
24213   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
24214   for (unsigned i = 0; i != NumElems; ++i)
24215     ShuffleVec[i] = i * SizeRatio;
24216
24217   // Can't shuffle using an illegal type.
24218   assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
24219           && "WideVecVT should be legal");
24220
24221   SDValue TruncatedVal = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
24222                                         DAG.getUNDEF(WideVecVT),
24223                                         &ShuffleVec[0]);
24224
24225   SDValue NewMask;
24226   SDValue Mask = Mst->getMask();
24227   if (Mask.getValueType() == VT) {
24228     // Mask and original value have the same type
24229     NewMask = DAG.getBitcast(WideVecVT, Mask);
24230     for (unsigned i = 0; i != NumElems; ++i)
24231       ShuffleVec[i] = i * SizeRatio;
24232     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
24233       ShuffleVec[i] = NumElems*SizeRatio;
24234     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
24235                                    DAG.getConstant(0, dl, WideVecVT),
24236                                    &ShuffleVec[0]);
24237   }
24238   else {
24239     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
24240     unsigned WidenNumElts = NumElems*SizeRatio;
24241     unsigned MaskNumElts = VT.getVectorNumElements();
24242     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
24243                                      WidenNumElts);
24244
24245     unsigned NumConcat = WidenNumElts / MaskNumElts;
24246     SmallVector<SDValue, 16> Ops(NumConcat);
24247     SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
24248     Ops[0] = Mask;
24249     for (unsigned i = 1; i != NumConcat; ++i)
24250       Ops[i] = ZeroVal;
24251
24252     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
24253   }
24254
24255   return DAG.getMaskedStore(Mst->getChain(), dl, TruncatedVal, Mst->getBasePtr(),
24256                             NewMask, StVT, Mst->getMemOperand(), false);
24257 }
24258 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
24259 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
24260                                    const X86Subtarget *Subtarget) {
24261   StoreSDNode *St = cast<StoreSDNode>(N);
24262   EVT VT = St->getValue().getValueType();
24263   EVT StVT = St->getMemoryVT();
24264   SDLoc dl(St);
24265   SDValue StoredVal = St->getOperand(1);
24266   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24267
24268   // If we are saving a concatenation of two XMM registers and 32-byte stores
24269   // are slow, such as on Sandy Bridge, perform two 16-byte stores.
24270   unsigned Alignment = St->getAlignment();
24271   bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
24272   if (VT.is256BitVector() && Subtarget->isUnalignedMem32Slow() &&
24273       StVT == VT && !IsAligned) {
24274     unsigned NumElems = VT.getVectorNumElements();
24275     if (NumElems < 2)
24276       return SDValue();
24277
24278     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
24279     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
24280
24281     SDValue Stride =
24282         DAG.getConstant(16, dl, TLI.getPointerTy(DAG.getDataLayout()));
24283     SDValue Ptr0 = St->getBasePtr();
24284     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
24285
24286     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
24287                                 St->getPointerInfo(), St->isVolatile(),
24288                                 St->isNonTemporal(), Alignment);
24289     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
24290                                 St->getPointerInfo(), St->isVolatile(),
24291                                 St->isNonTemporal(),
24292                                 std::min(16U, Alignment));
24293     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
24294   }
24295
24296   // Optimize trunc store (of multiple scalars) to shuffle and store.
24297   // First, pack all of the elements in one place. Next, store to memory
24298   // in fewer chunks.
24299   if (St->isTruncatingStore() && VT.isVector()) {
24300     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24301     unsigned NumElems = VT.getVectorNumElements();
24302     assert(StVT != VT && "Cannot truncate to the same type");
24303     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
24304     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
24305
24306     // The truncating store is legal in some cases. For example
24307     // vpmovqb, vpmovqw, vpmovqd, vpmovdb, vpmovdw
24308     // are designated for truncate store.
24309     // In this case we don't need any further transformations.
24310     if (TLI.isTruncStoreLegal(VT, StVT))
24311       return SDValue();
24312
24313     // From, To sizes and ElemCount must be pow of two
24314     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
24315     // We are going to use the original vector elt for storing.
24316     // Accumulated smaller vector elements must be a multiple of the store size.
24317     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
24318
24319     unsigned SizeRatio  = FromSz / ToSz;
24320
24321     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
24322
24323     // Create a type on which we perform the shuffle
24324     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
24325             StVT.getScalarType(), NumElems*SizeRatio);
24326
24327     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
24328
24329     SDValue WideVec = DAG.getBitcast(WideVecVT, St->getValue());
24330     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
24331     for (unsigned i = 0; i != NumElems; ++i)
24332       ShuffleVec[i] = i * SizeRatio;
24333
24334     // Can't shuffle using an illegal type.
24335     if (!TLI.isTypeLegal(WideVecVT))
24336       return SDValue();
24337
24338     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
24339                                          DAG.getUNDEF(WideVecVT),
24340                                          &ShuffleVec[0]);
24341     // At this point all of the data is stored at the bottom of the
24342     // register. We now need to save it to mem.
24343
24344     // Find the largest store unit
24345     MVT StoreType = MVT::i8;
24346     for (MVT Tp : MVT::integer_valuetypes()) {
24347       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
24348         StoreType = Tp;
24349     }
24350
24351     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
24352     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
24353         (64 <= NumElems * ToSz))
24354       StoreType = MVT::f64;
24355
24356     // Bitcast the original vector into a vector of store-size units
24357     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
24358             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
24359     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
24360     SDValue ShuffWide = DAG.getBitcast(StoreVecVT, Shuff);
24361     SmallVector<SDValue, 8> Chains;
24362     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, dl,
24363                                         TLI.getPointerTy(DAG.getDataLayout()));
24364     SDValue Ptr = St->getBasePtr();
24365
24366     // Perform one or more big stores into memory.
24367     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
24368       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
24369                                    StoreType, ShuffWide,
24370                                    DAG.getIntPtrConstant(i, dl));
24371       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
24372                                 St->getPointerInfo(), St->isVolatile(),
24373                                 St->isNonTemporal(), St->getAlignment());
24374       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
24375       Chains.push_back(Ch);
24376     }
24377
24378     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
24379   }
24380
24381   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
24382   // the FP state in cases where an emms may be missing.
24383   // A preferable solution to the general problem is to figure out the right
24384   // places to insert EMMS.  This qualifies as a quick hack.
24385
24386   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
24387   if (VT.getSizeInBits() != 64)
24388     return SDValue();
24389
24390   const Function *F = DAG.getMachineFunction().getFunction();
24391   bool NoImplicitFloatOps = F->hasFnAttribute(Attribute::NoImplicitFloat);
24392   bool F64IsLegal =
24393       !Subtarget->useSoftFloat() && !NoImplicitFloatOps && Subtarget->hasSSE2();
24394   if ((VT.isVector() ||
24395        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
24396       isa<LoadSDNode>(St->getValue()) &&
24397       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
24398       St->getChain().hasOneUse() && !St->isVolatile()) {
24399     SDNode* LdVal = St->getValue().getNode();
24400     LoadSDNode *Ld = nullptr;
24401     int TokenFactorIndex = -1;
24402     SmallVector<SDValue, 8> Ops;
24403     SDNode* ChainVal = St->getChain().getNode();
24404     // Must be a store of a load.  We currently handle two cases:  the load
24405     // is a direct child, and it's under an intervening TokenFactor.  It is
24406     // possible to dig deeper under nested TokenFactors.
24407     if (ChainVal == LdVal)
24408       Ld = cast<LoadSDNode>(St->getChain());
24409     else if (St->getValue().hasOneUse() &&
24410              ChainVal->getOpcode() == ISD::TokenFactor) {
24411       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
24412         if (ChainVal->getOperand(i).getNode() == LdVal) {
24413           TokenFactorIndex = i;
24414           Ld = cast<LoadSDNode>(St->getValue());
24415         } else
24416           Ops.push_back(ChainVal->getOperand(i));
24417       }
24418     }
24419
24420     if (!Ld || !ISD::isNormalLoad(Ld))
24421       return SDValue();
24422
24423     // If this is not the MMX case, i.e. we are just turning i64 load/store
24424     // into f64 load/store, avoid the transformation if there are multiple
24425     // uses of the loaded value.
24426     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
24427       return SDValue();
24428
24429     SDLoc LdDL(Ld);
24430     SDLoc StDL(N);
24431     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
24432     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
24433     // pair instead.
24434     if (Subtarget->is64Bit() || F64IsLegal) {
24435       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
24436       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
24437                                   Ld->getPointerInfo(), Ld->isVolatile(),
24438                                   Ld->isNonTemporal(), Ld->isInvariant(),
24439                                   Ld->getAlignment());
24440       SDValue NewChain = NewLd.getValue(1);
24441       if (TokenFactorIndex != -1) {
24442         Ops.push_back(NewChain);
24443         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
24444       }
24445       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
24446                           St->getPointerInfo(),
24447                           St->isVolatile(), St->isNonTemporal(),
24448                           St->getAlignment());
24449     }
24450
24451     // Otherwise, lower to two pairs of 32-bit loads / stores.
24452     SDValue LoAddr = Ld->getBasePtr();
24453     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
24454                                  DAG.getConstant(4, LdDL, MVT::i32));
24455
24456     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
24457                                Ld->getPointerInfo(),
24458                                Ld->isVolatile(), Ld->isNonTemporal(),
24459                                Ld->isInvariant(), Ld->getAlignment());
24460     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
24461                                Ld->getPointerInfo().getWithOffset(4),
24462                                Ld->isVolatile(), Ld->isNonTemporal(),
24463                                Ld->isInvariant(),
24464                                MinAlign(Ld->getAlignment(), 4));
24465
24466     SDValue NewChain = LoLd.getValue(1);
24467     if (TokenFactorIndex != -1) {
24468       Ops.push_back(LoLd);
24469       Ops.push_back(HiLd);
24470       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
24471     }
24472
24473     LoAddr = St->getBasePtr();
24474     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
24475                          DAG.getConstant(4, StDL, MVT::i32));
24476
24477     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
24478                                 St->getPointerInfo(),
24479                                 St->isVolatile(), St->isNonTemporal(),
24480                                 St->getAlignment());
24481     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
24482                                 St->getPointerInfo().getWithOffset(4),
24483                                 St->isVolatile(),
24484                                 St->isNonTemporal(),
24485                                 MinAlign(St->getAlignment(), 4));
24486     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
24487   }
24488
24489   // This is similar to the above case, but here we handle a scalar 64-bit
24490   // integer store that is extracted from a vector on a 32-bit target.
24491   // If we have SSE2, then we can treat it like a floating-point double
24492   // to get past legalization. The execution dependencies fixup pass will
24493   // choose the optimal machine instruction for the store if this really is
24494   // an integer or v2f32 rather than an f64.
24495   if (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit() &&
24496       St->getOperand(1).getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
24497     SDValue OldExtract = St->getOperand(1);
24498     SDValue ExtOp0 = OldExtract.getOperand(0);
24499     unsigned VecSize = ExtOp0.getValueSizeInBits();
24500     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, VecSize / 64);
24501     SDValue BitCast = DAG.getBitcast(VecVT, ExtOp0);
24502     SDValue NewExtract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
24503                                      BitCast, OldExtract.getOperand(1));
24504     return DAG.getStore(St->getChain(), dl, NewExtract, St->getBasePtr(),
24505                         St->getPointerInfo(), St->isVolatile(),
24506                         St->isNonTemporal(), St->getAlignment());
24507   }
24508
24509   return SDValue();
24510 }
24511
24512 /// Return 'true' if this vector operation is "horizontal"
24513 /// and return the operands for the horizontal operation in LHS and RHS.  A
24514 /// horizontal operation performs the binary operation on successive elements
24515 /// of its first operand, then on successive elements of its second operand,
24516 /// returning the resulting values in a vector.  For example, if
24517 ///   A = < float a0, float a1, float a2, float a3 >
24518 /// and
24519 ///   B = < float b0, float b1, float b2, float b3 >
24520 /// then the result of doing a horizontal operation on A and B is
24521 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
24522 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
24523 /// A horizontal-op B, for some already available A and B, and if so then LHS is
24524 /// set to A, RHS to B, and the routine returns 'true'.
24525 /// Note that the binary operation should have the property that if one of the
24526 /// operands is UNDEF then the result is UNDEF.
24527 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
24528   // Look for the following pattern: if
24529   //   A = < float a0, float a1, float a2, float a3 >
24530   //   B = < float b0, float b1, float b2, float b3 >
24531   // and
24532   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
24533   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
24534   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
24535   // which is A horizontal-op B.
24536
24537   // At least one of the operands should be a vector shuffle.
24538   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
24539       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
24540     return false;
24541
24542   MVT VT = LHS.getSimpleValueType();
24543
24544   assert((VT.is128BitVector() || VT.is256BitVector()) &&
24545          "Unsupported vector type for horizontal add/sub");
24546
24547   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
24548   // operate independently on 128-bit lanes.
24549   unsigned NumElts = VT.getVectorNumElements();
24550   unsigned NumLanes = VT.getSizeInBits()/128;
24551   unsigned NumLaneElts = NumElts / NumLanes;
24552   assert((NumLaneElts % 2 == 0) &&
24553          "Vector type should have an even number of elements in each lane");
24554   unsigned HalfLaneElts = NumLaneElts/2;
24555
24556   // View LHS in the form
24557   //   LHS = VECTOR_SHUFFLE A, B, LMask
24558   // If LHS is not a shuffle then pretend it is the shuffle
24559   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
24560   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
24561   // type VT.
24562   SDValue A, B;
24563   SmallVector<int, 16> LMask(NumElts);
24564   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
24565     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
24566       A = LHS.getOperand(0);
24567     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
24568       B = LHS.getOperand(1);
24569     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
24570     std::copy(Mask.begin(), Mask.end(), LMask.begin());
24571   } else {
24572     if (LHS.getOpcode() != ISD::UNDEF)
24573       A = LHS;
24574     for (unsigned i = 0; i != NumElts; ++i)
24575       LMask[i] = i;
24576   }
24577
24578   // Likewise, view RHS in the form
24579   //   RHS = VECTOR_SHUFFLE C, D, RMask
24580   SDValue C, D;
24581   SmallVector<int, 16> RMask(NumElts);
24582   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
24583     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
24584       C = RHS.getOperand(0);
24585     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
24586       D = RHS.getOperand(1);
24587     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
24588     std::copy(Mask.begin(), Mask.end(), RMask.begin());
24589   } else {
24590     if (RHS.getOpcode() != ISD::UNDEF)
24591       C = RHS;
24592     for (unsigned i = 0; i != NumElts; ++i)
24593       RMask[i] = i;
24594   }
24595
24596   // Check that the shuffles are both shuffling the same vectors.
24597   if (!(A == C && B == D) && !(A == D && B == C))
24598     return false;
24599
24600   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
24601   if (!A.getNode() && !B.getNode())
24602     return false;
24603
24604   // If A and B occur in reverse order in RHS, then "swap" them (which means
24605   // rewriting the mask).
24606   if (A != C)
24607     ShuffleVectorSDNode::commuteMask(RMask);
24608
24609   // At this point LHS and RHS are equivalent to
24610   //   LHS = VECTOR_SHUFFLE A, B, LMask
24611   //   RHS = VECTOR_SHUFFLE A, B, RMask
24612   // Check that the masks correspond to performing a horizontal operation.
24613   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
24614     for (unsigned i = 0; i != NumLaneElts; ++i) {
24615       int LIdx = LMask[i+l], RIdx = RMask[i+l];
24616
24617       // Ignore any UNDEF components.
24618       if (LIdx < 0 || RIdx < 0 ||
24619           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
24620           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
24621         continue;
24622
24623       // Check that successive elements are being operated on.  If not, this is
24624       // not a horizontal operation.
24625       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
24626       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
24627       if (!(LIdx == Index && RIdx == Index + 1) &&
24628           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
24629         return false;
24630     }
24631   }
24632
24633   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
24634   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
24635   return true;
24636 }
24637
24638 /// Do target-specific dag combines on floating point adds.
24639 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
24640                                   const X86Subtarget *Subtarget) {
24641   EVT VT = N->getValueType(0);
24642   SDValue LHS = N->getOperand(0);
24643   SDValue RHS = N->getOperand(1);
24644
24645   // Try to synthesize horizontal adds from adds of shuffles.
24646   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
24647        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
24648       isHorizontalBinOp(LHS, RHS, true))
24649     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
24650   return SDValue();
24651 }
24652
24653 /// Do target-specific dag combines on floating point subs.
24654 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
24655                                   const X86Subtarget *Subtarget) {
24656   EVT VT = N->getValueType(0);
24657   SDValue LHS = N->getOperand(0);
24658   SDValue RHS = N->getOperand(1);
24659
24660   // Try to synthesize horizontal subs from subs of shuffles.
24661   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
24662        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
24663       isHorizontalBinOp(LHS, RHS, false))
24664     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
24665   return SDValue();
24666 }
24667
24668 /// Do target-specific dag combines on X86ISD::FOR and X86ISD::FXOR nodes.
24669 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
24670   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
24671
24672   // F[X]OR(0.0, x) -> x
24673   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
24674     if (C->getValueAPF().isPosZero())
24675       return N->getOperand(1);
24676
24677   // F[X]OR(x, 0.0) -> x
24678   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
24679     if (C->getValueAPF().isPosZero())
24680       return N->getOperand(0);
24681   return SDValue();
24682 }
24683
24684 /// Do target-specific dag combines on X86ISD::FMIN and X86ISD::FMAX nodes.
24685 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
24686   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
24687
24688   // Only perform optimizations if UnsafeMath is used.
24689   if (!DAG.getTarget().Options.UnsafeFPMath)
24690     return SDValue();
24691
24692   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
24693   // into FMINC and FMAXC, which are Commutative operations.
24694   unsigned NewOp = 0;
24695   switch (N->getOpcode()) {
24696     default: llvm_unreachable("unknown opcode");
24697     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
24698     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
24699   }
24700
24701   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
24702                      N->getOperand(0), N->getOperand(1));
24703 }
24704
24705 /// Do target-specific dag combines on X86ISD::FAND nodes.
24706 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
24707   // FAND(0.0, x) -> 0.0
24708   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
24709     if (C->getValueAPF().isPosZero())
24710       return N->getOperand(0);
24711
24712   // FAND(x, 0.0) -> 0.0
24713   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
24714     if (C->getValueAPF().isPosZero())
24715       return N->getOperand(1);
24716
24717   return SDValue();
24718 }
24719
24720 /// Do target-specific dag combines on X86ISD::FANDN nodes
24721 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
24722   // FANDN(0.0, x) -> x
24723   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
24724     if (C->getValueAPF().isPosZero())
24725       return N->getOperand(1);
24726
24727   // FANDN(x, 0.0) -> 0.0
24728   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
24729     if (C->getValueAPF().isPosZero())
24730       return N->getOperand(1);
24731
24732   return SDValue();
24733 }
24734
24735 static SDValue PerformBTCombine(SDNode *N,
24736                                 SelectionDAG &DAG,
24737                                 TargetLowering::DAGCombinerInfo &DCI) {
24738   // BT ignores high bits in the bit index operand.
24739   SDValue Op1 = N->getOperand(1);
24740   if (Op1.hasOneUse()) {
24741     unsigned BitWidth = Op1.getValueSizeInBits();
24742     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
24743     APInt KnownZero, KnownOne;
24744     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
24745                                           !DCI.isBeforeLegalizeOps());
24746     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24747     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
24748         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
24749       DCI.CommitTargetLoweringOpt(TLO);
24750   }
24751   return SDValue();
24752 }
24753
24754 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
24755   SDValue Op = N->getOperand(0);
24756   if (Op.getOpcode() == ISD::BITCAST)
24757     Op = Op.getOperand(0);
24758   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
24759   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
24760       VT.getVectorElementType().getSizeInBits() ==
24761       OpVT.getVectorElementType().getSizeInBits()) {
24762     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
24763   }
24764   return SDValue();
24765 }
24766
24767 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
24768                                                const X86Subtarget *Subtarget) {
24769   EVT VT = N->getValueType(0);
24770   if (!VT.isVector())
24771     return SDValue();
24772
24773   SDValue N0 = N->getOperand(0);
24774   SDValue N1 = N->getOperand(1);
24775   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
24776   SDLoc dl(N);
24777
24778   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
24779   // both SSE and AVX2 since there is no sign-extended shift right
24780   // operation on a vector with 64-bit elements.
24781   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
24782   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
24783   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
24784       N0.getOpcode() == ISD::SIGN_EXTEND)) {
24785     SDValue N00 = N0.getOperand(0);
24786
24787     // EXTLOAD has a better solution on AVX2,
24788     // it may be replaced with X86ISD::VSEXT node.
24789     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
24790       if (!ISD::isNormalLoad(N00.getNode()))
24791         return SDValue();
24792
24793     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
24794         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
24795                                   N00, N1);
24796       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
24797     }
24798   }
24799   return SDValue();
24800 }
24801
24802 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
24803                                   TargetLowering::DAGCombinerInfo &DCI,
24804                                   const X86Subtarget *Subtarget) {
24805   SDValue N0 = N->getOperand(0);
24806   EVT VT = N->getValueType(0);
24807   EVT SVT = VT.getScalarType();
24808   EVT InVT = N0.getValueType();
24809   EVT InSVT = InVT.getScalarType();
24810   SDLoc DL(N);
24811
24812   // (i8,i32 sext (sdivrem (i8 x, i8 y)) ->
24813   // (i8,i32 (sdivrem_sext_hreg (i8 x, i8 y)
24814   // This exposes the sext to the sdivrem lowering, so that it directly extends
24815   // from AH (which we otherwise need to do contortions to access).
24816   if (N0.getOpcode() == ISD::SDIVREM && N0.getResNo() == 1 &&
24817       InVT == MVT::i8 && VT == MVT::i32) {
24818     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
24819     SDValue R = DAG.getNode(X86ISD::SDIVREM8_SEXT_HREG, DL, NodeTys,
24820                             N0.getOperand(0), N0.getOperand(1));
24821     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
24822     return R.getValue(1);
24823   }
24824
24825   if (!DCI.isBeforeLegalizeOps()) {
24826     if (InVT == MVT::i1) {
24827       SDValue Zero = DAG.getConstant(0, DL, VT);
24828       SDValue AllOnes =
24829         DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL, VT);
24830       return DAG.getNode(ISD::SELECT, DL, VT, N0, AllOnes, Zero);
24831     }
24832     return SDValue();
24833   }
24834
24835   if (VT.isVector() && Subtarget->hasSSE2()) {
24836     auto ExtendVecSize = [&DAG](SDLoc DL, SDValue N, unsigned Size) {
24837       EVT InVT = N.getValueType();
24838       EVT OutVT = EVT::getVectorVT(*DAG.getContext(), InVT.getScalarType(),
24839                                    Size / InVT.getScalarSizeInBits());
24840       SmallVector<SDValue, 8> Opnds(Size / InVT.getSizeInBits(),
24841                                     DAG.getUNDEF(InVT));
24842       Opnds[0] = N;
24843       return DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Opnds);
24844     };
24845
24846     // If target-size is less than 128-bits, extend to a type that would extend
24847     // to 128 bits, extend that and extract the original target vector.
24848     if (VT.getSizeInBits() < 128 && !(128 % VT.getSizeInBits()) &&
24849         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
24850         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
24851       unsigned Scale = 128 / VT.getSizeInBits();
24852       EVT ExVT =
24853           EVT::getVectorVT(*DAG.getContext(), SVT, 128 / SVT.getSizeInBits());
24854       SDValue Ex = ExtendVecSize(DL, N0, Scale * InVT.getSizeInBits());
24855       SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, ExVT, Ex);
24856       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, SExt,
24857                          DAG.getIntPtrConstant(0, DL));
24858     }
24859
24860     // If target-size is 128-bits, then convert to ISD::SIGN_EXTEND_VECTOR_INREG
24861     // which ensures lowering to X86ISD::VSEXT (pmovsx*).
24862     if (VT.getSizeInBits() == 128 &&
24863         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
24864         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
24865       SDValue ExOp = ExtendVecSize(DL, N0, 128);
24866       return DAG.getSignExtendVectorInReg(ExOp, DL, VT);
24867     }
24868
24869     // On pre-AVX2 targets, split into 128-bit nodes of
24870     // ISD::SIGN_EXTEND_VECTOR_INREG.
24871     if (!Subtarget->hasInt256() && !(VT.getSizeInBits() % 128) &&
24872         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
24873         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
24874       unsigned NumVecs = VT.getSizeInBits() / 128;
24875       unsigned NumSubElts = 128 / SVT.getSizeInBits();
24876       EVT SubVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumSubElts);
24877       EVT InSubVT = EVT::getVectorVT(*DAG.getContext(), InSVT, NumSubElts);
24878
24879       SmallVector<SDValue, 8> Opnds;
24880       for (unsigned i = 0, Offset = 0; i != NumVecs;
24881            ++i, Offset += NumSubElts) {
24882         SDValue SrcVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InSubVT, N0,
24883                                      DAG.getIntPtrConstant(Offset, DL));
24884         SrcVec = ExtendVecSize(DL, SrcVec, 128);
24885         SrcVec = DAG.getSignExtendVectorInReg(SrcVec, DL, SubVT);
24886         Opnds.push_back(SrcVec);
24887       }
24888       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Opnds);
24889     }
24890   }
24891
24892   if (!Subtarget->hasFp256())
24893     return SDValue();
24894
24895   if (VT.isVector() && VT.getSizeInBits() == 256)
24896     if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
24897       return R;
24898
24899   return SDValue();
24900 }
24901
24902 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
24903                                  const X86Subtarget* Subtarget) {
24904   SDLoc dl(N);
24905   EVT VT = N->getValueType(0);
24906
24907   // Let legalize expand this if it isn't a legal type yet.
24908   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
24909     return SDValue();
24910
24911   EVT ScalarVT = VT.getScalarType();
24912   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
24913       (!Subtarget->hasFMA() && !Subtarget->hasFMA4() &&
24914        !Subtarget->hasAVX512()))
24915     return SDValue();
24916
24917   SDValue A = N->getOperand(0);
24918   SDValue B = N->getOperand(1);
24919   SDValue C = N->getOperand(2);
24920
24921   bool NegA = (A.getOpcode() == ISD::FNEG);
24922   bool NegB = (B.getOpcode() == ISD::FNEG);
24923   bool NegC = (C.getOpcode() == ISD::FNEG);
24924
24925   // Negative multiplication when NegA xor NegB
24926   bool NegMul = (NegA != NegB);
24927   if (NegA)
24928     A = A.getOperand(0);
24929   if (NegB)
24930     B = B.getOperand(0);
24931   if (NegC)
24932     C = C.getOperand(0);
24933
24934   unsigned Opcode;
24935   if (!NegMul)
24936     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
24937   else
24938     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
24939
24940   return DAG.getNode(Opcode, dl, VT, A, B, C);
24941 }
24942
24943 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
24944                                   TargetLowering::DAGCombinerInfo &DCI,
24945                                   const X86Subtarget *Subtarget) {
24946   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
24947   //           (and (i32 x86isd::setcc_carry), 1)
24948   // This eliminates the zext. This transformation is necessary because
24949   // ISD::SETCC is always legalized to i8.
24950   SDLoc dl(N);
24951   SDValue N0 = N->getOperand(0);
24952   EVT VT = N->getValueType(0);
24953
24954   if (N0.getOpcode() == ISD::AND &&
24955       N0.hasOneUse() &&
24956       N0.getOperand(0).hasOneUse()) {
24957     SDValue N00 = N0.getOperand(0);
24958     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
24959       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
24960       if (!C || C->getZExtValue() != 1)
24961         return SDValue();
24962       return DAG.getNode(ISD::AND, dl, VT,
24963                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
24964                                      N00.getOperand(0), N00.getOperand(1)),
24965                          DAG.getConstant(1, dl, VT));
24966     }
24967   }
24968
24969   if (N0.getOpcode() == ISD::TRUNCATE &&
24970       N0.hasOneUse() &&
24971       N0.getOperand(0).hasOneUse()) {
24972     SDValue N00 = N0.getOperand(0);
24973     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
24974       return DAG.getNode(ISD::AND, dl, VT,
24975                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
24976                                      N00.getOperand(0), N00.getOperand(1)),
24977                          DAG.getConstant(1, dl, VT));
24978     }
24979   }
24980
24981   if (VT.is256BitVector())
24982     if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
24983       return R;
24984
24985   // (i8,i32 zext (udivrem (i8 x, i8 y)) ->
24986   // (i8,i32 (udivrem_zext_hreg (i8 x, i8 y)
24987   // This exposes the zext to the udivrem lowering, so that it directly extends
24988   // from AH (which we otherwise need to do contortions to access).
24989   if (N0.getOpcode() == ISD::UDIVREM &&
24990       N0.getResNo() == 1 && N0.getValueType() == MVT::i8 &&
24991       (VT == MVT::i32 || VT == MVT::i64)) {
24992     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
24993     SDValue R = DAG.getNode(X86ISD::UDIVREM8_ZEXT_HREG, dl, NodeTys,
24994                             N0.getOperand(0), N0.getOperand(1));
24995     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
24996     return R.getValue(1);
24997   }
24998
24999   return SDValue();
25000 }
25001
25002 // Optimize x == -y --> x+y == 0
25003 //          x != -y --> x+y != 0
25004 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
25005                                       const X86Subtarget* Subtarget) {
25006   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
25007   SDValue LHS = N->getOperand(0);
25008   SDValue RHS = N->getOperand(1);
25009   EVT VT = N->getValueType(0);
25010   SDLoc DL(N);
25011
25012   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
25013     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
25014       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
25015         SDValue addV = DAG.getNode(ISD::ADD, DL, LHS.getValueType(), RHS,
25016                                    LHS.getOperand(1));
25017         return DAG.getSetCC(DL, N->getValueType(0), addV,
25018                             DAG.getConstant(0, DL, addV.getValueType()), CC);
25019       }
25020   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
25021     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
25022       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
25023         SDValue addV = DAG.getNode(ISD::ADD, DL, RHS.getValueType(), LHS,
25024                                    RHS.getOperand(1));
25025         return DAG.getSetCC(DL, N->getValueType(0), addV,
25026                             DAG.getConstant(0, DL, addV.getValueType()), CC);
25027       }
25028
25029   if (VT.getScalarType() == MVT::i1 &&
25030       (CC == ISD::SETNE || CC == ISD::SETEQ || ISD::isSignedIntSetCC(CC))) {
25031     bool IsSEXT0 =
25032         (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
25033         (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
25034     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
25035
25036     if (!IsSEXT0 || !IsVZero1) {
25037       // Swap the operands and update the condition code.
25038       std::swap(LHS, RHS);
25039       CC = ISD::getSetCCSwappedOperands(CC);
25040
25041       IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
25042                 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
25043       IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
25044     }
25045
25046     if (IsSEXT0 && IsVZero1) {
25047       assert(VT == LHS.getOperand(0).getValueType() &&
25048              "Uexpected operand type");
25049       if (CC == ISD::SETGT)
25050         return DAG.getConstant(0, DL, VT);
25051       if (CC == ISD::SETLE)
25052         return DAG.getConstant(1, DL, VT);
25053       if (CC == ISD::SETEQ || CC == ISD::SETGE)
25054         return DAG.getNOT(DL, LHS.getOperand(0), VT);
25055
25056       assert((CC == ISD::SETNE || CC == ISD::SETLT) &&
25057              "Unexpected condition code!");
25058       return LHS.getOperand(0);
25059     }
25060   }
25061
25062   return SDValue();
25063 }
25064
25065 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
25066                                          SelectionDAG &DAG) {
25067   SDLoc dl(Load);
25068   MVT VT = Load->getSimpleValueType(0);
25069   MVT EVT = VT.getVectorElementType();
25070   SDValue Addr = Load->getOperand(1);
25071   SDValue NewAddr = DAG.getNode(
25072       ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
25073       DAG.getConstant(Index * EVT.getStoreSize(), dl,
25074                       Addr.getSimpleValueType()));
25075
25076   SDValue NewLoad =
25077       DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
25078                   DAG.getMachineFunction().getMachineMemOperand(
25079                       Load->getMemOperand(), 0, EVT.getStoreSize()));
25080   return NewLoad;
25081 }
25082
25083 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
25084                                       const X86Subtarget *Subtarget) {
25085   SDLoc dl(N);
25086   MVT VT = N->getOperand(1)->getSimpleValueType(0);
25087   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
25088          "X86insertps is only defined for v4x32");
25089
25090   SDValue Ld = N->getOperand(1);
25091   if (MayFoldLoad(Ld)) {
25092     // Extract the countS bits from the immediate so we can get the proper
25093     // address when narrowing the vector load to a specific element.
25094     // When the second source op is a memory address, insertps doesn't use
25095     // countS and just gets an f32 from that address.
25096     unsigned DestIndex =
25097         cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
25098
25099     Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
25100
25101     // Create this as a scalar to vector to match the instruction pattern.
25102     SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
25103     // countS bits are ignored when loading from memory on insertps, which
25104     // means we don't need to explicitly set them to 0.
25105     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
25106                        LoadScalarToVector, N->getOperand(2));
25107   }
25108   return SDValue();
25109 }
25110
25111 static SDValue PerformBLENDICombine(SDNode *N, SelectionDAG &DAG) {
25112   SDValue V0 = N->getOperand(0);
25113   SDValue V1 = N->getOperand(1);
25114   SDLoc DL(N);
25115   EVT VT = N->getValueType(0);
25116
25117   // Canonicalize a v2f64 blend with a mask of 2 by swapping the vector
25118   // operands and changing the mask to 1. This saves us a bunch of
25119   // pattern-matching possibilities related to scalar math ops in SSE/AVX.
25120   // x86InstrInfo knows how to commute this back after instruction selection
25121   // if it would help register allocation.
25122
25123   // TODO: If optimizing for size or a processor that doesn't suffer from
25124   // partial register update stalls, this should be transformed into a MOVSD
25125   // instruction because a MOVSD is 1-2 bytes smaller than a BLENDPD.
25126
25127   if (VT == MVT::v2f64)
25128     if (auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(2)))
25129       if (Mask->getZExtValue() == 2 && !isShuffleFoldableLoad(V0)) {
25130         SDValue NewMask = DAG.getConstant(1, DL, MVT::i8);
25131         return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V0, NewMask);
25132       }
25133
25134   return SDValue();
25135 }
25136
25137 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
25138 // as "sbb reg,reg", since it can be extended without zext and produces
25139 // an all-ones bit which is more useful than 0/1 in some cases.
25140 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
25141                                MVT VT) {
25142   if (VT == MVT::i8)
25143     return DAG.getNode(ISD::AND, DL, VT,
25144                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
25145                                    DAG.getConstant(X86::COND_B, DL, MVT::i8),
25146                                    EFLAGS),
25147                        DAG.getConstant(1, DL, VT));
25148   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
25149   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
25150                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
25151                                  DAG.getConstant(X86::COND_B, DL, MVT::i8),
25152                                  EFLAGS));
25153 }
25154
25155 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
25156 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
25157                                    TargetLowering::DAGCombinerInfo &DCI,
25158                                    const X86Subtarget *Subtarget) {
25159   SDLoc DL(N);
25160   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
25161   SDValue EFLAGS = N->getOperand(1);
25162
25163   if (CC == X86::COND_A) {
25164     // Try to convert COND_A into COND_B in an attempt to facilitate
25165     // materializing "setb reg".
25166     //
25167     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
25168     // cannot take an immediate as its first operand.
25169     //
25170     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
25171         EFLAGS.getValueType().isInteger() &&
25172         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
25173       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
25174                                    EFLAGS.getNode()->getVTList(),
25175                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
25176       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
25177       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
25178     }
25179   }
25180
25181   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
25182   // a zext and produces an all-ones bit which is more useful than 0/1 in some
25183   // cases.
25184   if (CC == X86::COND_B)
25185     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
25186
25187   if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
25188     SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
25189     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
25190   }
25191
25192   return SDValue();
25193 }
25194
25195 // Optimize branch condition evaluation.
25196 //
25197 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
25198                                     TargetLowering::DAGCombinerInfo &DCI,
25199                                     const X86Subtarget *Subtarget) {
25200   SDLoc DL(N);
25201   SDValue Chain = N->getOperand(0);
25202   SDValue Dest = N->getOperand(1);
25203   SDValue EFLAGS = N->getOperand(3);
25204   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
25205
25206   if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
25207     SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
25208     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
25209                        Flags);
25210   }
25211
25212   return SDValue();
25213 }
25214
25215 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
25216                                                          SelectionDAG &DAG) {
25217   // Take advantage of vector comparisons producing 0 or -1 in each lane to
25218   // optimize away operation when it's from a constant.
25219   //
25220   // The general transformation is:
25221   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
25222   //       AND(VECTOR_CMP(x,y), constant2)
25223   //    constant2 = UNARYOP(constant)
25224
25225   // Early exit if this isn't a vector operation, the operand of the
25226   // unary operation isn't a bitwise AND, or if the sizes of the operations
25227   // aren't the same.
25228   EVT VT = N->getValueType(0);
25229   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
25230       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
25231       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
25232     return SDValue();
25233
25234   // Now check that the other operand of the AND is a constant. We could
25235   // make the transformation for non-constant splats as well, but it's unclear
25236   // that would be a benefit as it would not eliminate any operations, just
25237   // perform one more step in scalar code before moving to the vector unit.
25238   if (BuildVectorSDNode *BV =
25239           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
25240     // Bail out if the vector isn't a constant.
25241     if (!BV->isConstant())
25242       return SDValue();
25243
25244     // Everything checks out. Build up the new and improved node.
25245     SDLoc DL(N);
25246     EVT IntVT = BV->getValueType(0);
25247     // Create a new constant of the appropriate type for the transformed
25248     // DAG.
25249     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
25250     // The AND node needs bitcasts to/from an integer vector type around it.
25251     SDValue MaskConst = DAG.getBitcast(IntVT, SourceConst);
25252     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
25253                                  N->getOperand(0)->getOperand(0), MaskConst);
25254     SDValue Res = DAG.getBitcast(VT, NewAnd);
25255     return Res;
25256   }
25257
25258   return SDValue();
25259 }
25260
25261 static SDValue PerformUINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
25262                                         const X86Subtarget *Subtarget) {
25263   SDValue Op0 = N->getOperand(0);
25264   EVT VT = N->getValueType(0);
25265   EVT InVT = Op0.getValueType();
25266   EVT InSVT = InVT.getScalarType();
25267   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25268
25269   // UINT_TO_FP(vXi8) -> SINT_TO_FP(ZEXT(vXi8 to vXi32))
25270   // UINT_TO_FP(vXi16) -> SINT_TO_FP(ZEXT(vXi16 to vXi32))
25271   if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
25272     SDLoc dl(N);
25273     EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
25274                                  InVT.getVectorNumElements());
25275     SDValue P = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Op0);
25276
25277     if (TLI.isOperationLegal(ISD::UINT_TO_FP, DstVT))
25278       return DAG.getNode(ISD::UINT_TO_FP, dl, VT, P);
25279
25280     return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
25281   }
25282
25283   return SDValue();
25284 }
25285
25286 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
25287                                         const X86Subtarget *Subtarget) {
25288   // First try to optimize away the conversion entirely when it's
25289   // conditionally from a constant. Vectors only.
25290   if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
25291     return Res;
25292
25293   // Now move on to more general possibilities.
25294   SDValue Op0 = N->getOperand(0);
25295   EVT VT = N->getValueType(0);
25296   EVT InVT = Op0.getValueType();
25297   EVT InSVT = InVT.getScalarType();
25298
25299   // SINT_TO_FP(vXi8) -> SINT_TO_FP(SEXT(vXi8 to vXi32))
25300   // SINT_TO_FP(vXi16) -> SINT_TO_FP(SEXT(vXi16 to vXi32))
25301   if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
25302     SDLoc dl(N);
25303     EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
25304                                  InVT.getVectorNumElements());
25305     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
25306     return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
25307   }
25308
25309   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
25310   // a 32-bit target where SSE doesn't support i64->FP operations.
25311   if (Op0.getOpcode() == ISD::LOAD) {
25312     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
25313     EVT LdVT = Ld->getValueType(0);
25314
25315     // This transformation is not supported if the result type is f16
25316     if (VT == MVT::f16)
25317       return SDValue();
25318
25319     if (!Ld->isVolatile() && !VT.isVector() &&
25320         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
25321         !Subtarget->is64Bit() && LdVT == MVT::i64) {
25322       SDValue FILDChain = Subtarget->getTargetLowering()->BuildFILD(
25323           SDValue(N, 0), LdVT, Ld->getChain(), Op0, DAG);
25324       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
25325       return FILDChain;
25326     }
25327   }
25328   return SDValue();
25329 }
25330
25331 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
25332 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
25333                                  X86TargetLowering::DAGCombinerInfo &DCI) {
25334   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
25335   // the result is either zero or one (depending on the input carry bit).
25336   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
25337   if (X86::isZeroNode(N->getOperand(0)) &&
25338       X86::isZeroNode(N->getOperand(1)) &&
25339       // We don't have a good way to replace an EFLAGS use, so only do this when
25340       // dead right now.
25341       SDValue(N, 1).use_empty()) {
25342     SDLoc DL(N);
25343     EVT VT = N->getValueType(0);
25344     SDValue CarryOut = DAG.getConstant(0, DL, N->getValueType(1));
25345     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
25346                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
25347                                            DAG.getConstant(X86::COND_B, DL,
25348                                                            MVT::i8),
25349                                            N->getOperand(2)),
25350                                DAG.getConstant(1, DL, VT));
25351     return DCI.CombineTo(N, Res1, CarryOut);
25352   }
25353
25354   return SDValue();
25355 }
25356
25357 // fold (add Y, (sete  X, 0)) -> adc  0, Y
25358 //      (add Y, (setne X, 0)) -> sbb -1, Y
25359 //      (sub (sete  X, 0), Y) -> sbb  0, Y
25360 //      (sub (setne X, 0), Y) -> adc -1, Y
25361 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
25362   SDLoc DL(N);
25363
25364   // Look through ZExts.
25365   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
25366   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
25367     return SDValue();
25368
25369   SDValue SetCC = Ext.getOperand(0);
25370   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
25371     return SDValue();
25372
25373   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
25374   if (CC != X86::COND_E && CC != X86::COND_NE)
25375     return SDValue();
25376
25377   SDValue Cmp = SetCC.getOperand(1);
25378   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
25379       !X86::isZeroNode(Cmp.getOperand(1)) ||
25380       !Cmp.getOperand(0).getValueType().isInteger())
25381     return SDValue();
25382
25383   SDValue CmpOp0 = Cmp.getOperand(0);
25384   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
25385                                DAG.getConstant(1, DL, CmpOp0.getValueType()));
25386
25387   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
25388   if (CC == X86::COND_NE)
25389     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
25390                        DL, OtherVal.getValueType(), OtherVal,
25391                        DAG.getConstant(-1ULL, DL, OtherVal.getValueType()),
25392                        NewCmp);
25393   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
25394                      DL, OtherVal.getValueType(), OtherVal,
25395                      DAG.getConstant(0, DL, OtherVal.getValueType()), NewCmp);
25396 }
25397
25398 /// PerformADDCombine - Do target-specific dag combines on integer adds.
25399 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
25400                                  const X86Subtarget *Subtarget) {
25401   EVT VT = N->getValueType(0);
25402   SDValue Op0 = N->getOperand(0);
25403   SDValue Op1 = N->getOperand(1);
25404
25405   // Try to synthesize horizontal adds from adds of shuffles.
25406   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
25407        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
25408       isHorizontalBinOp(Op0, Op1, true))
25409     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
25410
25411   return OptimizeConditionalInDecrement(N, DAG);
25412 }
25413
25414 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
25415                                  const X86Subtarget *Subtarget) {
25416   SDValue Op0 = N->getOperand(0);
25417   SDValue Op1 = N->getOperand(1);
25418
25419   // X86 can't encode an immediate LHS of a sub. See if we can push the
25420   // negation into a preceding instruction.
25421   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
25422     // If the RHS of the sub is a XOR with one use and a constant, invert the
25423     // immediate. Then add one to the LHS of the sub so we can turn
25424     // X-Y -> X+~Y+1, saving one register.
25425     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
25426         isa<ConstantSDNode>(Op1.getOperand(1))) {
25427       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
25428       EVT VT = Op0.getValueType();
25429       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
25430                                    Op1.getOperand(0),
25431                                    DAG.getConstant(~XorC, SDLoc(Op1), VT));
25432       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
25433                          DAG.getConstant(C->getAPIntValue() + 1, SDLoc(N), VT));
25434     }
25435   }
25436
25437   // Try to synthesize horizontal adds from adds of shuffles.
25438   EVT VT = N->getValueType(0);
25439   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
25440        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
25441       isHorizontalBinOp(Op0, Op1, true))
25442     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
25443
25444   return OptimizeConditionalInDecrement(N, DAG);
25445 }
25446
25447 /// performVZEXTCombine - Performs build vector combines
25448 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
25449                                    TargetLowering::DAGCombinerInfo &DCI,
25450                                    const X86Subtarget *Subtarget) {
25451   SDLoc DL(N);
25452   MVT VT = N->getSimpleValueType(0);
25453   SDValue Op = N->getOperand(0);
25454   MVT OpVT = Op.getSimpleValueType();
25455   MVT OpEltVT = OpVT.getVectorElementType();
25456   unsigned InputBits = OpEltVT.getSizeInBits() * VT.getVectorNumElements();
25457
25458   // (vzext (bitcast (vzext (x)) -> (vzext x)
25459   SDValue V = Op;
25460   while (V.getOpcode() == ISD::BITCAST)
25461     V = V.getOperand(0);
25462
25463   if (V != Op && V.getOpcode() == X86ISD::VZEXT) {
25464     MVT InnerVT = V.getSimpleValueType();
25465     MVT InnerEltVT = InnerVT.getVectorElementType();
25466
25467     // If the element sizes match exactly, we can just do one larger vzext. This
25468     // is always an exact type match as vzext operates on integer types.
25469     if (OpEltVT == InnerEltVT) {
25470       assert(OpVT == InnerVT && "Types must match for vzext!");
25471       return DAG.getNode(X86ISD::VZEXT, DL, VT, V.getOperand(0));
25472     }
25473
25474     // The only other way we can combine them is if only a single element of the
25475     // inner vzext is used in the input to the outer vzext.
25476     if (InnerEltVT.getSizeInBits() < InputBits)
25477       return SDValue();
25478
25479     // In this case, the inner vzext is completely dead because we're going to
25480     // only look at bits inside of the low element. Just do the outer vzext on
25481     // a bitcast of the input to the inner.
25482     return DAG.getNode(X86ISD::VZEXT, DL, VT, DAG.getBitcast(OpVT, V));
25483   }
25484
25485   // Check if we can bypass extracting and re-inserting an element of an input
25486   // vector. Essentialy:
25487   // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
25488   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR &&
25489       V.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
25490       V.getOperand(0).getSimpleValueType().getSizeInBits() == InputBits) {
25491     SDValue ExtractedV = V.getOperand(0);
25492     SDValue OrigV = ExtractedV.getOperand(0);
25493     if (auto *ExtractIdx = dyn_cast<ConstantSDNode>(ExtractedV.getOperand(1)))
25494       if (ExtractIdx->getZExtValue() == 0) {
25495         MVT OrigVT = OrigV.getSimpleValueType();
25496         // Extract a subvector if necessary...
25497         if (OrigVT.getSizeInBits() > OpVT.getSizeInBits()) {
25498           int Ratio = OrigVT.getSizeInBits() / OpVT.getSizeInBits();
25499           OrigVT = MVT::getVectorVT(OrigVT.getVectorElementType(),
25500                                     OrigVT.getVectorNumElements() / Ratio);
25501           OrigV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigVT, OrigV,
25502                               DAG.getIntPtrConstant(0, DL));
25503         }
25504         Op = DAG.getBitcast(OpVT, OrigV);
25505         return DAG.getNode(X86ISD::VZEXT, DL, VT, Op);
25506       }
25507   }
25508
25509   return SDValue();
25510 }
25511
25512 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
25513                                              DAGCombinerInfo &DCI) const {
25514   SelectionDAG &DAG = DCI.DAG;
25515   switch (N->getOpcode()) {
25516   default: break;
25517   case ISD::EXTRACT_VECTOR_ELT:
25518     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
25519   case ISD::VSELECT:
25520   case ISD::SELECT:
25521   case X86ISD::SHRUNKBLEND:
25522     return PerformSELECTCombine(N, DAG, DCI, Subtarget);
25523   case ISD::BITCAST:        return PerformBITCASTCombine(N, DAG);
25524   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
25525   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
25526   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
25527   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
25528   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
25529   case ISD::SHL:
25530   case ISD::SRA:
25531   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
25532   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
25533   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
25534   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
25535   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
25536   case ISD::MLOAD:          return PerformMLOADCombine(N, DAG, DCI, Subtarget);
25537   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
25538   case ISD::MSTORE:         return PerformMSTORECombine(N, DAG, Subtarget);
25539   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, Subtarget);
25540   case ISD::UINT_TO_FP:     return PerformUINT_TO_FPCombine(N, DAG, Subtarget);
25541   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
25542   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
25543   case X86ISD::FXOR:
25544   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
25545   case X86ISD::FMIN:
25546   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
25547   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
25548   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
25549   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
25550   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
25551   case ISD::ANY_EXTEND:
25552   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
25553   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
25554   case ISD::SIGN_EXTEND_INREG:
25555     return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
25556   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
25557   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
25558   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
25559   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
25560   case X86ISD::SHUFP:       // Handle all target specific shuffles
25561   case X86ISD::PALIGNR:
25562   case X86ISD::UNPCKH:
25563   case X86ISD::UNPCKL:
25564   case X86ISD::MOVHLPS:
25565   case X86ISD::MOVLHPS:
25566   case X86ISD::PSHUFB:
25567   case X86ISD::PSHUFD:
25568   case X86ISD::PSHUFHW:
25569   case X86ISD::PSHUFLW:
25570   case X86ISD::MOVSS:
25571   case X86ISD::MOVSD:
25572   case X86ISD::VPERMILPI:
25573   case X86ISD::VPERM2X128:
25574   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
25575   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
25576   case ISD::INTRINSIC_WO_CHAIN:
25577     return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
25578   case X86ISD::INSERTPS: {
25579     if (getTargetMachine().getOptLevel() > CodeGenOpt::None)
25580       return PerformINSERTPSCombine(N, DAG, Subtarget);
25581     break;
25582   }
25583   case X86ISD::BLENDI:    return PerformBLENDICombine(N, DAG);
25584   }
25585
25586   return SDValue();
25587 }
25588
25589 /// isTypeDesirableForOp - Return true if the target has native support for
25590 /// the specified value type and it is 'desirable' to use the type for the
25591 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
25592 /// instruction encodings are longer and some i16 instructions are slow.
25593 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
25594   if (!isTypeLegal(VT))
25595     return false;
25596   if (VT != MVT::i16)
25597     return true;
25598
25599   switch (Opc) {
25600   default:
25601     return true;
25602   case ISD::LOAD:
25603   case ISD::SIGN_EXTEND:
25604   case ISD::ZERO_EXTEND:
25605   case ISD::ANY_EXTEND:
25606   case ISD::SHL:
25607   case ISD::SRL:
25608   case ISD::SUB:
25609   case ISD::ADD:
25610   case ISD::MUL:
25611   case ISD::AND:
25612   case ISD::OR:
25613   case ISD::XOR:
25614     return false;
25615   }
25616 }
25617
25618 /// IsDesirableToPromoteOp - This method query the target whether it is
25619 /// beneficial for dag combiner to promote the specified node. If true, it
25620 /// should return the desired promotion type by reference.
25621 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
25622   EVT VT = Op.getValueType();
25623   if (VT != MVT::i16)
25624     return false;
25625
25626   bool Promote = false;
25627   bool Commute = false;
25628   switch (Op.getOpcode()) {
25629   default: break;
25630   case ISD::LOAD: {
25631     LoadSDNode *LD = cast<LoadSDNode>(Op);
25632     // If the non-extending load has a single use and it's not live out, then it
25633     // might be folded.
25634     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
25635                                                      Op.hasOneUse()*/) {
25636       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
25637              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
25638         // The only case where we'd want to promote LOAD (rather then it being
25639         // promoted as an operand is when it's only use is liveout.
25640         if (UI->getOpcode() != ISD::CopyToReg)
25641           return false;
25642       }
25643     }
25644     Promote = true;
25645     break;
25646   }
25647   case ISD::SIGN_EXTEND:
25648   case ISD::ZERO_EXTEND:
25649   case ISD::ANY_EXTEND:
25650     Promote = true;
25651     break;
25652   case ISD::SHL:
25653   case ISD::SRL: {
25654     SDValue N0 = Op.getOperand(0);
25655     // Look out for (store (shl (load), x)).
25656     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
25657       return false;
25658     Promote = true;
25659     break;
25660   }
25661   case ISD::ADD:
25662   case ISD::MUL:
25663   case ISD::AND:
25664   case ISD::OR:
25665   case ISD::XOR:
25666     Commute = true;
25667     // fallthrough
25668   case ISD::SUB: {
25669     SDValue N0 = Op.getOperand(0);
25670     SDValue N1 = Op.getOperand(1);
25671     if (!Commute && MayFoldLoad(N1))
25672       return false;
25673     // Avoid disabling potential load folding opportunities.
25674     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
25675       return false;
25676     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
25677       return false;
25678     Promote = true;
25679   }
25680   }
25681
25682   PVT = MVT::i32;
25683   return Promote;
25684 }
25685
25686 //===----------------------------------------------------------------------===//
25687 //                           X86 Inline Assembly Support
25688 //===----------------------------------------------------------------------===//
25689
25690 // Helper to match a string separated by whitespace.
25691 static bool matchAsm(StringRef S, ArrayRef<const char *> Pieces) {
25692   S = S.substr(S.find_first_not_of(" \t")); // Skip leading whitespace.
25693
25694   for (StringRef Piece : Pieces) {
25695     if (!S.startswith(Piece)) // Check if the piece matches.
25696       return false;
25697
25698     S = S.substr(Piece.size());
25699     StringRef::size_type Pos = S.find_first_not_of(" \t");
25700     if (Pos == 0) // We matched a prefix.
25701       return false;
25702
25703     S = S.substr(Pos);
25704   }
25705
25706   return S.empty();
25707 }
25708
25709 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
25710
25711   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
25712     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
25713         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
25714         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
25715
25716       if (AsmPieces.size() == 3)
25717         return true;
25718       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
25719         return true;
25720     }
25721   }
25722   return false;
25723 }
25724
25725 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
25726   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
25727
25728   std::string AsmStr = IA->getAsmString();
25729
25730   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
25731   if (!Ty || Ty->getBitWidth() % 16 != 0)
25732     return false;
25733
25734   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
25735   SmallVector<StringRef, 4> AsmPieces;
25736   SplitString(AsmStr, AsmPieces, ";\n");
25737
25738   switch (AsmPieces.size()) {
25739   default: return false;
25740   case 1:
25741     // FIXME: this should verify that we are targeting a 486 or better.  If not,
25742     // we will turn this bswap into something that will be lowered to logical
25743     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
25744     // lower so don't worry about this.
25745     // bswap $0
25746     if (matchAsm(AsmPieces[0], {"bswap", "$0"}) ||
25747         matchAsm(AsmPieces[0], {"bswapl", "$0"}) ||
25748         matchAsm(AsmPieces[0], {"bswapq", "$0"}) ||
25749         matchAsm(AsmPieces[0], {"bswap", "${0:q}"}) ||
25750         matchAsm(AsmPieces[0], {"bswapl", "${0:q}"}) ||
25751         matchAsm(AsmPieces[0], {"bswapq", "${0:q}"})) {
25752       // No need to check constraints, nothing other than the equivalent of
25753       // "=r,0" would be valid here.
25754       return IntrinsicLowering::LowerToByteSwap(CI);
25755     }
25756
25757     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
25758     if (CI->getType()->isIntegerTy(16) &&
25759         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
25760         (matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) ||
25761          matchAsm(AsmPieces[0], {"rolw", "$$8,", "${0:w}"}))) {
25762       AsmPieces.clear();
25763       StringRef ConstraintsStr = IA->getConstraintString();
25764       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
25765       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
25766       if (clobbersFlagRegisters(AsmPieces))
25767         return IntrinsicLowering::LowerToByteSwap(CI);
25768     }
25769     break;
25770   case 3:
25771     if (CI->getType()->isIntegerTy(32) &&
25772         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
25773         matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) &&
25774         matchAsm(AsmPieces[1], {"rorl", "$$16,", "$0"}) &&
25775         matchAsm(AsmPieces[2], {"rorw", "$$8,", "${0:w}"})) {
25776       AsmPieces.clear();
25777       StringRef ConstraintsStr = IA->getConstraintString();
25778       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
25779       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
25780       if (clobbersFlagRegisters(AsmPieces))
25781         return IntrinsicLowering::LowerToByteSwap(CI);
25782     }
25783
25784     if (CI->getType()->isIntegerTy(64)) {
25785       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
25786       if (Constraints.size() >= 2 &&
25787           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
25788           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
25789         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
25790         if (matchAsm(AsmPieces[0], {"bswap", "%eax"}) &&
25791             matchAsm(AsmPieces[1], {"bswap", "%edx"}) &&
25792             matchAsm(AsmPieces[2], {"xchgl", "%eax,", "%edx"}))
25793           return IntrinsicLowering::LowerToByteSwap(CI);
25794       }
25795     }
25796     break;
25797   }
25798   return false;
25799 }
25800
25801 /// getConstraintType - Given a constraint letter, return the type of
25802 /// constraint it is for this target.
25803 X86TargetLowering::ConstraintType
25804 X86TargetLowering::getConstraintType(StringRef Constraint) const {
25805   if (Constraint.size() == 1) {
25806     switch (Constraint[0]) {
25807     case 'R':
25808     case 'q':
25809     case 'Q':
25810     case 'f':
25811     case 't':
25812     case 'u':
25813     case 'y':
25814     case 'x':
25815     case 'Y':
25816     case 'l':
25817       return C_RegisterClass;
25818     case 'a':
25819     case 'b':
25820     case 'c':
25821     case 'd':
25822     case 'S':
25823     case 'D':
25824     case 'A':
25825       return C_Register;
25826     case 'I':
25827     case 'J':
25828     case 'K':
25829     case 'L':
25830     case 'M':
25831     case 'N':
25832     case 'G':
25833     case 'C':
25834     case 'e':
25835     case 'Z':
25836       return C_Other;
25837     default:
25838       break;
25839     }
25840   }
25841   return TargetLowering::getConstraintType(Constraint);
25842 }
25843
25844 /// Examine constraint type and operand type and determine a weight value.
25845 /// This object must already have been set up with the operand type
25846 /// and the current alternative constraint selected.
25847 TargetLowering::ConstraintWeight
25848   X86TargetLowering::getSingleConstraintMatchWeight(
25849     AsmOperandInfo &info, const char *constraint) const {
25850   ConstraintWeight weight = CW_Invalid;
25851   Value *CallOperandVal = info.CallOperandVal;
25852     // If we don't have a value, we can't do a match,
25853     // but allow it at the lowest weight.
25854   if (!CallOperandVal)
25855     return CW_Default;
25856   Type *type = CallOperandVal->getType();
25857   // Look at the constraint type.
25858   switch (*constraint) {
25859   default:
25860     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
25861   case 'R':
25862   case 'q':
25863   case 'Q':
25864   case 'a':
25865   case 'b':
25866   case 'c':
25867   case 'd':
25868   case 'S':
25869   case 'D':
25870   case 'A':
25871     if (CallOperandVal->getType()->isIntegerTy())
25872       weight = CW_SpecificReg;
25873     break;
25874   case 'f':
25875   case 't':
25876   case 'u':
25877     if (type->isFloatingPointTy())
25878       weight = CW_SpecificReg;
25879     break;
25880   case 'y':
25881     if (type->isX86_MMXTy() && Subtarget->hasMMX())
25882       weight = CW_SpecificReg;
25883     break;
25884   case 'x':
25885   case 'Y':
25886     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
25887         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
25888       weight = CW_Register;
25889     break;
25890   case 'I':
25891     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
25892       if (C->getZExtValue() <= 31)
25893         weight = CW_Constant;
25894     }
25895     break;
25896   case 'J':
25897     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25898       if (C->getZExtValue() <= 63)
25899         weight = CW_Constant;
25900     }
25901     break;
25902   case 'K':
25903     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25904       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
25905         weight = CW_Constant;
25906     }
25907     break;
25908   case 'L':
25909     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25910       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
25911         weight = CW_Constant;
25912     }
25913     break;
25914   case 'M':
25915     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25916       if (C->getZExtValue() <= 3)
25917         weight = CW_Constant;
25918     }
25919     break;
25920   case 'N':
25921     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25922       if (C->getZExtValue() <= 0xff)
25923         weight = CW_Constant;
25924     }
25925     break;
25926   case 'G':
25927   case 'C':
25928     if (isa<ConstantFP>(CallOperandVal)) {
25929       weight = CW_Constant;
25930     }
25931     break;
25932   case 'e':
25933     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25934       if ((C->getSExtValue() >= -0x80000000LL) &&
25935           (C->getSExtValue() <= 0x7fffffffLL))
25936         weight = CW_Constant;
25937     }
25938     break;
25939   case 'Z':
25940     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25941       if (C->getZExtValue() <= 0xffffffff)
25942         weight = CW_Constant;
25943     }
25944     break;
25945   }
25946   return weight;
25947 }
25948
25949 /// LowerXConstraint - try to replace an X constraint, which matches anything,
25950 /// with another that has more specific requirements based on the type of the
25951 /// corresponding operand.
25952 const char *X86TargetLowering::
25953 LowerXConstraint(EVT ConstraintVT) const {
25954   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
25955   // 'f' like normal targets.
25956   if (ConstraintVT.isFloatingPoint()) {
25957     if (Subtarget->hasSSE2())
25958       return "Y";
25959     if (Subtarget->hasSSE1())
25960       return "x";
25961   }
25962
25963   return TargetLowering::LowerXConstraint(ConstraintVT);
25964 }
25965
25966 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
25967 /// vector.  If it is invalid, don't add anything to Ops.
25968 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
25969                                                      std::string &Constraint,
25970                                                      std::vector<SDValue>&Ops,
25971                                                      SelectionDAG &DAG) const {
25972   SDValue Result;
25973
25974   // Only support length 1 constraints for now.
25975   if (Constraint.length() > 1) return;
25976
25977   char ConstraintLetter = Constraint[0];
25978   switch (ConstraintLetter) {
25979   default: break;
25980   case 'I':
25981     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25982       if (C->getZExtValue() <= 31) {
25983         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
25984                                        Op.getValueType());
25985         break;
25986       }
25987     }
25988     return;
25989   case 'J':
25990     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25991       if (C->getZExtValue() <= 63) {
25992         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
25993                                        Op.getValueType());
25994         break;
25995       }
25996     }
25997     return;
25998   case 'K':
25999     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26000       if (isInt<8>(C->getSExtValue())) {
26001         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26002                                        Op.getValueType());
26003         break;
26004       }
26005     }
26006     return;
26007   case 'L':
26008     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26009       if (C->getZExtValue() == 0xff || C->getZExtValue() == 0xffff ||
26010           (Subtarget->is64Bit() && C->getZExtValue() == 0xffffffff)) {
26011         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op),
26012                                        Op.getValueType());
26013         break;
26014       }
26015     }
26016     return;
26017   case 'M':
26018     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26019       if (C->getZExtValue() <= 3) {
26020         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26021                                        Op.getValueType());
26022         break;
26023       }
26024     }
26025     return;
26026   case 'N':
26027     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26028       if (C->getZExtValue() <= 255) {
26029         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26030                                        Op.getValueType());
26031         break;
26032       }
26033     }
26034     return;
26035   case 'O':
26036     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26037       if (C->getZExtValue() <= 127) {
26038         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26039                                        Op.getValueType());
26040         break;
26041       }
26042     }
26043     return;
26044   case 'e': {
26045     // 32-bit signed value
26046     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26047       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
26048                                            C->getSExtValue())) {
26049         // Widen to 64 bits here to get it sign extended.
26050         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op), MVT::i64);
26051         break;
26052       }
26053     // FIXME gcc accepts some relocatable values here too, but only in certain
26054     // memory models; it's complicated.
26055     }
26056     return;
26057   }
26058   case 'Z': {
26059     // 32-bit unsigned value
26060     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26061       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
26062                                            C->getZExtValue())) {
26063         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26064                                        Op.getValueType());
26065         break;
26066       }
26067     }
26068     // FIXME gcc accepts some relocatable values here too, but only in certain
26069     // memory models; it's complicated.
26070     return;
26071   }
26072   case 'i': {
26073     // Literal immediates are always ok.
26074     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
26075       // Widen to 64 bits here to get it sign extended.
26076       Result = DAG.getTargetConstant(CST->getSExtValue(), SDLoc(Op), MVT::i64);
26077       break;
26078     }
26079
26080     // In any sort of PIC mode addresses need to be computed at runtime by
26081     // adding in a register or some sort of table lookup.  These can't
26082     // be used as immediates.
26083     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
26084       return;
26085
26086     // If we are in non-pic codegen mode, we allow the address of a global (with
26087     // an optional displacement) to be used with 'i'.
26088     GlobalAddressSDNode *GA = nullptr;
26089     int64_t Offset = 0;
26090
26091     // Match either (GA), (GA+C), (GA+C1+C2), etc.
26092     while (1) {
26093       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
26094         Offset += GA->getOffset();
26095         break;
26096       } else if (Op.getOpcode() == ISD::ADD) {
26097         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
26098           Offset += C->getZExtValue();
26099           Op = Op.getOperand(0);
26100           continue;
26101         }
26102       } else if (Op.getOpcode() == ISD::SUB) {
26103         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
26104           Offset += -C->getZExtValue();
26105           Op = Op.getOperand(0);
26106           continue;
26107         }
26108       }
26109
26110       // Otherwise, this isn't something we can handle, reject it.
26111       return;
26112     }
26113
26114     const GlobalValue *GV = GA->getGlobal();
26115     // If we require an extra load to get this address, as in PIC mode, we
26116     // can't accept it.
26117     if (isGlobalStubReference(
26118             Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
26119       return;
26120
26121     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
26122                                         GA->getValueType(0), Offset);
26123     break;
26124   }
26125   }
26126
26127   if (Result.getNode()) {
26128     Ops.push_back(Result);
26129     return;
26130   }
26131   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
26132 }
26133
26134 std::pair<unsigned, const TargetRegisterClass *>
26135 X86TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
26136                                                 StringRef Constraint,
26137                                                 MVT VT) const {
26138   // First, see if this is a constraint that directly corresponds to an LLVM
26139   // register class.
26140   if (Constraint.size() == 1) {
26141     // GCC Constraint Letters
26142     switch (Constraint[0]) {
26143     default: break;
26144       // TODO: Slight differences here in allocation order and leaving
26145       // RIP in the class. Do they matter any more here than they do
26146       // in the normal allocation?
26147     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
26148       if (Subtarget->is64Bit()) {
26149         if (VT == MVT::i32 || VT == MVT::f32)
26150           return std::make_pair(0U, &X86::GR32RegClass);
26151         if (VT == MVT::i16)
26152           return std::make_pair(0U, &X86::GR16RegClass);
26153         if (VT == MVT::i8 || VT == MVT::i1)
26154           return std::make_pair(0U, &X86::GR8RegClass);
26155         if (VT == MVT::i64 || VT == MVT::f64)
26156           return std::make_pair(0U, &X86::GR64RegClass);
26157         break;
26158       }
26159       // 32-bit fallthrough
26160     case 'Q':   // Q_REGS
26161       if (VT == MVT::i32 || VT == MVT::f32)
26162         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
26163       if (VT == MVT::i16)
26164         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
26165       if (VT == MVT::i8 || VT == MVT::i1)
26166         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
26167       if (VT == MVT::i64)
26168         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
26169       break;
26170     case 'r':   // GENERAL_REGS
26171     case 'l':   // INDEX_REGS
26172       if (VT == MVT::i8 || VT == MVT::i1)
26173         return std::make_pair(0U, &X86::GR8RegClass);
26174       if (VT == MVT::i16)
26175         return std::make_pair(0U, &X86::GR16RegClass);
26176       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
26177         return std::make_pair(0U, &X86::GR32RegClass);
26178       return std::make_pair(0U, &X86::GR64RegClass);
26179     case 'R':   // LEGACY_REGS
26180       if (VT == MVT::i8 || VT == MVT::i1)
26181         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
26182       if (VT == MVT::i16)
26183         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
26184       if (VT == MVT::i32 || !Subtarget->is64Bit())
26185         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
26186       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
26187     case 'f':  // FP Stack registers.
26188       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
26189       // value to the correct fpstack register class.
26190       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
26191         return std::make_pair(0U, &X86::RFP32RegClass);
26192       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
26193         return std::make_pair(0U, &X86::RFP64RegClass);
26194       return std::make_pair(0U, &X86::RFP80RegClass);
26195     case 'y':   // MMX_REGS if MMX allowed.
26196       if (!Subtarget->hasMMX()) break;
26197       return std::make_pair(0U, &X86::VR64RegClass);
26198     case 'Y':   // SSE_REGS if SSE2 allowed
26199       if (!Subtarget->hasSSE2()) break;
26200       // FALL THROUGH.
26201     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
26202       if (!Subtarget->hasSSE1()) break;
26203
26204       switch (VT.SimpleTy) {
26205       default: break;
26206       // Scalar SSE types.
26207       case MVT::f32:
26208       case MVT::i32:
26209         return std::make_pair(0U, &X86::FR32RegClass);
26210       case MVT::f64:
26211       case MVT::i64:
26212         return std::make_pair(0U, &X86::FR64RegClass);
26213       // Vector types.
26214       case MVT::v16i8:
26215       case MVT::v8i16:
26216       case MVT::v4i32:
26217       case MVT::v2i64:
26218       case MVT::v4f32:
26219       case MVT::v2f64:
26220         return std::make_pair(0U, &X86::VR128RegClass);
26221       // AVX types.
26222       case MVT::v32i8:
26223       case MVT::v16i16:
26224       case MVT::v8i32:
26225       case MVT::v4i64:
26226       case MVT::v8f32:
26227       case MVT::v4f64:
26228         return std::make_pair(0U, &X86::VR256RegClass);
26229       case MVT::v8f64:
26230       case MVT::v16f32:
26231       case MVT::v16i32:
26232       case MVT::v8i64:
26233         return std::make_pair(0U, &X86::VR512RegClass);
26234       }
26235       break;
26236     }
26237   }
26238
26239   // Use the default implementation in TargetLowering to convert the register
26240   // constraint into a member of a register class.
26241   std::pair<unsigned, const TargetRegisterClass*> Res;
26242   Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
26243
26244   // Not found as a standard register?
26245   if (!Res.second) {
26246     // Map st(0) -> st(7) -> ST0
26247     if (Constraint.size() == 7 && Constraint[0] == '{' &&
26248         tolower(Constraint[1]) == 's' &&
26249         tolower(Constraint[2]) == 't' &&
26250         Constraint[3] == '(' &&
26251         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
26252         Constraint[5] == ')' &&
26253         Constraint[6] == '}') {
26254
26255       Res.first = X86::FP0+Constraint[4]-'0';
26256       Res.second = &X86::RFP80RegClass;
26257       return Res;
26258     }
26259
26260     // GCC allows "st(0)" to be called just plain "st".
26261     if (StringRef("{st}").equals_lower(Constraint)) {
26262       Res.first = X86::FP0;
26263       Res.second = &X86::RFP80RegClass;
26264       return Res;
26265     }
26266
26267     // flags -> EFLAGS
26268     if (StringRef("{flags}").equals_lower(Constraint)) {
26269       Res.first = X86::EFLAGS;
26270       Res.second = &X86::CCRRegClass;
26271       return Res;
26272     }
26273
26274     // 'A' means EAX + EDX.
26275     if (Constraint == "A") {
26276       Res.first = X86::EAX;
26277       Res.second = &X86::GR32_ADRegClass;
26278       return Res;
26279     }
26280     return Res;
26281   }
26282
26283   // Otherwise, check to see if this is a register class of the wrong value
26284   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
26285   // turn into {ax},{dx}.
26286   // MVT::Other is used to specify clobber names.
26287   if (Res.second->hasType(VT) || VT == MVT::Other)
26288     return Res;   // Correct type already, nothing to do.
26289
26290   // Get a matching integer of the correct size. i.e. "ax" with MVT::32 should
26291   // return "eax". This should even work for things like getting 64bit integer
26292   // registers when given an f64 type.
26293   const TargetRegisterClass *Class = Res.second;
26294   if (Class == &X86::GR8RegClass || Class == &X86::GR16RegClass ||
26295       Class == &X86::GR32RegClass || Class == &X86::GR64RegClass) {
26296     unsigned Size = VT.getSizeInBits();
26297     MVT::SimpleValueType SimpleTy = Size == 1 || Size == 8 ? MVT::i8
26298                                   : Size == 16 ? MVT::i16
26299                                   : Size == 32 ? MVT::i32
26300                                   : Size == 64 ? MVT::i64
26301                                   : MVT::Other;
26302     unsigned DestReg = getX86SubSuperRegisterOrZero(Res.first, SimpleTy);
26303     if (DestReg > 0) {
26304       Res.first = DestReg;
26305       Res.second = SimpleTy == MVT::i8 ? &X86::GR8RegClass
26306                  : SimpleTy == MVT::i16 ? &X86::GR16RegClass
26307                  : SimpleTy == MVT::i32 ? &X86::GR32RegClass
26308                  : &X86::GR64RegClass;
26309       assert(Res.second->contains(Res.first) && "Register in register class");
26310     } else {
26311       // No register found/type mismatch.
26312       Res.first = 0;
26313       Res.second = nullptr;
26314     }
26315   } else if (Class == &X86::FR32RegClass || Class == &X86::FR64RegClass ||
26316              Class == &X86::VR128RegClass || Class == &X86::VR256RegClass ||
26317              Class == &X86::FR32XRegClass || Class == &X86::FR64XRegClass ||
26318              Class == &X86::VR128XRegClass || Class == &X86::VR256XRegClass ||
26319              Class == &X86::VR512RegClass) {
26320     // Handle references to XMM physical registers that got mapped into the
26321     // wrong class.  This can happen with constraints like {xmm0} where the
26322     // target independent register mapper will just pick the first match it can
26323     // find, ignoring the required type.
26324
26325     if (VT == MVT::f32 || VT == MVT::i32)
26326       Res.second = &X86::FR32RegClass;
26327     else if (VT == MVT::f64 || VT == MVT::i64)
26328       Res.second = &X86::FR64RegClass;
26329     else if (X86::VR128RegClass.hasType(VT))
26330       Res.second = &X86::VR128RegClass;
26331     else if (X86::VR256RegClass.hasType(VT))
26332       Res.second = &X86::VR256RegClass;
26333     else if (X86::VR512RegClass.hasType(VT))
26334       Res.second = &X86::VR512RegClass;
26335     else {
26336       // Type mismatch and not a clobber: Return an error;
26337       Res.first = 0;
26338       Res.second = nullptr;
26339     }
26340   }
26341
26342   return Res;
26343 }
26344
26345 int X86TargetLowering::getScalingFactorCost(const DataLayout &DL,
26346                                             const AddrMode &AM, Type *Ty,
26347                                             unsigned AS) const {
26348   // Scaling factors are not free at all.
26349   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
26350   // will take 2 allocations in the out of order engine instead of 1
26351   // for plain addressing mode, i.e. inst (reg1).
26352   // E.g.,
26353   // vaddps (%rsi,%drx), %ymm0, %ymm1
26354   // Requires two allocations (one for the load, one for the computation)
26355   // whereas:
26356   // vaddps (%rsi), %ymm0, %ymm1
26357   // Requires just 1 allocation, i.e., freeing allocations for other operations
26358   // and having less micro operations to execute.
26359   //
26360   // For some X86 architectures, this is even worse because for instance for
26361   // stores, the complex addressing mode forces the instruction to use the
26362   // "load" ports instead of the dedicated "store" port.
26363   // E.g., on Haswell:
26364   // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
26365   // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
26366   if (isLegalAddressingMode(DL, AM, Ty, AS))
26367     // Scale represents reg2 * scale, thus account for 1
26368     // as soon as we use a second register.
26369     return AM.Scale != 0;
26370   return -1;
26371 }
26372
26373 bool X86TargetLowering::isTargetFTOL() const {
26374   return Subtarget->isTargetKnownWindowsMSVC() && !Subtarget->is64Bit();
26375 }