[TargetLowering] StringRefize asm constraint getters.
[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 = 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(), 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::SETCC,              MVT::v2i64, Custom);
829     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
830     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
831     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
832
833     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
834     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
835     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
836     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
837     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
838
839     setOperationAction(ISD::CTPOP,              MVT::v16i8, Custom);
840     setOperationAction(ISD::CTPOP,              MVT::v8i16, Custom);
841     setOperationAction(ISD::CTPOP,              MVT::v4i32, Custom);
842     setOperationAction(ISD::CTPOP,              MVT::v2i64, Custom);
843
844     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
845     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
846       MVT VT = (MVT::SimpleValueType)i;
847       // Do not attempt to custom lower non-power-of-2 vectors
848       if (!isPowerOf2_32(VT.getVectorNumElements()))
849         continue;
850       // Do not attempt to custom lower non-128-bit vectors
851       if (!VT.is128BitVector())
852         continue;
853       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
854       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
855       setOperationAction(ISD::VSELECT,            VT, Custom);
856       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
857     }
858
859     // We support custom legalizing of sext and anyext loads for specific
860     // memory vector types which we can load as a scalar (or sequence of
861     // scalars) and extend in-register to a legal 128-bit vector type. For sext
862     // loads these must work with a single scalar load.
863     for (MVT VT : MVT::integer_vector_valuetypes()) {
864       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i8, Custom);
865       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i16, Custom);
866       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v8i8, Custom);
867       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i8, Custom);
868       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i16, Custom);
869       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i32, Custom);
870       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i8, Custom);
871       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i16, Custom);
872       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8i8, Custom);
873     }
874
875     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
876     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
877     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
878     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
879     setOperationAction(ISD::VSELECT,            MVT::v2f64, Custom);
880     setOperationAction(ISD::VSELECT,            MVT::v2i64, Custom);
881     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
882     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
883
884     if (Subtarget->is64Bit()) {
885       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
886       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
887     }
888
889     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
890     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
891       MVT VT = (MVT::SimpleValueType)i;
892
893       // Do not attempt to promote non-128-bit vectors
894       if (!VT.is128BitVector())
895         continue;
896
897       setOperationAction(ISD::AND,    VT, Promote);
898       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
899       setOperationAction(ISD::OR,     VT, Promote);
900       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
901       setOperationAction(ISD::XOR,    VT, Promote);
902       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
903       setOperationAction(ISD::LOAD,   VT, Promote);
904       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
905       setOperationAction(ISD::SELECT, VT, Promote);
906       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
907     }
908
909     // Custom lower v2i64 and v2f64 selects.
910     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
911     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
912     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
913     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
914
915     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
916     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
917
918     setOperationAction(ISD::SINT_TO_FP,         MVT::v2i32, Custom);
919
920     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
921     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
922     // As there is no 64-bit GPR available, we need build a special custom
923     // sequence to convert from v2i32 to v2f32.
924     if (!Subtarget->is64Bit())
925       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
926
927     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
928     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
929
930     for (MVT VT : MVT::fp_vector_valuetypes())
931       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2f32, Legal);
932
933     setOperationAction(ISD::BITCAST,            MVT::v2i32, Custom);
934     setOperationAction(ISD::BITCAST,            MVT::v4i16, Custom);
935     setOperationAction(ISD::BITCAST,            MVT::v8i8,  Custom);
936   }
937
938   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE41()) {
939     for (MVT RoundedTy : {MVT::f32, MVT::f64, MVT::v4f32, MVT::v2f64}) {
940       setOperationAction(ISD::FFLOOR,           RoundedTy,  Legal);
941       setOperationAction(ISD::FCEIL,            RoundedTy,  Legal);
942       setOperationAction(ISD::FTRUNC,           RoundedTy,  Legal);
943       setOperationAction(ISD::FRINT,            RoundedTy,  Legal);
944       setOperationAction(ISD::FNEARBYINT,       RoundedTy,  Legal);
945     }
946
947     // FIXME: Do we need to handle scalar-to-vector here?
948     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
949
950     // We directly match byte blends in the backend as they match the VSELECT
951     // condition form.
952     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
953
954     // SSE41 brings specific instructions for doing vector sign extend even in
955     // cases where we don't have SRA.
956     for (MVT VT : MVT::integer_vector_valuetypes()) {
957       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i8, Custom);
958       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i16, Custom);
959       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i32, Custom);
960     }
961
962     // SSE41 also has vector sign/zero extending loads, PMOV[SZ]X
963     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i16, MVT::v8i8,  Legal);
964     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i8,  Legal);
965     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i8,  Legal);
966     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
967     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
968     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
969
970     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i16, MVT::v8i8,  Legal);
971     setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i8,  Legal);
972     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i8,  Legal);
973     setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
974     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
975     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
976
977     // i8 and i16 vectors are custom because the source register and source
978     // source memory operand types are not the same width.  f32 vectors are
979     // custom since the immediate controlling the insert encodes additional
980     // information.
981     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
982     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
983     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
984     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
985
986     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
987     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
988     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
989     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
990
991     // FIXME: these should be Legal, but that's only for the case where
992     // the index is constant.  For now custom expand to deal with that.
993     if (Subtarget->is64Bit()) {
994       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
995       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
996     }
997   }
998
999   if (Subtarget->hasSSE2()) {
1000     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v2i64, Custom);
1001     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v4i32, Custom);
1002     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v8i16, Custom);
1003
1004     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1005     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1006
1007     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1008     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1009
1010     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1011     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1012
1013     // In the customized shift lowering, the legal cases in AVX2 will be
1014     // recognized.
1015     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1016     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1017
1018     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1019     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1020
1021     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1022   }
1023
1024   if (!Subtarget->useSoftFloat() && Subtarget->hasFp256()) {
1025     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1026     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1027     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1028     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1029     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1030     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1031
1032     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1033     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1034     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1035
1036     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1037     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1038     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1039     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1040     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1041     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1042     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1043     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1044     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1045     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1046     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1047     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1048
1049     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1050     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1051     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1052     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1053     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1054     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1055     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1056     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1057     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1058     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1059     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1060     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1061
1062     // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1063     // even though v8i16 is a legal type.
1064     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Promote);
1065     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i16, Promote);
1066     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1067
1068     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1069     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1070     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1071
1072     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1073     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1074
1075     for (MVT VT : MVT::fp_vector_valuetypes())
1076       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4f32, Legal);
1077
1078     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1079     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1080
1081     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1082     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1083
1084     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1085     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1086
1087     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1088     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1089     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1090     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1091
1092     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1093     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1094     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1095
1096     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1097     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1098     setOperationAction(ISD::SIGN_EXTEND,       MVT::v16i16, Custom);
1099     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1100     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1101     setOperationAction(ISD::ZERO_EXTEND,       MVT::v16i16, Custom);
1102     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1103     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1104     setOperationAction(ISD::ANY_EXTEND,        MVT::v16i16, Custom);
1105     setOperationAction(ISD::TRUNCATE,          MVT::v16i8, Custom);
1106     setOperationAction(ISD::TRUNCATE,          MVT::v8i16, Custom);
1107     setOperationAction(ISD::TRUNCATE,          MVT::v4i32, Custom);
1108
1109     setOperationAction(ISD::CTPOP,             MVT::v32i8, Custom);
1110     setOperationAction(ISD::CTPOP,             MVT::v16i16, Custom);
1111     setOperationAction(ISD::CTPOP,             MVT::v8i32, Custom);
1112     setOperationAction(ISD::CTPOP,             MVT::v4i64, Custom);
1113
1114     if (Subtarget->hasFMA() || Subtarget->hasFMA4() || Subtarget->hasAVX512()) {
1115       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1116       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1117       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1118       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1119       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1120       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1121     }
1122
1123     if (Subtarget->hasInt256()) {
1124       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1125       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1126       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1127       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1128
1129       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1130       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1131       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1132       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1133
1134       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1135       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1136       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1137       setOperationAction(ISD::MUL,             MVT::v32i8, Custom);
1138
1139       setOperationAction(ISD::UMUL_LOHI,       MVT::v8i32, Custom);
1140       setOperationAction(ISD::SMUL_LOHI,       MVT::v8i32, Custom);
1141       setOperationAction(ISD::MULHU,           MVT::v16i16, Legal);
1142       setOperationAction(ISD::MULHS,           MVT::v16i16, Legal);
1143
1144       // The custom lowering for UINT_TO_FP for v8i32 becomes interesting
1145       // when we have a 256bit-wide blend with immediate.
1146       setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Custom);
1147
1148       // AVX2 also has wider vector sign/zero extending loads, VPMOV[SZ]X
1149       setLoadExtAction(ISD::SEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1150       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32,  MVT::v8i8,  Legal);
1151       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i8,  Legal);
1152       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32,  MVT::v8i16, Legal);
1153       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i16, Legal);
1154       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i32, Legal);
1155
1156       setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1157       setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32,  MVT::v8i8,  Legal);
1158       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i8,  Legal);
1159       setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32,  MVT::v8i16, Legal);
1160       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i16, Legal);
1161       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i32, Legal);
1162     } else {
1163       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1164       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1165       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1166       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1167
1168       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1169       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1170       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1171       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1172
1173       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1174       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1175       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1176       setOperationAction(ISD::MUL,             MVT::v32i8, Custom);
1177     }
1178
1179     // In the customized shift lowering, the legal cases in AVX2 will be
1180     // recognized.
1181     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1182     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1183
1184     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1185     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1186
1187     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1188
1189     // Custom lower several nodes for 256-bit types.
1190     for (MVT VT : MVT::vector_valuetypes()) {
1191       if (VT.getScalarSizeInBits() >= 32) {
1192         setOperationAction(ISD::MLOAD,  VT, Legal);
1193         setOperationAction(ISD::MSTORE, VT, Legal);
1194       }
1195       // Extract subvector is special because the value type
1196       // (result) is 128-bit but the source is 256-bit wide.
1197       if (VT.is128BitVector()) {
1198         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1199       }
1200       // Do not attempt to custom lower other non-256-bit vectors
1201       if (!VT.is256BitVector())
1202         continue;
1203
1204       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1205       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1206       setOperationAction(ISD::VSELECT,            VT, Custom);
1207       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1208       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1209       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1210       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1211       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1212     }
1213
1214     if (Subtarget->hasInt256())
1215       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1216
1217
1218     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1219     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1220       MVT VT = (MVT::SimpleValueType)i;
1221
1222       // Do not attempt to promote non-256-bit vectors
1223       if (!VT.is256BitVector())
1224         continue;
1225
1226       setOperationAction(ISD::AND,    VT, Promote);
1227       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1228       setOperationAction(ISD::OR,     VT, Promote);
1229       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1230       setOperationAction(ISD::XOR,    VT, Promote);
1231       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1232       setOperationAction(ISD::LOAD,   VT, Promote);
1233       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1234       setOperationAction(ISD::SELECT, VT, Promote);
1235       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1236     }
1237   }
1238
1239   if (!Subtarget->useSoftFloat() && Subtarget->hasAVX512()) {
1240     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1241     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1242     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1243     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1244
1245     addRegisterClass(MVT::i1,     &X86::VK1RegClass);
1246     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1247     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1248
1249     for (MVT VT : MVT::fp_vector_valuetypes())
1250       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8f32, Legal);
1251
1252     setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i32, MVT::v16i8, Legal);
1253     setLoadExtAction(ISD::SEXTLOAD, MVT::v16i32, MVT::v16i8, Legal);
1254     setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i32, MVT::v16i16, Legal);
1255     setLoadExtAction(ISD::SEXTLOAD, MVT::v16i32, MVT::v16i16, Legal);
1256     setLoadExtAction(ISD::ZEXTLOAD, MVT::v32i16, MVT::v32i8, Legal);
1257     setLoadExtAction(ISD::SEXTLOAD, MVT::v32i16, MVT::v32i8, Legal);
1258     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i8,  Legal);
1259     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i8,  Legal);
1260     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i16,  Legal);
1261     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i16,  Legal);
1262     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i32,  Legal);
1263     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i32,  Legal);
1264
1265     setOperationAction(ISD::BR_CC,              MVT::i1,    Expand);
1266     setOperationAction(ISD::SETCC,              MVT::i1,    Custom);
1267     setOperationAction(ISD::XOR,                MVT::i1,    Legal);
1268     setOperationAction(ISD::OR,                 MVT::i1,    Legal);
1269     setOperationAction(ISD::AND,                MVT::i1,    Legal);
1270     setOperationAction(ISD::SUB,                MVT::i1,    Custom);
1271     setOperationAction(ISD::ADD,                MVT::i1,    Custom);
1272     setOperationAction(ISD::MUL,                MVT::i1,    Custom);
1273     setOperationAction(ISD::LOAD,               MVT::v16f32, Legal);
1274     setOperationAction(ISD::LOAD,               MVT::v8f64, Legal);
1275     setOperationAction(ISD::LOAD,               MVT::v8i64, Legal);
1276     setOperationAction(ISD::LOAD,               MVT::v16i32, Legal);
1277     setOperationAction(ISD::LOAD,               MVT::v16i1, Legal);
1278
1279     setOperationAction(ISD::FADD,               MVT::v16f32, Legal);
1280     setOperationAction(ISD::FSUB,               MVT::v16f32, Legal);
1281     setOperationAction(ISD::FMUL,               MVT::v16f32, Legal);
1282     setOperationAction(ISD::FDIV,               MVT::v16f32, Legal);
1283     setOperationAction(ISD::FSQRT,              MVT::v16f32, Legal);
1284     setOperationAction(ISD::FNEG,               MVT::v16f32, Custom);
1285
1286     setOperationAction(ISD::FADD,               MVT::v8f64, Legal);
1287     setOperationAction(ISD::FSUB,               MVT::v8f64, Legal);
1288     setOperationAction(ISD::FMUL,               MVT::v8f64, Legal);
1289     setOperationAction(ISD::FDIV,               MVT::v8f64, Legal);
1290     setOperationAction(ISD::FSQRT,              MVT::v8f64, Legal);
1291     setOperationAction(ISD::FNEG,               MVT::v8f64, Custom);
1292     setOperationAction(ISD::FMA,                MVT::v8f64, Legal);
1293     setOperationAction(ISD::FMA,                MVT::v16f32, Legal);
1294
1295     setOperationAction(ISD::FP_TO_SINT,         MVT::i32, Legal);
1296     setOperationAction(ISD::FP_TO_UINT,         MVT::i32, Legal);
1297     setOperationAction(ISD::SINT_TO_FP,         MVT::i32, Legal);
1298     setOperationAction(ISD::UINT_TO_FP,         MVT::i32, Legal);
1299     if (Subtarget->is64Bit()) {
1300       setOperationAction(ISD::FP_TO_UINT,       MVT::i64, Legal);
1301       setOperationAction(ISD::FP_TO_SINT,       MVT::i64, Legal);
1302       setOperationAction(ISD::SINT_TO_FP,       MVT::i64, Legal);
1303       setOperationAction(ISD::UINT_TO_FP,       MVT::i64, Legal);
1304     }
1305     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1306     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1307     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1308     setOperationAction(ISD::FP_TO_UINT,         MVT::v4i32, Legal);
1309     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1310     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i1,   Custom);
1311     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i1,  Custom);
1312     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i8,  Promote);
1313     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i16, Promote);
1314     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1315     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1316     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Legal);
1317     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i8, Custom);
1318     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i16, Custom);
1319     setOperationAction(ISD::FP_ROUND,           MVT::v8f32, Legal);
1320     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Legal);
1321
1322     setOperationAction(ISD::TRUNCATE,           MVT::i1, Custom);
1323     setOperationAction(ISD::TRUNCATE,           MVT::v16i8, Custom);
1324     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1325     if (Subtarget->hasDQI()) {
1326       setOperationAction(ISD::TRUNCATE,           MVT::v2i1, Custom);
1327       setOperationAction(ISD::TRUNCATE,           MVT::v4i1, Custom);
1328     }
1329     setOperationAction(ISD::TRUNCATE,           MVT::v8i1, Custom);
1330     setOperationAction(ISD::TRUNCATE,           MVT::v16i1, Custom);
1331     setOperationAction(ISD::TRUNCATE,           MVT::v16i16, Custom);
1332     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1333     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1334     setOperationAction(ISD::ANY_EXTEND,         MVT::v16i32, Custom);
1335     setOperationAction(ISD::ANY_EXTEND,         MVT::v8i64, Custom);
1336     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1337     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1338     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i8, Custom);
1339     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i16, Custom);
1340     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i16, Custom);
1341     if (Subtarget->hasDQI()) {
1342       setOperationAction(ISD::SIGN_EXTEND,        MVT::v4i32, Custom);
1343       setOperationAction(ISD::SIGN_EXTEND,        MVT::v2i64, Custom);
1344     }
1345     setOperationAction(ISD::FFLOOR,             MVT::v16f32, Legal);
1346     setOperationAction(ISD::FFLOOR,             MVT::v8f64, Legal);
1347     setOperationAction(ISD::FCEIL,              MVT::v16f32, Legal);
1348     setOperationAction(ISD::FCEIL,              MVT::v8f64, Legal);
1349     setOperationAction(ISD::FTRUNC,             MVT::v16f32, Legal);
1350     setOperationAction(ISD::FTRUNC,             MVT::v8f64, Legal);
1351     setOperationAction(ISD::FRINT,              MVT::v16f32, Legal);
1352     setOperationAction(ISD::FRINT,              MVT::v8f64, Legal);
1353     setOperationAction(ISD::FNEARBYINT,         MVT::v16f32, Legal);
1354     setOperationAction(ISD::FNEARBYINT,         MVT::v8f64, Legal);
1355
1356     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1357     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1358     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1359     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1360     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i1, Legal);
1361
1362     setOperationAction(ISD::SETCC,              MVT::v16i1, Custom);
1363     setOperationAction(ISD::SETCC,              MVT::v8i1, Custom);
1364
1365     setOperationAction(ISD::MUL,              MVT::v8i64, Custom);
1366
1367     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1,  Custom);
1368     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1369     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i1, Custom);
1370     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i1, Custom);
1371     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i1, Custom);
1372     setOperationAction(ISD::BUILD_VECTOR,       MVT::v16i1, Custom);
1373     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1374     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1375     setOperationAction(ISD::SELECT,             MVT::v16f32, Custom);
1376     setOperationAction(ISD::SELECT,             MVT::v16i1, Custom);
1377     setOperationAction(ISD::SELECT,             MVT::v8i1,  Custom);
1378
1379     setOperationAction(ISD::ADD,                MVT::v8i64, Legal);
1380     setOperationAction(ISD::ADD,                MVT::v16i32, Legal);
1381
1382     setOperationAction(ISD::SUB,                MVT::v8i64, Legal);
1383     setOperationAction(ISD::SUB,                MVT::v16i32, Legal);
1384
1385     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1386
1387     setOperationAction(ISD::SRL,                MVT::v8i64, Custom);
1388     setOperationAction(ISD::SRL,                MVT::v16i32, Custom);
1389
1390     setOperationAction(ISD::SHL,                MVT::v8i64, Custom);
1391     setOperationAction(ISD::SHL,                MVT::v16i32, Custom);
1392
1393     setOperationAction(ISD::SRA,                MVT::v8i64, Custom);
1394     setOperationAction(ISD::SRA,                MVT::v16i32, Custom);
1395
1396     setOperationAction(ISD::AND,                MVT::v8i64, Legal);
1397     setOperationAction(ISD::OR,                 MVT::v8i64, Legal);
1398     setOperationAction(ISD::XOR,                MVT::v8i64, Legal);
1399     setOperationAction(ISD::AND,                MVT::v16i32, Legal);
1400     setOperationAction(ISD::OR,                 MVT::v16i32, Legal);
1401     setOperationAction(ISD::XOR,                MVT::v16i32, Legal);
1402
1403     if (Subtarget->hasCDI()) {
1404       setOperationAction(ISD::CTLZ,             MVT::v8i64, Legal);
1405       setOperationAction(ISD::CTLZ,             MVT::v16i32, Legal);
1406     }
1407     if (Subtarget->hasDQI()) {
1408       setOperationAction(ISD::MUL,             MVT::v2i64, Legal);
1409       setOperationAction(ISD::MUL,             MVT::v4i64, Legal);
1410       setOperationAction(ISD::MUL,             MVT::v8i64, Legal);
1411     }
1412     // Custom lower several nodes.
1413     for (MVT VT : MVT::vector_valuetypes()) {
1414       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1415       if (EltSize == 1) {
1416         setOperationAction(ISD::AND, VT, Legal);
1417         setOperationAction(ISD::OR,  VT, Legal);
1418         setOperationAction(ISD::XOR,  VT, Legal);
1419       }
1420       if (EltSize >= 32 && VT.getSizeInBits() <= 512) {
1421         setOperationAction(ISD::MGATHER,  VT, Custom);
1422         setOperationAction(ISD::MSCATTER, VT, Custom);
1423       }
1424       // Extract subvector is special because the value type
1425       // (result) is 256/128-bit but the source is 512-bit wide.
1426       if (VT.is128BitVector() || VT.is256BitVector()) {
1427         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1428       }
1429       if (VT.getVectorElementType() == MVT::i1)
1430         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1431
1432       // Do not attempt to custom lower other non-512-bit vectors
1433       if (!VT.is512BitVector())
1434         continue;
1435
1436       if (EltSize >= 32) {
1437         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1438         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1439         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1440         setOperationAction(ISD::VSELECT,             VT, Legal);
1441         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1442         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1443         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1444         setOperationAction(ISD::MLOAD,               VT, Legal);
1445         setOperationAction(ISD::MSTORE,              VT, Legal);
1446       }
1447     }
1448     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1449       MVT VT = (MVT::SimpleValueType)i;
1450
1451       // Do not attempt to promote non-512-bit vectors.
1452       if (!VT.is512BitVector())
1453         continue;
1454
1455       setOperationAction(ISD::SELECT, VT, Promote);
1456       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1457     }
1458   }// has  AVX-512
1459
1460   if (!Subtarget->useSoftFloat() && Subtarget->hasBWI()) {
1461     addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1462     addRegisterClass(MVT::v64i8,  &X86::VR512RegClass);
1463
1464     addRegisterClass(MVT::v32i1,  &X86::VK32RegClass);
1465     addRegisterClass(MVT::v64i1,  &X86::VK64RegClass);
1466
1467     setOperationAction(ISD::LOAD,               MVT::v32i16, Legal);
1468     setOperationAction(ISD::LOAD,               MVT::v64i8, Legal);
1469     setOperationAction(ISD::SETCC,              MVT::v32i1, Custom);
1470     setOperationAction(ISD::SETCC,              MVT::v64i1, Custom);
1471     setOperationAction(ISD::ADD,                MVT::v32i16, Legal);
1472     setOperationAction(ISD::ADD,                MVT::v64i8, Legal);
1473     setOperationAction(ISD::SUB,                MVT::v32i16, Legal);
1474     setOperationAction(ISD::SUB,                MVT::v64i8, Legal);
1475     setOperationAction(ISD::MUL,                MVT::v32i16, Legal);
1476     setOperationAction(ISD::MULHS,              MVT::v32i16, Legal);
1477     setOperationAction(ISD::MULHU,              MVT::v32i16, Legal);
1478     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v32i1, Custom);
1479     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v64i1, Custom);
1480     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v32i1, Custom);
1481     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v64i1, Custom);
1482     setOperationAction(ISD::SELECT,             MVT::v32i1, Custom);
1483     setOperationAction(ISD::SELECT,             MVT::v64i1, Custom);
1484     setOperationAction(ISD::SIGN_EXTEND,        MVT::v32i8, Custom);
1485     setOperationAction(ISD::ZERO_EXTEND,        MVT::v32i8, Custom);
1486     setOperationAction(ISD::SIGN_EXTEND,        MVT::v32i16, Custom);
1487     setOperationAction(ISD::ZERO_EXTEND,        MVT::v32i16, Custom);
1488     setOperationAction(ISD::SIGN_EXTEND,        MVT::v64i8, Custom);
1489     setOperationAction(ISD::ZERO_EXTEND,        MVT::v64i8, Custom);
1490     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v32i1, Custom);
1491     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v64i1, Custom);
1492     setOperationAction(ISD::VSELECT,            MVT::v32i16, Legal);
1493     setOperationAction(ISD::VSELECT,            MVT::v64i8, Legal);
1494     setOperationAction(ISD::TRUNCATE,           MVT::v32i1, Custom);
1495     setOperationAction(ISD::TRUNCATE,           MVT::v64i1, Custom);
1496
1497     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1498       const MVT VT = (MVT::SimpleValueType)i;
1499
1500       const unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1501
1502       // Do not attempt to promote non-512-bit vectors.
1503       if (!VT.is512BitVector())
1504         continue;
1505
1506       if (EltSize < 32) {
1507         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1508         setOperationAction(ISD::VSELECT,             VT, Legal);
1509       }
1510     }
1511   }
1512
1513   if (!Subtarget->useSoftFloat() && Subtarget->hasVLX()) {
1514     addRegisterClass(MVT::v4i1,   &X86::VK4RegClass);
1515     addRegisterClass(MVT::v2i1,   &X86::VK2RegClass);
1516
1517     setOperationAction(ISD::SETCC,              MVT::v4i1, Custom);
1518     setOperationAction(ISD::SETCC,              MVT::v2i1, Custom);
1519     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i1, Custom);
1520     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1, Custom);
1521     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v8i1, Custom);
1522     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v4i1, Custom);
1523     setOperationAction(ISD::SELECT,             MVT::v4i1, Custom);
1524     setOperationAction(ISD::SELECT,             MVT::v2i1, Custom);
1525     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4i1, Custom);
1526     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i1, Custom);
1527
1528     setOperationAction(ISD::AND,                MVT::v8i32, Legal);
1529     setOperationAction(ISD::OR,                 MVT::v8i32, Legal);
1530     setOperationAction(ISD::XOR,                MVT::v8i32, Legal);
1531     setOperationAction(ISD::AND,                MVT::v4i32, Legal);
1532     setOperationAction(ISD::OR,                 MVT::v4i32, Legal);
1533     setOperationAction(ISD::XOR,                MVT::v4i32, Legal);
1534     setOperationAction(ISD::SRA,                MVT::v2i64, Custom);
1535     setOperationAction(ISD::SRA,                MVT::v4i64, Custom);
1536   }
1537
1538   // We want to custom lower some of our intrinsics.
1539   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1540   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1541   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1542   if (!Subtarget->is64Bit())
1543     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1544
1545   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1546   // handle type legalization for these operations here.
1547   //
1548   // FIXME: We really should do custom legalization for addition and
1549   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1550   // than generic legalization for 64-bit multiplication-with-overflow, though.
1551   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1552     // Add/Sub/Mul with overflow operations are custom lowered.
1553     MVT VT = IntVTs[i];
1554     setOperationAction(ISD::SADDO, VT, Custom);
1555     setOperationAction(ISD::UADDO, VT, Custom);
1556     setOperationAction(ISD::SSUBO, VT, Custom);
1557     setOperationAction(ISD::USUBO, VT, Custom);
1558     setOperationAction(ISD::SMULO, VT, Custom);
1559     setOperationAction(ISD::UMULO, VT, Custom);
1560   }
1561
1562
1563   if (!Subtarget->is64Bit()) {
1564     // These libcalls are not available in 32-bit.
1565     setLibcallName(RTLIB::SHL_I128, nullptr);
1566     setLibcallName(RTLIB::SRL_I128, nullptr);
1567     setLibcallName(RTLIB::SRA_I128, nullptr);
1568   }
1569
1570   // Combine sin / cos into one node or libcall if possible.
1571   if (Subtarget->hasSinCos()) {
1572     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1573     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1574     if (Subtarget->isTargetDarwin()) {
1575       // For MacOSX, we don't want the normal expansion of a libcall to sincos.
1576       // We want to issue a libcall to __sincos_stret to avoid memory traffic.
1577       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1578       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1579     }
1580   }
1581
1582   if (Subtarget->isTargetWin64()) {
1583     setOperationAction(ISD::SDIV, MVT::i128, Custom);
1584     setOperationAction(ISD::UDIV, MVT::i128, Custom);
1585     setOperationAction(ISD::SREM, MVT::i128, Custom);
1586     setOperationAction(ISD::UREM, MVT::i128, Custom);
1587     setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1588     setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1589   }
1590
1591   // We have target-specific dag combine patterns for the following nodes:
1592   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1593   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1594   setTargetDAGCombine(ISD::BITCAST);
1595   setTargetDAGCombine(ISD::VSELECT);
1596   setTargetDAGCombine(ISD::SELECT);
1597   setTargetDAGCombine(ISD::SHL);
1598   setTargetDAGCombine(ISD::SRA);
1599   setTargetDAGCombine(ISD::SRL);
1600   setTargetDAGCombine(ISD::OR);
1601   setTargetDAGCombine(ISD::AND);
1602   setTargetDAGCombine(ISD::ADD);
1603   setTargetDAGCombine(ISD::FADD);
1604   setTargetDAGCombine(ISD::FSUB);
1605   setTargetDAGCombine(ISD::FMA);
1606   setTargetDAGCombine(ISD::SUB);
1607   setTargetDAGCombine(ISD::LOAD);
1608   setTargetDAGCombine(ISD::MLOAD);
1609   setTargetDAGCombine(ISD::STORE);
1610   setTargetDAGCombine(ISD::MSTORE);
1611   setTargetDAGCombine(ISD::ZERO_EXTEND);
1612   setTargetDAGCombine(ISD::ANY_EXTEND);
1613   setTargetDAGCombine(ISD::SIGN_EXTEND);
1614   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1615   setTargetDAGCombine(ISD::SINT_TO_FP);
1616   setTargetDAGCombine(ISD::UINT_TO_FP);
1617   setTargetDAGCombine(ISD::SETCC);
1618   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1619   setTargetDAGCombine(ISD::BUILD_VECTOR);
1620   setTargetDAGCombine(ISD::MUL);
1621   setTargetDAGCombine(ISD::XOR);
1622
1623   computeRegisterProperties(Subtarget->getRegisterInfo());
1624
1625   // On Darwin, -Os means optimize for size without hurting performance,
1626   // do not reduce the limit.
1627   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1628   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1629   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1630   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1631   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1632   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1633   setPrefLoopAlignment(4); // 2^4 bytes.
1634
1635   // Predictable cmov don't hurt on atom because it's in-order.
1636   PredictableSelectIsExpensive = !Subtarget->isAtom();
1637   EnableExtLdPromotion = true;
1638   setPrefFunctionAlignment(4); // 2^4 bytes.
1639
1640   verifyIntrinsicTables();
1641 }
1642
1643 // This has so far only been implemented for 64-bit MachO.
1644 bool X86TargetLowering::useLoadStackGuardNode() const {
1645   return Subtarget->isTargetMachO() && Subtarget->is64Bit();
1646 }
1647
1648 TargetLoweringBase::LegalizeTypeAction
1649 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1650   if (ExperimentalVectorWideningLegalization &&
1651       VT.getVectorNumElements() != 1 &&
1652       VT.getVectorElementType().getSimpleVT() != MVT::i1)
1653     return TypeWidenVector;
1654
1655   return TargetLoweringBase::getPreferredVectorAction(VT);
1656 }
1657
1658 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1659   if (!VT.isVector())
1660     return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1661
1662   const unsigned NumElts = VT.getVectorNumElements();
1663   const EVT EltVT = VT.getVectorElementType();
1664   if (VT.is512BitVector()) {
1665     if (Subtarget->hasAVX512())
1666       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1667           EltVT == MVT::f32 || EltVT == MVT::f64)
1668         switch(NumElts) {
1669         case  8: return MVT::v8i1;
1670         case 16: return MVT::v16i1;
1671       }
1672     if (Subtarget->hasBWI())
1673       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1674         switch(NumElts) {
1675         case 32: return MVT::v32i1;
1676         case 64: return MVT::v64i1;
1677       }
1678   }
1679
1680   if (VT.is256BitVector() || VT.is128BitVector()) {
1681     if (Subtarget->hasVLX())
1682       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1683           EltVT == MVT::f32 || EltVT == MVT::f64)
1684         switch(NumElts) {
1685         case 2: return MVT::v2i1;
1686         case 4: return MVT::v4i1;
1687         case 8: return MVT::v8i1;
1688       }
1689     if (Subtarget->hasBWI() && Subtarget->hasVLX())
1690       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1691         switch(NumElts) {
1692         case  8: return MVT::v8i1;
1693         case 16: return MVT::v16i1;
1694         case 32: return MVT::v32i1;
1695       }
1696   }
1697
1698   return VT.changeVectorElementTypeToInteger();
1699 }
1700
1701 /// Helper for getByValTypeAlignment to determine
1702 /// the desired ByVal argument alignment.
1703 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1704   if (MaxAlign == 16)
1705     return;
1706   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1707     if (VTy->getBitWidth() == 128)
1708       MaxAlign = 16;
1709   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1710     unsigned EltAlign = 0;
1711     getMaxByValAlign(ATy->getElementType(), EltAlign);
1712     if (EltAlign > MaxAlign)
1713       MaxAlign = EltAlign;
1714   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1715     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1716       unsigned EltAlign = 0;
1717       getMaxByValAlign(STy->getElementType(i), EltAlign);
1718       if (EltAlign > MaxAlign)
1719         MaxAlign = EltAlign;
1720       if (MaxAlign == 16)
1721         break;
1722     }
1723   }
1724 }
1725
1726 /// Return the desired alignment for ByVal aggregate
1727 /// function arguments in the caller parameter area. For X86, aggregates
1728 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1729 /// are at 4-byte boundaries.
1730 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1731   if (Subtarget->is64Bit()) {
1732     // Max of 8 and alignment of type.
1733     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1734     if (TyAlign > 8)
1735       return TyAlign;
1736     return 8;
1737   }
1738
1739   unsigned Align = 4;
1740   if (Subtarget->hasSSE1())
1741     getMaxByValAlign(Ty, Align);
1742   return Align;
1743 }
1744
1745 /// Returns the target specific optimal type for load
1746 /// and store operations as a result of memset, memcpy, and memmove
1747 /// lowering. If DstAlign is zero that means it's safe to destination
1748 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1749 /// means there isn't a need to check it against alignment requirement,
1750 /// probably because the source does not need to be loaded. If 'IsMemset' is
1751 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1752 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1753 /// source is constant so it does not need to be loaded.
1754 /// It returns EVT::Other if the type should be determined using generic
1755 /// target-independent logic.
1756 EVT
1757 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1758                                        unsigned DstAlign, unsigned SrcAlign,
1759                                        bool IsMemset, bool ZeroMemset,
1760                                        bool MemcpyStrSrc,
1761                                        MachineFunction &MF) const {
1762   const Function *F = MF.getFunction();
1763   if ((!IsMemset || ZeroMemset) &&
1764       !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1765     if (Size >= 16 &&
1766         (Subtarget->isUnalignedMemAccessFast() ||
1767          ((DstAlign == 0 || DstAlign >= 16) &&
1768           (SrcAlign == 0 || SrcAlign >= 16)))) {
1769       if (Size >= 32) {
1770         if (Subtarget->hasInt256())
1771           return MVT::v8i32;
1772         if (Subtarget->hasFp256())
1773           return MVT::v8f32;
1774       }
1775       if (Subtarget->hasSSE2())
1776         return MVT::v4i32;
1777       if (Subtarget->hasSSE1())
1778         return MVT::v4f32;
1779     } else if (!MemcpyStrSrc && Size >= 8 &&
1780                !Subtarget->is64Bit() &&
1781                Subtarget->hasSSE2()) {
1782       // Do not use f64 to lower memcpy if source is string constant. It's
1783       // better to use i32 to avoid the loads.
1784       return MVT::f64;
1785     }
1786   }
1787   if (Subtarget->is64Bit() && Size >= 8)
1788     return MVT::i64;
1789   return MVT::i32;
1790 }
1791
1792 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1793   if (VT == MVT::f32)
1794     return X86ScalarSSEf32;
1795   else if (VT == MVT::f64)
1796     return X86ScalarSSEf64;
1797   return true;
1798 }
1799
1800 bool
1801 X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1802                                                   unsigned,
1803                                                   unsigned,
1804                                                   bool *Fast) const {
1805   if (Fast)
1806     *Fast = Subtarget->isUnalignedMemAccessFast();
1807   return true;
1808 }
1809
1810 /// Return the entry encoding for a jump table in the
1811 /// current function.  The returned value is a member of the
1812 /// MachineJumpTableInfo::JTEntryKind enum.
1813 unsigned X86TargetLowering::getJumpTableEncoding() const {
1814   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1815   // symbol.
1816   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1817       Subtarget->isPICStyleGOT())
1818     return MachineJumpTableInfo::EK_Custom32;
1819
1820   // Otherwise, use the normal jump table encoding heuristics.
1821   return TargetLowering::getJumpTableEncoding();
1822 }
1823
1824 bool X86TargetLowering::useSoftFloat() const {
1825   return Subtarget->useSoftFloat();
1826 }
1827
1828 const MCExpr *
1829 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1830                                              const MachineBasicBlock *MBB,
1831                                              unsigned uid,MCContext &Ctx) const{
1832   assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
1833          Subtarget->isPICStyleGOT());
1834   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1835   // entries.
1836   return MCSymbolRefExpr::create(MBB->getSymbol(),
1837                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1838 }
1839
1840 /// Returns relocation base for the given PIC jumptable.
1841 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1842                                                     SelectionDAG &DAG) const {
1843   if (!Subtarget->is64Bit())
1844     // This doesn't have SDLoc associated with it, but is not really the
1845     // same as a Register.
1846     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1847   return Table;
1848 }
1849
1850 /// This returns the relocation base for the given PIC jumptable,
1851 /// the same as getPICJumpTableRelocBase, but as an MCExpr.
1852 const MCExpr *X86TargetLowering::
1853 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1854                              MCContext &Ctx) const {
1855   // X86-64 uses RIP relative addressing based on the jump table label.
1856   if (Subtarget->isPICStyleRIPRel())
1857     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1858
1859   // Otherwise, the reference is relative to the PIC base.
1860   return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
1861 }
1862
1863 std::pair<const TargetRegisterClass *, uint8_t>
1864 X86TargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1865                                            MVT VT) const {
1866   const TargetRegisterClass *RRC = nullptr;
1867   uint8_t Cost = 1;
1868   switch (VT.SimpleTy) {
1869   default:
1870     return TargetLowering::findRepresentativeClass(TRI, VT);
1871   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1872     RRC = Subtarget->is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
1873     break;
1874   case MVT::x86mmx:
1875     RRC = &X86::VR64RegClass;
1876     break;
1877   case MVT::f32: case MVT::f64:
1878   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1879   case MVT::v4f32: case MVT::v2f64:
1880   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1881   case MVT::v4f64:
1882     RRC = &X86::VR128RegClass;
1883     break;
1884   }
1885   return std::make_pair(RRC, Cost);
1886 }
1887
1888 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1889                                                unsigned &Offset) const {
1890   if (!Subtarget->isTargetLinux())
1891     return false;
1892
1893   if (Subtarget->is64Bit()) {
1894     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1895     Offset = 0x28;
1896     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1897       AddressSpace = 256;
1898     else
1899       AddressSpace = 257;
1900   } else {
1901     // %gs:0x14 on i386
1902     Offset = 0x14;
1903     AddressSpace = 256;
1904   }
1905   return true;
1906 }
1907
1908 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1909                                             unsigned DestAS) const {
1910   assert(SrcAS != DestAS && "Expected different address spaces!");
1911
1912   return SrcAS < 256 && DestAS < 256;
1913 }
1914
1915 //===----------------------------------------------------------------------===//
1916 //               Return Value Calling Convention Implementation
1917 //===----------------------------------------------------------------------===//
1918
1919 #include "X86GenCallingConv.inc"
1920
1921 bool
1922 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1923                                   MachineFunction &MF, bool isVarArg,
1924                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1925                         LLVMContext &Context) const {
1926   SmallVector<CCValAssign, 16> RVLocs;
1927   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
1928   return CCInfo.CheckReturn(Outs, RetCC_X86);
1929 }
1930
1931 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1932   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1933   return ScratchRegs;
1934 }
1935
1936 SDValue
1937 X86TargetLowering::LowerReturn(SDValue Chain,
1938                                CallingConv::ID CallConv, bool isVarArg,
1939                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1940                                const SmallVectorImpl<SDValue> &OutVals,
1941                                SDLoc dl, SelectionDAG &DAG) const {
1942   MachineFunction &MF = DAG.getMachineFunction();
1943   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1944
1945   SmallVector<CCValAssign, 16> RVLocs;
1946   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
1947   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1948
1949   SDValue Flag;
1950   SmallVector<SDValue, 6> RetOps;
1951   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1952   // Operand #1 = Bytes To Pop
1953   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(), dl,
1954                    MVT::i16));
1955
1956   // Copy the result values into the output registers.
1957   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1958     CCValAssign &VA = RVLocs[i];
1959     assert(VA.isRegLoc() && "Can only return in registers!");
1960     SDValue ValToCopy = OutVals[i];
1961     EVT ValVT = ValToCopy.getValueType();
1962
1963     // Promote values to the appropriate types.
1964     if (VA.getLocInfo() == CCValAssign::SExt)
1965       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1966     else if (VA.getLocInfo() == CCValAssign::ZExt)
1967       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1968     else if (VA.getLocInfo() == CCValAssign::AExt) {
1969       if (ValVT.isVector() && ValVT.getScalarType() == MVT::i1)
1970         ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1971       else
1972         ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1973     }
1974     else if (VA.getLocInfo() == CCValAssign::BCvt)
1975       ValToCopy = DAG.getBitcast(VA.getLocVT(), ValToCopy);
1976
1977     assert(VA.getLocInfo() != CCValAssign::FPExt &&
1978            "Unexpected FP-extend for return value.");
1979
1980     // If this is x86-64, and we disabled SSE, we can't return FP values,
1981     // or SSE or MMX vectors.
1982     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1983          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1984           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1985       report_fatal_error("SSE register return with SSE disabled");
1986     }
1987     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1988     // llvm-gcc has never done it right and no one has noticed, so this
1989     // should be OK for now.
1990     if (ValVT == MVT::f64 &&
1991         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1992       report_fatal_error("SSE2 register return with SSE2 disabled");
1993
1994     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1995     // the RET instruction and handled by the FP Stackifier.
1996     if (VA.getLocReg() == X86::FP0 ||
1997         VA.getLocReg() == X86::FP1) {
1998       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1999       // change the value to the FP stack register class.
2000       if (isScalarFPTypeInSSEReg(VA.getValVT()))
2001         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
2002       RetOps.push_back(ValToCopy);
2003       // Don't emit a copytoreg.
2004       continue;
2005     }
2006
2007     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
2008     // which is returned in RAX / RDX.
2009     if (Subtarget->is64Bit()) {
2010       if (ValVT == MVT::x86mmx) {
2011         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
2012           ValToCopy = DAG.getBitcast(MVT::i64, ValToCopy);
2013           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
2014                                   ValToCopy);
2015           // If we don't have SSE2 available, convert to v4f32 so the generated
2016           // register is legal.
2017           if (!Subtarget->hasSSE2())
2018             ValToCopy = DAG.getBitcast(MVT::v4f32, ValToCopy);
2019         }
2020       }
2021     }
2022
2023     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
2024     Flag = Chain.getValue(1);
2025     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2026   }
2027
2028   // All x86 ABIs require that for returning structs by value we copy
2029   // the sret argument into %rax/%eax (depending on ABI) for the return.
2030   // We saved the argument into a virtual register in the entry block,
2031   // so now we copy the value out and into %rax/%eax.
2032   //
2033   // Checking Function.hasStructRetAttr() here is insufficient because the IR
2034   // may not have an explicit sret argument. If FuncInfo.CanLowerReturn is
2035   // false, then an sret argument may be implicitly inserted in the SelDAG. In
2036   // either case FuncInfo->setSRetReturnReg() will have been called.
2037   if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
2038     SDValue Val = DAG.getCopyFromReg(Chain, dl, SRetReg, getPointerTy());
2039
2040     unsigned RetValReg
2041         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
2042           X86::RAX : X86::EAX;
2043     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2044     Flag = Chain.getValue(1);
2045
2046     // RAX/EAX now acts like a return value.
2047     RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
2048   }
2049
2050   RetOps[0] = Chain;  // Update chain.
2051
2052   // Add the flag if we have it.
2053   if (Flag.getNode())
2054     RetOps.push_back(Flag);
2055
2056   return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
2057 }
2058
2059 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2060   if (N->getNumValues() != 1)
2061     return false;
2062   if (!N->hasNUsesOfValue(1, 0))
2063     return false;
2064
2065   SDValue TCChain = Chain;
2066   SDNode *Copy = *N->use_begin();
2067   if (Copy->getOpcode() == ISD::CopyToReg) {
2068     // If the copy has a glue operand, we conservatively assume it isn't safe to
2069     // perform a tail call.
2070     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2071       return false;
2072     TCChain = Copy->getOperand(0);
2073   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2074     return false;
2075
2076   bool HasRet = false;
2077   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2078        UI != UE; ++UI) {
2079     if (UI->getOpcode() != X86ISD::RET_FLAG)
2080       return false;
2081     // If we are returning more than one value, we can definitely
2082     // not make a tail call see PR19530
2083     if (UI->getNumOperands() > 4)
2084       return false;
2085     if (UI->getNumOperands() == 4 &&
2086         UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2087       return false;
2088     HasRet = true;
2089   }
2090
2091   if (!HasRet)
2092     return false;
2093
2094   Chain = TCChain;
2095   return true;
2096 }
2097
2098 EVT
2099 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
2100                                             ISD::NodeType ExtendKind) const {
2101   MVT ReturnMVT;
2102   // TODO: Is this also valid on 32-bit?
2103   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2104     ReturnMVT = MVT::i8;
2105   else
2106     ReturnMVT = MVT::i32;
2107
2108   EVT MinVT = getRegisterType(Context, ReturnMVT);
2109   return VT.bitsLT(MinVT) ? MinVT : VT;
2110 }
2111
2112 /// Lower the result values of a call into the
2113 /// appropriate copies out of appropriate physical registers.
2114 ///
2115 SDValue
2116 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2117                                    CallingConv::ID CallConv, bool isVarArg,
2118                                    const SmallVectorImpl<ISD::InputArg> &Ins,
2119                                    SDLoc dl, SelectionDAG &DAG,
2120                                    SmallVectorImpl<SDValue> &InVals) const {
2121
2122   // Assign locations to each value returned by this call.
2123   SmallVector<CCValAssign, 16> RVLocs;
2124   bool Is64Bit = Subtarget->is64Bit();
2125   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2126                  *DAG.getContext());
2127   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2128
2129   // Copy all of the result registers out of their specified physreg.
2130   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2131     CCValAssign &VA = RVLocs[i];
2132     EVT CopyVT = VA.getLocVT();
2133
2134     // If this is x86-64, and we disabled SSE, we can't return FP values
2135     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2136         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2137       report_fatal_error("SSE register return with SSE disabled");
2138     }
2139
2140     // If we prefer to use the value in xmm registers, copy it out as f80 and
2141     // use a truncate to move it from fp stack reg to xmm reg.
2142     bool RoundAfterCopy = false;
2143     if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2144         isScalarFPTypeInSSEReg(VA.getValVT())) {
2145       CopyVT = MVT::f80;
2146       RoundAfterCopy = (CopyVT != VA.getLocVT());
2147     }
2148
2149     Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2150                                CopyVT, InFlag).getValue(1);
2151     SDValue Val = Chain.getValue(0);
2152
2153     if (RoundAfterCopy)
2154       Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2155                         // This truncation won't change the value.
2156                         DAG.getIntPtrConstant(1, dl));
2157
2158     if (VA.isExtInLoc() && VA.getValVT().getScalarType() == MVT::i1)
2159       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
2160
2161     InFlag = Chain.getValue(2);
2162     InVals.push_back(Val);
2163   }
2164
2165   return Chain;
2166 }
2167
2168 //===----------------------------------------------------------------------===//
2169 //                C & StdCall & Fast Calling Convention implementation
2170 //===----------------------------------------------------------------------===//
2171 //  StdCall calling convention seems to be standard for many Windows' API
2172 //  routines and around. It differs from C calling convention just a little:
2173 //  callee should clean up the stack, not caller. Symbols should be also
2174 //  decorated in some fancy way :) It doesn't support any vector arguments.
2175 //  For info on fast calling convention see Fast Calling Convention (tail call)
2176 //  implementation LowerX86_32FastCCCallTo.
2177
2178 /// CallIsStructReturn - Determines whether a call uses struct return
2179 /// semantics.
2180 enum StructReturnType {
2181   NotStructReturn,
2182   RegStructReturn,
2183   StackStructReturn
2184 };
2185 static StructReturnType
2186 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2187   if (Outs.empty())
2188     return NotStructReturn;
2189
2190   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2191   if (!Flags.isSRet())
2192     return NotStructReturn;
2193   if (Flags.isInReg())
2194     return RegStructReturn;
2195   return StackStructReturn;
2196 }
2197
2198 /// Determines whether a function uses struct return semantics.
2199 static StructReturnType
2200 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2201   if (Ins.empty())
2202     return NotStructReturn;
2203
2204   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2205   if (!Flags.isSRet())
2206     return NotStructReturn;
2207   if (Flags.isInReg())
2208     return RegStructReturn;
2209   return StackStructReturn;
2210 }
2211
2212 /// Make a copy of an aggregate at address specified by "Src" to address
2213 /// "Dst" with size and alignment information specified by the specific
2214 /// parameter attribute. The copy will be passed as a byval function parameter.
2215 static SDValue
2216 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2217                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2218                           SDLoc dl) {
2219   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
2220
2221   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2222                        /*isVolatile*/false, /*AlwaysInline=*/true,
2223                        /*isTailCall*/false,
2224                        MachinePointerInfo(), MachinePointerInfo());
2225 }
2226
2227 /// Return true if the calling convention is one that
2228 /// supports tail call optimization.
2229 static bool IsTailCallConvention(CallingConv::ID CC) {
2230   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2231           CC == CallingConv::HiPE);
2232 }
2233
2234 /// \brief Return true if the calling convention is a C calling convention.
2235 static bool IsCCallConvention(CallingConv::ID CC) {
2236   return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2237           CC == CallingConv::X86_64_SysV);
2238 }
2239
2240 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2241   auto Attr =
2242       CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2243   if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2244     return false;
2245
2246   CallSite CS(CI);
2247   CallingConv::ID CalleeCC = CS.getCallingConv();
2248   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2249     return false;
2250
2251   return true;
2252 }
2253
2254 /// Return true if the function is being made into
2255 /// a tailcall target by changing its ABI.
2256 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2257                                    bool GuaranteedTailCallOpt) {
2258   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2259 }
2260
2261 SDValue
2262 X86TargetLowering::LowerMemArgument(SDValue Chain,
2263                                     CallingConv::ID CallConv,
2264                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2265                                     SDLoc dl, SelectionDAG &DAG,
2266                                     const CCValAssign &VA,
2267                                     MachineFrameInfo *MFI,
2268                                     unsigned i) const {
2269   // Create the nodes corresponding to a load from this parameter slot.
2270   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2271   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2272       CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2273   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2274   EVT ValVT;
2275
2276   // If value is passed by pointer we have address passed instead of the value
2277   // itself.
2278   bool ExtendedInMem = VA.isExtInLoc() &&
2279     VA.getValVT().getScalarType() == MVT::i1;
2280
2281   if (VA.getLocInfo() == CCValAssign::Indirect || ExtendedInMem)
2282     ValVT = VA.getLocVT();
2283   else
2284     ValVT = VA.getValVT();
2285
2286   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2287   // changed with more analysis.
2288   // In case of tail call optimization mark all arguments mutable. Since they
2289   // could be overwritten by lowering of arguments in case of a tail call.
2290   if (Flags.isByVal()) {
2291     unsigned Bytes = Flags.getByValSize();
2292     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2293     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2294     return DAG.getFrameIndex(FI, getPointerTy());
2295   } else {
2296     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2297                                     VA.getLocMemOffset(), isImmutable);
2298     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2299     SDValue Val =  DAG.getLoad(ValVT, dl, Chain, FIN,
2300                                MachinePointerInfo::getFixedStack(FI),
2301                                false, false, false, 0);
2302     return ExtendedInMem ?
2303       DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val) : Val;
2304   }
2305 }
2306
2307 // FIXME: Get this from tablegen.
2308 static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
2309                                                 const X86Subtarget *Subtarget) {
2310   assert(Subtarget->is64Bit());
2311
2312   if (Subtarget->isCallingConvWin64(CallConv)) {
2313     static const MCPhysReg GPR64ArgRegsWin64[] = {
2314       X86::RCX, X86::RDX, X86::R8,  X86::R9
2315     };
2316     return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
2317   }
2318
2319   static const MCPhysReg GPR64ArgRegs64Bit[] = {
2320     X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2321   };
2322   return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
2323 }
2324
2325 // FIXME: Get this from tablegen.
2326 static ArrayRef<MCPhysReg> get64BitArgumentXMMs(MachineFunction &MF,
2327                                                 CallingConv::ID CallConv,
2328                                                 const X86Subtarget *Subtarget) {
2329   assert(Subtarget->is64Bit());
2330   if (Subtarget->isCallingConvWin64(CallConv)) {
2331     // The XMM registers which might contain var arg parameters are shadowed
2332     // in their paired GPR.  So we only need to save the GPR to their home
2333     // slots.
2334     // TODO: __vectorcall will change this.
2335     return None;
2336   }
2337
2338   const Function *Fn = MF.getFunction();
2339   bool NoImplicitFloatOps = Fn->hasFnAttribute(Attribute::NoImplicitFloat);
2340   bool isSoftFloat = Subtarget->useSoftFloat();
2341   assert(!(isSoftFloat && NoImplicitFloatOps) &&
2342          "SSE register cannot be used when SSE is disabled!");
2343   if (isSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
2344     // Kernel mode asks for SSE to be disabled, so there are no XMM argument
2345     // registers.
2346     return None;
2347
2348   static const MCPhysReg XMMArgRegs64Bit[] = {
2349     X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2350     X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2351   };
2352   return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
2353 }
2354
2355 SDValue
2356 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2357                                         CallingConv::ID CallConv,
2358                                         bool isVarArg,
2359                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2360                                         SDLoc dl,
2361                                         SelectionDAG &DAG,
2362                                         SmallVectorImpl<SDValue> &InVals)
2363                                           const {
2364   MachineFunction &MF = DAG.getMachineFunction();
2365   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2366   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
2367
2368   const Function* Fn = MF.getFunction();
2369   if (Fn->hasExternalLinkage() &&
2370       Subtarget->isTargetCygMing() &&
2371       Fn->getName() == "main")
2372     FuncInfo->setForceFramePointer(true);
2373
2374   MachineFrameInfo *MFI = MF.getFrameInfo();
2375   bool Is64Bit = Subtarget->is64Bit();
2376   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2377
2378   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2379          "Var args not supported with calling convention fastcc, ghc or hipe");
2380
2381   // Assign locations to all of the incoming arguments.
2382   SmallVector<CCValAssign, 16> ArgLocs;
2383   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2384
2385   // Allocate shadow area for Win64
2386   if (IsWin64)
2387     CCInfo.AllocateStack(32, 8);
2388
2389   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2390
2391   unsigned LastVal = ~0U;
2392   SDValue ArgValue;
2393   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2394     CCValAssign &VA = ArgLocs[i];
2395     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2396     // places.
2397     assert(VA.getValNo() != LastVal &&
2398            "Don't support value assigned to multiple locs yet");
2399     (void)LastVal;
2400     LastVal = VA.getValNo();
2401
2402     if (VA.isRegLoc()) {
2403       EVT RegVT = VA.getLocVT();
2404       const TargetRegisterClass *RC;
2405       if (RegVT == MVT::i32)
2406         RC = &X86::GR32RegClass;
2407       else if (Is64Bit && RegVT == MVT::i64)
2408         RC = &X86::GR64RegClass;
2409       else if (RegVT == MVT::f32)
2410         RC = &X86::FR32RegClass;
2411       else if (RegVT == MVT::f64)
2412         RC = &X86::FR64RegClass;
2413       else if (RegVT.is512BitVector())
2414         RC = &X86::VR512RegClass;
2415       else if (RegVT.is256BitVector())
2416         RC = &X86::VR256RegClass;
2417       else if (RegVT.is128BitVector())
2418         RC = &X86::VR128RegClass;
2419       else if (RegVT == MVT::x86mmx)
2420         RC = &X86::VR64RegClass;
2421       else if (RegVT == MVT::i1)
2422         RC = &X86::VK1RegClass;
2423       else if (RegVT == MVT::v8i1)
2424         RC = &X86::VK8RegClass;
2425       else if (RegVT == MVT::v16i1)
2426         RC = &X86::VK16RegClass;
2427       else if (RegVT == MVT::v32i1)
2428         RC = &X86::VK32RegClass;
2429       else if (RegVT == MVT::v64i1)
2430         RC = &X86::VK64RegClass;
2431       else
2432         llvm_unreachable("Unknown argument type!");
2433
2434       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2435       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2436
2437       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2438       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2439       // right size.
2440       if (VA.getLocInfo() == CCValAssign::SExt)
2441         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2442                                DAG.getValueType(VA.getValVT()));
2443       else if (VA.getLocInfo() == CCValAssign::ZExt)
2444         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2445                                DAG.getValueType(VA.getValVT()));
2446       else if (VA.getLocInfo() == CCValAssign::BCvt)
2447         ArgValue = DAG.getBitcast(VA.getValVT(), ArgValue);
2448
2449       if (VA.isExtInLoc()) {
2450         // Handle MMX values passed in XMM regs.
2451         if (RegVT.isVector() && VA.getValVT().getScalarType() != MVT::i1)
2452           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2453         else
2454           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2455       }
2456     } else {
2457       assert(VA.isMemLoc());
2458       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2459     }
2460
2461     // If value is passed via pointer - do a load.
2462     if (VA.getLocInfo() == CCValAssign::Indirect)
2463       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2464                              MachinePointerInfo(), false, false, false, 0);
2465
2466     InVals.push_back(ArgValue);
2467   }
2468
2469   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2470     // All x86 ABIs require that for returning structs by value we copy the
2471     // sret argument into %rax/%eax (depending on ABI) for the return. Save
2472     // the argument into a virtual register so that we can access it from the
2473     // return points.
2474     if (Ins[i].Flags.isSRet()) {
2475       unsigned Reg = FuncInfo->getSRetReturnReg();
2476       if (!Reg) {
2477         MVT PtrTy = getPointerTy();
2478         Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2479         FuncInfo->setSRetReturnReg(Reg);
2480       }
2481       SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2482       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2483       break;
2484     }
2485   }
2486
2487   unsigned StackSize = CCInfo.getNextStackOffset();
2488   // Align stack specially for tail calls.
2489   if (FuncIsMadeTailCallSafe(CallConv,
2490                              MF.getTarget().Options.GuaranteedTailCallOpt))
2491     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2492
2493   // If the function takes variable number of arguments, make a frame index for
2494   // the start of the first vararg value... for expansion of llvm.va_start. We
2495   // can skip this if there are no va_start calls.
2496   if (MFI->hasVAStart() &&
2497       (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2498                    CallConv != CallingConv::X86_ThisCall))) {
2499     FuncInfo->setVarArgsFrameIndex(
2500         MFI->CreateFixedObject(1, StackSize, true));
2501   }
2502
2503   MachineModuleInfo &MMI = MF.getMMI();
2504   const Function *WinEHParent = nullptr;
2505   if (IsWin64 && MMI.hasWinEHFuncInfo(Fn))
2506     WinEHParent = MMI.getWinEHParent(Fn);
2507   bool IsWinEHOutlined = WinEHParent && WinEHParent != Fn;
2508   bool IsWinEHParent = WinEHParent && WinEHParent == Fn;
2509
2510   // Figure out if XMM registers are in use.
2511   assert(!(Subtarget->useSoftFloat() &&
2512            Fn->hasFnAttribute(Attribute::NoImplicitFloat)) &&
2513          "SSE register cannot be used when SSE is disabled!");
2514
2515   // 64-bit calling conventions support varargs and register parameters, so we
2516   // have to do extra work to spill them in the prologue.
2517   if (Is64Bit && isVarArg && MFI->hasVAStart()) {
2518     // Find the first unallocated argument registers.
2519     ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
2520     ArrayRef<MCPhysReg> ArgXMMs = get64BitArgumentXMMs(MF, CallConv, Subtarget);
2521     unsigned NumIntRegs = CCInfo.getFirstUnallocated(ArgGPRs);
2522     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(ArgXMMs);
2523     assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2524            "SSE register cannot be used when SSE is disabled!");
2525
2526     // Gather all the live in physical registers.
2527     SmallVector<SDValue, 6> LiveGPRs;
2528     SmallVector<SDValue, 8> LiveXMMRegs;
2529     SDValue ALVal;
2530     for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
2531       unsigned GPR = MF.addLiveIn(Reg, &X86::GR64RegClass);
2532       LiveGPRs.push_back(
2533           DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64));
2534     }
2535     if (!ArgXMMs.empty()) {
2536       unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2537       ALVal = DAG.getCopyFromReg(Chain, dl, AL, MVT::i8);
2538       for (MCPhysReg Reg : ArgXMMs.slice(NumXMMRegs)) {
2539         unsigned XMMReg = MF.addLiveIn(Reg, &X86::VR128RegClass);
2540         LiveXMMRegs.push_back(
2541             DAG.getCopyFromReg(Chain, dl, XMMReg, MVT::v4f32));
2542       }
2543     }
2544
2545     if (IsWin64) {
2546       // Get to the caller-allocated home save location.  Add 8 to account
2547       // for the return address.
2548       int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2549       FuncInfo->setRegSaveFrameIndex(
2550           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2551       // Fixup to set vararg frame on shadow area (4 x i64).
2552       if (NumIntRegs < 4)
2553         FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2554     } else {
2555       // For X86-64, if there are vararg parameters that are passed via
2556       // registers, then we must store them to their spots on the stack so
2557       // they may be loaded by deferencing the result of va_next.
2558       FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2559       FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
2560       FuncInfo->setRegSaveFrameIndex(MFI->CreateStackObject(
2561           ArgGPRs.size() * 8 + ArgXMMs.size() * 16, 16, false));
2562     }
2563
2564     // Store the integer parameter registers.
2565     SmallVector<SDValue, 8> MemOps;
2566     SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2567                                       getPointerTy());
2568     unsigned Offset = FuncInfo->getVarArgsGPOffset();
2569     for (SDValue Val : LiveGPRs) {
2570       SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2571                                 DAG.getIntPtrConstant(Offset, dl));
2572       SDValue Store =
2573         DAG.getStore(Val.getValue(1), dl, Val, FIN,
2574                      MachinePointerInfo::getFixedStack(
2575                        FuncInfo->getRegSaveFrameIndex(), Offset),
2576                      false, false, 0);
2577       MemOps.push_back(Store);
2578       Offset += 8;
2579     }
2580
2581     if (!ArgXMMs.empty() && NumXMMRegs != ArgXMMs.size()) {
2582       // Now store the XMM (fp + vector) parameter registers.
2583       SmallVector<SDValue, 12> SaveXMMOps;
2584       SaveXMMOps.push_back(Chain);
2585       SaveXMMOps.push_back(ALVal);
2586       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2587                              FuncInfo->getRegSaveFrameIndex(), dl));
2588       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2589                              FuncInfo->getVarArgsFPOffset(), dl));
2590       SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
2591                         LiveXMMRegs.end());
2592       MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2593                                    MVT::Other, SaveXMMOps));
2594     }
2595
2596     if (!MemOps.empty())
2597       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2598   } else if (IsWinEHOutlined) {
2599     // Get to the caller-allocated home save location.  Add 8 to account
2600     // for the return address.
2601     int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2602     FuncInfo->setRegSaveFrameIndex(MFI->CreateFixedObject(
2603         /*Size=*/1, /*SPOffset=*/HomeOffset + 8, /*Immutable=*/false));
2604
2605     MMI.getWinEHFuncInfo(Fn)
2606         .CatchHandlerParentFrameObjIdx[const_cast<Function *>(Fn)] =
2607         FuncInfo->getRegSaveFrameIndex();
2608
2609     // Store the second integer parameter (rdx) into rsp+16 relative to the
2610     // stack pointer at the entry of the function.
2611     SDValue RSFIN =
2612         DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), getPointerTy());
2613     unsigned GPR = MF.addLiveIn(X86::RDX, &X86::GR64RegClass);
2614     SDValue Val = DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64);
2615     Chain = DAG.getStore(
2616         Val.getValue(1), dl, Val, RSFIN,
2617         MachinePointerInfo::getFixedStack(FuncInfo->getRegSaveFrameIndex()),
2618         /*isVolatile=*/true, /*isNonTemporal=*/false, /*Alignment=*/0);
2619   }
2620
2621   if (isVarArg && MFI->hasMustTailInVarArgFunc()) {
2622     // Find the largest legal vector type.
2623     MVT VecVT = MVT::Other;
2624     // FIXME: Only some x86_32 calling conventions support AVX512.
2625     if (Subtarget->hasAVX512() &&
2626         (Is64Bit || (CallConv == CallingConv::X86_VectorCall ||
2627                      CallConv == CallingConv::Intel_OCL_BI)))
2628       VecVT = MVT::v16f32;
2629     else if (Subtarget->hasAVX())
2630       VecVT = MVT::v8f32;
2631     else if (Subtarget->hasSSE2())
2632       VecVT = MVT::v4f32;
2633
2634     // We forward some GPRs and some vector types.
2635     SmallVector<MVT, 2> RegParmTypes;
2636     MVT IntVT = Is64Bit ? MVT::i64 : MVT::i32;
2637     RegParmTypes.push_back(IntVT);
2638     if (VecVT != MVT::Other)
2639       RegParmTypes.push_back(VecVT);
2640
2641     // Compute the set of forwarded registers. The rest are scratch.
2642     SmallVectorImpl<ForwardedRegister> &Forwards =
2643         FuncInfo->getForwardedMustTailRegParms();
2644     CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, CC_X86);
2645
2646     // Conservatively forward AL on x86_64, since it might be used for varargs.
2647     if (Is64Bit && !CCInfo.isAllocated(X86::AL)) {
2648       unsigned ALVReg = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2649       Forwards.push_back(ForwardedRegister(ALVReg, X86::AL, MVT::i8));
2650     }
2651
2652     // Copy all forwards from physical to virtual registers.
2653     for (ForwardedRegister &F : Forwards) {
2654       // FIXME: Can we use a less constrained schedule?
2655       SDValue RegVal = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2656       F.VReg = MF.getRegInfo().createVirtualRegister(getRegClassFor(F.VT));
2657       Chain = DAG.getCopyToReg(Chain, dl, F.VReg, RegVal);
2658     }
2659   }
2660
2661   // Some CCs need callee pop.
2662   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2663                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2664     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2665   } else {
2666     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2667     // If this is an sret function, the return should pop the hidden pointer.
2668     if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2669         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2670         argsAreStructReturn(Ins) == StackStructReturn)
2671       FuncInfo->setBytesToPopOnReturn(4);
2672   }
2673
2674   if (!Is64Bit) {
2675     // RegSaveFrameIndex is X86-64 only.
2676     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2677     if (CallConv == CallingConv::X86_FastCall ||
2678         CallConv == CallingConv::X86_ThisCall)
2679       // fastcc functions can't have varargs.
2680       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2681   }
2682
2683   FuncInfo->setArgumentStackSize(StackSize);
2684
2685   if (IsWinEHParent) {
2686     int UnwindHelpFI = MFI->CreateStackObject(8, 8, /*isSS=*/false);
2687     SDValue StackSlot = DAG.getFrameIndex(UnwindHelpFI, MVT::i64);
2688     MMI.getWinEHFuncInfo(MF.getFunction()).UnwindHelpFrameIdx = UnwindHelpFI;
2689     SDValue Neg2 = DAG.getConstant(-2, dl, MVT::i64);
2690     Chain = DAG.getStore(Chain, dl, Neg2, StackSlot,
2691                          MachinePointerInfo::getFixedStack(UnwindHelpFI),
2692                          /*isVolatile=*/true,
2693                          /*isNonTemporal=*/false, /*Alignment=*/0);
2694   }
2695
2696   return Chain;
2697 }
2698
2699 SDValue
2700 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2701                                     SDValue StackPtr, SDValue Arg,
2702                                     SDLoc dl, SelectionDAG &DAG,
2703                                     const CCValAssign &VA,
2704                                     ISD::ArgFlagsTy Flags) const {
2705   unsigned LocMemOffset = VA.getLocMemOffset();
2706   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
2707   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2708   if (Flags.isByVal())
2709     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2710
2711   return DAG.getStore(Chain, dl, Arg, PtrOff,
2712                       MachinePointerInfo::getStack(LocMemOffset),
2713                       false, false, 0);
2714 }
2715
2716 /// Emit a load of return address if tail call
2717 /// optimization is performed and it is required.
2718 SDValue
2719 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2720                                            SDValue &OutRetAddr, SDValue Chain,
2721                                            bool IsTailCall, bool Is64Bit,
2722                                            int FPDiff, SDLoc dl) const {
2723   // Adjust the Return address stack slot.
2724   EVT VT = getPointerTy();
2725   OutRetAddr = getReturnAddressFrameIndex(DAG);
2726
2727   // Load the "old" Return address.
2728   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2729                            false, false, false, 0);
2730   return SDValue(OutRetAddr.getNode(), 1);
2731 }
2732
2733 /// Emit a store of the return address if tail call
2734 /// optimization is performed and it is required (FPDiff!=0).
2735 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2736                                         SDValue Chain, SDValue RetAddrFrIdx,
2737                                         EVT PtrVT, unsigned SlotSize,
2738                                         int FPDiff, SDLoc dl) {
2739   // Store the return address to the appropriate stack slot.
2740   if (!FPDiff) return Chain;
2741   // Calculate the new stack slot for the return address.
2742   int NewReturnAddrFI =
2743     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2744                                          false);
2745   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2746   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2747                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2748                        false, false, 0);
2749   return Chain;
2750 }
2751
2752 SDValue
2753 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2754                              SmallVectorImpl<SDValue> &InVals) const {
2755   SelectionDAG &DAG                     = CLI.DAG;
2756   SDLoc &dl                             = CLI.DL;
2757   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2758   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2759   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2760   SDValue Chain                         = CLI.Chain;
2761   SDValue Callee                        = CLI.Callee;
2762   CallingConv::ID CallConv              = CLI.CallConv;
2763   bool &isTailCall                      = CLI.IsTailCall;
2764   bool isVarArg                         = CLI.IsVarArg;
2765
2766   MachineFunction &MF = DAG.getMachineFunction();
2767   bool Is64Bit        = Subtarget->is64Bit();
2768   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2769   StructReturnType SR = callIsStructReturn(Outs);
2770   bool IsSibcall      = false;
2771   X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2772   auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls");
2773
2774   if (Attr.getValueAsString() == "true")
2775     isTailCall = false;
2776
2777   if (Subtarget->isPICStyleGOT() &&
2778       !MF.getTarget().Options.GuaranteedTailCallOpt) {
2779     // If we are using a GOT, disable tail calls to external symbols with
2780     // default visibility. Tail calling such a symbol requires using a GOT
2781     // relocation, which forces early binding of the symbol. This breaks code
2782     // that require lazy function symbol resolution. Using musttail or
2783     // GuaranteedTailCallOpt will override this.
2784     GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2785     if (!G || (!G->getGlobal()->hasLocalLinkage() &&
2786                G->getGlobal()->hasDefaultVisibility()))
2787       isTailCall = false;
2788   }
2789
2790   bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2791   if (IsMustTail) {
2792     // Force this to be a tail call.  The verifier rules are enough to ensure
2793     // that we can lower this successfully without moving the return address
2794     // around.
2795     isTailCall = true;
2796   } else if (isTailCall) {
2797     // Check if it's really possible to do a tail call.
2798     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2799                     isVarArg, SR != NotStructReturn,
2800                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2801                     Outs, OutVals, Ins, DAG);
2802
2803     // Sibcalls are automatically detected tailcalls which do not require
2804     // ABI changes.
2805     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2806       IsSibcall = true;
2807
2808     if (isTailCall)
2809       ++NumTailCalls;
2810   }
2811
2812   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2813          "Var args not supported with calling convention fastcc, ghc or hipe");
2814
2815   // Analyze operands of the call, assigning locations to each operand.
2816   SmallVector<CCValAssign, 16> ArgLocs;
2817   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2818
2819   // Allocate shadow area for Win64
2820   if (IsWin64)
2821     CCInfo.AllocateStack(32, 8);
2822
2823   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2824
2825   // Get a count of how many bytes are to be pushed on the stack.
2826   unsigned NumBytes = CCInfo.getNextStackOffset();
2827   if (IsSibcall)
2828     // This is a sibcall. The memory operands are available in caller's
2829     // own caller's stack.
2830     NumBytes = 0;
2831   else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
2832            IsTailCallConvention(CallConv))
2833     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2834
2835   int FPDiff = 0;
2836   if (isTailCall && !IsSibcall && !IsMustTail) {
2837     // Lower arguments at fp - stackoffset + fpdiff.
2838     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2839
2840     FPDiff = NumBytesCallerPushed - NumBytes;
2841
2842     // Set the delta of movement of the returnaddr stackslot.
2843     // But only set if delta is greater than previous delta.
2844     if (FPDiff < X86Info->getTCReturnAddrDelta())
2845       X86Info->setTCReturnAddrDelta(FPDiff);
2846   }
2847
2848   unsigned NumBytesToPush = NumBytes;
2849   unsigned NumBytesToPop = NumBytes;
2850
2851   // If we have an inalloca argument, all stack space has already been allocated
2852   // for us and be right at the top of the stack.  We don't support multiple
2853   // arguments passed in memory when using inalloca.
2854   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2855     NumBytesToPush = 0;
2856     if (!ArgLocs.back().isMemLoc())
2857       report_fatal_error("cannot use inalloca attribute on a register "
2858                          "parameter");
2859     if (ArgLocs.back().getLocMemOffset() != 0)
2860       report_fatal_error("any parameter with the inalloca attribute must be "
2861                          "the only memory argument");
2862   }
2863
2864   if (!IsSibcall)
2865     Chain = DAG.getCALLSEQ_START(
2866         Chain, DAG.getIntPtrConstant(NumBytesToPush, dl, true), dl);
2867
2868   SDValue RetAddrFrIdx;
2869   // Load return address for tail calls.
2870   if (isTailCall && FPDiff)
2871     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2872                                     Is64Bit, FPDiff, dl);
2873
2874   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2875   SmallVector<SDValue, 8> MemOpChains;
2876   SDValue StackPtr;
2877
2878   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2879   // of tail call optimization arguments are handle later.
2880   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
2881   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2882     // Skip inalloca arguments, they have already been written.
2883     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2884     if (Flags.isInAlloca())
2885       continue;
2886
2887     CCValAssign &VA = ArgLocs[i];
2888     EVT RegVT = VA.getLocVT();
2889     SDValue Arg = OutVals[i];
2890     bool isByVal = Flags.isByVal();
2891
2892     // Promote the value if needed.
2893     switch (VA.getLocInfo()) {
2894     default: llvm_unreachable("Unknown loc info!");
2895     case CCValAssign::Full: break;
2896     case CCValAssign::SExt:
2897       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2898       break;
2899     case CCValAssign::ZExt:
2900       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2901       break;
2902     case CCValAssign::AExt:
2903       if (Arg.getValueType().isVector() &&
2904           Arg.getValueType().getScalarType() == MVT::i1)
2905         Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2906       else if (RegVT.is128BitVector()) {
2907         // Special case: passing MMX values in XMM registers.
2908         Arg = DAG.getBitcast(MVT::i64, Arg);
2909         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2910         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2911       } else
2912         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2913       break;
2914     case CCValAssign::BCvt:
2915       Arg = DAG.getBitcast(RegVT, Arg);
2916       break;
2917     case CCValAssign::Indirect: {
2918       // Store the argument.
2919       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2920       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2921       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2922                            MachinePointerInfo::getFixedStack(FI),
2923                            false, false, 0);
2924       Arg = SpillSlot;
2925       break;
2926     }
2927     }
2928
2929     if (VA.isRegLoc()) {
2930       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2931       if (isVarArg && IsWin64) {
2932         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2933         // shadow reg if callee is a varargs function.
2934         unsigned ShadowReg = 0;
2935         switch (VA.getLocReg()) {
2936         case X86::XMM0: ShadowReg = X86::RCX; break;
2937         case X86::XMM1: ShadowReg = X86::RDX; break;
2938         case X86::XMM2: ShadowReg = X86::R8; break;
2939         case X86::XMM3: ShadowReg = X86::R9; break;
2940         }
2941         if (ShadowReg)
2942           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2943       }
2944     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2945       assert(VA.isMemLoc());
2946       if (!StackPtr.getNode())
2947         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2948                                       getPointerTy());
2949       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2950                                              dl, DAG, VA, Flags));
2951     }
2952   }
2953
2954   if (!MemOpChains.empty())
2955     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2956
2957   if (Subtarget->isPICStyleGOT()) {
2958     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2959     // GOT pointer.
2960     if (!isTailCall) {
2961       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2962                DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2963     } else {
2964       // If we are tail calling and generating PIC/GOT style code load the
2965       // address of the callee into ECX. The value in ecx is used as target of
2966       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2967       // for tail calls on PIC/GOT architectures. Normally we would just put the
2968       // address of GOT into ebx and then call target@PLT. But for tail calls
2969       // ebx would be restored (since ebx is callee saved) before jumping to the
2970       // target@PLT.
2971
2972       // Note: The actual moving to ECX is done further down.
2973       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2974       if (G && !G->getGlobal()->hasLocalLinkage() &&
2975           G->getGlobal()->hasDefaultVisibility())
2976         Callee = LowerGlobalAddress(Callee, DAG);
2977       else if (isa<ExternalSymbolSDNode>(Callee))
2978         Callee = LowerExternalSymbol(Callee, DAG);
2979     }
2980   }
2981
2982   if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail) {
2983     // From AMD64 ABI document:
2984     // For calls that may call functions that use varargs or stdargs
2985     // (prototype-less calls or calls to functions containing ellipsis (...) in
2986     // the declaration) %al is used as hidden argument to specify the number
2987     // of SSE registers used. The contents of %al do not need to match exactly
2988     // the number of registers, but must be an ubound on the number of SSE
2989     // registers used and is in the range 0 - 8 inclusive.
2990
2991     // Count the number of XMM registers allocated.
2992     static const MCPhysReg XMMArgRegs[] = {
2993       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2994       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2995     };
2996     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
2997     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2998            && "SSE registers cannot be used when SSE is disabled");
2999
3000     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
3001                                         DAG.getConstant(NumXMMRegs, dl,
3002                                                         MVT::i8)));
3003   }
3004
3005   if (isVarArg && IsMustTail) {
3006     const auto &Forwards = X86Info->getForwardedMustTailRegParms();
3007     for (const auto &F : Forwards) {
3008       SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
3009       RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
3010     }
3011   }
3012
3013   // For tail calls lower the arguments to the 'real' stack slots.  Sibcalls
3014   // don't need this because the eligibility check rejects calls that require
3015   // shuffling arguments passed in memory.
3016   if (!IsSibcall && isTailCall) {
3017     // Force all the incoming stack arguments to be loaded from the stack
3018     // before any new outgoing arguments are stored to the stack, because the
3019     // outgoing stack slots may alias the incoming argument stack slots, and
3020     // the alias isn't otherwise explicit. This is slightly more conservative
3021     // than necessary, because it means that each store effectively depends
3022     // on every argument instead of just those arguments it would clobber.
3023     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
3024
3025     SmallVector<SDValue, 8> MemOpChains2;
3026     SDValue FIN;
3027     int FI = 0;
3028     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3029       CCValAssign &VA = ArgLocs[i];
3030       if (VA.isRegLoc())
3031         continue;
3032       assert(VA.isMemLoc());
3033       SDValue Arg = OutVals[i];
3034       ISD::ArgFlagsTy Flags = Outs[i].Flags;
3035       // Skip inalloca arguments.  They don't require any work.
3036       if (Flags.isInAlloca())
3037         continue;
3038       // Create frame index.
3039       int32_t Offset = VA.getLocMemOffset()+FPDiff;
3040       uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
3041       FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3042       FIN = DAG.getFrameIndex(FI, getPointerTy());
3043
3044       if (Flags.isByVal()) {
3045         // Copy relative to framepointer.
3046         SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset(), dl);
3047         if (!StackPtr.getNode())
3048           StackPtr = DAG.getCopyFromReg(Chain, dl,
3049                                         RegInfo->getStackRegister(),
3050                                         getPointerTy());
3051         Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
3052
3053         MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
3054                                                          ArgChain,
3055                                                          Flags, DAG, dl));
3056       } else {
3057         // Store relative to framepointer.
3058         MemOpChains2.push_back(
3059           DAG.getStore(ArgChain, dl, Arg, FIN,
3060                        MachinePointerInfo::getFixedStack(FI),
3061                        false, false, 0));
3062       }
3063     }
3064
3065     if (!MemOpChains2.empty())
3066       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3067
3068     // Store the return address to the appropriate stack slot.
3069     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
3070                                      getPointerTy(), RegInfo->getSlotSize(),
3071                                      FPDiff, dl);
3072   }
3073
3074   // Build a sequence of copy-to-reg nodes chained together with token chain
3075   // and flag operands which copy the outgoing args into registers.
3076   SDValue InFlag;
3077   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3078     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3079                              RegsToPass[i].second, InFlag);
3080     InFlag = Chain.getValue(1);
3081   }
3082
3083   if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
3084     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
3085     // In the 64-bit large code model, we have to make all calls
3086     // through a register, since the call instruction's 32-bit
3087     // pc-relative offset may not be large enough to hold the whole
3088     // address.
3089   } else if (Callee->getOpcode() == ISD::GlobalAddress) {
3090     // If the callee is a GlobalAddress node (quite common, every direct call
3091     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
3092     // it.
3093     GlobalAddressSDNode* G = cast<GlobalAddressSDNode>(Callee);
3094
3095     // We should use extra load for direct calls to dllimported functions in
3096     // non-JIT mode.
3097     const GlobalValue *GV = G->getGlobal();
3098     if (!GV->hasDLLImportStorageClass()) {
3099       unsigned char OpFlags = 0;
3100       bool ExtraLoad = false;
3101       unsigned WrapperKind = ISD::DELETED_NODE;
3102
3103       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
3104       // external symbols most go through the PLT in PIC mode.  If the symbol
3105       // has hidden or protected visibility, or if it is static or local, then
3106       // we don't need to use the PLT - we can directly call it.
3107       if (Subtarget->isTargetELF() &&
3108           DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
3109           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
3110         OpFlags = X86II::MO_PLT;
3111       } else if (Subtarget->isPICStyleStubAny() &&
3112                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
3113                  (!Subtarget->getTargetTriple().isMacOSX() ||
3114                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3115         // PC-relative references to external symbols should go through $stub,
3116         // unless we're building with the leopard linker or later, which
3117         // automatically synthesizes these stubs.
3118         OpFlags = X86II::MO_DARWIN_STUB;
3119       } else if (Subtarget->isPICStyleRIPRel() && isa<Function>(GV) &&
3120                  cast<Function>(GV)->hasFnAttribute(Attribute::NonLazyBind)) {
3121         // If the function is marked as non-lazy, generate an indirect call
3122         // which loads from the GOT directly. This avoids runtime overhead
3123         // at the cost of eager binding (and one extra byte of encoding).
3124         OpFlags = X86II::MO_GOTPCREL;
3125         WrapperKind = X86ISD::WrapperRIP;
3126         ExtraLoad = true;
3127       }
3128
3129       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
3130                                           G->getOffset(), OpFlags);
3131
3132       // Add a wrapper if needed.
3133       if (WrapperKind != ISD::DELETED_NODE)
3134         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
3135       // Add extra indirection if needed.
3136       if (ExtraLoad)
3137         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
3138                              MachinePointerInfo::getGOT(),
3139                              false, false, false, 0);
3140     }
3141   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3142     unsigned char OpFlags = 0;
3143
3144     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
3145     // external symbols should go through the PLT.
3146     if (Subtarget->isTargetELF() &&
3147         DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
3148       OpFlags = X86II::MO_PLT;
3149     } else if (Subtarget->isPICStyleStubAny() &&
3150                (!Subtarget->getTargetTriple().isMacOSX() ||
3151                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3152       // PC-relative references to external symbols should go through $stub,
3153       // unless we're building with the leopard linker or later, which
3154       // automatically synthesizes these stubs.
3155       OpFlags = X86II::MO_DARWIN_STUB;
3156     }
3157
3158     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
3159                                          OpFlags);
3160   } else if (Subtarget->isTarget64BitILP32() &&
3161              Callee->getValueType(0) == MVT::i32) {
3162     // Zero-extend the 32-bit Callee address into a 64-bit according to x32 ABI
3163     Callee = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Callee);
3164   }
3165
3166   // Returns a chain & a flag for retval copy to use.
3167   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3168   SmallVector<SDValue, 8> Ops;
3169
3170   if (!IsSibcall && isTailCall) {
3171     Chain = DAG.getCALLSEQ_END(Chain,
3172                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3173                                DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
3174     InFlag = Chain.getValue(1);
3175   }
3176
3177   Ops.push_back(Chain);
3178   Ops.push_back(Callee);
3179
3180   if (isTailCall)
3181     Ops.push_back(DAG.getConstant(FPDiff, dl, MVT::i32));
3182
3183   // Add argument registers to the end of the list so that they are known live
3184   // into the call.
3185   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3186     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3187                                   RegsToPass[i].second.getValueType()));
3188
3189   // Add a register mask operand representing the call-preserved registers.
3190   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
3191   const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
3192   assert(Mask && "Missing call preserved mask for calling convention");
3193   Ops.push_back(DAG.getRegisterMask(Mask));
3194
3195   if (InFlag.getNode())
3196     Ops.push_back(InFlag);
3197
3198   if (isTailCall) {
3199     // We used to do:
3200     //// If this is the first return lowered for this function, add the regs
3201     //// to the liveout set for the function.
3202     // This isn't right, although it's probably harmless on x86; liveouts
3203     // should be computed from returns not tail calls.  Consider a void
3204     // function making a tail call to a function returning int.
3205     MF.getFrameInfo()->setHasTailCall();
3206     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3207   }
3208
3209   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3210   InFlag = Chain.getValue(1);
3211
3212   // Create the CALLSEQ_END node.
3213   unsigned NumBytesForCalleeToPop;
3214   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3215                        DAG.getTarget().Options.GuaranteedTailCallOpt))
3216     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
3217   else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
3218            !Subtarget->getTargetTriple().isOSMSVCRT() &&
3219            SR == StackStructReturn)
3220     // If this is a call to a struct-return function, the callee
3221     // pops the hidden struct pointer, so we have to push it back.
3222     // This is common for Darwin/X86, Linux & Mingw32 targets.
3223     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3224     NumBytesForCalleeToPop = 4;
3225   else
3226     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
3227
3228   // Returns a flag for retval copy to use.
3229   if (!IsSibcall) {
3230     Chain = DAG.getCALLSEQ_END(Chain,
3231                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3232                                DAG.getIntPtrConstant(NumBytesForCalleeToPop, dl,
3233                                                      true),
3234                                InFlag, dl);
3235     InFlag = Chain.getValue(1);
3236   }
3237
3238   // Handle result values, copying them out of physregs into vregs that we
3239   // return.
3240   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3241                          Ins, dl, DAG, InVals);
3242 }
3243
3244 //===----------------------------------------------------------------------===//
3245 //                Fast Calling Convention (tail call) implementation
3246 //===----------------------------------------------------------------------===//
3247
3248 //  Like std call, callee cleans arguments, convention except that ECX is
3249 //  reserved for storing the tail called function address. Only 2 registers are
3250 //  free for argument passing (inreg). Tail call optimization is performed
3251 //  provided:
3252 //                * tailcallopt is enabled
3253 //                * caller/callee are fastcc
3254 //  On X86_64 architecture with GOT-style position independent code only local
3255 //  (within module) calls are supported at the moment.
3256 //  To keep the stack aligned according to platform abi the function
3257 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
3258 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3259 //  If a tail called function callee has more arguments than the caller the
3260 //  caller needs to make sure that there is room to move the RETADDR to. This is
3261 //  achieved by reserving an area the size of the argument delta right after the
3262 //  original RETADDR, but before the saved framepointer or the spilled registers
3263 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3264 //  stack layout:
3265 //    arg1
3266 //    arg2
3267 //    RETADDR
3268 //    [ new RETADDR
3269 //      move area ]
3270 //    (possible EBP)
3271 //    ESI
3272 //    EDI
3273 //    local1 ..
3274
3275 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3276 /// for a 16 byte align requirement.
3277 unsigned
3278 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3279                                                SelectionDAG& DAG) const {
3280   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3281   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
3282   unsigned StackAlignment = TFI.getStackAlignment();
3283   uint64_t AlignMask = StackAlignment - 1;
3284   int64_t Offset = StackSize;
3285   unsigned SlotSize = RegInfo->getSlotSize();
3286   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3287     // Number smaller than 12 so just add the difference.
3288     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3289   } else {
3290     // Mask out lower bits, add stackalignment once plus the 12 bytes.
3291     Offset = ((~AlignMask) & Offset) + StackAlignment +
3292       (StackAlignment-SlotSize);
3293   }
3294   return Offset;
3295 }
3296
3297 /// MatchingStackOffset - Return true if the given stack call argument is
3298 /// already available in the same position (relatively) of the caller's
3299 /// incoming argument stack.
3300 static
3301 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3302                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3303                          const X86InstrInfo *TII) {
3304   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3305   int FI = INT_MAX;
3306   if (Arg.getOpcode() == ISD::CopyFromReg) {
3307     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3308     if (!TargetRegisterInfo::isVirtualRegister(VR))
3309       return false;
3310     MachineInstr *Def = MRI->getVRegDef(VR);
3311     if (!Def)
3312       return false;
3313     if (!Flags.isByVal()) {
3314       if (!TII->isLoadFromStackSlot(Def, FI))
3315         return false;
3316     } else {
3317       unsigned Opcode = Def->getOpcode();
3318       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r ||
3319            Opcode == X86::LEA64_32r) &&
3320           Def->getOperand(1).isFI()) {
3321         FI = Def->getOperand(1).getIndex();
3322         Bytes = Flags.getByValSize();
3323       } else
3324         return false;
3325     }
3326   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3327     if (Flags.isByVal())
3328       // ByVal argument is passed in as a pointer but it's now being
3329       // dereferenced. e.g.
3330       // define @foo(%struct.X* %A) {
3331       //   tail call @bar(%struct.X* byval %A)
3332       // }
3333       return false;
3334     SDValue Ptr = Ld->getBasePtr();
3335     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3336     if (!FINode)
3337       return false;
3338     FI = FINode->getIndex();
3339   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3340     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3341     FI = FINode->getIndex();
3342     Bytes = Flags.getByValSize();
3343   } else
3344     return false;
3345
3346   assert(FI != INT_MAX);
3347   if (!MFI->isFixedObjectIndex(FI))
3348     return false;
3349   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3350 }
3351
3352 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3353 /// for tail call optimization. Targets which want to do tail call
3354 /// optimization should implement this function.
3355 bool
3356 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3357                                                      CallingConv::ID CalleeCC,
3358                                                      bool isVarArg,
3359                                                      bool isCalleeStructRet,
3360                                                      bool isCallerStructRet,
3361                                                      Type *RetTy,
3362                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3363                                     const SmallVectorImpl<SDValue> &OutVals,
3364                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3365                                                      SelectionDAG &DAG) const {
3366   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3367     return false;
3368
3369   // If -tailcallopt is specified, make fastcc functions tail-callable.
3370   const MachineFunction &MF = DAG.getMachineFunction();
3371   const Function *CallerF = MF.getFunction();
3372
3373   // If the function return type is x86_fp80 and the callee return type is not,
3374   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3375   // perform a tailcall optimization here.
3376   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3377     return false;
3378
3379   CallingConv::ID CallerCC = CallerF->getCallingConv();
3380   bool CCMatch = CallerCC == CalleeCC;
3381   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3382   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3383
3384   // Win64 functions have extra shadow space for argument homing. Don't do the
3385   // sibcall if the caller and callee have mismatched expectations for this
3386   // space.
3387   if (IsCalleeWin64 != IsCallerWin64)
3388     return false;
3389
3390   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3391     if (IsTailCallConvention(CalleeCC) && CCMatch)
3392       return true;
3393     return false;
3394   }
3395
3396   // Look for obvious safe cases to perform tail call optimization that do not
3397   // require ABI changes. This is what gcc calls sibcall.
3398
3399   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3400   // emit a special epilogue.
3401   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3402   if (RegInfo->needsStackRealignment(MF))
3403     return false;
3404
3405   // Also avoid sibcall optimization if either caller or callee uses struct
3406   // return semantics.
3407   if (isCalleeStructRet || isCallerStructRet)
3408     return false;
3409
3410   // An stdcall/thiscall caller is expected to clean up its arguments; the
3411   // callee isn't going to do that.
3412   // FIXME: this is more restrictive than needed. We could produce a tailcall
3413   // when the stack adjustment matches. For example, with a thiscall that takes
3414   // only one argument.
3415   if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3416                    CallerCC == CallingConv::X86_ThisCall))
3417     return false;
3418
3419   // Do not sibcall optimize vararg calls unless all arguments are passed via
3420   // registers.
3421   if (isVarArg && !Outs.empty()) {
3422
3423     // Optimizing for varargs on Win64 is unlikely to be safe without
3424     // additional testing.
3425     if (IsCalleeWin64 || IsCallerWin64)
3426       return false;
3427
3428     SmallVector<CCValAssign, 16> ArgLocs;
3429     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3430                    *DAG.getContext());
3431
3432     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3433     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3434       if (!ArgLocs[i].isRegLoc())
3435         return false;
3436   }
3437
3438   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3439   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3440   // this into a sibcall.
3441   bool Unused = false;
3442   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3443     if (!Ins[i].Used) {
3444       Unused = true;
3445       break;
3446     }
3447   }
3448   if (Unused) {
3449     SmallVector<CCValAssign, 16> RVLocs;
3450     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), RVLocs,
3451                    *DAG.getContext());
3452     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3453     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3454       CCValAssign &VA = RVLocs[i];
3455       if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3456         return false;
3457     }
3458   }
3459
3460   // If the calling conventions do not match, then we'd better make sure the
3461   // results are returned in the same way as what the caller expects.
3462   if (!CCMatch) {
3463     SmallVector<CCValAssign, 16> RVLocs1;
3464     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
3465                     *DAG.getContext());
3466     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3467
3468     SmallVector<CCValAssign, 16> RVLocs2;
3469     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
3470                     *DAG.getContext());
3471     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3472
3473     if (RVLocs1.size() != RVLocs2.size())
3474       return false;
3475     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3476       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3477         return false;
3478       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3479         return false;
3480       if (RVLocs1[i].isRegLoc()) {
3481         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3482           return false;
3483       } else {
3484         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3485           return false;
3486       }
3487     }
3488   }
3489
3490   // If the callee takes no arguments then go on to check the results of the
3491   // call.
3492   if (!Outs.empty()) {
3493     // Check if stack adjustment is needed. For now, do not do this if any
3494     // argument is passed on the stack.
3495     SmallVector<CCValAssign, 16> ArgLocs;
3496     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3497                    *DAG.getContext());
3498
3499     // Allocate shadow area for Win64
3500     if (IsCalleeWin64)
3501       CCInfo.AllocateStack(32, 8);
3502
3503     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3504     if (CCInfo.getNextStackOffset()) {
3505       MachineFunction &MF = DAG.getMachineFunction();
3506       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3507         return false;
3508
3509       // Check if the arguments are already laid out in the right way as
3510       // the caller's fixed stack objects.
3511       MachineFrameInfo *MFI = MF.getFrameInfo();
3512       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3513       const X86InstrInfo *TII = Subtarget->getInstrInfo();
3514       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3515         CCValAssign &VA = ArgLocs[i];
3516         SDValue Arg = OutVals[i];
3517         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3518         if (VA.getLocInfo() == CCValAssign::Indirect)
3519           return false;
3520         if (!VA.isRegLoc()) {
3521           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3522                                    MFI, MRI, TII))
3523             return false;
3524         }
3525       }
3526     }
3527
3528     // If the tailcall address may be in a register, then make sure it's
3529     // possible to register allocate for it. In 32-bit, the call address can
3530     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3531     // callee-saved registers are restored. These happen to be the same
3532     // registers used to pass 'inreg' arguments so watch out for those.
3533     if (!Subtarget->is64Bit() &&
3534         ((!isa<GlobalAddressSDNode>(Callee) &&
3535           !isa<ExternalSymbolSDNode>(Callee)) ||
3536          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3537       unsigned NumInRegs = 0;
3538       // In PIC we need an extra register to formulate the address computation
3539       // for the callee.
3540       unsigned MaxInRegs =
3541         (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3542
3543       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3544         CCValAssign &VA = ArgLocs[i];
3545         if (!VA.isRegLoc())
3546           continue;
3547         unsigned Reg = VA.getLocReg();
3548         switch (Reg) {
3549         default: break;
3550         case X86::EAX: case X86::EDX: case X86::ECX:
3551           if (++NumInRegs == MaxInRegs)
3552             return false;
3553           break;
3554         }
3555       }
3556     }
3557   }
3558
3559   return true;
3560 }
3561
3562 FastISel *
3563 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3564                                   const TargetLibraryInfo *libInfo) const {
3565   return X86::createFastISel(funcInfo, libInfo);
3566 }
3567
3568 //===----------------------------------------------------------------------===//
3569 //                           Other Lowering Hooks
3570 //===----------------------------------------------------------------------===//
3571
3572 static bool MayFoldLoad(SDValue Op) {
3573   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3574 }
3575
3576 static bool MayFoldIntoStore(SDValue Op) {
3577   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3578 }
3579
3580 static bool isTargetShuffle(unsigned Opcode) {
3581   switch(Opcode) {
3582   default: return false;
3583   case X86ISD::BLENDI:
3584   case X86ISD::PSHUFB:
3585   case X86ISD::PSHUFD:
3586   case X86ISD::PSHUFHW:
3587   case X86ISD::PSHUFLW:
3588   case X86ISD::SHUFP:
3589   case X86ISD::PALIGNR:
3590   case X86ISD::MOVLHPS:
3591   case X86ISD::MOVLHPD:
3592   case X86ISD::MOVHLPS:
3593   case X86ISD::MOVLPS:
3594   case X86ISD::MOVLPD:
3595   case X86ISD::MOVSHDUP:
3596   case X86ISD::MOVSLDUP:
3597   case X86ISD::MOVDDUP:
3598   case X86ISD::MOVSS:
3599   case X86ISD::MOVSD:
3600   case X86ISD::UNPCKL:
3601   case X86ISD::UNPCKH:
3602   case X86ISD::VPERMILPI:
3603   case X86ISD::VPERM2X128:
3604   case X86ISD::VPERMI:
3605     return true;
3606   }
3607 }
3608
3609 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3610                                     SDValue V1, unsigned TargetMask,
3611                                     SelectionDAG &DAG) {
3612   switch(Opc) {
3613   default: llvm_unreachable("Unknown x86 shuffle node");
3614   case X86ISD::PSHUFD:
3615   case X86ISD::PSHUFHW:
3616   case X86ISD::PSHUFLW:
3617   case X86ISD::VPERMILPI:
3618   case X86ISD::VPERMI:
3619     return DAG.getNode(Opc, dl, VT, V1,
3620                        DAG.getConstant(TargetMask, dl, MVT::i8));
3621   }
3622 }
3623
3624 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3625                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3626   switch(Opc) {
3627   default: llvm_unreachable("Unknown x86 shuffle node");
3628   case X86ISD::MOVLHPS:
3629   case X86ISD::MOVLHPD:
3630   case X86ISD::MOVHLPS:
3631   case X86ISD::MOVLPS:
3632   case X86ISD::MOVLPD:
3633   case X86ISD::MOVSS:
3634   case X86ISD::MOVSD:
3635   case X86ISD::UNPCKL:
3636   case X86ISD::UNPCKH:
3637     return DAG.getNode(Opc, dl, VT, V1, V2);
3638   }
3639 }
3640
3641 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3642   MachineFunction &MF = DAG.getMachineFunction();
3643   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3644   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3645   int ReturnAddrIndex = FuncInfo->getRAIndex();
3646
3647   if (ReturnAddrIndex == 0) {
3648     // Set up a frame object for the return address.
3649     unsigned SlotSize = RegInfo->getSlotSize();
3650     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3651                                                            -(int64_t)SlotSize,
3652                                                            false);
3653     FuncInfo->setRAIndex(ReturnAddrIndex);
3654   }
3655
3656   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3657 }
3658
3659 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3660                                        bool hasSymbolicDisplacement) {
3661   // Offset should fit into 32 bit immediate field.
3662   if (!isInt<32>(Offset))
3663     return false;
3664
3665   // If we don't have a symbolic displacement - we don't have any extra
3666   // restrictions.
3667   if (!hasSymbolicDisplacement)
3668     return true;
3669
3670   // FIXME: Some tweaks might be needed for medium code model.
3671   if (M != CodeModel::Small && M != CodeModel::Kernel)
3672     return false;
3673
3674   // For small code model we assume that latest object is 16MB before end of 31
3675   // bits boundary. We may also accept pretty large negative constants knowing
3676   // that all objects are in the positive half of address space.
3677   if (M == CodeModel::Small && Offset < 16*1024*1024)
3678     return true;
3679
3680   // For kernel code model we know that all object resist in the negative half
3681   // of 32bits address space. We may not accept negative offsets, since they may
3682   // be just off and we may accept pretty large positive ones.
3683   if (M == CodeModel::Kernel && Offset >= 0)
3684     return true;
3685
3686   return false;
3687 }
3688
3689 /// isCalleePop - Determines whether the callee is required to pop its
3690 /// own arguments. Callee pop is necessary to support tail calls.
3691 bool X86::isCalleePop(CallingConv::ID CallingConv,
3692                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3693   switch (CallingConv) {
3694   default:
3695     return false;
3696   case CallingConv::X86_StdCall:
3697   case CallingConv::X86_FastCall:
3698   case CallingConv::X86_ThisCall:
3699     return !is64Bit;
3700   case CallingConv::Fast:
3701   case CallingConv::GHC:
3702   case CallingConv::HiPE:
3703     if (IsVarArg)
3704       return false;
3705     return TailCallOpt;
3706   }
3707 }
3708
3709 /// \brief Return true if the condition is an unsigned comparison operation.
3710 static bool isX86CCUnsigned(unsigned X86CC) {
3711   switch (X86CC) {
3712   default: llvm_unreachable("Invalid integer condition!");
3713   case X86::COND_E:     return true;
3714   case X86::COND_G:     return false;
3715   case X86::COND_GE:    return false;
3716   case X86::COND_L:     return false;
3717   case X86::COND_LE:    return false;
3718   case X86::COND_NE:    return true;
3719   case X86::COND_B:     return true;
3720   case X86::COND_A:     return true;
3721   case X86::COND_BE:    return true;
3722   case X86::COND_AE:    return true;
3723   }
3724   llvm_unreachable("covered switch fell through?!");
3725 }
3726
3727 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3728 /// specific condition code, returning the condition code and the LHS/RHS of the
3729 /// comparison to make.
3730 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, SDLoc DL, bool isFP,
3731                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3732   if (!isFP) {
3733     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3734       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3735         // X > -1   -> X == 0, jump !sign.
3736         RHS = DAG.getConstant(0, DL, RHS.getValueType());
3737         return X86::COND_NS;
3738       }
3739       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3740         // X < 0   -> X == 0, jump on sign.
3741         return X86::COND_S;
3742       }
3743       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3744         // X < 1   -> X <= 0
3745         RHS = DAG.getConstant(0, DL, RHS.getValueType());
3746         return X86::COND_LE;
3747       }
3748     }
3749
3750     switch (SetCCOpcode) {
3751     default: llvm_unreachable("Invalid integer condition!");
3752     case ISD::SETEQ:  return X86::COND_E;
3753     case ISD::SETGT:  return X86::COND_G;
3754     case ISD::SETGE:  return X86::COND_GE;
3755     case ISD::SETLT:  return X86::COND_L;
3756     case ISD::SETLE:  return X86::COND_LE;
3757     case ISD::SETNE:  return X86::COND_NE;
3758     case ISD::SETULT: return X86::COND_B;
3759     case ISD::SETUGT: return X86::COND_A;
3760     case ISD::SETULE: return X86::COND_BE;
3761     case ISD::SETUGE: return X86::COND_AE;
3762     }
3763   }
3764
3765   // First determine if it is required or is profitable to flip the operands.
3766
3767   // If LHS is a foldable load, but RHS is not, flip the condition.
3768   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3769       !ISD::isNON_EXTLoad(RHS.getNode())) {
3770     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3771     std::swap(LHS, RHS);
3772   }
3773
3774   switch (SetCCOpcode) {
3775   default: break;
3776   case ISD::SETOLT:
3777   case ISD::SETOLE:
3778   case ISD::SETUGT:
3779   case ISD::SETUGE:
3780     std::swap(LHS, RHS);
3781     break;
3782   }
3783
3784   // On a floating point condition, the flags are set as follows:
3785   // ZF  PF  CF   op
3786   //  0 | 0 | 0 | X > Y
3787   //  0 | 0 | 1 | X < Y
3788   //  1 | 0 | 0 | X == Y
3789   //  1 | 1 | 1 | unordered
3790   switch (SetCCOpcode) {
3791   default: llvm_unreachable("Condcode should be pre-legalized away");
3792   case ISD::SETUEQ:
3793   case ISD::SETEQ:   return X86::COND_E;
3794   case ISD::SETOLT:              // flipped
3795   case ISD::SETOGT:
3796   case ISD::SETGT:   return X86::COND_A;
3797   case ISD::SETOLE:              // flipped
3798   case ISD::SETOGE:
3799   case ISD::SETGE:   return X86::COND_AE;
3800   case ISD::SETUGT:              // flipped
3801   case ISD::SETULT:
3802   case ISD::SETLT:   return X86::COND_B;
3803   case ISD::SETUGE:              // flipped
3804   case ISD::SETULE:
3805   case ISD::SETLE:   return X86::COND_BE;
3806   case ISD::SETONE:
3807   case ISD::SETNE:   return X86::COND_NE;
3808   case ISD::SETUO:   return X86::COND_P;
3809   case ISD::SETO:    return X86::COND_NP;
3810   case ISD::SETOEQ:
3811   case ISD::SETUNE:  return X86::COND_INVALID;
3812   }
3813 }
3814
3815 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3816 /// code. Current x86 isa includes the following FP cmov instructions:
3817 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3818 static bool hasFPCMov(unsigned X86CC) {
3819   switch (X86CC) {
3820   default:
3821     return false;
3822   case X86::COND_B:
3823   case X86::COND_BE:
3824   case X86::COND_E:
3825   case X86::COND_P:
3826   case X86::COND_A:
3827   case X86::COND_AE:
3828   case X86::COND_NE:
3829   case X86::COND_NP:
3830     return true;
3831   }
3832 }
3833
3834 /// isFPImmLegal - Returns true if the target can instruction select the
3835 /// specified FP immediate natively. If false, the legalizer will
3836 /// materialize the FP immediate as a load from a constant pool.
3837 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3838   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3839     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3840       return true;
3841   }
3842   return false;
3843 }
3844
3845 bool X86TargetLowering::shouldReduceLoadWidth(SDNode *Load,
3846                                               ISD::LoadExtType ExtTy,
3847                                               EVT NewVT) const {
3848   // "ELF Handling for Thread-Local Storage" specifies that R_X86_64_GOTTPOFF
3849   // relocation target a movq or addq instruction: don't let the load shrink.
3850   SDValue BasePtr = cast<LoadSDNode>(Load)->getBasePtr();
3851   if (BasePtr.getOpcode() == X86ISD::WrapperRIP)
3852     if (const auto *GA = dyn_cast<GlobalAddressSDNode>(BasePtr.getOperand(0)))
3853       return GA->getTargetFlags() != X86II::MO_GOTTPOFF;
3854   return true;
3855 }
3856
3857 /// \brief Returns true if it is beneficial to convert a load of a constant
3858 /// to just the constant itself.
3859 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3860                                                           Type *Ty) const {
3861   assert(Ty->isIntegerTy());
3862
3863   unsigned BitSize = Ty->getPrimitiveSizeInBits();
3864   if (BitSize == 0 || BitSize > 64)
3865     return false;
3866   return true;
3867 }
3868
3869 bool X86TargetLowering::isExtractSubvectorCheap(EVT ResVT,
3870                                                 unsigned Index) const {
3871   if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
3872     return false;
3873
3874   return (Index == 0 || Index == ResVT.getVectorNumElements());
3875 }
3876
3877 bool X86TargetLowering::isCheapToSpeculateCttz() const {
3878   // Speculate cttz only if we can directly use TZCNT.
3879   return Subtarget->hasBMI();
3880 }
3881
3882 bool X86TargetLowering::isCheapToSpeculateCtlz() const {
3883   // Speculate ctlz only if we can directly use LZCNT.
3884   return Subtarget->hasLZCNT();
3885 }
3886
3887 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3888 /// the specified range (L, H].
3889 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3890   return (Val < 0) || (Val >= Low && Val < Hi);
3891 }
3892
3893 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3894 /// specified value.
3895 static bool isUndefOrEqual(int Val, int CmpVal) {
3896   return (Val < 0 || Val == CmpVal);
3897 }
3898
3899 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3900 /// from position Pos and ending in Pos+Size, falls within the specified
3901 /// sequential range (Low, Low+Size]. or is undef.
3902 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3903                                        unsigned Pos, unsigned Size, int Low) {
3904   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3905     if (!isUndefOrEqual(Mask[i], Low))
3906       return false;
3907   return true;
3908 }
3909
3910 /// isVEXTRACTIndex - Return true if the specified
3911 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3912 /// suitable for instruction that extract 128 or 256 bit vectors
3913 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
3914   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
3915   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3916     return false;
3917
3918   // The index should be aligned on a vecWidth-bit boundary.
3919   uint64_t Index =
3920     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3921
3922   MVT VT = N->getSimpleValueType(0);
3923   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
3924   bool Result = (Index * ElSize) % vecWidth == 0;
3925
3926   return Result;
3927 }
3928
3929 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
3930 /// operand specifies a subvector insert that is suitable for input to
3931 /// insertion of 128 or 256-bit subvectors
3932 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
3933   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
3934   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3935     return false;
3936   // The index should be aligned on a vecWidth-bit boundary.
3937   uint64_t Index =
3938     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3939
3940   MVT VT = N->getSimpleValueType(0);
3941   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
3942   bool Result = (Index * ElSize) % vecWidth == 0;
3943
3944   return Result;
3945 }
3946
3947 bool X86::isVINSERT128Index(SDNode *N) {
3948   return isVINSERTIndex(N, 128);
3949 }
3950
3951 bool X86::isVINSERT256Index(SDNode *N) {
3952   return isVINSERTIndex(N, 256);
3953 }
3954
3955 bool X86::isVEXTRACT128Index(SDNode *N) {
3956   return isVEXTRACTIndex(N, 128);
3957 }
3958
3959 bool X86::isVEXTRACT256Index(SDNode *N) {
3960   return isVEXTRACTIndex(N, 256);
3961 }
3962
3963 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
3964   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
3965   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3966     llvm_unreachable("Illegal extract subvector for VEXTRACT");
3967
3968   uint64_t Index =
3969     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3970
3971   MVT VecVT = N->getOperand(0).getSimpleValueType();
3972   MVT ElVT = VecVT.getVectorElementType();
3973
3974   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
3975   return Index / NumElemsPerChunk;
3976 }
3977
3978 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
3979   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
3980   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3981     llvm_unreachable("Illegal insert subvector for VINSERT");
3982
3983   uint64_t Index =
3984     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3985
3986   MVT VecVT = N->getSimpleValueType(0);
3987   MVT ElVT = VecVT.getVectorElementType();
3988
3989   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
3990   return Index / NumElemsPerChunk;
3991 }
3992
3993 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
3994 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
3995 /// and VINSERTI128 instructions.
3996 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
3997   return getExtractVEXTRACTImmediate(N, 128);
3998 }
3999
4000 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4001 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4002 /// and VINSERTI64x4 instructions.
4003 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4004   return getExtractVEXTRACTImmediate(N, 256);
4005 }
4006
4007 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4008 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4009 /// and VINSERTI128 instructions.
4010 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4011   return getInsertVINSERTImmediate(N, 128);
4012 }
4013
4014 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4015 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4016 /// and VINSERTI64x4 instructions.
4017 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4018   return getInsertVINSERTImmediate(N, 256);
4019 }
4020
4021 /// isZero - Returns true if Elt is a constant integer zero
4022 static bool isZero(SDValue V) {
4023   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4024   return C && C->isNullValue();
4025 }
4026
4027 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4028 /// constant +0.0.
4029 bool X86::isZeroNode(SDValue Elt) {
4030   if (isZero(Elt))
4031     return true;
4032   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4033     return CFP->getValueAPF().isPosZero();
4034   return false;
4035 }
4036
4037 /// getZeroVector - Returns a vector of specified type with all zero elements.
4038 ///
4039 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4040                              SelectionDAG &DAG, SDLoc dl) {
4041   assert(VT.isVector() && "Expected a vector type");
4042
4043   // Always build SSE zero vectors as <4 x i32> bitcasted
4044   // to their dest type. This ensures they get CSE'd.
4045   SDValue Vec;
4046   if (VT.is128BitVector()) {  // SSE
4047     if (Subtarget->hasSSE2()) {  // SSE2
4048       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4049       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4050     } else { // SSE1
4051       SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4052       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4053     }
4054   } else if (VT.is256BitVector()) { // AVX
4055     if (Subtarget->hasInt256()) { // AVX2
4056       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4057       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4058       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4059     } else {
4060       // 256-bit logic and arithmetic instructions in AVX are all
4061       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4062       SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4063       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4064       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4065     }
4066   } else if (VT.is512BitVector()) { // AVX-512
4067       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4068       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4069                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4070       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4071   } else if (VT.getScalarType() == MVT::i1) {
4072
4073     assert((Subtarget->hasBWI() || VT.getVectorNumElements() <= 16)
4074             && "Unexpected vector type");
4075     assert((Subtarget->hasVLX() || VT.getVectorNumElements() >= 8)
4076             && "Unexpected vector type");
4077     SDValue Cst = DAG.getConstant(0, dl, MVT::i1);
4078     SmallVector<SDValue, 64> Ops(VT.getVectorNumElements(), Cst);
4079     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4080   } else
4081     llvm_unreachable("Unexpected vector type");
4082
4083   return DAG.getBitcast(VT, Vec);
4084 }
4085
4086 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
4087                                 SelectionDAG &DAG, SDLoc dl,
4088                                 unsigned vectorWidth) {
4089   assert((vectorWidth == 128 || vectorWidth == 256) &&
4090          "Unsupported vector width");
4091   EVT VT = Vec.getValueType();
4092   EVT ElVT = VT.getVectorElementType();
4093   unsigned Factor = VT.getSizeInBits()/vectorWidth;
4094   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
4095                                   VT.getVectorNumElements()/Factor);
4096
4097   // Extract from UNDEF is UNDEF.
4098   if (Vec.getOpcode() == ISD::UNDEF)
4099     return DAG.getUNDEF(ResultVT);
4100
4101   // Extract the relevant vectorWidth bits.  Generate an EXTRACT_SUBVECTOR
4102   unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
4103
4104   // This is the index of the first element of the vectorWidth-bit chunk
4105   // we want.
4106   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
4107                                * ElemsPerChunk);
4108
4109   // If the input is a buildvector just emit a smaller one.
4110   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
4111     return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
4112                        makeArrayRef(Vec->op_begin() + NormalizedIdxVal,
4113                                     ElemsPerChunk));
4114
4115   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4116   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec, VecIdx);
4117 }
4118
4119 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
4120 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
4121 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
4122 /// instructions or a simple subregister reference. Idx is an index in the
4123 /// 128 bits we want.  It need not be aligned to a 128-bit boundary.  That makes
4124 /// lowering EXTRACT_VECTOR_ELT operations easier.
4125 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
4126                                    SelectionDAG &DAG, SDLoc dl) {
4127   assert((Vec.getValueType().is256BitVector() ||
4128           Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
4129   return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
4130 }
4131
4132 /// Generate a DAG to grab 256-bits from a 512-bit vector.
4133 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
4134                                    SelectionDAG &DAG, SDLoc dl) {
4135   assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
4136   return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
4137 }
4138
4139 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
4140                                unsigned IdxVal, SelectionDAG &DAG,
4141                                SDLoc dl, unsigned vectorWidth) {
4142   assert((vectorWidth == 128 || vectorWidth == 256) &&
4143          "Unsupported vector width");
4144   // Inserting UNDEF is Result
4145   if (Vec.getOpcode() == ISD::UNDEF)
4146     return Result;
4147   EVT VT = Vec.getValueType();
4148   EVT ElVT = VT.getVectorElementType();
4149   EVT ResultVT = Result.getValueType();
4150
4151   // Insert the relevant vectorWidth bits.
4152   unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
4153
4154   // This is the index of the first element of the vectorWidth-bit chunk
4155   // we want.
4156   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
4157                                * ElemsPerChunk);
4158
4159   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4160   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec, VecIdx);
4161 }
4162
4163 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
4164 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
4165 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
4166 /// simple superregister reference.  Idx is an index in the 128 bits
4167 /// we want.  It need not be aligned to a 128-bit boundary.  That makes
4168 /// lowering INSERT_VECTOR_ELT operations easier.
4169 static SDValue Insert128BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4170                                   SelectionDAG &DAG, SDLoc dl) {
4171   assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
4172
4173   // For insertion into the zero index (low half) of a 256-bit vector, it is
4174   // more efficient to generate a blend with immediate instead of an insert*128.
4175   // We are still creating an INSERT_SUBVECTOR below with an undef node to
4176   // extend the subvector to the size of the result vector. Make sure that
4177   // we are not recursing on that node by checking for undef here.
4178   if (IdxVal == 0 && Result.getValueType().is256BitVector() &&
4179       Result.getOpcode() != ISD::UNDEF) {
4180     EVT ResultVT = Result.getValueType();
4181     SDValue ZeroIndex = DAG.getIntPtrConstant(0, dl);
4182     SDValue Undef = DAG.getUNDEF(ResultVT);
4183     SDValue Vec256 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Undef,
4184                                  Vec, ZeroIndex);
4185
4186     // The blend instruction, and therefore its mask, depend on the data type.
4187     MVT ScalarType = ResultVT.getScalarType().getSimpleVT();
4188     if (ScalarType.isFloatingPoint()) {
4189       // Choose either vblendps (float) or vblendpd (double).
4190       unsigned ScalarSize = ScalarType.getSizeInBits();
4191       assert((ScalarSize == 64 || ScalarSize == 32) && "Unknown float type");
4192       unsigned MaskVal = (ScalarSize == 64) ? 0x03 : 0x0f;
4193       SDValue Mask = DAG.getConstant(MaskVal, dl, MVT::i8);
4194       return DAG.getNode(X86ISD::BLENDI, dl, ResultVT, Result, Vec256, Mask);
4195     }
4196
4197     const X86Subtarget &Subtarget =
4198     static_cast<const X86Subtarget &>(DAG.getSubtarget());
4199
4200     // AVX2 is needed for 256-bit integer blend support.
4201     // Integers must be cast to 32-bit because there is only vpblendd;
4202     // vpblendw can't be used for this because it has a handicapped mask.
4203
4204     // If we don't have AVX2, then cast to float. Using a wrong domain blend
4205     // is still more efficient than using the wrong domain vinsertf128 that
4206     // will be created by InsertSubVector().
4207     MVT CastVT = Subtarget.hasAVX2() ? MVT::v8i32 : MVT::v8f32;
4208
4209     SDValue Mask = DAG.getConstant(0x0f, dl, MVT::i8);
4210     Vec256 = DAG.getBitcast(CastVT, Vec256);
4211     Vec256 = DAG.getNode(X86ISD::BLENDI, dl, CastVT, Result, Vec256, Mask);
4212     return DAG.getBitcast(ResultVT, Vec256);
4213   }
4214
4215   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
4216 }
4217
4218 static SDValue Insert256BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4219                                   SelectionDAG &DAG, SDLoc dl) {
4220   assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
4221   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
4222 }
4223
4224 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
4225 /// instructions. This is used because creating CONCAT_VECTOR nodes of
4226 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
4227 /// large BUILD_VECTORS.
4228 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
4229                                    unsigned NumElems, SelectionDAG &DAG,
4230                                    SDLoc dl) {
4231   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4232   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
4233 }
4234
4235 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
4236                                    unsigned NumElems, SelectionDAG &DAG,
4237                                    SDLoc dl) {
4238   SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4239   return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
4240 }
4241
4242 /// getOnesVector - Returns a vector of specified type with all bits set.
4243 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4244 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4245 /// Then bitcast to their original type, ensuring they get CSE'd.
4246 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4247                              SDLoc dl) {
4248   assert(VT.isVector() && "Expected a vector type");
4249
4250   SDValue Cst = DAG.getConstant(~0U, dl, MVT::i32);
4251   SDValue Vec;
4252   if (VT.is256BitVector()) {
4253     if (HasInt256) { // AVX2
4254       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4255       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4256     } else { // AVX
4257       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4258       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4259     }
4260   } else if (VT.is128BitVector()) {
4261     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4262   } else
4263     llvm_unreachable("Unexpected vector type");
4264
4265   return DAG.getBitcast(VT, Vec);
4266 }
4267
4268 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4269 /// operation of specified width.
4270 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4271                        SDValue V2) {
4272   unsigned NumElems = VT.getVectorNumElements();
4273   SmallVector<int, 8> Mask;
4274   Mask.push_back(NumElems);
4275   for (unsigned i = 1; i != NumElems; ++i)
4276     Mask.push_back(i);
4277   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4278 }
4279
4280 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4281 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4282                           SDValue V2) {
4283   unsigned NumElems = VT.getVectorNumElements();
4284   SmallVector<int, 8> Mask;
4285   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4286     Mask.push_back(i);
4287     Mask.push_back(i + NumElems);
4288   }
4289   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4290 }
4291
4292 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4293 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4294                           SDValue V2) {
4295   unsigned NumElems = VT.getVectorNumElements();
4296   SmallVector<int, 8> Mask;
4297   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4298     Mask.push_back(i + Half);
4299     Mask.push_back(i + NumElems + Half);
4300   }
4301   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4302 }
4303
4304 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4305 /// vector of zero or undef vector.  This produces a shuffle where the low
4306 /// element of V2 is swizzled into the zero/undef vector, landing at element
4307 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4308 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4309                                            bool IsZero,
4310                                            const X86Subtarget *Subtarget,
4311                                            SelectionDAG &DAG) {
4312   MVT VT = V2.getSimpleValueType();
4313   SDValue V1 = IsZero
4314     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
4315   unsigned NumElems = VT.getVectorNumElements();
4316   SmallVector<int, 16> MaskVec;
4317   for (unsigned i = 0; i != NumElems; ++i)
4318     // If this is the insertion idx, put the low elt of V2 here.
4319     MaskVec.push_back(i == Idx ? NumElems : i);
4320   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
4321 }
4322
4323 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4324 /// target specific opcode. Returns true if the Mask could be calculated. Sets
4325 /// IsUnary to true if only uses one source. Note that this will set IsUnary for
4326 /// shuffles which use a single input multiple times, and in those cases it will
4327 /// adjust the mask to only have indices within that single input.
4328 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4329                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
4330   unsigned NumElems = VT.getVectorNumElements();
4331   SDValue ImmN;
4332
4333   IsUnary = false;
4334   bool IsFakeUnary = false;
4335   switch(N->getOpcode()) {
4336   case X86ISD::BLENDI:
4337     ImmN = N->getOperand(N->getNumOperands()-1);
4338     DecodeBLENDMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4339     break;
4340   case X86ISD::SHUFP:
4341     ImmN = N->getOperand(N->getNumOperands()-1);
4342     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4343     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4344     break;
4345   case X86ISD::UNPCKH:
4346     DecodeUNPCKHMask(VT, Mask);
4347     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4348     break;
4349   case X86ISD::UNPCKL:
4350     DecodeUNPCKLMask(VT, Mask);
4351     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4352     break;
4353   case X86ISD::MOVHLPS:
4354     DecodeMOVHLPSMask(NumElems, Mask);
4355     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4356     break;
4357   case X86ISD::MOVLHPS:
4358     DecodeMOVLHPSMask(NumElems, Mask);
4359     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4360     break;
4361   case X86ISD::PALIGNR:
4362     ImmN = N->getOperand(N->getNumOperands()-1);
4363     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4364     break;
4365   case X86ISD::PSHUFD:
4366   case X86ISD::VPERMILPI:
4367     ImmN = N->getOperand(N->getNumOperands()-1);
4368     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4369     IsUnary = true;
4370     break;
4371   case X86ISD::PSHUFHW:
4372     ImmN = N->getOperand(N->getNumOperands()-1);
4373     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4374     IsUnary = true;
4375     break;
4376   case X86ISD::PSHUFLW:
4377     ImmN = N->getOperand(N->getNumOperands()-1);
4378     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4379     IsUnary = true;
4380     break;
4381   case X86ISD::PSHUFB: {
4382     IsUnary = true;
4383     SDValue MaskNode = N->getOperand(1);
4384     while (MaskNode->getOpcode() == ISD::BITCAST)
4385       MaskNode = MaskNode->getOperand(0);
4386
4387     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4388       // If we have a build-vector, then things are easy.
4389       EVT VT = MaskNode.getValueType();
4390       assert(VT.isVector() &&
4391              "Can't produce a non-vector with a build_vector!");
4392       if (!VT.isInteger())
4393         return false;
4394
4395       int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
4396
4397       SmallVector<uint64_t, 32> RawMask;
4398       for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
4399         SDValue Op = MaskNode->getOperand(i);
4400         if (Op->getOpcode() == ISD::UNDEF) {
4401           RawMask.push_back((uint64_t)SM_SentinelUndef);
4402           continue;
4403         }
4404         auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4405         if (!CN)
4406           return false;
4407         APInt MaskElement = CN->getAPIntValue();
4408
4409         // We now have to decode the element which could be any integer size and
4410         // extract each byte of it.
4411         for (int j = 0; j < NumBytesPerElement; ++j) {
4412           // Note that this is x86 and so always little endian: the low byte is
4413           // the first byte of the mask.
4414           RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
4415           MaskElement = MaskElement.lshr(8);
4416         }
4417       }
4418       DecodePSHUFBMask(RawMask, Mask);
4419       break;
4420     }
4421
4422     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4423     if (!MaskLoad)
4424       return false;
4425
4426     SDValue Ptr = MaskLoad->getBasePtr();
4427     if (Ptr->getOpcode() == X86ISD::Wrapper ||
4428         Ptr->getOpcode() == X86ISD::WrapperRIP)
4429       Ptr = Ptr->getOperand(0);
4430
4431     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4432     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4433       return false;
4434
4435     if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
4436       DecodePSHUFBMask(C, Mask);
4437       if (Mask.empty())
4438         return false;
4439       break;
4440     }
4441
4442     return false;
4443   }
4444   case X86ISD::VPERMI:
4445     ImmN = N->getOperand(N->getNumOperands()-1);
4446     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4447     IsUnary = true;
4448     break;
4449   case X86ISD::MOVSS:
4450   case X86ISD::MOVSD:
4451     DecodeScalarMoveMask(VT, /* IsLoad */ false, Mask);
4452     break;
4453   case X86ISD::VPERM2X128:
4454     ImmN = N->getOperand(N->getNumOperands()-1);
4455     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4456     if (Mask.empty()) return false;
4457     break;
4458   case X86ISD::MOVSLDUP:
4459     DecodeMOVSLDUPMask(VT, Mask);
4460     IsUnary = true;
4461     break;
4462   case X86ISD::MOVSHDUP:
4463     DecodeMOVSHDUPMask(VT, Mask);
4464     IsUnary = true;
4465     break;
4466   case X86ISD::MOVDDUP:
4467     DecodeMOVDDUPMask(VT, Mask);
4468     IsUnary = true;
4469     break;
4470   case X86ISD::MOVLHPD:
4471   case X86ISD::MOVLPD:
4472   case X86ISD::MOVLPS:
4473     // Not yet implemented
4474     return false;
4475   default: llvm_unreachable("unknown target shuffle node");
4476   }
4477
4478   // If we have a fake unary shuffle, the shuffle mask is spread across two
4479   // inputs that are actually the same node. Re-map the mask to always point
4480   // into the first input.
4481   if (IsFakeUnary)
4482     for (int &M : Mask)
4483       if (M >= (int)Mask.size())
4484         M -= Mask.size();
4485
4486   return true;
4487 }
4488
4489 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4490 /// element of the result of the vector shuffle.
4491 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4492                                    unsigned Depth) {
4493   if (Depth == 6)
4494     return SDValue();  // Limit search depth.
4495
4496   SDValue V = SDValue(N, 0);
4497   EVT VT = V.getValueType();
4498   unsigned Opcode = V.getOpcode();
4499
4500   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4501   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4502     int Elt = SV->getMaskElt(Index);
4503
4504     if (Elt < 0)
4505       return DAG.getUNDEF(VT.getVectorElementType());
4506
4507     unsigned NumElems = VT.getVectorNumElements();
4508     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4509                                          : SV->getOperand(1);
4510     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4511   }
4512
4513   // Recurse into target specific vector shuffles to find scalars.
4514   if (isTargetShuffle(Opcode)) {
4515     MVT ShufVT = V.getSimpleValueType();
4516     unsigned NumElems = ShufVT.getVectorNumElements();
4517     SmallVector<int, 16> ShuffleMask;
4518     bool IsUnary;
4519
4520     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4521       return SDValue();
4522
4523     int Elt = ShuffleMask[Index];
4524     if (Elt < 0)
4525       return DAG.getUNDEF(ShufVT.getVectorElementType());
4526
4527     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4528                                          : N->getOperand(1);
4529     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4530                                Depth+1);
4531   }
4532
4533   // Actual nodes that may contain scalar elements
4534   if (Opcode == ISD::BITCAST) {
4535     V = V.getOperand(0);
4536     EVT SrcVT = V.getValueType();
4537     unsigned NumElems = VT.getVectorNumElements();
4538
4539     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4540       return SDValue();
4541   }
4542
4543   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4544     return (Index == 0) ? V.getOperand(0)
4545                         : DAG.getUNDEF(VT.getVectorElementType());
4546
4547   if (V.getOpcode() == ISD::BUILD_VECTOR)
4548     return V.getOperand(Index);
4549
4550   return SDValue();
4551 }
4552
4553 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4554 ///
4555 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4556                                        unsigned NumNonZero, unsigned NumZero,
4557                                        SelectionDAG &DAG,
4558                                        const X86Subtarget* Subtarget,
4559                                        const TargetLowering &TLI) {
4560   if (NumNonZero > 8)
4561     return SDValue();
4562
4563   SDLoc dl(Op);
4564   SDValue V;
4565   bool First = true;
4566
4567   // SSE4.1 - use PINSRB to insert each byte directly.
4568   if (Subtarget->hasSSE41()) {
4569     for (unsigned i = 0; i < 16; ++i) {
4570       bool isNonZero = (NonZeros & (1 << i)) != 0;
4571       if (isNonZero) {
4572         if (First) {
4573           if (NumZero)
4574             V = getZeroVector(MVT::v16i8, Subtarget, DAG, dl);
4575           else
4576             V = DAG.getUNDEF(MVT::v16i8);
4577           First = false;
4578         }
4579         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4580                         MVT::v16i8, V, Op.getOperand(i),
4581                         DAG.getIntPtrConstant(i, dl));
4582       }
4583     }
4584
4585     return V;
4586   }
4587
4588   // Pre-SSE4.1 - merge byte pairs and insert with PINSRW.
4589   for (unsigned i = 0; i < 16; ++i) {
4590     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4591     if (ThisIsNonZero && First) {
4592       if (NumZero)
4593         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4594       else
4595         V = DAG.getUNDEF(MVT::v8i16);
4596       First = false;
4597     }
4598
4599     if ((i & 1) != 0) {
4600       SDValue ThisElt, LastElt;
4601       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4602       if (LastIsNonZero) {
4603         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4604                               MVT::i16, Op.getOperand(i-1));
4605       }
4606       if (ThisIsNonZero) {
4607         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4608         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4609                               ThisElt, DAG.getConstant(8, dl, MVT::i8));
4610         if (LastIsNonZero)
4611           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4612       } else
4613         ThisElt = LastElt;
4614
4615       if (ThisElt.getNode())
4616         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4617                         DAG.getIntPtrConstant(i/2, dl));
4618     }
4619   }
4620
4621   return DAG.getBitcast(MVT::v16i8, V);
4622 }
4623
4624 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4625 ///
4626 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4627                                      unsigned NumNonZero, unsigned NumZero,
4628                                      SelectionDAG &DAG,
4629                                      const X86Subtarget* Subtarget,
4630                                      const TargetLowering &TLI) {
4631   if (NumNonZero > 4)
4632     return SDValue();
4633
4634   SDLoc dl(Op);
4635   SDValue V;
4636   bool First = true;
4637   for (unsigned i = 0; i < 8; ++i) {
4638     bool isNonZero = (NonZeros & (1 << i)) != 0;
4639     if (isNonZero) {
4640       if (First) {
4641         if (NumZero)
4642           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4643         else
4644           V = DAG.getUNDEF(MVT::v8i16);
4645         First = false;
4646       }
4647       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4648                       MVT::v8i16, V, Op.getOperand(i),
4649                       DAG.getIntPtrConstant(i, dl));
4650     }
4651   }
4652
4653   return V;
4654 }
4655
4656 /// LowerBuildVectorv4x32 - Custom lower build_vector of v4i32 or v4f32.
4657 static SDValue LowerBuildVectorv4x32(SDValue Op, SelectionDAG &DAG,
4658                                      const X86Subtarget *Subtarget,
4659                                      const TargetLowering &TLI) {
4660   // Find all zeroable elements.
4661   std::bitset<4> Zeroable;
4662   for (int i=0; i < 4; ++i) {
4663     SDValue Elt = Op->getOperand(i);
4664     Zeroable[i] = (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt));
4665   }
4666   assert(Zeroable.size() - Zeroable.count() > 1 &&
4667          "We expect at least two non-zero elements!");
4668
4669   // We only know how to deal with build_vector nodes where elements are either
4670   // zeroable or extract_vector_elt with constant index.
4671   SDValue FirstNonZero;
4672   unsigned FirstNonZeroIdx;
4673   for (unsigned i=0; i < 4; ++i) {
4674     if (Zeroable[i])
4675       continue;
4676     SDValue Elt = Op->getOperand(i);
4677     if (Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4678         !isa<ConstantSDNode>(Elt.getOperand(1)))
4679       return SDValue();
4680     // Make sure that this node is extracting from a 128-bit vector.
4681     MVT VT = Elt.getOperand(0).getSimpleValueType();
4682     if (!VT.is128BitVector())
4683       return SDValue();
4684     if (!FirstNonZero.getNode()) {
4685       FirstNonZero = Elt;
4686       FirstNonZeroIdx = i;
4687     }
4688   }
4689
4690   assert(FirstNonZero.getNode() && "Unexpected build vector of all zeros!");
4691   SDValue V1 = FirstNonZero.getOperand(0);
4692   MVT VT = V1.getSimpleValueType();
4693
4694   // See if this build_vector can be lowered as a blend with zero.
4695   SDValue Elt;
4696   unsigned EltMaskIdx, EltIdx;
4697   int Mask[4];
4698   for (EltIdx = 0; EltIdx < 4; ++EltIdx) {
4699     if (Zeroable[EltIdx]) {
4700       // The zero vector will be on the right hand side.
4701       Mask[EltIdx] = EltIdx+4;
4702       continue;
4703     }
4704
4705     Elt = Op->getOperand(EltIdx);
4706     // By construction, Elt is a EXTRACT_VECTOR_ELT with constant index.
4707     EltMaskIdx = cast<ConstantSDNode>(Elt.getOperand(1))->getZExtValue();
4708     if (Elt.getOperand(0) != V1 || EltMaskIdx != EltIdx)
4709       break;
4710     Mask[EltIdx] = EltIdx;
4711   }
4712
4713   if (EltIdx == 4) {
4714     // Let the shuffle legalizer deal with blend operations.
4715     SDValue VZero = getZeroVector(VT, Subtarget, DAG, SDLoc(Op));
4716     if (V1.getSimpleValueType() != VT)
4717       V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), VT, V1);
4718     return DAG.getVectorShuffle(VT, SDLoc(V1), V1, VZero, &Mask[0]);
4719   }
4720
4721   // See if we can lower this build_vector to a INSERTPS.
4722   if (!Subtarget->hasSSE41())
4723     return SDValue();
4724
4725   SDValue V2 = Elt.getOperand(0);
4726   if (Elt == FirstNonZero && EltIdx == FirstNonZeroIdx)
4727     V1 = SDValue();
4728
4729   bool CanFold = true;
4730   for (unsigned i = EltIdx + 1; i < 4 && CanFold; ++i) {
4731     if (Zeroable[i])
4732       continue;
4733
4734     SDValue Current = Op->getOperand(i);
4735     SDValue SrcVector = Current->getOperand(0);
4736     if (!V1.getNode())
4737       V1 = SrcVector;
4738     CanFold = SrcVector == V1 &&
4739       cast<ConstantSDNode>(Current.getOperand(1))->getZExtValue() == i;
4740   }
4741
4742   if (!CanFold)
4743     return SDValue();
4744
4745   assert(V1.getNode() && "Expected at least two non-zero elements!");
4746   if (V1.getSimpleValueType() != MVT::v4f32)
4747     V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), MVT::v4f32, V1);
4748   if (V2.getSimpleValueType() != MVT::v4f32)
4749     V2 = DAG.getNode(ISD::BITCAST, SDLoc(V2), MVT::v4f32, V2);
4750
4751   // Ok, we can emit an INSERTPS instruction.
4752   unsigned ZMask = Zeroable.to_ulong();
4753
4754   unsigned InsertPSMask = EltMaskIdx << 6 | EltIdx << 4 | ZMask;
4755   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
4756   SDLoc DL(Op);
4757   SDValue Result = DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
4758                                DAG.getIntPtrConstant(InsertPSMask, DL));
4759   return DAG.getBitcast(VT, Result);
4760 }
4761
4762 /// Return a vector logical shift node.
4763 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4764                          unsigned NumBits, SelectionDAG &DAG,
4765                          const TargetLowering &TLI, SDLoc dl) {
4766   assert(VT.is128BitVector() && "Unknown type for VShift");
4767   MVT ShVT = MVT::v2i64;
4768   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4769   SrcOp = DAG.getBitcast(ShVT, SrcOp);
4770   MVT ScalarShiftTy = TLI.getScalarShiftAmountTy(SrcOp.getValueType());
4771   assert(NumBits % 8 == 0 && "Only support byte sized shifts");
4772   SDValue ShiftVal = DAG.getConstant(NumBits/8, dl, ScalarShiftTy);
4773   return DAG.getBitcast(VT, DAG.getNode(Opc, dl, ShVT, SrcOp, ShiftVal));
4774 }
4775
4776 static SDValue
4777 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
4778
4779   // Check if the scalar load can be widened into a vector load. And if
4780   // the address is "base + cst" see if the cst can be "absorbed" into
4781   // the shuffle mask.
4782   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4783     SDValue Ptr = LD->getBasePtr();
4784     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4785       return SDValue();
4786     EVT PVT = LD->getValueType(0);
4787     if (PVT != MVT::i32 && PVT != MVT::f32)
4788       return SDValue();
4789
4790     int FI = -1;
4791     int64_t Offset = 0;
4792     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4793       FI = FINode->getIndex();
4794       Offset = 0;
4795     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4796                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4797       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4798       Offset = Ptr.getConstantOperandVal(1);
4799       Ptr = Ptr.getOperand(0);
4800     } else {
4801       return SDValue();
4802     }
4803
4804     // FIXME: 256-bit vector instructions don't require a strict alignment,
4805     // improve this code to support it better.
4806     unsigned RequiredAlign = VT.getSizeInBits()/8;
4807     SDValue Chain = LD->getChain();
4808     // Make sure the stack object alignment is at least 16 or 32.
4809     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4810     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4811       if (MFI->isFixedObjectIndex(FI)) {
4812         // Can't change the alignment. FIXME: It's possible to compute
4813         // the exact stack offset and reference FI + adjust offset instead.
4814         // If someone *really* cares about this. That's the way to implement it.
4815         return SDValue();
4816       } else {
4817         MFI->setObjectAlignment(FI, RequiredAlign);
4818       }
4819     }
4820
4821     // (Offset % 16 or 32) must be multiple of 4. Then address is then
4822     // Ptr + (Offset & ~15).
4823     if (Offset < 0)
4824       return SDValue();
4825     if ((Offset % RequiredAlign) & 3)
4826       return SDValue();
4827     int64_t StartOffset = Offset & ~(RequiredAlign-1);
4828     if (StartOffset) {
4829       SDLoc DL(Ptr);
4830       Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
4831                         DAG.getConstant(StartOffset, DL, Ptr.getValueType()));
4832     }
4833
4834     int EltNo = (Offset - StartOffset) >> 2;
4835     unsigned NumElems = VT.getVectorNumElements();
4836
4837     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4838     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4839                              LD->getPointerInfo().getWithOffset(StartOffset),
4840                              false, false, false, 0);
4841
4842     SmallVector<int, 8> Mask(NumElems, EltNo);
4843
4844     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
4845   }
4846
4847   return SDValue();
4848 }
4849
4850 /// Given the initializing elements 'Elts' of a vector of type 'VT', see if the
4851 /// elements can be replaced by a single large load which has the same value as
4852 /// a build_vector or insert_subvector whose loaded operands are 'Elts'.
4853 ///
4854 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4855 ///
4856 /// FIXME: we'd also like to handle the case where the last elements are zero
4857 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4858 /// There's even a handy isZeroNode for that purpose.
4859 static SDValue EltsFromConsecutiveLoads(EVT VT, ArrayRef<SDValue> Elts,
4860                                         SDLoc &DL, SelectionDAG &DAG,
4861                                         bool isAfterLegalize) {
4862   unsigned NumElems = Elts.size();
4863
4864   LoadSDNode *LDBase = nullptr;
4865   unsigned LastLoadedElt = -1U;
4866
4867   // For each element in the initializer, see if we've found a load or an undef.
4868   // If we don't find an initial load element, or later load elements are
4869   // non-consecutive, bail out.
4870   for (unsigned i = 0; i < NumElems; ++i) {
4871     SDValue Elt = Elts[i];
4872     // Look through a bitcast.
4873     if (Elt.getNode() && Elt.getOpcode() == ISD::BITCAST)
4874       Elt = Elt.getOperand(0);
4875     if (!Elt.getNode() ||
4876         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4877       return SDValue();
4878     if (!LDBase) {
4879       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4880         return SDValue();
4881       LDBase = cast<LoadSDNode>(Elt.getNode());
4882       LastLoadedElt = i;
4883       continue;
4884     }
4885     if (Elt.getOpcode() == ISD::UNDEF)
4886       continue;
4887
4888     LoadSDNode *LD = cast<LoadSDNode>(Elt);
4889     EVT LdVT = Elt.getValueType();
4890     // Each loaded element must be the correct fractional portion of the
4891     // requested vector load.
4892     if (LdVT.getSizeInBits() != VT.getSizeInBits() / NumElems)
4893       return SDValue();
4894     if (!DAG.isConsecutiveLoad(LD, LDBase, LdVT.getSizeInBits() / 8, i))
4895       return SDValue();
4896     LastLoadedElt = i;
4897   }
4898
4899   // If we have found an entire vector of loads and undefs, then return a large
4900   // load of the entire vector width starting at the base pointer.  If we found
4901   // consecutive loads for the low half, generate a vzext_load node.
4902   if (LastLoadedElt == NumElems - 1) {
4903     assert(LDBase && "Did not find base load for merging consecutive loads");
4904     EVT EltVT = LDBase->getValueType(0);
4905     // Ensure that the input vector size for the merged loads matches the
4906     // cumulative size of the input elements.
4907     if (VT.getSizeInBits() != EltVT.getSizeInBits() * NumElems)
4908       return SDValue();
4909
4910     if (isAfterLegalize &&
4911         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
4912       return SDValue();
4913
4914     SDValue NewLd = SDValue();
4915
4916     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4917                         LDBase->getPointerInfo(), LDBase->isVolatile(),
4918                         LDBase->isNonTemporal(), LDBase->isInvariant(),
4919                         LDBase->getAlignment());
4920
4921     if (LDBase->hasAnyUseOfValue(1)) {
4922       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
4923                                      SDValue(LDBase, 1),
4924                                      SDValue(NewLd.getNode(), 1));
4925       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
4926       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
4927                              SDValue(NewLd.getNode(), 1));
4928     }
4929
4930     return NewLd;
4931   }
4932
4933   //TODO: The code below fires only for for loading the low v2i32 / v2f32
4934   //of a v4i32 / v4f32. It's probably worth generalizing.
4935   EVT EltVT = VT.getVectorElementType();
4936   if (NumElems == 4 && LastLoadedElt == 1 && (EltVT.getSizeInBits() == 32) &&
4937       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
4938     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4939     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4940     SDValue ResNode =
4941         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
4942                                 LDBase->getPointerInfo(),
4943                                 LDBase->getAlignment(),
4944                                 false/*isVolatile*/, true/*ReadMem*/,
4945                                 false/*WriteMem*/);
4946
4947     // Make sure the newly-created LOAD is in the same position as LDBase in
4948     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
4949     // update uses of LDBase's output chain to use the TokenFactor.
4950     if (LDBase->hasAnyUseOfValue(1)) {
4951       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
4952                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
4953       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
4954       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
4955                              SDValue(ResNode.getNode(), 1));
4956     }
4957
4958     return DAG.getBitcast(VT, ResNode);
4959   }
4960   return SDValue();
4961 }
4962
4963 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
4964 /// to generate a splat value for the following cases:
4965 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
4966 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
4967 /// a scalar load, or a constant.
4968 /// The VBROADCAST node is returned when a pattern is found,
4969 /// or SDValue() otherwise.
4970 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
4971                                     SelectionDAG &DAG) {
4972   // VBROADCAST requires AVX.
4973   // TODO: Splats could be generated for non-AVX CPUs using SSE
4974   // instructions, but there's less potential gain for only 128-bit vectors.
4975   if (!Subtarget->hasAVX())
4976     return SDValue();
4977
4978   MVT VT = Op.getSimpleValueType();
4979   SDLoc dl(Op);
4980
4981   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
4982          "Unsupported vector type for broadcast.");
4983
4984   SDValue Ld;
4985   bool ConstSplatVal;
4986
4987   switch (Op.getOpcode()) {
4988     default:
4989       // Unknown pattern found.
4990       return SDValue();
4991
4992     case ISD::BUILD_VECTOR: {
4993       auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
4994       BitVector UndefElements;
4995       SDValue Splat = BVOp->getSplatValue(&UndefElements);
4996
4997       // We need a splat of a single value to use broadcast, and it doesn't
4998       // make any sense if the value is only in one element of the vector.
4999       if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
5000         return SDValue();
5001
5002       Ld = Splat;
5003       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5004                        Ld.getOpcode() == ISD::ConstantFP);
5005
5006       // Make sure that all of the users of a non-constant load are from the
5007       // BUILD_VECTOR node.
5008       if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
5009         return SDValue();
5010       break;
5011     }
5012
5013     case ISD::VECTOR_SHUFFLE: {
5014       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5015
5016       // Shuffles must have a splat mask where the first element is
5017       // broadcasted.
5018       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5019         return SDValue();
5020
5021       SDValue Sc = Op.getOperand(0);
5022       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5023           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5024
5025         if (!Subtarget->hasInt256())
5026           return SDValue();
5027
5028         // Use the register form of the broadcast instruction available on AVX2.
5029         if (VT.getSizeInBits() >= 256)
5030           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5031         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5032       }
5033
5034       Ld = Sc.getOperand(0);
5035       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5036                        Ld.getOpcode() == ISD::ConstantFP);
5037
5038       // The scalar_to_vector node and the suspected
5039       // load node must have exactly one user.
5040       // Constants may have multiple users.
5041
5042       // AVX-512 has register version of the broadcast
5043       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5044         Ld.getValueType().getSizeInBits() >= 32;
5045       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5046           !hasRegVer))
5047         return SDValue();
5048       break;
5049     }
5050   }
5051
5052   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5053   bool IsGE256 = (VT.getSizeInBits() >= 256);
5054
5055   // When optimizing for size, generate up to 5 extra bytes for a broadcast
5056   // instruction to save 8 or more bytes of constant pool data.
5057   // TODO: If multiple splats are generated to load the same constant,
5058   // it may be detrimental to overall size. There needs to be a way to detect
5059   // that condition to know if this is truly a size win.
5060   const Function *F = DAG.getMachineFunction().getFunction();
5061   bool OptForSize = F->hasFnAttribute(Attribute::OptimizeForSize);
5062
5063   // Handle broadcasting a single constant scalar from the constant pool
5064   // into a vector.
5065   // On Sandybridge (no AVX2), it is still better to load a constant vector
5066   // from the constant pool and not to broadcast it from a scalar.
5067   // But override that restriction when optimizing for size.
5068   // TODO: Check if splatting is recommended for other AVX-capable CPUs.
5069   if (ConstSplatVal && (Subtarget->hasAVX2() || OptForSize)) {
5070     EVT CVT = Ld.getValueType();
5071     assert(!CVT.isVector() && "Must not broadcast a vector type");
5072
5073     // Splat f32, i32, v4f64, v4i64 in all cases with AVX2.
5074     // For size optimization, also splat v2f64 and v2i64, and for size opt
5075     // with AVX2, also splat i8 and i16.
5076     // With pattern matching, the VBROADCAST node may become a VMOVDDUP.
5077     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5078         (OptForSize && (ScalarSize == 64 || Subtarget->hasAVX2()))) {
5079       const Constant *C = nullptr;
5080       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5081         C = CI->getConstantIntValue();
5082       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5083         C = CF->getConstantFPValue();
5084
5085       assert(C && "Invalid constant type");
5086
5087       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5088       SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
5089       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5090       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5091                        MachinePointerInfo::getConstantPool(),
5092                        false, false, false, Alignment);
5093
5094       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5095     }
5096   }
5097
5098   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5099
5100   // Handle AVX2 in-register broadcasts.
5101   if (!IsLoad && Subtarget->hasInt256() &&
5102       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5103     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5104
5105   // The scalar source must be a normal load.
5106   if (!IsLoad)
5107     return SDValue();
5108
5109   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5110       (Subtarget->hasVLX() && ScalarSize == 64))
5111     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5112
5113   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5114   // double since there is no vbroadcastsd xmm
5115   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5116     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5117       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5118   }
5119
5120   // Unsupported broadcast.
5121   return SDValue();
5122 }
5123
5124 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5125 /// underlying vector and index.
5126 ///
5127 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5128 /// index.
5129 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5130                                          SDValue ExtIdx) {
5131   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5132   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5133     return Idx;
5134
5135   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5136   // lowered this:
5137   //   (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5138   // to:
5139   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
5140   //                           (extract_subvector (v8f32 %vreg0), Constant<4>),
5141   //                           undef)
5142   //                       Constant<0>)
5143   // In this case the vector is the extract_subvector expression and the index
5144   // is 2, as specified by the shuffle.
5145   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5146   SDValue ShuffleVec = SVOp->getOperand(0);
5147   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5148   assert(ShuffleVecVT.getVectorElementType() ==
5149          ExtractedFromVec.getSimpleValueType().getVectorElementType());
5150
5151   int ShuffleIdx = SVOp->getMaskElt(Idx);
5152   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5153     ExtractedFromVec = ShuffleVec;
5154     return ShuffleIdx;
5155   }
5156   return Idx;
5157 }
5158
5159 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5160   MVT VT = Op.getSimpleValueType();
5161
5162   // Skip if insert_vec_elt is not supported.
5163   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5164   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5165     return SDValue();
5166
5167   SDLoc DL(Op);
5168   unsigned NumElems = Op.getNumOperands();
5169
5170   SDValue VecIn1;
5171   SDValue VecIn2;
5172   SmallVector<unsigned, 4> InsertIndices;
5173   SmallVector<int, 8> Mask(NumElems, -1);
5174
5175   for (unsigned i = 0; i != NumElems; ++i) {
5176     unsigned Opc = Op.getOperand(i).getOpcode();
5177
5178     if (Opc == ISD::UNDEF)
5179       continue;
5180
5181     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5182       // Quit if more than 1 elements need inserting.
5183       if (InsertIndices.size() > 1)
5184         return SDValue();
5185
5186       InsertIndices.push_back(i);
5187       continue;
5188     }
5189
5190     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5191     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5192     // Quit if non-constant index.
5193     if (!isa<ConstantSDNode>(ExtIdx))
5194       return SDValue();
5195     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5196
5197     // Quit if extracted from vector of different type.
5198     if (ExtractedFromVec.getValueType() != VT)
5199       return SDValue();
5200
5201     if (!VecIn1.getNode())
5202       VecIn1 = ExtractedFromVec;
5203     else if (VecIn1 != ExtractedFromVec) {
5204       if (!VecIn2.getNode())
5205         VecIn2 = ExtractedFromVec;
5206       else if (VecIn2 != ExtractedFromVec)
5207         // Quit if more than 2 vectors to shuffle
5208         return SDValue();
5209     }
5210
5211     if (ExtractedFromVec == VecIn1)
5212       Mask[i] = Idx;
5213     else if (ExtractedFromVec == VecIn2)
5214       Mask[i] = Idx + NumElems;
5215   }
5216
5217   if (!VecIn1.getNode())
5218     return SDValue();
5219
5220   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5221   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5222   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5223     unsigned Idx = InsertIndices[i];
5224     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5225                      DAG.getIntPtrConstant(Idx, DL));
5226   }
5227
5228   return NV;
5229 }
5230
5231 static SDValue ConvertI1VectorToInterger(SDValue Op, SelectionDAG &DAG) {
5232   assert(ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
5233          Op.getScalarValueSizeInBits() == 1 &&
5234          "Can not convert non-constant vector");
5235   uint64_t Immediate = 0;
5236   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5237     SDValue In = Op.getOperand(idx);
5238     if (In.getOpcode() != ISD::UNDEF)
5239       Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5240   }
5241   SDLoc dl(Op);
5242   MVT VT =
5243    MVT::getIntegerVT(std::max((int)Op.getValueType().getSizeInBits(), 8));
5244   return DAG.getConstant(Immediate, dl, VT);
5245 }
5246 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5247 SDValue
5248 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5249
5250   MVT VT = Op.getSimpleValueType();
5251   assert((VT.getVectorElementType() == MVT::i1) &&
5252          "Unexpected type in LowerBUILD_VECTORvXi1!");
5253
5254   SDLoc dl(Op);
5255   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5256     SDValue Cst = DAG.getTargetConstant(0, dl, MVT::i1);
5257     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5258     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5259   }
5260
5261   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5262     SDValue Cst = DAG.getTargetConstant(1, dl, MVT::i1);
5263     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5264     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5265   }
5266
5267   if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
5268     SDValue Imm = ConvertI1VectorToInterger(Op, DAG);
5269     if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5270       return DAG.getBitcast(VT, Imm);
5271     SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5272     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5273                         DAG.getIntPtrConstant(0, dl));
5274   }
5275
5276   // Vector has one or more non-const elements
5277   uint64_t Immediate = 0;
5278   SmallVector<unsigned, 16> NonConstIdx;
5279   bool IsSplat = true;
5280   bool HasConstElts = false;
5281   int SplatIdx = -1;
5282   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5283     SDValue In = Op.getOperand(idx);
5284     if (In.getOpcode() == ISD::UNDEF)
5285       continue;
5286     if (!isa<ConstantSDNode>(In))
5287       NonConstIdx.push_back(idx);
5288     else {
5289       Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5290       HasConstElts = true;
5291     }
5292     if (SplatIdx == -1)
5293       SplatIdx = idx;
5294     else if (In != Op.getOperand(SplatIdx))
5295       IsSplat = false;
5296   }
5297
5298   // for splat use " (select i1 splat_elt, all-ones, all-zeroes)"
5299   if (IsSplat)
5300     return DAG.getNode(ISD::SELECT, dl, VT, Op.getOperand(SplatIdx),
5301                        DAG.getConstant(1, dl, VT),
5302                        DAG.getConstant(0, dl, VT));
5303
5304   // insert elements one by one
5305   SDValue DstVec;
5306   SDValue Imm;
5307   if (Immediate) {
5308     MVT ImmVT = MVT::getIntegerVT(std::max((int)VT.getSizeInBits(), 8));
5309     Imm = DAG.getConstant(Immediate, dl, ImmVT);
5310   }
5311   else if (HasConstElts)
5312     Imm = DAG.getConstant(0, dl, VT);
5313   else
5314     Imm = DAG.getUNDEF(VT);
5315   if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5316     DstVec = DAG.getBitcast(VT, Imm);
5317   else {
5318     SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5319     DstVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5320                          DAG.getIntPtrConstant(0, dl));
5321   }
5322
5323   for (unsigned i = 0; i < NonConstIdx.size(); ++i) {
5324     unsigned InsertIdx = NonConstIdx[i];
5325     DstVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5326                          Op.getOperand(InsertIdx),
5327                          DAG.getIntPtrConstant(InsertIdx, dl));
5328   }
5329   return DstVec;
5330 }
5331
5332 /// \brief Return true if \p N implements a horizontal binop and return the
5333 /// operands for the horizontal binop into V0 and V1.
5334 ///
5335 /// This is a helper function of LowerToHorizontalOp().
5336 /// This function checks that the build_vector \p N in input implements a
5337 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
5338 /// operation to match.
5339 /// For example, if \p Opcode is equal to ISD::ADD, then this function
5340 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
5341 /// is equal to ISD::SUB, then this function checks if this is a horizontal
5342 /// arithmetic sub.
5343 ///
5344 /// This function only analyzes elements of \p N whose indices are
5345 /// in range [BaseIdx, LastIdx).
5346 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
5347                               SelectionDAG &DAG,
5348                               unsigned BaseIdx, unsigned LastIdx,
5349                               SDValue &V0, SDValue &V1) {
5350   EVT VT = N->getValueType(0);
5351
5352   assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
5353   assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
5354          "Invalid Vector in input!");
5355
5356   bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
5357   bool CanFold = true;
5358   unsigned ExpectedVExtractIdx = BaseIdx;
5359   unsigned NumElts = LastIdx - BaseIdx;
5360   V0 = DAG.getUNDEF(VT);
5361   V1 = DAG.getUNDEF(VT);
5362
5363   // Check if N implements a horizontal binop.
5364   for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
5365     SDValue Op = N->getOperand(i + BaseIdx);
5366
5367     // Skip UNDEFs.
5368     if (Op->getOpcode() == ISD::UNDEF) {
5369       // Update the expected vector extract index.
5370       if (i * 2 == NumElts)
5371         ExpectedVExtractIdx = BaseIdx;
5372       ExpectedVExtractIdx += 2;
5373       continue;
5374     }
5375
5376     CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
5377
5378     if (!CanFold)
5379       break;
5380
5381     SDValue Op0 = Op.getOperand(0);
5382     SDValue Op1 = Op.getOperand(1);
5383
5384     // Try to match the following pattern:
5385     // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
5386     CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5387         Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5388         Op0.getOperand(0) == Op1.getOperand(0) &&
5389         isa<ConstantSDNode>(Op0.getOperand(1)) &&
5390         isa<ConstantSDNode>(Op1.getOperand(1)));
5391     if (!CanFold)
5392       break;
5393
5394     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5395     unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
5396
5397     if (i * 2 < NumElts) {
5398       if (V0.getOpcode() == ISD::UNDEF) {
5399         V0 = Op0.getOperand(0);
5400         if (V0.getValueType() != VT)
5401           return false;
5402       }
5403     } else {
5404       if (V1.getOpcode() == ISD::UNDEF) {
5405         V1 = Op0.getOperand(0);
5406         if (V1.getValueType() != VT)
5407           return false;
5408       }
5409       if (i * 2 == NumElts)
5410         ExpectedVExtractIdx = BaseIdx;
5411     }
5412
5413     SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
5414     if (I0 == ExpectedVExtractIdx)
5415       CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
5416     else if (IsCommutable && I1 == ExpectedVExtractIdx) {
5417       // Try to match the following dag sequence:
5418       // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
5419       CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
5420     } else
5421       CanFold = false;
5422
5423     ExpectedVExtractIdx += 2;
5424   }
5425
5426   return CanFold;
5427 }
5428
5429 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
5430 /// a concat_vector.
5431 ///
5432 /// This is a helper function of LowerToHorizontalOp().
5433 /// This function expects two 256-bit vectors called V0 and V1.
5434 /// At first, each vector is split into two separate 128-bit vectors.
5435 /// Then, the resulting 128-bit vectors are used to implement two
5436 /// horizontal binary operations.
5437 ///
5438 /// The kind of horizontal binary operation is defined by \p X86Opcode.
5439 ///
5440 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
5441 /// the two new horizontal binop.
5442 /// When Mode is set, the first horizontal binop dag node would take as input
5443 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
5444 /// horizontal binop dag node would take as input the lower 128-bit of V1
5445 /// and the upper 128-bit of V1.
5446 ///   Example:
5447 ///     HADD V0_LO, V0_HI
5448 ///     HADD V1_LO, V1_HI
5449 ///
5450 /// Otherwise, the first horizontal binop dag node takes as input the lower
5451 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
5452 /// dag node takes the upper 128-bit of V0 and the upper 128-bit of V1.
5453 ///   Example:
5454 ///     HADD V0_LO, V1_LO
5455 ///     HADD V0_HI, V1_HI
5456 ///
5457 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
5458 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
5459 /// the upper 128-bits of the result.
5460 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
5461                                      SDLoc DL, SelectionDAG &DAG,
5462                                      unsigned X86Opcode, bool Mode,
5463                                      bool isUndefLO, bool isUndefHI) {
5464   EVT VT = V0.getValueType();
5465   assert(VT.is256BitVector() && VT == V1.getValueType() &&
5466          "Invalid nodes in input!");
5467
5468   unsigned NumElts = VT.getVectorNumElements();
5469   SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
5470   SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
5471   SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
5472   SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
5473   EVT NewVT = V0_LO.getValueType();
5474
5475   SDValue LO = DAG.getUNDEF(NewVT);
5476   SDValue HI = DAG.getUNDEF(NewVT);
5477
5478   if (Mode) {
5479     // Don't emit a horizontal binop if the result is expected to be UNDEF.
5480     if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
5481       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
5482     if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
5483       HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
5484   } else {
5485     // Don't emit a horizontal binop if the result is expected to be UNDEF.
5486     if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
5487                        V1_LO->getOpcode() != ISD::UNDEF))
5488       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
5489
5490     if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
5491                        V1_HI->getOpcode() != ISD::UNDEF))
5492       HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
5493   }
5494
5495   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
5496 }
5497
5498 /// Try to fold a build_vector that performs an 'addsub' to an X86ISD::ADDSUB
5499 /// node.
5500 static SDValue LowerToAddSub(const BuildVectorSDNode *BV,
5501                              const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5502   EVT VT = BV->getValueType(0);
5503   if ((!Subtarget->hasSSE3() || (VT != MVT::v4f32 && VT != MVT::v2f64)) &&
5504       (!Subtarget->hasAVX() || (VT != MVT::v8f32 && VT != MVT::v4f64)))
5505     return SDValue();
5506
5507   SDLoc DL(BV);
5508   unsigned NumElts = VT.getVectorNumElements();
5509   SDValue InVec0 = DAG.getUNDEF(VT);
5510   SDValue InVec1 = DAG.getUNDEF(VT);
5511
5512   assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
5513           VT == MVT::v2f64) && "build_vector with an invalid type found!");
5514
5515   // Odd-numbered elements in the input build vector are obtained from
5516   // adding two integer/float elements.
5517   // Even-numbered elements in the input build vector are obtained from
5518   // subtracting two integer/float elements.
5519   unsigned ExpectedOpcode = ISD::FSUB;
5520   unsigned NextExpectedOpcode = ISD::FADD;
5521   bool AddFound = false;
5522   bool SubFound = false;
5523
5524   for (unsigned i = 0, e = NumElts; i != e; ++i) {
5525     SDValue Op = BV->getOperand(i);
5526
5527     // Skip 'undef' values.
5528     unsigned Opcode = Op.getOpcode();
5529     if (Opcode == ISD::UNDEF) {
5530       std::swap(ExpectedOpcode, NextExpectedOpcode);
5531       continue;
5532     }
5533
5534     // Early exit if we found an unexpected opcode.
5535     if (Opcode != ExpectedOpcode)
5536       return SDValue();
5537
5538     SDValue Op0 = Op.getOperand(0);
5539     SDValue Op1 = Op.getOperand(1);
5540
5541     // Try to match the following pattern:
5542     // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
5543     // Early exit if we cannot match that sequence.
5544     if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5545         Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5546         !isa<ConstantSDNode>(Op0.getOperand(1)) ||
5547         !isa<ConstantSDNode>(Op1.getOperand(1)) ||
5548         Op0.getOperand(1) != Op1.getOperand(1))
5549       return SDValue();
5550
5551     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5552     if (I0 != i)
5553       return SDValue();
5554
5555     // We found a valid add/sub node. Update the information accordingly.
5556     if (i & 1)
5557       AddFound = true;
5558     else
5559       SubFound = true;
5560
5561     // Update InVec0 and InVec1.
5562     if (InVec0.getOpcode() == ISD::UNDEF) {
5563       InVec0 = Op0.getOperand(0);
5564       if (InVec0.getValueType() != VT)
5565         return SDValue();
5566     }
5567     if (InVec1.getOpcode() == ISD::UNDEF) {
5568       InVec1 = Op1.getOperand(0);
5569       if (InVec1.getValueType() != VT)
5570         return SDValue();
5571     }
5572
5573     // Make sure that operands in input to each add/sub node always
5574     // come from a same pair of vectors.
5575     if (InVec0 != Op0.getOperand(0)) {
5576       if (ExpectedOpcode == ISD::FSUB)
5577         return SDValue();
5578
5579       // FADD is commutable. Try to commute the operands
5580       // and then test again.
5581       std::swap(Op0, Op1);
5582       if (InVec0 != Op0.getOperand(0))
5583         return SDValue();
5584     }
5585
5586     if (InVec1 != Op1.getOperand(0))
5587       return SDValue();
5588
5589     // Update the pair of expected opcodes.
5590     std::swap(ExpectedOpcode, NextExpectedOpcode);
5591   }
5592
5593   // Don't try to fold this build_vector into an ADDSUB if the inputs are undef.
5594   if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
5595       InVec1.getOpcode() != ISD::UNDEF)
5596     return DAG.getNode(X86ISD::ADDSUB, DL, VT, InVec0, InVec1);
5597
5598   return SDValue();
5599 }
5600
5601 /// Lower BUILD_VECTOR to a horizontal add/sub operation if possible.
5602 static SDValue LowerToHorizontalOp(const BuildVectorSDNode *BV,
5603                                    const X86Subtarget *Subtarget,
5604                                    SelectionDAG &DAG) {
5605   EVT VT = BV->getValueType(0);
5606   unsigned NumElts = VT.getVectorNumElements();
5607   unsigned NumUndefsLO = 0;
5608   unsigned NumUndefsHI = 0;
5609   unsigned Half = NumElts/2;
5610
5611   // Count the number of UNDEF operands in the build_vector in input.
5612   for (unsigned i = 0, e = Half; i != e; ++i)
5613     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5614       NumUndefsLO++;
5615
5616   for (unsigned i = Half, e = NumElts; i != e; ++i)
5617     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5618       NumUndefsHI++;
5619
5620   // Early exit if this is either a build_vector of all UNDEFs or all the
5621   // operands but one are UNDEF.
5622   if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
5623     return SDValue();
5624
5625   SDLoc DL(BV);
5626   SDValue InVec0, InVec1;
5627   if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
5628     // Try to match an SSE3 float HADD/HSUB.
5629     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5630       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5631
5632     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5633       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5634   } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
5635     // Try to match an SSSE3 integer HADD/HSUB.
5636     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5637       return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
5638
5639     if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5640       return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
5641   }
5642
5643   if (!Subtarget->hasAVX())
5644     return SDValue();
5645
5646   if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
5647     // Try to match an AVX horizontal add/sub of packed single/double
5648     // precision floating point values from 256-bit vectors.
5649     SDValue InVec2, InVec3;
5650     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
5651         isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
5652         ((InVec0.getOpcode() == ISD::UNDEF ||
5653           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5654         ((InVec1.getOpcode() == ISD::UNDEF ||
5655           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5656       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5657
5658     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
5659         isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
5660         ((InVec0.getOpcode() == ISD::UNDEF ||
5661           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5662         ((InVec1.getOpcode() == ISD::UNDEF ||
5663           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5664       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5665   } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
5666     // Try to match an AVX2 horizontal add/sub of signed integers.
5667     SDValue InVec2, InVec3;
5668     unsigned X86Opcode;
5669     bool CanFold = true;
5670
5671     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
5672         isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
5673         ((InVec0.getOpcode() == ISD::UNDEF ||
5674           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5675         ((InVec1.getOpcode() == ISD::UNDEF ||
5676           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5677       X86Opcode = X86ISD::HADD;
5678     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
5679         isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
5680         ((InVec0.getOpcode() == ISD::UNDEF ||
5681           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5682         ((InVec1.getOpcode() == ISD::UNDEF ||
5683           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5684       X86Opcode = X86ISD::HSUB;
5685     else
5686       CanFold = false;
5687
5688     if (CanFold) {
5689       // Fold this build_vector into a single horizontal add/sub.
5690       // Do this only if the target has AVX2.
5691       if (Subtarget->hasAVX2())
5692         return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
5693
5694       // Do not try to expand this build_vector into a pair of horizontal
5695       // add/sub if we can emit a pair of scalar add/sub.
5696       if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5697         return SDValue();
5698
5699       // Convert this build_vector into a pair of horizontal binop followed by
5700       // a concat vector.
5701       bool isUndefLO = NumUndefsLO == Half;
5702       bool isUndefHI = NumUndefsHI == Half;
5703       return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
5704                                    isUndefLO, isUndefHI);
5705     }
5706   }
5707
5708   if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
5709        VT == MVT::v16i16) && Subtarget->hasAVX()) {
5710     unsigned X86Opcode;
5711     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5712       X86Opcode = X86ISD::HADD;
5713     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5714       X86Opcode = X86ISD::HSUB;
5715     else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5716       X86Opcode = X86ISD::FHADD;
5717     else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5718       X86Opcode = X86ISD::FHSUB;
5719     else
5720       return SDValue();
5721
5722     // Don't try to expand this build_vector into a pair of horizontal add/sub
5723     // if we can simply emit a pair of scalar add/sub.
5724     if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5725       return SDValue();
5726
5727     // Convert this build_vector into two horizontal add/sub followed by
5728     // a concat vector.
5729     bool isUndefLO = NumUndefsLO == Half;
5730     bool isUndefHI = NumUndefsHI == Half;
5731     return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
5732                                  isUndefLO, isUndefHI);
5733   }
5734
5735   return SDValue();
5736 }
5737
5738 SDValue
5739 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5740   SDLoc dl(Op);
5741
5742   MVT VT = Op.getSimpleValueType();
5743   MVT ExtVT = VT.getVectorElementType();
5744   unsigned NumElems = Op.getNumOperands();
5745
5746   // Generate vectors for predicate vectors.
5747   if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
5748     return LowerBUILD_VECTORvXi1(Op, DAG);
5749
5750   // Vectors containing all zeros can be matched by pxor and xorps later
5751   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5752     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5753     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5754     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
5755       return Op;
5756
5757     return getZeroVector(VT, Subtarget, DAG, dl);
5758   }
5759
5760   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5761   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5762   // vpcmpeqd on 256-bit vectors.
5763   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5764     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5765       return Op;
5766
5767     if (!VT.is512BitVector())
5768       return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5769   }
5770
5771   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(Op.getNode());
5772   if (SDValue AddSub = LowerToAddSub(BV, Subtarget, DAG))
5773     return AddSub;
5774   if (SDValue HorizontalOp = LowerToHorizontalOp(BV, Subtarget, DAG))
5775     return HorizontalOp;
5776   if (SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG))
5777     return Broadcast;
5778
5779   unsigned EVTBits = ExtVT.getSizeInBits();
5780
5781   unsigned NumZero  = 0;
5782   unsigned NumNonZero = 0;
5783   unsigned NonZeros = 0;
5784   bool IsAllConstants = true;
5785   SmallSet<SDValue, 8> Values;
5786   for (unsigned i = 0; i < NumElems; ++i) {
5787     SDValue Elt = Op.getOperand(i);
5788     if (Elt.getOpcode() == ISD::UNDEF)
5789       continue;
5790     Values.insert(Elt);
5791     if (Elt.getOpcode() != ISD::Constant &&
5792         Elt.getOpcode() != ISD::ConstantFP)
5793       IsAllConstants = false;
5794     if (X86::isZeroNode(Elt))
5795       NumZero++;
5796     else {
5797       NonZeros |= (1 << i);
5798       NumNonZero++;
5799     }
5800   }
5801
5802   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5803   if (NumNonZero == 0)
5804     return DAG.getUNDEF(VT);
5805
5806   // Special case for single non-zero, non-undef, element.
5807   if (NumNonZero == 1) {
5808     unsigned Idx = countTrailingZeros(NonZeros);
5809     SDValue Item = Op.getOperand(Idx);
5810
5811     // If this is an insertion of an i64 value on x86-32, and if the top bits of
5812     // the value are obviously zero, truncate the value to i32 and do the
5813     // insertion that way.  Only do this if the value is non-constant or if the
5814     // value is a constant being inserted into element 0.  It is cheaper to do
5815     // a constant pool load than it is to do a movd + shuffle.
5816     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5817         (!IsAllConstants || Idx == 0)) {
5818       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5819         // Handle SSE only.
5820         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5821         EVT VecVT = MVT::v4i32;
5822
5823         // Truncate the value (which may itself be a constant) to i32, and
5824         // convert it to a vector with movd (S2V+shuffle to zero extend).
5825         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5826         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5827         return DAG.getBitcast(VT, getShuffleVectorZeroOrUndef(
5828                                       Item, Idx * 2, true, Subtarget, DAG));
5829       }
5830     }
5831
5832     // If we have a constant or non-constant insertion into the low element of
5833     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5834     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5835     // depending on what the source datatype is.
5836     if (Idx == 0) {
5837       if (NumZero == 0)
5838         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5839
5840       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5841           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5842         if (VT.is512BitVector()) {
5843           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5844           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5845                              Item, DAG.getIntPtrConstant(0, dl));
5846         }
5847         assert((VT.is128BitVector() || VT.is256BitVector()) &&
5848                "Expected an SSE value type!");
5849         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5850         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5851         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5852       }
5853
5854       // We can't directly insert an i8 or i16 into a vector, so zero extend
5855       // it to i32 first.
5856       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5857         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5858         if (VT.is256BitVector()) {
5859           if (Subtarget->hasAVX()) {
5860             Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v8i32, Item);
5861             Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5862           } else {
5863             // Without AVX, we need to extend to a 128-bit vector and then
5864             // insert into the 256-bit vector.
5865             Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5866             SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5867             Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5868           }
5869         } else {
5870           assert(VT.is128BitVector() && "Expected an SSE value type!");
5871           Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5872           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5873         }
5874         return DAG.getBitcast(VT, Item);
5875       }
5876     }
5877
5878     // Is it a vector logical left shift?
5879     if (NumElems == 2 && Idx == 1 &&
5880         X86::isZeroNode(Op.getOperand(0)) &&
5881         !X86::isZeroNode(Op.getOperand(1))) {
5882       unsigned NumBits = VT.getSizeInBits();
5883       return getVShift(true, VT,
5884                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5885                                    VT, Op.getOperand(1)),
5886                        NumBits/2, DAG, *this, dl);
5887     }
5888
5889     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5890       return SDValue();
5891
5892     // Otherwise, if this is a vector with i32 or f32 elements, and the element
5893     // is a non-constant being inserted into an element other than the low one,
5894     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
5895     // movd/movss) to move this into the low element, then shuffle it into
5896     // place.
5897     if (EVTBits == 32) {
5898       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5899       return getShuffleVectorZeroOrUndef(Item, Idx, NumZero > 0, Subtarget, DAG);
5900     }
5901   }
5902
5903   // Splat is obviously ok. Let legalizer expand it to a shuffle.
5904   if (Values.size() == 1) {
5905     if (EVTBits == 32) {
5906       // Instead of a shuffle like this:
5907       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5908       // Check if it's possible to issue this instead.
5909       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5910       unsigned Idx = countTrailingZeros(NonZeros);
5911       SDValue Item = Op.getOperand(Idx);
5912       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5913         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5914     }
5915     return SDValue();
5916   }
5917
5918   // A vector full of immediates; various special cases are already
5919   // handled, so this is best done with a single constant-pool load.
5920   if (IsAllConstants)
5921     return SDValue();
5922
5923   // For AVX-length vectors, see if we can use a vector load to get all of the
5924   // elements, otherwise build the individual 128-bit pieces and use
5925   // shuffles to put them in place.
5926   if (VT.is256BitVector() || VT.is512BitVector()) {
5927     SmallVector<SDValue, 64> V(Op->op_begin(), Op->op_begin() + NumElems);
5928
5929     // Check for a build vector of consecutive loads.
5930     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
5931       return LD;
5932
5933     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5934
5935     // Build both the lower and upper subvector.
5936     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
5937                                 makeArrayRef(&V[0], NumElems/2));
5938     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
5939                                 makeArrayRef(&V[NumElems / 2], NumElems/2));
5940
5941     // Recreate the wider vector with the lower and upper part.
5942     if (VT.is256BitVector())
5943       return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5944     return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5945   }
5946
5947   // Let legalizer expand 2-wide build_vectors.
5948   if (EVTBits == 64) {
5949     if (NumNonZero == 1) {
5950       // One half is zero or undef.
5951       unsigned Idx = countTrailingZeros(NonZeros);
5952       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5953                                  Op.getOperand(Idx));
5954       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
5955     }
5956     return SDValue();
5957   }
5958
5959   // If element VT is < 32 bits, convert it to inserts into a zero vector.
5960   if (EVTBits == 8 && NumElems == 16)
5961     if (SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5962                                         Subtarget, *this))
5963       return V;
5964
5965   if (EVTBits == 16 && NumElems == 8)
5966     if (SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5967                                       Subtarget, *this))
5968       return V;
5969
5970   // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
5971   if (EVTBits == 32 && NumElems == 4)
5972     if (SDValue V = LowerBuildVectorv4x32(Op, DAG, Subtarget, *this))
5973       return V;
5974
5975   // If element VT is == 32 bits, turn it into a number of shuffles.
5976   SmallVector<SDValue, 8> V(NumElems);
5977   if (NumElems == 4 && NumZero > 0) {
5978     for (unsigned i = 0; i < 4; ++i) {
5979       bool isZero = !(NonZeros & (1 << i));
5980       if (isZero)
5981         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
5982       else
5983         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5984     }
5985
5986     for (unsigned i = 0; i < 2; ++i) {
5987       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5988         default: break;
5989         case 0:
5990           V[i] = V[i*2];  // Must be a zero vector.
5991           break;
5992         case 1:
5993           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5994           break;
5995         case 2:
5996           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5997           break;
5998         case 3:
5999           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6000           break;
6001       }
6002     }
6003
6004     bool Reverse1 = (NonZeros & 0x3) == 2;
6005     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6006     int MaskVec[] = {
6007       Reverse1 ? 1 : 0,
6008       Reverse1 ? 0 : 1,
6009       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6010       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
6011     };
6012     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6013   }
6014
6015   if (Values.size() > 1 && VT.is128BitVector()) {
6016     // Check for a build vector of consecutive loads.
6017     for (unsigned i = 0; i < NumElems; ++i)
6018       V[i] = Op.getOperand(i);
6019
6020     // Check for elements which are consecutive loads.
6021     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6022       return LD;
6023
6024     // Check for a build vector from mostly shuffle plus few inserting.
6025     if (SDValue Sh = buildFromShuffleMostly(Op, DAG))
6026       return Sh;
6027
6028     // For SSE 4.1, use insertps to put the high elements into the low element.
6029     if (Subtarget->hasSSE41()) {
6030       SDValue Result;
6031       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6032         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6033       else
6034         Result = DAG.getUNDEF(VT);
6035
6036       for (unsigned i = 1; i < NumElems; ++i) {
6037         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6038         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6039                              Op.getOperand(i), DAG.getIntPtrConstant(i, dl));
6040       }
6041       return Result;
6042     }
6043
6044     // Otherwise, expand into a number of unpckl*, start by extending each of
6045     // our (non-undef) elements to the full vector width with the element in the
6046     // bottom slot of the vector (which generates no code for SSE).
6047     for (unsigned i = 0; i < NumElems; ++i) {
6048       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6049         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6050       else
6051         V[i] = DAG.getUNDEF(VT);
6052     }
6053
6054     // Next, we iteratively mix elements, e.g. for v4f32:
6055     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6056     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6057     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
6058     unsigned EltStride = NumElems >> 1;
6059     while (EltStride != 0) {
6060       for (unsigned i = 0; i < EltStride; ++i) {
6061         // If V[i+EltStride] is undef and this is the first round of mixing,
6062         // then it is safe to just drop this shuffle: V[i] is already in the
6063         // right place, the one element (since it's the first round) being
6064         // inserted as undef can be dropped.  This isn't safe for successive
6065         // rounds because they will permute elements within both vectors.
6066         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6067             EltStride == NumElems/2)
6068           continue;
6069
6070         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6071       }
6072       EltStride >>= 1;
6073     }
6074     return V[0];
6075   }
6076   return SDValue();
6077 }
6078
6079 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6080 // to create 256-bit vectors from two other 128-bit ones.
6081 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6082   SDLoc dl(Op);
6083   MVT ResVT = Op.getSimpleValueType();
6084
6085   assert((ResVT.is256BitVector() ||
6086           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6087
6088   SDValue V1 = Op.getOperand(0);
6089   SDValue V2 = Op.getOperand(1);
6090   unsigned NumElems = ResVT.getVectorNumElements();
6091   if (ResVT.is256BitVector())
6092     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6093
6094   if (Op.getNumOperands() == 4) {
6095     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6096                                 ResVT.getVectorNumElements()/2);
6097     SDValue V3 = Op.getOperand(2);
6098     SDValue V4 = Op.getOperand(3);
6099     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6100       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6101   }
6102   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6103 }
6104
6105 static SDValue LowerCONCAT_VECTORSvXi1(SDValue Op,
6106                                        const X86Subtarget *Subtarget,
6107                                        SelectionDAG & DAG) {
6108   SDLoc dl(Op);
6109   MVT ResVT = Op.getSimpleValueType();
6110   unsigned NumOfOperands = Op.getNumOperands();
6111
6112   assert(isPowerOf2_32(NumOfOperands) &&
6113          "Unexpected number of operands in CONCAT_VECTORS");
6114
6115   if (NumOfOperands > 2) {
6116     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6117                                   ResVT.getVectorNumElements()/2);
6118     SmallVector<SDValue, 2> Ops;
6119     for (unsigned i = 0; i < NumOfOperands/2; i++)
6120       Ops.push_back(Op.getOperand(i));
6121     SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6122     Ops.clear();
6123     for (unsigned i = NumOfOperands/2; i < NumOfOperands; i++)
6124       Ops.push_back(Op.getOperand(i));
6125     SDValue Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6126     return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Lo, Hi);
6127   }
6128
6129   SDValue V1 = Op.getOperand(0);
6130   SDValue V2 = Op.getOperand(1);
6131   bool IsZeroV1 = ISD::isBuildVectorAllZeros(V1.getNode());
6132   bool IsZeroV2 = ISD::isBuildVectorAllZeros(V2.getNode());
6133
6134   if (IsZeroV1 && IsZeroV2)
6135     return getZeroVector(ResVT, Subtarget, DAG, dl);
6136
6137   SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
6138   SDValue Undef = DAG.getUNDEF(ResVT);
6139   unsigned NumElems = ResVT.getVectorNumElements();
6140   SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
6141
6142   V2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V2, ZeroIdx);
6143   V2 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V2, ShiftBits);
6144   if (IsZeroV1)
6145     return V2;
6146
6147   V1 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V1, ZeroIdx);
6148   // Zero the upper bits of V1
6149   V1 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V1, ShiftBits);
6150   V1 = DAG.getNode(X86ISD::VSRLI, dl, ResVT, V1, ShiftBits);
6151   if (IsZeroV2)
6152     return V1;
6153   return DAG.getNode(ISD::OR, dl, ResVT, V1, V2);
6154 }
6155
6156 static SDValue LowerCONCAT_VECTORS(SDValue Op,
6157                                    const X86Subtarget *Subtarget,
6158                                    SelectionDAG &DAG) {
6159   MVT VT = Op.getSimpleValueType();
6160   if (VT.getVectorElementType() == MVT::i1)
6161     return LowerCONCAT_VECTORSvXi1(Op, Subtarget, DAG);
6162
6163   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6164          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6165           Op.getNumOperands() == 4)));
6166
6167   // AVX can use the vinsertf128 instruction to create 256-bit vectors
6168   // from two other 128-bit ones.
6169
6170   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6171   return LowerAVXCONCAT_VECTORS(Op, DAG);
6172 }
6173
6174
6175 //===----------------------------------------------------------------------===//
6176 // Vector shuffle lowering
6177 //
6178 // This is an experimental code path for lowering vector shuffles on x86. It is
6179 // designed to handle arbitrary vector shuffles and blends, gracefully
6180 // degrading performance as necessary. It works hard to recognize idiomatic
6181 // shuffles and lower them to optimal instruction patterns without leaving
6182 // a framework that allows reasonably efficient handling of all vector shuffle
6183 // patterns.
6184 //===----------------------------------------------------------------------===//
6185
6186 /// \brief Tiny helper function to identify a no-op mask.
6187 ///
6188 /// This is a somewhat boring predicate function. It checks whether the mask
6189 /// array input, which is assumed to be a single-input shuffle mask of the kind
6190 /// used by the X86 shuffle instructions (not a fully general
6191 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
6192 /// in-place shuffle are 'no-op's.
6193 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
6194   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6195     if (Mask[i] != -1 && Mask[i] != i)
6196       return false;
6197   return true;
6198 }
6199
6200 /// \brief Helper function to classify a mask as a single-input mask.
6201 ///
6202 /// This isn't a generic single-input test because in the vector shuffle
6203 /// lowering we canonicalize single inputs to be the first input operand. This
6204 /// means we can more quickly test for a single input by only checking whether
6205 /// an input from the second operand exists. We also assume that the size of
6206 /// mask corresponds to the size of the input vectors which isn't true in the
6207 /// fully general case.
6208 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
6209   for (int M : Mask)
6210     if (M >= (int)Mask.size())
6211       return false;
6212   return true;
6213 }
6214
6215 /// \brief Test whether there are elements crossing 128-bit lanes in this
6216 /// shuffle mask.
6217 ///
6218 /// X86 divides up its shuffles into in-lane and cross-lane shuffle operations
6219 /// and we routinely test for these.
6220 static bool is128BitLaneCrossingShuffleMask(MVT VT, ArrayRef<int> Mask) {
6221   int LaneSize = 128 / VT.getScalarSizeInBits();
6222   int Size = Mask.size();
6223   for (int i = 0; i < Size; ++i)
6224     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
6225       return true;
6226   return false;
6227 }
6228
6229 /// \brief Test whether a shuffle mask is equivalent within each 128-bit lane.
6230 ///
6231 /// This checks a shuffle mask to see if it is performing the same
6232 /// 128-bit lane-relative shuffle in each 128-bit lane. This trivially implies
6233 /// that it is also not lane-crossing. It may however involve a blend from the
6234 /// same lane of a second vector.
6235 ///
6236 /// The specific repeated shuffle mask is populated in \p RepeatedMask, as it is
6237 /// non-trivial to compute in the face of undef lanes. The representation is
6238 /// *not* suitable for use with existing 128-bit shuffles as it will contain
6239 /// entries from both V1 and V2 inputs to the wider mask.
6240 static bool
6241 is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
6242                                 SmallVectorImpl<int> &RepeatedMask) {
6243   int LaneSize = 128 / VT.getScalarSizeInBits();
6244   RepeatedMask.resize(LaneSize, -1);
6245   int Size = Mask.size();
6246   for (int i = 0; i < Size; ++i) {
6247     if (Mask[i] < 0)
6248       continue;
6249     if ((Mask[i] % Size) / LaneSize != i / LaneSize)
6250       // This entry crosses lanes, so there is no way to model this shuffle.
6251       return false;
6252
6253     // Ok, handle the in-lane shuffles by detecting if and when they repeat.
6254     if (RepeatedMask[i % LaneSize] == -1)
6255       // This is the first non-undef entry in this slot of a 128-bit lane.
6256       RepeatedMask[i % LaneSize] =
6257           Mask[i] < Size ? Mask[i] % LaneSize : Mask[i] % LaneSize + Size;
6258     else if (RepeatedMask[i % LaneSize] + (i / LaneSize) * LaneSize != Mask[i])
6259       // Found a mismatch with the repeated mask.
6260       return false;
6261   }
6262   return true;
6263 }
6264
6265 /// \brief Checks whether a shuffle mask is equivalent to an explicit list of
6266 /// arguments.
6267 ///
6268 /// This is a fast way to test a shuffle mask against a fixed pattern:
6269 ///
6270 ///   if (isShuffleEquivalent(Mask, 3, 2, {1, 0})) { ... }
6271 ///
6272 /// It returns true if the mask is exactly as wide as the argument list, and
6273 /// each element of the mask is either -1 (signifying undef) or the value given
6274 /// in the argument.
6275 static bool isShuffleEquivalent(SDValue V1, SDValue V2, ArrayRef<int> Mask,
6276                                 ArrayRef<int> ExpectedMask) {
6277   if (Mask.size() != ExpectedMask.size())
6278     return false;
6279
6280   int Size = Mask.size();
6281
6282   // If the values are build vectors, we can look through them to find
6283   // equivalent inputs that make the shuffles equivalent.
6284   auto *BV1 = dyn_cast<BuildVectorSDNode>(V1);
6285   auto *BV2 = dyn_cast<BuildVectorSDNode>(V2);
6286
6287   for (int i = 0; i < Size; ++i)
6288     if (Mask[i] != -1 && Mask[i] != ExpectedMask[i]) {
6289       auto *MaskBV = Mask[i] < Size ? BV1 : BV2;
6290       auto *ExpectedBV = ExpectedMask[i] < Size ? BV1 : BV2;
6291       if (!MaskBV || !ExpectedBV ||
6292           MaskBV->getOperand(Mask[i] % Size) !=
6293               ExpectedBV->getOperand(ExpectedMask[i] % Size))
6294         return false;
6295     }
6296
6297   return true;
6298 }
6299
6300 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
6301 ///
6302 /// This helper function produces an 8-bit shuffle immediate corresponding to
6303 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
6304 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
6305 /// example.
6306 ///
6307 /// NB: We rely heavily on "undef" masks preserving the input lane.
6308 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask, SDLoc DL,
6309                                           SelectionDAG &DAG) {
6310   assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
6311   assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
6312   assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
6313   assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
6314   assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
6315
6316   unsigned Imm = 0;
6317   Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
6318   Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
6319   Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
6320   Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
6321   return DAG.getConstant(Imm, DL, MVT::i8);
6322 }
6323
6324 /// \brief Try to emit a blend instruction for a shuffle using bit math.
6325 ///
6326 /// This is used as a fallback approach when first class blend instructions are
6327 /// unavailable. Currently it is only suitable for integer vectors, but could
6328 /// be generalized for floating point vectors if desirable.
6329 static SDValue lowerVectorShuffleAsBitBlend(SDLoc DL, MVT VT, SDValue V1,
6330                                             SDValue V2, ArrayRef<int> Mask,
6331                                             SelectionDAG &DAG) {
6332   assert(VT.isInteger() && "Only supports integer vector types!");
6333   MVT EltVT = VT.getScalarType();
6334   int NumEltBits = EltVT.getSizeInBits();
6335   SDValue Zero = DAG.getConstant(0, DL, EltVT);
6336   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6337                                     EltVT);
6338   SmallVector<SDValue, 16> MaskOps;
6339   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6340     if (Mask[i] != -1 && Mask[i] != i && Mask[i] != i + Size)
6341       return SDValue(); // Shuffled input!
6342     MaskOps.push_back(Mask[i] < Size ? AllOnes : Zero);
6343   }
6344
6345   SDValue V1Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, MaskOps);
6346   V1 = DAG.getNode(ISD::AND, DL, VT, V1, V1Mask);
6347   // We have to cast V2 around.
6348   MVT MaskVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
6349   V2 = DAG.getBitcast(VT, DAG.getNode(X86ISD::ANDNP, DL, MaskVT,
6350                                       DAG.getBitcast(MaskVT, V1Mask),
6351                                       DAG.getBitcast(MaskVT, V2)));
6352   return DAG.getNode(ISD::OR, DL, VT, V1, V2);
6353 }
6354
6355 /// \brief Try to emit a blend instruction for a shuffle.
6356 ///
6357 /// This doesn't do any checks for the availability of instructions for blending
6358 /// these values. It relies on the availability of the X86ISD::BLENDI pattern to
6359 /// be matched in the backend with the type given. What it does check for is
6360 /// that the shuffle mask is in fact a blend.
6361 static SDValue lowerVectorShuffleAsBlend(SDLoc DL, MVT VT, SDValue V1,
6362                                          SDValue V2, ArrayRef<int> Mask,
6363                                          const X86Subtarget *Subtarget,
6364                                          SelectionDAG &DAG) {
6365   unsigned BlendMask = 0;
6366   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6367     if (Mask[i] >= Size) {
6368       if (Mask[i] != i + Size)
6369         return SDValue(); // Shuffled V2 input!
6370       BlendMask |= 1u << i;
6371       continue;
6372     }
6373     if (Mask[i] >= 0 && Mask[i] != i)
6374       return SDValue(); // Shuffled V1 input!
6375   }
6376   switch (VT.SimpleTy) {
6377   case MVT::v2f64:
6378   case MVT::v4f32:
6379   case MVT::v4f64:
6380   case MVT::v8f32:
6381     return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V2,
6382                        DAG.getConstant(BlendMask, DL, MVT::i8));
6383
6384   case MVT::v4i64:
6385   case MVT::v8i32:
6386     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6387     // FALLTHROUGH
6388   case MVT::v2i64:
6389   case MVT::v4i32:
6390     // If we have AVX2 it is faster to use VPBLENDD when the shuffle fits into
6391     // that instruction.
6392     if (Subtarget->hasAVX2()) {
6393       // Scale the blend by the number of 32-bit dwords per element.
6394       int Scale =  VT.getScalarSizeInBits() / 32;
6395       BlendMask = 0;
6396       for (int i = 0, Size = Mask.size(); i < Size; ++i)
6397         if (Mask[i] >= Size)
6398           for (int j = 0; j < Scale; ++j)
6399             BlendMask |= 1u << (i * Scale + j);
6400
6401       MVT BlendVT = VT.getSizeInBits() > 128 ? MVT::v8i32 : MVT::v4i32;
6402       V1 = DAG.getBitcast(BlendVT, V1);
6403       V2 = DAG.getBitcast(BlendVT, V2);
6404       return DAG.getBitcast(
6405           VT, DAG.getNode(X86ISD::BLENDI, DL, BlendVT, V1, V2,
6406                           DAG.getConstant(BlendMask, DL, MVT::i8)));
6407     }
6408     // FALLTHROUGH
6409   case MVT::v8i16: {
6410     // For integer shuffles we need to expand the mask and cast the inputs to
6411     // v8i16s prior to blending.
6412     int Scale = 8 / VT.getVectorNumElements();
6413     BlendMask = 0;
6414     for (int i = 0, Size = Mask.size(); i < Size; ++i)
6415       if (Mask[i] >= Size)
6416         for (int j = 0; j < Scale; ++j)
6417           BlendMask |= 1u << (i * Scale + j);
6418
6419     V1 = DAG.getBitcast(MVT::v8i16, V1);
6420     V2 = DAG.getBitcast(MVT::v8i16, V2);
6421     return DAG.getBitcast(VT,
6422                           DAG.getNode(X86ISD::BLENDI, DL, MVT::v8i16, V1, V2,
6423                                       DAG.getConstant(BlendMask, DL, MVT::i8)));
6424   }
6425
6426   case MVT::v16i16: {
6427     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6428     SmallVector<int, 8> RepeatedMask;
6429     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
6430       // We can lower these with PBLENDW which is mirrored across 128-bit lanes.
6431       assert(RepeatedMask.size() == 8 && "Repeated mask size doesn't match!");
6432       BlendMask = 0;
6433       for (int i = 0; i < 8; ++i)
6434         if (RepeatedMask[i] >= 16)
6435           BlendMask |= 1u << i;
6436       return DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
6437                          DAG.getConstant(BlendMask, DL, MVT::i8));
6438     }
6439   }
6440     // FALLTHROUGH
6441   case MVT::v16i8:
6442   case MVT::v32i8: {
6443     assert((VT.getSizeInBits() == 128 || Subtarget->hasAVX2()) &&
6444            "256-bit byte-blends require AVX2 support!");
6445
6446     // Scale the blend by the number of bytes per element.
6447     int Scale = VT.getScalarSizeInBits() / 8;
6448
6449     // This form of blend is always done on bytes. Compute the byte vector
6450     // type.
6451     MVT BlendVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
6452
6453     // Compute the VSELECT mask. Note that VSELECT is really confusing in the
6454     // mix of LLVM's code generator and the x86 backend. We tell the code
6455     // generator that boolean values in the elements of an x86 vector register
6456     // are -1 for true and 0 for false. We then use the LLVM semantics of 'true'
6457     // mapping a select to operand #1, and 'false' mapping to operand #2. The
6458     // reality in x86 is that vector masks (pre-AVX-512) use only the high bit
6459     // of the element (the remaining are ignored) and 0 in that high bit would
6460     // mean operand #1 while 1 in the high bit would mean operand #2. So while
6461     // the LLVM model for boolean values in vector elements gets the relevant
6462     // bit set, it is set backwards and over constrained relative to x86's
6463     // actual model.
6464     SmallVector<SDValue, 32> VSELECTMask;
6465     for (int i = 0, Size = Mask.size(); i < Size; ++i)
6466       for (int j = 0; j < Scale; ++j)
6467         VSELECTMask.push_back(
6468             Mask[i] < 0 ? DAG.getUNDEF(MVT::i8)
6469                         : DAG.getConstant(Mask[i] < Size ? -1 : 0, DL,
6470                                           MVT::i8));
6471
6472     V1 = DAG.getBitcast(BlendVT, V1);
6473     V2 = DAG.getBitcast(BlendVT, V2);
6474     return DAG.getBitcast(VT, DAG.getNode(ISD::VSELECT, DL, BlendVT,
6475                                           DAG.getNode(ISD::BUILD_VECTOR, DL,
6476                                                       BlendVT, VSELECTMask),
6477                                           V1, V2));
6478   }
6479
6480   default:
6481     llvm_unreachable("Not a supported integer vector type!");
6482   }
6483 }
6484
6485 /// \brief Try to lower as a blend of elements from two inputs followed by
6486 /// a single-input permutation.
6487 ///
6488 /// This matches the pattern where we can blend elements from two inputs and
6489 /// then reduce the shuffle to a single-input permutation.
6490 static SDValue lowerVectorShuffleAsBlendAndPermute(SDLoc DL, MVT VT, SDValue V1,
6491                                                    SDValue V2,
6492                                                    ArrayRef<int> Mask,
6493                                                    SelectionDAG &DAG) {
6494   // We build up the blend mask while checking whether a blend is a viable way
6495   // to reduce the shuffle.
6496   SmallVector<int, 32> BlendMask(Mask.size(), -1);
6497   SmallVector<int, 32> PermuteMask(Mask.size(), -1);
6498
6499   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6500     if (Mask[i] < 0)
6501       continue;
6502
6503     assert(Mask[i] < Size * 2 && "Shuffle input is out of bounds.");
6504
6505     if (BlendMask[Mask[i] % Size] == -1)
6506       BlendMask[Mask[i] % Size] = Mask[i];
6507     else if (BlendMask[Mask[i] % Size] != Mask[i])
6508       return SDValue(); // Can't blend in the needed input!
6509
6510     PermuteMask[i] = Mask[i] % Size;
6511   }
6512
6513   SDValue V = DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6514   return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), PermuteMask);
6515 }
6516
6517 /// \brief Generic routine to decompose a shuffle and blend into indepndent
6518 /// blends and permutes.
6519 ///
6520 /// This matches the extremely common pattern for handling combined
6521 /// shuffle+blend operations on newer X86 ISAs where we have very fast blend
6522 /// operations. It will try to pick the best arrangement of shuffles and
6523 /// blends.
6524 static SDValue lowerVectorShuffleAsDecomposedShuffleBlend(SDLoc DL, MVT VT,
6525                                                           SDValue V1,
6526                                                           SDValue V2,
6527                                                           ArrayRef<int> Mask,
6528                                                           SelectionDAG &DAG) {
6529   // Shuffle the input elements into the desired positions in V1 and V2 and
6530   // blend them together.
6531   SmallVector<int, 32> V1Mask(Mask.size(), -1);
6532   SmallVector<int, 32> V2Mask(Mask.size(), -1);
6533   SmallVector<int, 32> BlendMask(Mask.size(), -1);
6534   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6535     if (Mask[i] >= 0 && Mask[i] < Size) {
6536       V1Mask[i] = Mask[i];
6537       BlendMask[i] = i;
6538     } else if (Mask[i] >= Size) {
6539       V2Mask[i] = Mask[i] - Size;
6540       BlendMask[i] = i + Size;
6541     }
6542
6543   // Try to lower with the simpler initial blend strategy unless one of the
6544   // input shuffles would be a no-op. We prefer to shuffle inputs as the
6545   // shuffle may be able to fold with a load or other benefit. However, when
6546   // we'll have to do 2x as many shuffles in order to achieve this, blending
6547   // first is a better strategy.
6548   if (!isNoopShuffleMask(V1Mask) && !isNoopShuffleMask(V2Mask))
6549     if (SDValue BlendPerm =
6550             lowerVectorShuffleAsBlendAndPermute(DL, VT, V1, V2, Mask, DAG))
6551       return BlendPerm;
6552
6553   V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
6554   V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
6555   return DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6556 }
6557
6558 /// \brief Try to lower a vector shuffle as a byte rotation.
6559 ///
6560 /// SSSE3 has a generic PALIGNR instruction in x86 that will do an arbitrary
6561 /// byte-rotation of the concatenation of two vectors; pre-SSSE3 can use
6562 /// a PSRLDQ/PSLLDQ/POR pattern to get a similar effect. This routine will
6563 /// try to generically lower a vector shuffle through such an pattern. It
6564 /// does not check for the profitability of lowering either as PALIGNR or
6565 /// PSRLDQ/PSLLDQ/POR, only whether the mask is valid to lower in that form.
6566 /// This matches shuffle vectors that look like:
6567 ///
6568 ///   v8i16 [11, 12, 13, 14, 15, 0, 1, 2]
6569 ///
6570 /// Essentially it concatenates V1 and V2, shifts right by some number of
6571 /// elements, and takes the low elements as the result. Note that while this is
6572 /// specified as a *right shift* because x86 is little-endian, it is a *left
6573 /// rotate* of the vector lanes.
6574 static SDValue lowerVectorShuffleAsByteRotate(SDLoc DL, MVT VT, SDValue V1,
6575                                               SDValue V2,
6576                                               ArrayRef<int> Mask,
6577                                               const X86Subtarget *Subtarget,
6578                                               SelectionDAG &DAG) {
6579   assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
6580
6581   int NumElts = Mask.size();
6582   int NumLanes = VT.getSizeInBits() / 128;
6583   int NumLaneElts = NumElts / NumLanes;
6584
6585   // We need to detect various ways of spelling a rotation:
6586   //   [11, 12, 13, 14, 15,  0,  1,  2]
6587   //   [-1, 12, 13, 14, -1, -1,  1, -1]
6588   //   [-1, -1, -1, -1, -1, -1,  1,  2]
6589   //   [ 3,  4,  5,  6,  7,  8,  9, 10]
6590   //   [-1,  4,  5,  6, -1, -1,  9, -1]
6591   //   [-1,  4,  5,  6, -1, -1, -1, -1]
6592   int Rotation = 0;
6593   SDValue Lo, Hi;
6594   for (int l = 0; l < NumElts; l += NumLaneElts) {
6595     for (int i = 0; i < NumLaneElts; ++i) {
6596       if (Mask[l + i] == -1)
6597         continue;
6598       assert(Mask[l + i] >= 0 && "Only -1 is a valid negative mask element!");
6599
6600       // Get the mod-Size index and lane correct it.
6601       int LaneIdx = (Mask[l + i] % NumElts) - l;
6602       // Make sure it was in this lane.
6603       if (LaneIdx < 0 || LaneIdx >= NumLaneElts)
6604         return SDValue();
6605
6606       // Determine where a rotated vector would have started.
6607       int StartIdx = i - LaneIdx;
6608       if (StartIdx == 0)
6609         // The identity rotation isn't interesting, stop.
6610         return SDValue();
6611
6612       // If we found the tail of a vector the rotation must be the missing
6613       // front. If we found the head of a vector, it must be how much of the
6614       // head.
6615       int CandidateRotation = StartIdx < 0 ? -StartIdx : NumLaneElts - StartIdx;
6616
6617       if (Rotation == 0)
6618         Rotation = CandidateRotation;
6619       else if (Rotation != CandidateRotation)
6620         // The rotations don't match, so we can't match this mask.
6621         return SDValue();
6622
6623       // Compute which value this mask is pointing at.
6624       SDValue MaskV = Mask[l + i] < NumElts ? V1 : V2;
6625
6626       // Compute which of the two target values this index should be assigned
6627       // to. This reflects whether the high elements are remaining or the low
6628       // elements are remaining.
6629       SDValue &TargetV = StartIdx < 0 ? Hi : Lo;
6630
6631       // Either set up this value if we've not encountered it before, or check
6632       // that it remains consistent.
6633       if (!TargetV)
6634         TargetV = MaskV;
6635       else if (TargetV != MaskV)
6636         // This may be a rotation, but it pulls from the inputs in some
6637         // unsupported interleaving.
6638         return SDValue();
6639     }
6640   }
6641
6642   // Check that we successfully analyzed the mask, and normalize the results.
6643   assert(Rotation != 0 && "Failed to locate a viable rotation!");
6644   assert((Lo || Hi) && "Failed to find a rotated input vector!");
6645   if (!Lo)
6646     Lo = Hi;
6647   else if (!Hi)
6648     Hi = Lo;
6649
6650   // The actual rotate instruction rotates bytes, so we need to scale the
6651   // rotation based on how many bytes are in the vector lane.
6652   int Scale = 16 / NumLaneElts;
6653
6654   // SSSE3 targets can use the palignr instruction.
6655   if (Subtarget->hasSSSE3()) {
6656     // Cast the inputs to i8 vector of correct length to match PALIGNR.
6657     MVT AlignVT = MVT::getVectorVT(MVT::i8, 16 * NumLanes);
6658     Lo = DAG.getBitcast(AlignVT, Lo);
6659     Hi = DAG.getBitcast(AlignVT, Hi);
6660
6661     return DAG.getBitcast(
6662         VT, DAG.getNode(X86ISD::PALIGNR, DL, AlignVT, Hi, Lo,
6663                         DAG.getConstant(Rotation * Scale, DL, MVT::i8)));
6664   }
6665
6666   assert(VT.getSizeInBits() == 128 &&
6667          "Rotate-based lowering only supports 128-bit lowering!");
6668   assert(Mask.size() <= 16 &&
6669          "Can shuffle at most 16 bytes in a 128-bit vector!");
6670
6671   // Default SSE2 implementation
6672   int LoByteShift = 16 - Rotation * Scale;
6673   int HiByteShift = Rotation * Scale;
6674
6675   // Cast the inputs to v2i64 to match PSLLDQ/PSRLDQ.
6676   Lo = DAG.getBitcast(MVT::v2i64, Lo);
6677   Hi = DAG.getBitcast(MVT::v2i64, Hi);
6678
6679   SDValue LoShift = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v2i64, Lo,
6680                                 DAG.getConstant(LoByteShift, DL, MVT::i8));
6681   SDValue HiShift = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v2i64, Hi,
6682                                 DAG.getConstant(HiByteShift, DL, MVT::i8));
6683   return DAG.getBitcast(VT,
6684                         DAG.getNode(ISD::OR, DL, MVT::v2i64, LoShift, HiShift));
6685 }
6686
6687 /// \brief Compute whether each element of a shuffle is zeroable.
6688 ///
6689 /// A "zeroable" vector shuffle element is one which can be lowered to zero.
6690 /// Either it is an undef element in the shuffle mask, the element of the input
6691 /// referenced is undef, or the element of the input referenced is known to be
6692 /// zero. Many x86 shuffles can zero lanes cheaply and we often want to handle
6693 /// as many lanes with this technique as possible to simplify the remaining
6694 /// shuffle.
6695 static SmallBitVector computeZeroableShuffleElements(ArrayRef<int> Mask,
6696                                                      SDValue V1, SDValue V2) {
6697   SmallBitVector Zeroable(Mask.size(), false);
6698
6699   while (V1.getOpcode() == ISD::BITCAST)
6700     V1 = V1->getOperand(0);
6701   while (V2.getOpcode() == ISD::BITCAST)
6702     V2 = V2->getOperand(0);
6703
6704   bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
6705   bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
6706
6707   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6708     int M = Mask[i];
6709     // Handle the easy cases.
6710     if (M < 0 || (M >= 0 && M < Size && V1IsZero) || (M >= Size && V2IsZero)) {
6711       Zeroable[i] = true;
6712       continue;
6713     }
6714
6715     // If this is an index into a build_vector node (which has the same number
6716     // of elements), dig out the input value and use it.
6717     SDValue V = M < Size ? V1 : V2;
6718     if (V.getOpcode() != ISD::BUILD_VECTOR || Size != (int)V.getNumOperands())
6719       continue;
6720
6721     SDValue Input = V.getOperand(M % Size);
6722     // The UNDEF opcode check really should be dead code here, but not quite
6723     // worth asserting on (it isn't invalid, just unexpected).
6724     if (Input.getOpcode() == ISD::UNDEF || X86::isZeroNode(Input))
6725       Zeroable[i] = true;
6726   }
6727
6728   return Zeroable;
6729 }
6730
6731 /// \brief Try to emit a bitmask instruction for a shuffle.
6732 ///
6733 /// This handles cases where we can model a blend exactly as a bitmask due to
6734 /// one of the inputs being zeroable.
6735 static SDValue lowerVectorShuffleAsBitMask(SDLoc DL, MVT VT, SDValue V1,
6736                                            SDValue V2, ArrayRef<int> Mask,
6737                                            SelectionDAG &DAG) {
6738   MVT EltVT = VT.getScalarType();
6739   int NumEltBits = EltVT.getSizeInBits();
6740   MVT IntEltVT = MVT::getIntegerVT(NumEltBits);
6741   SDValue Zero = DAG.getConstant(0, DL, IntEltVT);
6742   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6743                                     IntEltVT);
6744   if (EltVT.isFloatingPoint()) {
6745     Zero = DAG.getBitcast(EltVT, Zero);
6746     AllOnes = DAG.getBitcast(EltVT, AllOnes);
6747   }
6748   SmallVector<SDValue, 16> VMaskOps(Mask.size(), Zero);
6749   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6750   SDValue V;
6751   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6752     if (Zeroable[i])
6753       continue;
6754     if (Mask[i] % Size != i)
6755       return SDValue(); // Not a blend.
6756     if (!V)
6757       V = Mask[i] < Size ? V1 : V2;
6758     else if (V != (Mask[i] < Size ? V1 : V2))
6759       return SDValue(); // Can only let one input through the mask.
6760
6761     VMaskOps[i] = AllOnes;
6762   }
6763   if (!V)
6764     return SDValue(); // No non-zeroable elements!
6765
6766   SDValue VMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, VMaskOps);
6767   V = DAG.getNode(VT.isFloatingPoint()
6768                   ? (unsigned) X86ISD::FAND : (unsigned) ISD::AND,
6769                   DL, VT, V, VMask);
6770   return V;
6771 }
6772
6773 /// \brief Try to lower a vector shuffle as a bit shift (shifts in zeros).
6774 ///
6775 /// Attempts to match a shuffle mask against the PSLL(W/D/Q/DQ) and
6776 /// PSRL(W/D/Q/DQ) SSE2 and AVX2 logical bit-shift instructions. The function
6777 /// matches elements from one of the input vectors shuffled to the left or
6778 /// right with zeroable elements 'shifted in'. It handles both the strictly
6779 /// bit-wise element shifts and the byte shift across an entire 128-bit double
6780 /// quad word lane.
6781 ///
6782 /// PSHL : (little-endian) left bit shift.
6783 /// [ zz, 0, zz,  2 ]
6784 /// [ -1, 4, zz, -1 ]
6785 /// PSRL : (little-endian) right bit shift.
6786 /// [  1, zz,  3, zz]
6787 /// [ -1, -1,  7, zz]
6788 /// PSLLDQ : (little-endian) left byte shift
6789 /// [ zz,  0,  1,  2,  3,  4,  5,  6]
6790 /// [ zz, zz, -1, -1,  2,  3,  4, -1]
6791 /// [ zz, zz, zz, zz, zz, zz, -1,  1]
6792 /// PSRLDQ : (little-endian) right byte shift
6793 /// [  5, 6,  7, zz, zz, zz, zz, zz]
6794 /// [ -1, 5,  6,  7, zz, zz, zz, zz]
6795 /// [  1, 2, -1, -1, -1, -1, zz, zz]
6796 static SDValue lowerVectorShuffleAsShift(SDLoc DL, MVT VT, SDValue V1,
6797                                          SDValue V2, ArrayRef<int> Mask,
6798                                          SelectionDAG &DAG) {
6799   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6800
6801   int Size = Mask.size();
6802   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
6803
6804   auto CheckZeros = [&](int Shift, int Scale, bool Left) {
6805     for (int i = 0; i < Size; i += Scale)
6806       for (int j = 0; j < Shift; ++j)
6807         if (!Zeroable[i + j + (Left ? 0 : (Scale - Shift))])
6808           return false;
6809
6810     return true;
6811   };
6812
6813   auto MatchShift = [&](int Shift, int Scale, bool Left, SDValue V) {
6814     for (int i = 0; i != Size; i += Scale) {
6815       unsigned Pos = Left ? i + Shift : i;
6816       unsigned Low = Left ? i : i + Shift;
6817       unsigned Len = Scale - Shift;
6818       if (!isSequentialOrUndefInRange(Mask, Pos, Len,
6819                                       Low + (V == V1 ? 0 : Size)))
6820         return SDValue();
6821     }
6822
6823     int ShiftEltBits = VT.getScalarSizeInBits() * Scale;
6824     bool ByteShift = ShiftEltBits > 64;
6825     unsigned OpCode = Left ? (ByteShift ? X86ISD::VSHLDQ : X86ISD::VSHLI)
6826                            : (ByteShift ? X86ISD::VSRLDQ : X86ISD::VSRLI);
6827     int ShiftAmt = Shift * VT.getScalarSizeInBits() / (ByteShift ? 8 : 1);
6828
6829     // Normalize the scale for byte shifts to still produce an i64 element
6830     // type.
6831     Scale = ByteShift ? Scale / 2 : Scale;
6832
6833     // We need to round trip through the appropriate type for the shift.
6834     MVT ShiftSVT = MVT::getIntegerVT(VT.getScalarSizeInBits() * Scale);
6835     MVT ShiftVT = MVT::getVectorVT(ShiftSVT, Size / Scale);
6836     assert(DAG.getTargetLoweringInfo().isTypeLegal(ShiftVT) &&
6837            "Illegal integer vector type");
6838     V = DAG.getBitcast(ShiftVT, V);
6839
6840     V = DAG.getNode(OpCode, DL, ShiftVT, V,
6841                     DAG.getConstant(ShiftAmt, DL, MVT::i8));
6842     return DAG.getBitcast(VT, V);
6843   };
6844
6845   // SSE/AVX supports logical shifts up to 64-bit integers - so we can just
6846   // keep doubling the size of the integer elements up to that. We can
6847   // then shift the elements of the integer vector by whole multiples of
6848   // their width within the elements of the larger integer vector. Test each
6849   // multiple to see if we can find a match with the moved element indices
6850   // and that the shifted in elements are all zeroable.
6851   for (int Scale = 2; Scale * VT.getScalarSizeInBits() <= 128; Scale *= 2)
6852     for (int Shift = 1; Shift != Scale; ++Shift)
6853       for (bool Left : {true, false})
6854         if (CheckZeros(Shift, Scale, Left))
6855           for (SDValue V : {V1, V2})
6856             if (SDValue Match = MatchShift(Shift, Scale, Left, V))
6857               return Match;
6858
6859   // no match
6860   return SDValue();
6861 }
6862
6863 /// \brief Lower a vector shuffle as a zero or any extension.
6864 ///
6865 /// Given a specific number of elements, element bit width, and extension
6866 /// stride, produce either a zero or any extension based on the available
6867 /// features of the subtarget.
6868 static SDValue lowerVectorShuffleAsSpecificZeroOrAnyExtend(
6869     SDLoc DL, MVT VT, int Scale, bool AnyExt, SDValue InputV,
6870     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6871   assert(Scale > 1 && "Need a scale to extend.");
6872   int NumElements = VT.getVectorNumElements();
6873   int EltBits = VT.getScalarSizeInBits();
6874   assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
6875          "Only 8, 16, and 32 bit elements can be extended.");
6876   assert(Scale * EltBits <= 64 && "Cannot zero extend past 64 bits.");
6877
6878   // Found a valid zext mask! Try various lowering strategies based on the
6879   // input type and available ISA extensions.
6880   if (Subtarget->hasSSE41()) {
6881     MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits * Scale),
6882                                  NumElements / Scale);
6883     return DAG.getBitcast(VT, DAG.getNode(X86ISD::VZEXT, DL, ExtVT, InputV));
6884   }
6885
6886   // For any extends we can cheat for larger element sizes and use shuffle
6887   // instructions that can fold with a load and/or copy.
6888   if (AnyExt && EltBits == 32) {
6889     int PSHUFDMask[4] = {0, -1, 1, -1};
6890     return DAG.getBitcast(
6891         VT, DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
6892                         DAG.getBitcast(MVT::v4i32, InputV),
6893                         getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
6894   }
6895   if (AnyExt && EltBits == 16 && Scale > 2) {
6896     int PSHUFDMask[4] = {0, -1, 0, -1};
6897     InputV = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
6898                          DAG.getBitcast(MVT::v4i32, InputV),
6899                          getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG));
6900     int PSHUFHWMask[4] = {1, -1, -1, -1};
6901     return DAG.getBitcast(
6902         VT, DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16,
6903                         DAG.getBitcast(MVT::v8i16, InputV),
6904                         getV4X86ShuffleImm8ForMask(PSHUFHWMask, DL, DAG)));
6905   }
6906
6907   // If this would require more than 2 unpack instructions to expand, use
6908   // pshufb when available. We can only use more than 2 unpack instructions
6909   // when zero extending i8 elements which also makes it easier to use pshufb.
6910   if (Scale > 4 && EltBits == 8 && Subtarget->hasSSSE3()) {
6911     assert(NumElements == 16 && "Unexpected byte vector width!");
6912     SDValue PSHUFBMask[16];
6913     for (int i = 0; i < 16; ++i)
6914       PSHUFBMask[i] =
6915           DAG.getConstant((i % Scale == 0) ? i / Scale : 0x80, DL, MVT::i8);
6916     InputV = DAG.getBitcast(MVT::v16i8, InputV);
6917     return DAG.getBitcast(VT,
6918                           DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, InputV,
6919                                       DAG.getNode(ISD::BUILD_VECTOR, DL,
6920                                                   MVT::v16i8, PSHUFBMask)));
6921   }
6922
6923   // Otherwise emit a sequence of unpacks.
6924   do {
6925     MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
6926     SDValue Ext = AnyExt ? DAG.getUNDEF(InputVT)
6927                          : getZeroVector(InputVT, Subtarget, DAG, DL);
6928     InputV = DAG.getBitcast(InputVT, InputV);
6929     InputV = DAG.getNode(X86ISD::UNPCKL, DL, InputVT, InputV, Ext);
6930     Scale /= 2;
6931     EltBits *= 2;
6932     NumElements /= 2;
6933   } while (Scale > 1);
6934   return DAG.getBitcast(VT, InputV);
6935 }
6936
6937 /// \brief Try to lower a vector shuffle as a zero extension on any microarch.
6938 ///
6939 /// This routine will try to do everything in its power to cleverly lower
6940 /// a shuffle which happens to match the pattern of a zero extend. It doesn't
6941 /// check for the profitability of this lowering,  it tries to aggressively
6942 /// match this pattern. It will use all of the micro-architectural details it
6943 /// can to emit an efficient lowering. It handles both blends with all-zero
6944 /// inputs to explicitly zero-extend and undef-lanes (sometimes undef due to
6945 /// masking out later).
6946 ///
6947 /// The reason we have dedicated lowering for zext-style shuffles is that they
6948 /// are both incredibly common and often quite performance sensitive.
6949 static SDValue lowerVectorShuffleAsZeroOrAnyExtend(
6950     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
6951     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6952   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6953
6954   int Bits = VT.getSizeInBits();
6955   int NumElements = VT.getVectorNumElements();
6956   assert(VT.getScalarSizeInBits() <= 32 &&
6957          "Exceeds 32-bit integer zero extension limit");
6958   assert((int)Mask.size() == NumElements && "Unexpected shuffle mask size");
6959
6960   // Define a helper function to check a particular ext-scale and lower to it if
6961   // valid.
6962   auto Lower = [&](int Scale) -> SDValue {
6963     SDValue InputV;
6964     bool AnyExt = true;
6965     for (int i = 0; i < NumElements; ++i) {
6966       if (Mask[i] == -1)
6967         continue; // Valid anywhere but doesn't tell us anything.
6968       if (i % Scale != 0) {
6969         // Each of the extended elements need to be zeroable.
6970         if (!Zeroable[i])
6971           return SDValue();
6972
6973         // We no longer are in the anyext case.
6974         AnyExt = false;
6975         continue;
6976       }
6977
6978       // Each of the base elements needs to be consecutive indices into the
6979       // same input vector.
6980       SDValue V = Mask[i] < NumElements ? V1 : V2;
6981       if (!InputV)
6982         InputV = V;
6983       else if (InputV != V)
6984         return SDValue(); // Flip-flopping inputs.
6985
6986       if (Mask[i] % NumElements != i / Scale)
6987         return SDValue(); // Non-consecutive strided elements.
6988     }
6989
6990     // If we fail to find an input, we have a zero-shuffle which should always
6991     // have already been handled.
6992     // FIXME: Maybe handle this here in case during blending we end up with one?
6993     if (!InputV)
6994       return SDValue();
6995
6996     return lowerVectorShuffleAsSpecificZeroOrAnyExtend(
6997         DL, VT, Scale, AnyExt, InputV, Subtarget, DAG);
6998   };
6999
7000   // The widest scale possible for extending is to a 64-bit integer.
7001   assert(Bits % 64 == 0 &&
7002          "The number of bits in a vector must be divisible by 64 on x86!");
7003   int NumExtElements = Bits / 64;
7004
7005   // Each iteration, try extending the elements half as much, but into twice as
7006   // many elements.
7007   for (; NumExtElements < NumElements; NumExtElements *= 2) {
7008     assert(NumElements % NumExtElements == 0 &&
7009            "The input vector size must be divisible by the extended size.");
7010     if (SDValue V = Lower(NumElements / NumExtElements))
7011       return V;
7012   }
7013
7014   // General extends failed, but 128-bit vectors may be able to use MOVQ.
7015   if (Bits != 128)
7016     return SDValue();
7017
7018   // Returns one of the source operands if the shuffle can be reduced to a
7019   // MOVQ, copying the lower 64-bits and zero-extending to the upper 64-bits.
7020   auto CanZExtLowHalf = [&]() {
7021     for (int i = NumElements / 2; i != NumElements; ++i)
7022       if (!Zeroable[i])
7023         return SDValue();
7024     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, 0))
7025       return V1;
7026     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, NumElements))
7027       return V2;
7028     return SDValue();
7029   };
7030
7031   if (SDValue V = CanZExtLowHalf()) {
7032     V = DAG.getBitcast(MVT::v2i64, V);
7033     V = DAG.getNode(X86ISD::VZEXT_MOVL, DL, MVT::v2i64, V);
7034     return DAG.getBitcast(VT, V);
7035   }
7036
7037   // No viable ext lowering found.
7038   return SDValue();
7039 }
7040
7041 /// \brief Try to get a scalar value for a specific element of a vector.
7042 ///
7043 /// Looks through BUILD_VECTOR and SCALAR_TO_VECTOR nodes to find a scalar.
7044 static SDValue getScalarValueForVectorElement(SDValue V, int Idx,
7045                                               SelectionDAG &DAG) {
7046   MVT VT = V.getSimpleValueType();
7047   MVT EltVT = VT.getVectorElementType();
7048   while (V.getOpcode() == ISD::BITCAST)
7049     V = V.getOperand(0);
7050   // If the bitcasts shift the element size, we can't extract an equivalent
7051   // element from it.
7052   MVT NewVT = V.getSimpleValueType();
7053   if (!NewVT.isVector() || NewVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
7054     return SDValue();
7055
7056   if (V.getOpcode() == ISD::BUILD_VECTOR ||
7057       (Idx == 0 && V.getOpcode() == ISD::SCALAR_TO_VECTOR)) {
7058     // Ensure the scalar operand is the same size as the destination.
7059     // FIXME: Add support for scalar truncation where possible.
7060     SDValue S = V.getOperand(Idx);
7061     if (EltVT.getSizeInBits() == S.getSimpleValueType().getSizeInBits())
7062       return DAG.getNode(ISD::BITCAST, SDLoc(V), EltVT, S);
7063   }
7064
7065   return SDValue();
7066 }
7067
7068 /// \brief Helper to test for a load that can be folded with x86 shuffles.
7069 ///
7070 /// This is particularly important because the set of instructions varies
7071 /// significantly based on whether the operand is a load or not.
7072 static bool isShuffleFoldableLoad(SDValue V) {
7073   while (V.getOpcode() == ISD::BITCAST)
7074     V = V.getOperand(0);
7075
7076   return ISD::isNON_EXTLoad(V.getNode());
7077 }
7078
7079 /// \brief Try to lower insertion of a single element into a zero vector.
7080 ///
7081 /// This is a common pattern that we have especially efficient patterns to lower
7082 /// across all subtarget feature sets.
7083 static SDValue lowerVectorShuffleAsElementInsertion(
7084     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7085     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7086   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7087   MVT ExtVT = VT;
7088   MVT EltVT = VT.getVectorElementType();
7089
7090   int V2Index = std::find_if(Mask.begin(), Mask.end(),
7091                              [&Mask](int M) { return M >= (int)Mask.size(); }) -
7092                 Mask.begin();
7093   bool IsV1Zeroable = true;
7094   for (int i = 0, Size = Mask.size(); i < Size; ++i)
7095     if (i != V2Index && !Zeroable[i]) {
7096       IsV1Zeroable = false;
7097       break;
7098     }
7099
7100   // Check for a single input from a SCALAR_TO_VECTOR node.
7101   // FIXME: All of this should be canonicalized into INSERT_VECTOR_ELT and
7102   // all the smarts here sunk into that routine. However, the current
7103   // lowering of BUILD_VECTOR makes that nearly impossible until the old
7104   // vector shuffle lowering is dead.
7105   if (SDValue V2S = getScalarValueForVectorElement(
7106           V2, Mask[V2Index] - Mask.size(), DAG)) {
7107     // We need to zext the scalar if it is smaller than an i32.
7108     V2S = DAG.getBitcast(EltVT, V2S);
7109     if (EltVT == MVT::i8 || EltVT == MVT::i16) {
7110       // Using zext to expand a narrow element won't work for non-zero
7111       // insertions.
7112       if (!IsV1Zeroable)
7113         return SDValue();
7114
7115       // Zero-extend directly to i32.
7116       ExtVT = MVT::v4i32;
7117       V2S = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, V2S);
7118     }
7119     V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
7120   } else if (Mask[V2Index] != (int)Mask.size() || EltVT == MVT::i8 ||
7121              EltVT == MVT::i16) {
7122     // Either not inserting from the low element of the input or the input
7123     // element size is too small to use VZEXT_MOVL to clear the high bits.
7124     return SDValue();
7125   }
7126
7127   if (!IsV1Zeroable) {
7128     // If V1 can't be treated as a zero vector we have fewer options to lower
7129     // this. We can't support integer vectors or non-zero targets cheaply, and
7130     // the V1 elements can't be permuted in any way.
7131     assert(VT == ExtVT && "Cannot change extended type when non-zeroable!");
7132     if (!VT.isFloatingPoint() || V2Index != 0)
7133       return SDValue();
7134     SmallVector<int, 8> V1Mask(Mask.begin(), Mask.end());
7135     V1Mask[V2Index] = -1;
7136     if (!isNoopShuffleMask(V1Mask))
7137       return SDValue();
7138     // This is essentially a special case blend operation, but if we have
7139     // general purpose blend operations, they are always faster. Bail and let
7140     // the rest of the lowering handle these as blends.
7141     if (Subtarget->hasSSE41())
7142       return SDValue();
7143
7144     // Otherwise, use MOVSD or MOVSS.
7145     assert((EltVT == MVT::f32 || EltVT == MVT::f64) &&
7146            "Only two types of floating point element types to handle!");
7147     return DAG.getNode(EltVT == MVT::f32 ? X86ISD::MOVSS : X86ISD::MOVSD, DL,
7148                        ExtVT, V1, V2);
7149   }
7150
7151   // This lowering only works for the low element with floating point vectors.
7152   if (VT.isFloatingPoint() && V2Index != 0)
7153     return SDValue();
7154
7155   V2 = DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2);
7156   if (ExtVT != VT)
7157     V2 = DAG.getBitcast(VT, V2);
7158
7159   if (V2Index != 0) {
7160     // If we have 4 or fewer lanes we can cheaply shuffle the element into
7161     // the desired position. Otherwise it is more efficient to do a vector
7162     // shift left. We know that we can do a vector shift left because all
7163     // the inputs are zero.
7164     if (VT.isFloatingPoint() || VT.getVectorNumElements() <= 4) {
7165       SmallVector<int, 4> V2Shuffle(Mask.size(), 1);
7166       V2Shuffle[V2Index] = 0;
7167       V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Shuffle);
7168     } else {
7169       V2 = DAG.getBitcast(MVT::v2i64, V2);
7170       V2 = DAG.getNode(
7171           X86ISD::VSHLDQ, DL, MVT::v2i64, V2,
7172           DAG.getConstant(
7173               V2Index * EltVT.getSizeInBits()/8, DL,
7174               DAG.getTargetLoweringInfo().getScalarShiftAmountTy(MVT::v2i64)));
7175       V2 = DAG.getBitcast(VT, V2);
7176     }
7177   }
7178   return V2;
7179 }
7180
7181 /// \brief Try to lower broadcast of a single element.
7182 ///
7183 /// For convenience, this code also bundles all of the subtarget feature set
7184 /// filtering. While a little annoying to re-dispatch on type here, there isn't
7185 /// a convenient way to factor it out.
7186 static SDValue lowerVectorShuffleAsBroadcast(SDLoc DL, MVT VT, SDValue V,
7187                                              ArrayRef<int> Mask,
7188                                              const X86Subtarget *Subtarget,
7189                                              SelectionDAG &DAG) {
7190   if (!Subtarget->hasAVX())
7191     return SDValue();
7192   if (VT.isInteger() && !Subtarget->hasAVX2())
7193     return SDValue();
7194
7195   // Check that the mask is a broadcast.
7196   int BroadcastIdx = -1;
7197   for (int M : Mask)
7198     if (M >= 0 && BroadcastIdx == -1)
7199       BroadcastIdx = M;
7200     else if (M >= 0 && M != BroadcastIdx)
7201       return SDValue();
7202
7203   assert(BroadcastIdx < (int)Mask.size() && "We only expect to be called with "
7204                                             "a sorted mask where the broadcast "
7205                                             "comes from V1.");
7206
7207   // Go up the chain of (vector) values to find a scalar load that we can
7208   // combine with the broadcast.
7209   for (;;) {
7210     switch (V.getOpcode()) {
7211     case ISD::CONCAT_VECTORS: {
7212       int OperandSize = Mask.size() / V.getNumOperands();
7213       V = V.getOperand(BroadcastIdx / OperandSize);
7214       BroadcastIdx %= OperandSize;
7215       continue;
7216     }
7217
7218     case ISD::INSERT_SUBVECTOR: {
7219       SDValue VOuter = V.getOperand(0), VInner = V.getOperand(1);
7220       auto ConstantIdx = dyn_cast<ConstantSDNode>(V.getOperand(2));
7221       if (!ConstantIdx)
7222         break;
7223
7224       int BeginIdx = (int)ConstantIdx->getZExtValue();
7225       int EndIdx =
7226           BeginIdx + (int)VInner.getValueType().getVectorNumElements();
7227       if (BroadcastIdx >= BeginIdx && BroadcastIdx < EndIdx) {
7228         BroadcastIdx -= BeginIdx;
7229         V = VInner;
7230       } else {
7231         V = VOuter;
7232       }
7233       continue;
7234     }
7235     }
7236     break;
7237   }
7238
7239   // Check if this is a broadcast of a scalar. We special case lowering
7240   // for scalars so that we can more effectively fold with loads.
7241   if (V.getOpcode() == ISD::BUILD_VECTOR ||
7242       (V.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)) {
7243     V = V.getOperand(BroadcastIdx);
7244
7245     // If the scalar isn't a load, we can't broadcast from it in AVX1.
7246     // Only AVX2 has register broadcasts.
7247     if (!Subtarget->hasAVX2() && !isShuffleFoldableLoad(V))
7248       return SDValue();
7249   } else if (BroadcastIdx != 0 || !Subtarget->hasAVX2()) {
7250     // We can't broadcast from a vector register without AVX2, and we can only
7251     // broadcast from the zero-element of a vector register.
7252     return SDValue();
7253   }
7254
7255   return DAG.getNode(X86ISD::VBROADCAST, DL, VT, V);
7256 }
7257
7258 // Check for whether we can use INSERTPS to perform the shuffle. We only use
7259 // INSERTPS when the V1 elements are already in the correct locations
7260 // because otherwise we can just always use two SHUFPS instructions which
7261 // are much smaller to encode than a SHUFPS and an INSERTPS. We can also
7262 // perform INSERTPS if a single V1 element is out of place and all V2
7263 // elements are zeroable.
7264 static SDValue lowerVectorShuffleAsInsertPS(SDValue Op, SDValue V1, SDValue V2,
7265                                             ArrayRef<int> Mask,
7266                                             SelectionDAG &DAG) {
7267   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7268   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7269   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7270   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7271
7272   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7273
7274   unsigned ZMask = 0;
7275   int V1DstIndex = -1;
7276   int V2DstIndex = -1;
7277   bool V1UsedInPlace = false;
7278
7279   for (int i = 0; i < 4; ++i) {
7280     // Synthesize a zero mask from the zeroable elements (includes undefs).
7281     if (Zeroable[i]) {
7282       ZMask |= 1 << i;
7283       continue;
7284     }
7285
7286     // Flag if we use any V1 inputs in place.
7287     if (i == Mask[i]) {
7288       V1UsedInPlace = true;
7289       continue;
7290     }
7291
7292     // We can only insert a single non-zeroable element.
7293     if (V1DstIndex != -1 || V2DstIndex != -1)
7294       return SDValue();
7295
7296     if (Mask[i] < 4) {
7297       // V1 input out of place for insertion.
7298       V1DstIndex = i;
7299     } else {
7300       // V2 input for insertion.
7301       V2DstIndex = i;
7302     }
7303   }
7304
7305   // Don't bother if we have no (non-zeroable) element for insertion.
7306   if (V1DstIndex == -1 && V2DstIndex == -1)
7307     return SDValue();
7308
7309   // Determine element insertion src/dst indices. The src index is from the
7310   // start of the inserted vector, not the start of the concatenated vector.
7311   unsigned V2SrcIndex = 0;
7312   if (V1DstIndex != -1) {
7313     // If we have a V1 input out of place, we use V1 as the V2 element insertion
7314     // and don't use the original V2 at all.
7315     V2SrcIndex = Mask[V1DstIndex];
7316     V2DstIndex = V1DstIndex;
7317     V2 = V1;
7318   } else {
7319     V2SrcIndex = Mask[V2DstIndex] - 4;
7320   }
7321
7322   // If no V1 inputs are used in place, then the result is created only from
7323   // the zero mask and the V2 insertion - so remove V1 dependency.
7324   if (!V1UsedInPlace)
7325     V1 = DAG.getUNDEF(MVT::v4f32);
7326
7327   unsigned InsertPSMask = V2SrcIndex << 6 | V2DstIndex << 4 | ZMask;
7328   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
7329
7330   // Insert the V2 element into the desired position.
7331   SDLoc DL(Op);
7332   return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
7333                      DAG.getConstant(InsertPSMask, DL, MVT::i8));
7334 }
7335
7336 /// \brief Try to lower a shuffle as a permute of the inputs followed by an
7337 /// UNPCK instruction.
7338 ///
7339 /// This specifically targets cases where we end up with alternating between
7340 /// the two inputs, and so can permute them into something that feeds a single
7341 /// UNPCK instruction. Note that this routine only targets integer vectors
7342 /// because for floating point vectors we have a generalized SHUFPS lowering
7343 /// strategy that handles everything that doesn't *exactly* match an unpack,
7344 /// making this clever lowering unnecessary.
7345 static SDValue lowerVectorShuffleAsUnpack(SDLoc DL, MVT VT, SDValue V1,
7346                                           SDValue V2, ArrayRef<int> Mask,
7347                                           SelectionDAG &DAG) {
7348   assert(!VT.isFloatingPoint() &&
7349          "This routine only supports integer vectors.");
7350   assert(!isSingleInputShuffleMask(Mask) &&
7351          "This routine should only be used when blending two inputs.");
7352   assert(Mask.size() >= 2 && "Single element masks are invalid.");
7353
7354   int Size = Mask.size();
7355
7356   int NumLoInputs = std::count_if(Mask.begin(), Mask.end(), [Size](int M) {
7357     return M >= 0 && M % Size < Size / 2;
7358   });
7359   int NumHiInputs = std::count_if(
7360       Mask.begin(), Mask.end(), [Size](int M) { return M % Size >= Size / 2; });
7361
7362   bool UnpackLo = NumLoInputs >= NumHiInputs;
7363
7364   auto TryUnpack = [&](MVT UnpackVT, int Scale) {
7365     SmallVector<int, 32> V1Mask(Mask.size(), -1);
7366     SmallVector<int, 32> V2Mask(Mask.size(), -1);
7367
7368     for (int i = 0; i < Size; ++i) {
7369       if (Mask[i] < 0)
7370         continue;
7371
7372       // Each element of the unpack contains Scale elements from this mask.
7373       int UnpackIdx = i / Scale;
7374
7375       // We only handle the case where V1 feeds the first slots of the unpack.
7376       // We rely on canonicalization to ensure this is the case.
7377       if ((UnpackIdx % 2 == 0) != (Mask[i] < Size))
7378         return SDValue();
7379
7380       // Setup the mask for this input. The indexing is tricky as we have to
7381       // handle the unpack stride.
7382       SmallVectorImpl<int> &VMask = (UnpackIdx % 2 == 0) ? V1Mask : V2Mask;
7383       VMask[(UnpackIdx / 2) * Scale + i % Scale + (UnpackLo ? 0 : Size / 2)] =
7384           Mask[i] % Size;
7385     }
7386
7387     // If we will have to shuffle both inputs to use the unpack, check whether
7388     // we can just unpack first and shuffle the result. If so, skip this unpack.
7389     if ((NumLoInputs == 0 || NumHiInputs == 0) && !isNoopShuffleMask(V1Mask) &&
7390         !isNoopShuffleMask(V2Mask))
7391       return SDValue();
7392
7393     // Shuffle the inputs into place.
7394     V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
7395     V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
7396
7397     // Cast the inputs to the type we will use to unpack them.
7398     V1 = DAG.getBitcast(UnpackVT, V1);
7399     V2 = DAG.getBitcast(UnpackVT, V2);
7400
7401     // Unpack the inputs and cast the result back to the desired type.
7402     return DAG.getBitcast(
7403         VT, DAG.getNode(UnpackLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
7404                         UnpackVT, V1, V2));
7405   };
7406
7407   // We try each unpack from the largest to the smallest to try and find one
7408   // that fits this mask.
7409   int OrigNumElements = VT.getVectorNumElements();
7410   int OrigScalarSize = VT.getScalarSizeInBits();
7411   for (int ScalarSize = 64; ScalarSize >= OrigScalarSize; ScalarSize /= 2) {
7412     int Scale = ScalarSize / OrigScalarSize;
7413     int NumElements = OrigNumElements / Scale;
7414     MVT UnpackVT = MVT::getVectorVT(MVT::getIntegerVT(ScalarSize), NumElements);
7415     if (SDValue Unpack = TryUnpack(UnpackVT, Scale))
7416       return Unpack;
7417   }
7418
7419   // If none of the unpack-rooted lowerings worked (or were profitable) try an
7420   // initial unpack.
7421   if (NumLoInputs == 0 || NumHiInputs == 0) {
7422     assert((NumLoInputs > 0 || NumHiInputs > 0) &&
7423            "We have to have *some* inputs!");
7424     int HalfOffset = NumLoInputs == 0 ? Size / 2 : 0;
7425
7426     // FIXME: We could consider the total complexity of the permute of each
7427     // possible unpacking. Or at the least we should consider how many
7428     // half-crossings are created.
7429     // FIXME: We could consider commuting the unpacks.
7430
7431     SmallVector<int, 32> PermMask;
7432     PermMask.assign(Size, -1);
7433     for (int i = 0; i < Size; ++i) {
7434       if (Mask[i] < 0)
7435         continue;
7436
7437       assert(Mask[i] % Size >= HalfOffset && "Found input from wrong half!");
7438
7439       PermMask[i] =
7440           2 * ((Mask[i] % Size) - HalfOffset) + (Mask[i] < Size ? 0 : 1);
7441     }
7442     return DAG.getVectorShuffle(
7443         VT, DL, DAG.getNode(NumLoInputs == 0 ? X86ISD::UNPCKH : X86ISD::UNPCKL,
7444                             DL, VT, V1, V2),
7445         DAG.getUNDEF(VT), PermMask);
7446   }
7447
7448   return SDValue();
7449 }
7450
7451 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
7452 ///
7453 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
7454 /// support for floating point shuffles but not integer shuffles. These
7455 /// instructions will incur a domain crossing penalty on some chips though so
7456 /// it is better to avoid lowering through this for integer vectors where
7457 /// possible.
7458 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7459                                        const X86Subtarget *Subtarget,
7460                                        SelectionDAG &DAG) {
7461   SDLoc DL(Op);
7462   assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
7463   assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7464   assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7465   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7466   ArrayRef<int> Mask = SVOp->getMask();
7467   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7468
7469   if (isSingleInputShuffleMask(Mask)) {
7470     // Use low duplicate instructions for masks that match their pattern.
7471     if (Subtarget->hasSSE3())
7472       if (isShuffleEquivalent(V1, V2, Mask, {0, 0}))
7473         return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v2f64, V1);
7474
7475     // Straight shuffle of a single input vector. Simulate this by using the
7476     // single input as both of the "inputs" to this instruction..
7477     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
7478
7479     if (Subtarget->hasAVX()) {
7480       // If we have AVX, we can use VPERMILPS which will allow folding a load
7481       // into the shuffle.
7482       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v2f64, V1,
7483                          DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7484     }
7485
7486     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V1,
7487                        DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7488   }
7489   assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
7490   assert(Mask[1] >= 2 && "Non-canonicalized blend!");
7491
7492   // If we have a single input, insert that into V1 if we can do so cheaply.
7493   if ((Mask[0] >= 2) + (Mask[1] >= 2) == 1) {
7494     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7495             DL, MVT::v2f64, V1, V2, Mask, Subtarget, DAG))
7496       return Insertion;
7497     // Try inverting the insertion since for v2 masks it is easy to do and we
7498     // can't reliably sort the mask one way or the other.
7499     int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
7500                           Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
7501     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7502             DL, MVT::v2f64, V2, V1, InverseMask, Subtarget, DAG))
7503       return Insertion;
7504   }
7505
7506   // Try to use one of the special instruction patterns to handle two common
7507   // blend patterns if a zero-blend above didn't work.
7508   if (isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
7509       isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7510     if (SDValue V1S = getScalarValueForVectorElement(V1, Mask[0], DAG))
7511       // We can either use a special instruction to load over the low double or
7512       // to move just the low double.
7513       return DAG.getNode(
7514           isShuffleFoldableLoad(V1S) ? X86ISD::MOVLPD : X86ISD::MOVSD,
7515           DL, MVT::v2f64, V2,
7516           DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V1S));
7517
7518   if (Subtarget->hasSSE41())
7519     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2f64, V1, V2, Mask,
7520                                                   Subtarget, DAG))
7521       return Blend;
7522
7523   // Use dedicated unpack instructions for masks that match their pattern.
7524   if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7525     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2f64, V1, V2);
7526   if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7527     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2f64, V1, V2);
7528
7529   unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
7530   return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V2,
7531                      DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7532 }
7533
7534 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
7535 ///
7536 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
7537 /// the integer unit to minimize domain crossing penalties. However, for blends
7538 /// it falls back to the floating point shuffle operation with appropriate bit
7539 /// casting.
7540 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7541                                        const X86Subtarget *Subtarget,
7542                                        SelectionDAG &DAG) {
7543   SDLoc DL(Op);
7544   assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
7545   assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7546   assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7547   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7548   ArrayRef<int> Mask = SVOp->getMask();
7549   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7550
7551   if (isSingleInputShuffleMask(Mask)) {
7552     // Check for being able to broadcast a single element.
7553     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v2i64, V1,
7554                                                           Mask, Subtarget, DAG))
7555       return Broadcast;
7556
7557     // Straight shuffle of a single input vector. For everything from SSE2
7558     // onward this has a single fast instruction with no scary immediates.
7559     // We have to map the mask as it is actually a v4i32 shuffle instruction.
7560     V1 = DAG.getBitcast(MVT::v4i32, V1);
7561     int WidenedMask[4] = {
7562         std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
7563         std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
7564     return DAG.getBitcast(
7565         MVT::v2i64,
7566         DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
7567                     getV4X86ShuffleImm8ForMask(WidenedMask, DL, DAG)));
7568   }
7569   assert(Mask[0] != -1 && "No undef lanes in multi-input v2 shuffles!");
7570   assert(Mask[1] != -1 && "No undef lanes in multi-input v2 shuffles!");
7571   assert(Mask[0] < 2 && "We sort V1 to be the first input.");
7572   assert(Mask[1] >= 2 && "We sort V2 to be the second input.");
7573
7574   // If we have a blend of two PACKUS operations an the blend aligns with the
7575   // low and half halves, we can just merge the PACKUS operations. This is
7576   // particularly important as it lets us merge shuffles that this routine itself
7577   // creates.
7578   auto GetPackNode = [](SDValue V) {
7579     while (V.getOpcode() == ISD::BITCAST)
7580       V = V.getOperand(0);
7581
7582     return V.getOpcode() == X86ISD::PACKUS ? V : SDValue();
7583   };
7584   if (SDValue V1Pack = GetPackNode(V1))
7585     if (SDValue V2Pack = GetPackNode(V2))
7586       return DAG.getBitcast(MVT::v2i64,
7587                             DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8,
7588                                         Mask[0] == 0 ? V1Pack.getOperand(0)
7589                                                      : V1Pack.getOperand(1),
7590                                         Mask[1] == 2 ? V2Pack.getOperand(0)
7591                                                      : V2Pack.getOperand(1)));
7592
7593   // Try to use shift instructions.
7594   if (SDValue Shift =
7595           lowerVectorShuffleAsShift(DL, MVT::v2i64, V1, V2, Mask, DAG))
7596     return Shift;
7597
7598   // When loading a scalar and then shuffling it into a vector we can often do
7599   // the insertion cheaply.
7600   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7601           DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
7602     return Insertion;
7603   // Try inverting the insertion since for v2 masks it is easy to do and we
7604   // can't reliably sort the mask one way or the other.
7605   int InverseMask[2] = {Mask[0] ^ 2, Mask[1] ^ 2};
7606   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7607           DL, MVT::v2i64, V2, V1, InverseMask, Subtarget, DAG))
7608     return Insertion;
7609
7610   // We have different paths for blend lowering, but they all must use the
7611   // *exact* same predicate.
7612   bool IsBlendSupported = Subtarget->hasSSE41();
7613   if (IsBlendSupported)
7614     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2i64, V1, V2, Mask,
7615                                                   Subtarget, DAG))
7616       return Blend;
7617
7618   // Use dedicated unpack instructions for masks that match their pattern.
7619   if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7620     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, V1, V2);
7621   if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7622     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2i64, V1, V2);
7623
7624   // Try to use byte rotation instructions.
7625   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
7626   if (Subtarget->hasSSSE3())
7627     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
7628             DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
7629       return Rotate;
7630
7631   // If we have direct support for blends, we should lower by decomposing into
7632   // a permute. That will be faster than the domain cross.
7633   if (IsBlendSupported)
7634     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v2i64, V1, V2,
7635                                                       Mask, DAG);
7636
7637   // We implement this with SHUFPD which is pretty lame because it will likely
7638   // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
7639   // However, all the alternatives are still more cycles and newer chips don't
7640   // have this problem. It would be really nice if x86 had better shuffles here.
7641   V1 = DAG.getBitcast(MVT::v2f64, V1);
7642   V2 = DAG.getBitcast(MVT::v2f64, V2);
7643   return DAG.getBitcast(MVT::v2i64,
7644                         DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
7645 }
7646
7647 /// \brief Test whether this can be lowered with a single SHUFPS instruction.
7648 ///
7649 /// This is used to disable more specialized lowerings when the shufps lowering
7650 /// will happen to be efficient.
7651 static bool isSingleSHUFPSMask(ArrayRef<int> Mask) {
7652   // This routine only handles 128-bit shufps.
7653   assert(Mask.size() == 4 && "Unsupported mask size!");
7654
7655   // To lower with a single SHUFPS we need to have the low half and high half
7656   // each requiring a single input.
7657   if (Mask[0] != -1 && Mask[1] != -1 && (Mask[0] < 4) != (Mask[1] < 4))
7658     return false;
7659   if (Mask[2] != -1 && Mask[3] != -1 && (Mask[2] < 4) != (Mask[3] < 4))
7660     return false;
7661
7662   return true;
7663 }
7664
7665 /// \brief Lower a vector shuffle using the SHUFPS instruction.
7666 ///
7667 /// This is a helper routine dedicated to lowering vector shuffles using SHUFPS.
7668 /// It makes no assumptions about whether this is the *best* lowering, it simply
7669 /// uses it.
7670 static SDValue lowerVectorShuffleWithSHUFPS(SDLoc DL, MVT VT,
7671                                             ArrayRef<int> Mask, SDValue V1,
7672                                             SDValue V2, SelectionDAG &DAG) {
7673   SDValue LowV = V1, HighV = V2;
7674   int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
7675
7676   int NumV2Elements =
7677       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7678
7679   if (NumV2Elements == 1) {
7680     int V2Index =
7681         std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
7682         Mask.begin();
7683
7684     // Compute the index adjacent to V2Index and in the same half by toggling
7685     // the low bit.
7686     int V2AdjIndex = V2Index ^ 1;
7687
7688     if (Mask[V2AdjIndex] == -1) {
7689       // Handles all the cases where we have a single V2 element and an undef.
7690       // This will only ever happen in the high lanes because we commute the
7691       // vector otherwise.
7692       if (V2Index < 2)
7693         std::swap(LowV, HighV);
7694       NewMask[V2Index] -= 4;
7695     } else {
7696       // Handle the case where the V2 element ends up adjacent to a V1 element.
7697       // To make this work, blend them together as the first step.
7698       int V1Index = V2AdjIndex;
7699       int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
7700       V2 = DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
7701                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
7702
7703       // Now proceed to reconstruct the final blend as we have the necessary
7704       // high or low half formed.
7705       if (V2Index < 2) {
7706         LowV = V2;
7707         HighV = V1;
7708       } else {
7709         HighV = V2;
7710       }
7711       NewMask[V1Index] = 2; // We put the V1 element in V2[2].
7712       NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
7713     }
7714   } else if (NumV2Elements == 2) {
7715     if (Mask[0] < 4 && Mask[1] < 4) {
7716       // Handle the easy case where we have V1 in the low lanes and V2 in the
7717       // high lanes.
7718       NewMask[2] -= 4;
7719       NewMask[3] -= 4;
7720     } else if (Mask[2] < 4 && Mask[3] < 4) {
7721       // We also handle the reversed case because this utility may get called
7722       // when we detect a SHUFPS pattern but can't easily commute the shuffle to
7723       // arrange things in the right direction.
7724       NewMask[0] -= 4;
7725       NewMask[1] -= 4;
7726       HighV = V1;
7727       LowV = V2;
7728     } else {
7729       // We have a mixture of V1 and V2 in both low and high lanes. Rather than
7730       // trying to place elements directly, just blend them and set up the final
7731       // shuffle to place them.
7732
7733       // The first two blend mask elements are for V1, the second two are for
7734       // V2.
7735       int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
7736                           Mask[2] < 4 ? Mask[2] : Mask[3],
7737                           (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
7738                           (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
7739       V1 = DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
7740                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
7741
7742       // Now we do a normal shuffle of V1 by giving V1 as both operands to
7743       // a blend.
7744       LowV = HighV = V1;
7745       NewMask[0] = Mask[0] < 4 ? 0 : 2;
7746       NewMask[1] = Mask[0] < 4 ? 2 : 0;
7747       NewMask[2] = Mask[2] < 4 ? 1 : 3;
7748       NewMask[3] = Mask[2] < 4 ? 3 : 1;
7749     }
7750   }
7751   return DAG.getNode(X86ISD::SHUFP, DL, VT, LowV, HighV,
7752                      getV4X86ShuffleImm8ForMask(NewMask, DL, DAG));
7753 }
7754
7755 /// \brief Lower 4-lane 32-bit floating point shuffles.
7756 ///
7757 /// Uses instructions exclusively from the floating point unit to minimize
7758 /// domain crossing penalties, as these are sufficient to implement all v4f32
7759 /// shuffles.
7760 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7761                                        const X86Subtarget *Subtarget,
7762                                        SelectionDAG &DAG) {
7763   SDLoc DL(Op);
7764   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7765   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7766   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7767   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7768   ArrayRef<int> Mask = SVOp->getMask();
7769   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7770
7771   int NumV2Elements =
7772       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7773
7774   if (NumV2Elements == 0) {
7775     // Check for being able to broadcast a single element.
7776     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f32, V1,
7777                                                           Mask, Subtarget, DAG))
7778       return Broadcast;
7779
7780     // Use even/odd duplicate instructions for masks that match their pattern.
7781     if (Subtarget->hasSSE3()) {
7782       if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
7783         return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v4f32, V1);
7784       if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3}))
7785         return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v4f32, V1);
7786     }
7787
7788     if (Subtarget->hasAVX()) {
7789       // If we have AVX, we can use VPERMILPS which will allow folding a load
7790       // into the shuffle.
7791       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f32, V1,
7792                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
7793     }
7794
7795     // Otherwise, use a straight shuffle of a single input vector. We pass the
7796     // input vector to both operands to simulate this with a SHUFPS.
7797     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
7798                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
7799   }
7800
7801   // There are special ways we can lower some single-element blends. However, we
7802   // have custom ways we can lower more complex single-element blends below that
7803   // we defer to if both this and BLENDPS fail to match, so restrict this to
7804   // when the V2 input is targeting element 0 of the mask -- that is the fast
7805   // case here.
7806   if (NumV2Elements == 1 && Mask[0] >= 4)
7807     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4f32, V1, V2,
7808                                                          Mask, Subtarget, DAG))
7809       return V;
7810
7811   if (Subtarget->hasSSE41()) {
7812     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f32, V1, V2, Mask,
7813                                                   Subtarget, DAG))
7814       return Blend;
7815
7816     // Use INSERTPS if we can complete the shuffle efficiently.
7817     if (SDValue V = lowerVectorShuffleAsInsertPS(Op, V1, V2, Mask, DAG))
7818       return V;
7819
7820     if (!isSingleSHUFPSMask(Mask))
7821       if (SDValue BlendPerm = lowerVectorShuffleAsBlendAndPermute(
7822               DL, MVT::v4f32, V1, V2, Mask, DAG))
7823         return BlendPerm;
7824   }
7825
7826   // Use dedicated unpack instructions for masks that match their pattern.
7827   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
7828     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V1, V2);
7829   if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
7830     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V1, V2);
7831   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
7832     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V2, V1);
7833   if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
7834     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V2, V1);
7835
7836   // Otherwise fall back to a SHUFPS lowering strategy.
7837   return lowerVectorShuffleWithSHUFPS(DL, MVT::v4f32, Mask, V1, V2, DAG);
7838 }
7839
7840 /// \brief Lower 4-lane i32 vector shuffles.
7841 ///
7842 /// We try to handle these with integer-domain shuffles where we can, but for
7843 /// blends we use the floating point domain blend instructions.
7844 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7845                                        const X86Subtarget *Subtarget,
7846                                        SelectionDAG &DAG) {
7847   SDLoc DL(Op);
7848   assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
7849   assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7850   assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7851   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7852   ArrayRef<int> Mask = SVOp->getMask();
7853   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7854
7855   // Whenever we can lower this as a zext, that instruction is strictly faster
7856   // than any alternative. It also allows us to fold memory operands into the
7857   // shuffle in many cases.
7858   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v4i32, V1, V2,
7859                                                          Mask, Subtarget, DAG))
7860     return ZExt;
7861
7862   int NumV2Elements =
7863       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7864
7865   if (NumV2Elements == 0) {
7866     // Check for being able to broadcast a single element.
7867     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i32, V1,
7868                                                           Mask, Subtarget, DAG))
7869       return Broadcast;
7870
7871     // Straight shuffle of a single input vector. For everything from SSE2
7872     // onward this has a single fast instruction with no scary immediates.
7873     // We coerce the shuffle pattern to be compatible with UNPCK instructions
7874     // but we aren't actually going to use the UNPCK instruction because doing
7875     // so prevents folding a load into this instruction or making a copy.
7876     const int UnpackLoMask[] = {0, 0, 1, 1};
7877     const int UnpackHiMask[] = {2, 2, 3, 3};
7878     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 1, 1}))
7879       Mask = UnpackLoMask;
7880     else if (isShuffleEquivalent(V1, V2, Mask, {2, 2, 3, 3}))
7881       Mask = UnpackHiMask;
7882
7883     return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
7884                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
7885   }
7886
7887   // Try to use shift instructions.
7888   if (SDValue Shift =
7889           lowerVectorShuffleAsShift(DL, MVT::v4i32, V1, V2, Mask, DAG))
7890     return Shift;
7891
7892   // There are special ways we can lower some single-element blends.
7893   if (NumV2Elements == 1)
7894     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4i32, V1, V2,
7895                                                          Mask, Subtarget, DAG))
7896       return V;
7897
7898   // We have different paths for blend lowering, but they all must use the
7899   // *exact* same predicate.
7900   bool IsBlendSupported = Subtarget->hasSSE41();
7901   if (IsBlendSupported)
7902     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i32, V1, V2, Mask,
7903                                                   Subtarget, DAG))
7904       return Blend;
7905
7906   if (SDValue Masked =
7907           lowerVectorShuffleAsBitMask(DL, MVT::v4i32, V1, V2, Mask, DAG))
7908     return Masked;
7909
7910   // Use dedicated unpack instructions for masks that match their pattern.
7911   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
7912     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V1, V2);
7913   if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
7914     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V1, V2);
7915   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
7916     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V2, V1);
7917   if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
7918     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V2, V1);
7919
7920   // Try to use byte rotation instructions.
7921   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
7922   if (Subtarget->hasSSSE3())
7923     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
7924             DL, MVT::v4i32, V1, V2, Mask, Subtarget, DAG))
7925       return Rotate;
7926
7927   // If we have direct support for blends, we should lower by decomposing into
7928   // a permute. That will be faster than the domain cross.
7929   if (IsBlendSupported)
7930     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i32, V1, V2,
7931                                                       Mask, DAG);
7932
7933   // Try to lower by permuting the inputs into an unpack instruction.
7934   if (SDValue Unpack =
7935           lowerVectorShuffleAsUnpack(DL, MVT::v4i32, V1, V2, Mask, DAG))
7936     return Unpack;
7937
7938   // We implement this with SHUFPS because it can blend from two vectors.
7939   // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
7940   // up the inputs, bypassing domain shift penalties that we would encur if we
7941   // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
7942   // relevant.
7943   return DAG.getBitcast(
7944       MVT::v4i32,
7945       DAG.getVectorShuffle(MVT::v4f32, DL, DAG.getBitcast(MVT::v4f32, V1),
7946                            DAG.getBitcast(MVT::v4f32, V2), Mask));
7947 }
7948
7949 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
7950 /// shuffle lowering, and the most complex part.
7951 ///
7952 /// The lowering strategy is to try to form pairs of input lanes which are
7953 /// targeted at the same half of the final vector, and then use a dword shuffle
7954 /// to place them onto the right half, and finally unpack the paired lanes into
7955 /// their final position.
7956 ///
7957 /// The exact breakdown of how to form these dword pairs and align them on the
7958 /// correct sides is really tricky. See the comments within the function for
7959 /// more of the details.
7960 ///
7961 /// This code also handles repeated 128-bit lanes of v8i16 shuffles, but each
7962 /// lane must shuffle the *exact* same way. In fact, you must pass a v8 Mask to
7963 /// this routine for it to work correctly. To shuffle a 256-bit or 512-bit i16
7964 /// vector, form the analogous 128-bit 8-element Mask.
7965 static SDValue lowerV8I16GeneralSingleInputVectorShuffle(
7966     SDLoc DL, MVT VT, SDValue V, MutableArrayRef<int> Mask,
7967     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7968   assert(VT.getScalarType() == MVT::i16 && "Bad input type!");
7969   MVT PSHUFDVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
7970
7971   assert(Mask.size() == 8 && "Shuffle mask length doen't match!");
7972   MutableArrayRef<int> LoMask = Mask.slice(0, 4);
7973   MutableArrayRef<int> HiMask = Mask.slice(4, 4);
7974
7975   SmallVector<int, 4> LoInputs;
7976   std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
7977                [](int M) { return M >= 0; });
7978   std::sort(LoInputs.begin(), LoInputs.end());
7979   LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
7980   SmallVector<int, 4> HiInputs;
7981   std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
7982                [](int M) { return M >= 0; });
7983   std::sort(HiInputs.begin(), HiInputs.end());
7984   HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
7985   int NumLToL =
7986       std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
7987   int NumHToL = LoInputs.size() - NumLToL;
7988   int NumLToH =
7989       std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
7990   int NumHToH = HiInputs.size() - NumLToH;
7991   MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
7992   MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
7993   MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
7994   MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
7995
7996   // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
7997   // such inputs we can swap two of the dwords across the half mark and end up
7998   // with <=2 inputs to each half in each half. Once there, we can fall through
7999   // to the generic code below. For example:
8000   //
8001   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8002   // Mask:  [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
8003   //
8004   // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
8005   // and an existing 2-into-2 on the other half. In this case we may have to
8006   // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
8007   // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
8008   // Fortunately, we don't have to handle anything but a 2-into-2 pattern
8009   // because any other situation (including a 3-into-1 or 1-into-3 in the other
8010   // half than the one we target for fixing) will be fixed when we re-enter this
8011   // path. We will also combine away any sequence of PSHUFD instructions that
8012   // result into a single instruction. Here is an example of the tricky case:
8013   //
8014   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8015   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
8016   //
8017   // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
8018   //
8019   // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
8020   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
8021   //
8022   // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
8023   // Mask:  [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
8024   //
8025   // The result is fine to be handled by the generic logic.
8026   auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
8027                           ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
8028                           int AOffset, int BOffset) {
8029     assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
8030            "Must call this with A having 3 or 1 inputs from the A half.");
8031     assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
8032            "Must call this with B having 1 or 3 inputs from the B half.");
8033     assert(AToAInputs.size() + BToAInputs.size() == 4 &&
8034            "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
8035
8036     // Compute the index of dword with only one word among the three inputs in
8037     // a half by taking the sum of the half with three inputs and subtracting
8038     // the sum of the actual three inputs. The difference is the remaining
8039     // slot.
8040     int ADWord, BDWord;
8041     int &TripleDWord = AToAInputs.size() == 3 ? ADWord : BDWord;
8042     int &OneInputDWord = AToAInputs.size() == 3 ? BDWord : ADWord;
8043     int TripleInputOffset = AToAInputs.size() == 3 ? AOffset : BOffset;
8044     ArrayRef<int> TripleInputs = AToAInputs.size() == 3 ? AToAInputs : BToAInputs;
8045     int OneInput = AToAInputs.size() == 3 ? BToAInputs[0] : AToAInputs[0];
8046     int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
8047     int TripleNonInputIdx =
8048         TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
8049     TripleDWord = TripleNonInputIdx / 2;
8050
8051     // We use xor with one to compute the adjacent DWord to whichever one the
8052     // OneInput is in.
8053     OneInputDWord = (OneInput / 2) ^ 1;
8054
8055     // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
8056     // and BToA inputs. If there is also such a problem with the BToB and AToB
8057     // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
8058     // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
8059     // is essential that we don't *create* a 3<-1 as then we might oscillate.
8060     if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
8061       // Compute how many inputs will be flipped by swapping these DWords. We
8062       // need
8063       // to balance this to ensure we don't form a 3-1 shuffle in the other
8064       // half.
8065       int NumFlippedAToBInputs =
8066           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
8067           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
8068       int NumFlippedBToBInputs =
8069           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
8070           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
8071       if ((NumFlippedAToBInputs == 1 &&
8072            (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
8073           (NumFlippedBToBInputs == 1 &&
8074            (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
8075         // We choose whether to fix the A half or B half based on whether that
8076         // half has zero flipped inputs. At zero, we may not be able to fix it
8077         // with that half. We also bias towards fixing the B half because that
8078         // will more commonly be the high half, and we have to bias one way.
8079         auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
8080                                                        ArrayRef<int> Inputs) {
8081           int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
8082           bool IsFixIdxInput = std::find(Inputs.begin(), Inputs.end(),
8083                                          PinnedIdx ^ 1) != Inputs.end();
8084           // Determine whether the free index is in the flipped dword or the
8085           // unflipped dword based on where the pinned index is. We use this bit
8086           // in an xor to conditionally select the adjacent dword.
8087           int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
8088           bool IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8089                                              FixFreeIdx) != Inputs.end();
8090           if (IsFixIdxInput == IsFixFreeIdxInput)
8091             FixFreeIdx += 1;
8092           IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8093                                         FixFreeIdx) != Inputs.end();
8094           assert(IsFixIdxInput != IsFixFreeIdxInput &&
8095                  "We need to be changing the number of flipped inputs!");
8096           int PSHUFHalfMask[] = {0, 1, 2, 3};
8097           std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
8098           V = DAG.getNode(FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
8099                           MVT::v8i16, V,
8100                           getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DL, DAG));
8101
8102           for (int &M : Mask)
8103             if (M != -1 && M == FixIdx)
8104               M = FixFreeIdx;
8105             else if (M != -1 && M == FixFreeIdx)
8106               M = FixIdx;
8107         };
8108         if (NumFlippedBToBInputs != 0) {
8109           int BPinnedIdx =
8110               BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8111           FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
8112         } else {
8113           assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
8114           int APinnedIdx =
8115               AToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8116           FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
8117         }
8118       }
8119     }
8120
8121     int PSHUFDMask[] = {0, 1, 2, 3};
8122     PSHUFDMask[ADWord] = BDWord;
8123     PSHUFDMask[BDWord] = ADWord;
8124     V = DAG.getBitcast(
8125         VT,
8126         DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
8127                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
8128
8129     // Adjust the mask to match the new locations of A and B.
8130     for (int &M : Mask)
8131       if (M != -1 && M/2 == ADWord)
8132         M = 2 * BDWord + M % 2;
8133       else if (M != -1 && M/2 == BDWord)
8134         M = 2 * ADWord + M % 2;
8135
8136     // Recurse back into this routine to re-compute state now that this isn't
8137     // a 3 and 1 problem.
8138     return lowerV8I16GeneralSingleInputVectorShuffle(DL, VT, V, Mask, Subtarget,
8139                                                      DAG);
8140   };
8141   if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
8142     return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
8143   else if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
8144     return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
8145
8146   // At this point there are at most two inputs to the low and high halves from
8147   // each half. That means the inputs can always be grouped into dwords and
8148   // those dwords can then be moved to the correct half with a dword shuffle.
8149   // We use at most one low and one high word shuffle to collect these paired
8150   // inputs into dwords, and finally a dword shuffle to place them.
8151   int PSHUFLMask[4] = {-1, -1, -1, -1};
8152   int PSHUFHMask[4] = {-1, -1, -1, -1};
8153   int PSHUFDMask[4] = {-1, -1, -1, -1};
8154
8155   // First fix the masks for all the inputs that are staying in their
8156   // original halves. This will then dictate the targets of the cross-half
8157   // shuffles.
8158   auto fixInPlaceInputs =
8159       [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
8160                     MutableArrayRef<int> SourceHalfMask,
8161                     MutableArrayRef<int> HalfMask, int HalfOffset) {
8162     if (InPlaceInputs.empty())
8163       return;
8164     if (InPlaceInputs.size() == 1) {
8165       SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8166           InPlaceInputs[0] - HalfOffset;
8167       PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
8168       return;
8169     }
8170     if (IncomingInputs.empty()) {
8171       // Just fix all of the in place inputs.
8172       for (int Input : InPlaceInputs) {
8173         SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
8174         PSHUFDMask[Input / 2] = Input / 2;
8175       }
8176       return;
8177     }
8178
8179     assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
8180     SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8181         InPlaceInputs[0] - HalfOffset;
8182     // Put the second input next to the first so that they are packed into
8183     // a dword. We find the adjacent index by toggling the low bit.
8184     int AdjIndex = InPlaceInputs[0] ^ 1;
8185     SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
8186     std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
8187     PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
8188   };
8189   fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
8190   fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
8191
8192   // Now gather the cross-half inputs and place them into a free dword of
8193   // their target half.
8194   // FIXME: This operation could almost certainly be simplified dramatically to
8195   // look more like the 3-1 fixing operation.
8196   auto moveInputsToRightHalf = [&PSHUFDMask](
8197       MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
8198       MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
8199       MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
8200       int DestOffset) {
8201     auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
8202       return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
8203     };
8204     auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
8205                                                int Word) {
8206       int LowWord = Word & ~1;
8207       int HighWord = Word | 1;
8208       return isWordClobbered(SourceHalfMask, LowWord) ||
8209              isWordClobbered(SourceHalfMask, HighWord);
8210     };
8211
8212     if (IncomingInputs.empty())
8213       return;
8214
8215     if (ExistingInputs.empty()) {
8216       // Map any dwords with inputs from them into the right half.
8217       for (int Input : IncomingInputs) {
8218         // If the source half mask maps over the inputs, turn those into
8219         // swaps and use the swapped lane.
8220         if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
8221           if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
8222             SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
8223                 Input - SourceOffset;
8224             // We have to swap the uses in our half mask in one sweep.
8225             for (int &M : HalfMask)
8226               if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
8227                 M = Input;
8228               else if (M == Input)
8229                 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8230           } else {
8231             assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
8232                        Input - SourceOffset &&
8233                    "Previous placement doesn't match!");
8234           }
8235           // Note that this correctly re-maps both when we do a swap and when
8236           // we observe the other side of the swap above. We rely on that to
8237           // avoid swapping the members of the input list directly.
8238           Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8239         }
8240
8241         // Map the input's dword into the correct half.
8242         if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
8243           PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
8244         else
8245           assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
8246                      Input / 2 &&
8247                  "Previous placement doesn't match!");
8248       }
8249
8250       // And just directly shift any other-half mask elements to be same-half
8251       // as we will have mirrored the dword containing the element into the
8252       // same position within that half.
8253       for (int &M : HalfMask)
8254         if (M >= SourceOffset && M < SourceOffset + 4) {
8255           M = M - SourceOffset + DestOffset;
8256           assert(M >= 0 && "This should never wrap below zero!");
8257         }
8258       return;
8259     }
8260
8261     // Ensure we have the input in a viable dword of its current half. This
8262     // is particularly tricky because the original position may be clobbered
8263     // by inputs being moved and *staying* in that half.
8264     if (IncomingInputs.size() == 1) {
8265       if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8266         int InputFixed = std::find(std::begin(SourceHalfMask),
8267                                    std::end(SourceHalfMask), -1) -
8268                          std::begin(SourceHalfMask) + SourceOffset;
8269         SourceHalfMask[InputFixed - SourceOffset] =
8270             IncomingInputs[0] - SourceOffset;
8271         std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
8272                      InputFixed);
8273         IncomingInputs[0] = InputFixed;
8274       }
8275     } else if (IncomingInputs.size() == 2) {
8276       if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
8277           isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8278         // We have two non-adjacent or clobbered inputs we need to extract from
8279         // the source half. To do this, we need to map them into some adjacent
8280         // dword slot in the source mask.
8281         int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
8282                               IncomingInputs[1] - SourceOffset};
8283
8284         // If there is a free slot in the source half mask adjacent to one of
8285         // the inputs, place the other input in it. We use (Index XOR 1) to
8286         // compute an adjacent index.
8287         if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
8288             SourceHalfMask[InputsFixed[0] ^ 1] == -1) {
8289           SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
8290           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8291           InputsFixed[1] = InputsFixed[0] ^ 1;
8292         } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
8293                    SourceHalfMask[InputsFixed[1] ^ 1] == -1) {
8294           SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
8295           SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
8296           InputsFixed[0] = InputsFixed[1] ^ 1;
8297         } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] == -1 &&
8298                    SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] == -1) {
8299           // The two inputs are in the same DWord but it is clobbered and the
8300           // adjacent DWord isn't used at all. Move both inputs to the free
8301           // slot.
8302           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
8303           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
8304           InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
8305           InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
8306         } else {
8307           // The only way we hit this point is if there is no clobbering
8308           // (because there are no off-half inputs to this half) and there is no
8309           // free slot adjacent to one of the inputs. In this case, we have to
8310           // swap an input with a non-input.
8311           for (int i = 0; i < 4; ++i)
8312             assert((SourceHalfMask[i] == -1 || SourceHalfMask[i] == i) &&
8313                    "We can't handle any clobbers here!");
8314           assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
8315                  "Cannot have adjacent inputs here!");
8316
8317           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8318           SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
8319
8320           // We also have to update the final source mask in this case because
8321           // it may need to undo the above swap.
8322           for (int &M : FinalSourceHalfMask)
8323             if (M == (InputsFixed[0] ^ 1) + SourceOffset)
8324               M = InputsFixed[1] + SourceOffset;
8325             else if (M == InputsFixed[1] + SourceOffset)
8326               M = (InputsFixed[0] ^ 1) + SourceOffset;
8327
8328           InputsFixed[1] = InputsFixed[0] ^ 1;
8329         }
8330
8331         // Point everything at the fixed inputs.
8332         for (int &M : HalfMask)
8333           if (M == IncomingInputs[0])
8334             M = InputsFixed[0] + SourceOffset;
8335           else if (M == IncomingInputs[1])
8336             M = InputsFixed[1] + SourceOffset;
8337
8338         IncomingInputs[0] = InputsFixed[0] + SourceOffset;
8339         IncomingInputs[1] = InputsFixed[1] + SourceOffset;
8340       }
8341     } else {
8342       llvm_unreachable("Unhandled input size!");
8343     }
8344
8345     // Now hoist the DWord down to the right half.
8346     int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
8347     assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
8348     PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
8349     for (int &M : HalfMask)
8350       for (int Input : IncomingInputs)
8351         if (M == Input)
8352           M = FreeDWord * 2 + Input % 2;
8353   };
8354   moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
8355                         /*SourceOffset*/ 4, /*DestOffset*/ 0);
8356   moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
8357                         /*SourceOffset*/ 0, /*DestOffset*/ 4);
8358
8359   // Now enact all the shuffles we've computed to move the inputs into their
8360   // target half.
8361   if (!isNoopShuffleMask(PSHUFLMask))
8362     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8363                     getV4X86ShuffleImm8ForMask(PSHUFLMask, DL, DAG));
8364   if (!isNoopShuffleMask(PSHUFHMask))
8365     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8366                     getV4X86ShuffleImm8ForMask(PSHUFHMask, DL, DAG));
8367   if (!isNoopShuffleMask(PSHUFDMask))
8368     V = DAG.getBitcast(
8369         VT,
8370         DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
8371                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
8372
8373   // At this point, each half should contain all its inputs, and we can then
8374   // just shuffle them into their final position.
8375   assert(std::count_if(LoMask.begin(), LoMask.end(),
8376                        [](int M) { return M >= 4; }) == 0 &&
8377          "Failed to lift all the high half inputs to the low mask!");
8378   assert(std::count_if(HiMask.begin(), HiMask.end(),
8379                        [](int M) { return M >= 0 && M < 4; }) == 0 &&
8380          "Failed to lift all the low half inputs to the high mask!");
8381
8382   // Do a half shuffle for the low mask.
8383   if (!isNoopShuffleMask(LoMask))
8384     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8385                     getV4X86ShuffleImm8ForMask(LoMask, DL, DAG));
8386
8387   // Do a half shuffle with the high mask after shifting its values down.
8388   for (int &M : HiMask)
8389     if (M >= 0)
8390       M -= 4;
8391   if (!isNoopShuffleMask(HiMask))
8392     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8393                     getV4X86ShuffleImm8ForMask(HiMask, DL, DAG));
8394
8395   return V;
8396 }
8397
8398 /// \brief Helper to form a PSHUFB-based shuffle+blend.
8399 static SDValue lowerVectorShuffleAsPSHUFB(SDLoc DL, MVT VT, SDValue V1,
8400                                           SDValue V2, ArrayRef<int> Mask,
8401                                           SelectionDAG &DAG, bool &V1InUse,
8402                                           bool &V2InUse) {
8403   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
8404   SDValue V1Mask[16];
8405   SDValue V2Mask[16];
8406   V1InUse = false;
8407   V2InUse = false;
8408
8409   int Size = Mask.size();
8410   int Scale = 16 / Size;
8411   for (int i = 0; i < 16; ++i) {
8412     if (Mask[i / Scale] == -1) {
8413       V1Mask[i] = V2Mask[i] = DAG.getUNDEF(MVT::i8);
8414     } else {
8415       const int ZeroMask = 0x80;
8416       int V1Idx = Mask[i / Scale] < Size ? Mask[i / Scale] * Scale + i % Scale
8417                                           : ZeroMask;
8418       int V2Idx = Mask[i / Scale] < Size
8419                       ? ZeroMask
8420                       : (Mask[i / Scale] - Size) * Scale + i % Scale;
8421       if (Zeroable[i / Scale])
8422         V1Idx = V2Idx = ZeroMask;
8423       V1Mask[i] = DAG.getConstant(V1Idx, DL, MVT::i8);
8424       V2Mask[i] = DAG.getConstant(V2Idx, DL, MVT::i8);
8425       V1InUse |= (ZeroMask != V1Idx);
8426       V2InUse |= (ZeroMask != V2Idx);
8427     }
8428   }
8429
8430   if (V1InUse)
8431     V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8432                      DAG.getBitcast(MVT::v16i8, V1),
8433                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
8434   if (V2InUse)
8435     V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8436                      DAG.getBitcast(MVT::v16i8, V2),
8437                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
8438
8439   // If we need shuffled inputs from both, blend the two.
8440   SDValue V;
8441   if (V1InUse && V2InUse)
8442     V = DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
8443   else
8444     V = V1InUse ? V1 : V2;
8445
8446   // Cast the result back to the correct type.
8447   return DAG.getBitcast(VT, V);
8448 }
8449
8450 /// \brief Generic lowering of 8-lane i16 shuffles.
8451 ///
8452 /// This handles both single-input shuffles and combined shuffle/blends with
8453 /// two inputs. The single input shuffles are immediately delegated to
8454 /// a dedicated lowering routine.
8455 ///
8456 /// The blends are lowered in one of three fundamental ways. If there are few
8457 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
8458 /// of the input is significantly cheaper when lowered as an interleaving of
8459 /// the two inputs, try to interleave them. Otherwise, blend the low and high
8460 /// halves of the inputs separately (making them have relatively few inputs)
8461 /// and then concatenate them.
8462 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8463                                        const X86Subtarget *Subtarget,
8464                                        SelectionDAG &DAG) {
8465   SDLoc DL(Op);
8466   assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
8467   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8468   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8469   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8470   ArrayRef<int> OrigMask = SVOp->getMask();
8471   int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
8472                         OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
8473   MutableArrayRef<int> Mask(MaskStorage);
8474
8475   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
8476
8477   // Whenever we can lower this as a zext, that instruction is strictly faster
8478   // than any alternative.
8479   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
8480           DL, MVT::v8i16, V1, V2, OrigMask, Subtarget, DAG))
8481     return ZExt;
8482
8483   auto isV1 = [](int M) { return M >= 0 && M < 8; };
8484   (void)isV1;
8485   auto isV2 = [](int M) { return M >= 8; };
8486
8487   int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
8488
8489   if (NumV2Inputs == 0) {
8490     // Check for being able to broadcast a single element.
8491     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i16, V1,
8492                                                           Mask, Subtarget, DAG))
8493       return Broadcast;
8494
8495     // Try to use shift instructions.
8496     if (SDValue Shift =
8497             lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V1, Mask, DAG))
8498       return Shift;
8499
8500     // Use dedicated unpack instructions for masks that match their pattern.
8501     if (isShuffleEquivalent(V1, V1, Mask, {0, 0, 1, 1, 2, 2, 3, 3}))
8502       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V1);
8503     if (isShuffleEquivalent(V1, V1, Mask, {4, 4, 5, 5, 6, 6, 7, 7}))
8504       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V1);
8505
8506     // Try to use byte rotation instructions.
8507     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(DL, MVT::v8i16, V1, V1,
8508                                                         Mask, Subtarget, DAG))
8509       return Rotate;
8510
8511     return lowerV8I16GeneralSingleInputVectorShuffle(DL, MVT::v8i16, V1, Mask,
8512                                                      Subtarget, DAG);
8513   }
8514
8515   assert(std::any_of(Mask.begin(), Mask.end(), isV1) &&
8516          "All single-input shuffles should be canonicalized to be V1-input "
8517          "shuffles.");
8518
8519   // Try to use shift instructions.
8520   if (SDValue Shift =
8521           lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V2, Mask, DAG))
8522     return Shift;
8523
8524   // There are special ways we can lower some single-element blends.
8525   if (NumV2Inputs == 1)
8526     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v8i16, V1, V2,
8527                                                          Mask, Subtarget, DAG))
8528       return V;
8529
8530   // We have different paths for blend lowering, but they all must use the
8531   // *exact* same predicate.
8532   bool IsBlendSupported = Subtarget->hasSSE41();
8533   if (IsBlendSupported)
8534     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i16, V1, V2, Mask,
8535                                                   Subtarget, DAG))
8536       return Blend;
8537
8538   if (SDValue Masked =
8539           lowerVectorShuffleAsBitMask(DL, MVT::v8i16, V1, V2, Mask, DAG))
8540     return Masked;
8541
8542   // Use dedicated unpack instructions for masks that match their pattern.
8543   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 2, 10, 3, 11}))
8544     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V2);
8545   if (isShuffleEquivalent(V1, V2, Mask, {4, 12, 5, 13, 6, 14, 7, 15}))
8546     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V2);
8547
8548   // Try to use byte rotation instructions.
8549   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8550           DL, MVT::v8i16, V1, V2, Mask, Subtarget, DAG))
8551     return Rotate;
8552
8553   if (SDValue BitBlend =
8554           lowerVectorShuffleAsBitBlend(DL, MVT::v8i16, V1, V2, Mask, DAG))
8555     return BitBlend;
8556
8557   if (SDValue Unpack =
8558           lowerVectorShuffleAsUnpack(DL, MVT::v8i16, V1, V2, Mask, DAG))
8559     return Unpack;
8560
8561   // If we can't directly blend but can use PSHUFB, that will be better as it
8562   // can both shuffle and set up the inefficient blend.
8563   if (!IsBlendSupported && Subtarget->hasSSSE3()) {
8564     bool V1InUse, V2InUse;
8565     return lowerVectorShuffleAsPSHUFB(DL, MVT::v8i16, V1, V2, Mask, DAG,
8566                                       V1InUse, V2InUse);
8567   }
8568
8569   // We can always bit-blend if we have to so the fallback strategy is to
8570   // decompose into single-input permutes and blends.
8571   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i16, V1, V2,
8572                                                       Mask, DAG);
8573 }
8574
8575 /// \brief Check whether a compaction lowering can be done by dropping even
8576 /// elements and compute how many times even elements must be dropped.
8577 ///
8578 /// This handles shuffles which take every Nth element where N is a power of
8579 /// two. Example shuffle masks:
8580 ///
8581 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14,  0,  2,  4,  6,  8, 10, 12, 14
8582 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
8583 ///  N = 2:  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12
8584 ///  N = 2:  0,  4,  8, 12, 16, 20, 24, 28,  0,  4,  8, 12, 16, 20, 24, 28
8585 ///  N = 3:  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8
8586 ///  N = 3:  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24
8587 ///
8588 /// Any of these lanes can of course be undef.
8589 ///
8590 /// This routine only supports N <= 3.
8591 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
8592 /// for larger N.
8593 ///
8594 /// \returns N above, or the number of times even elements must be dropped if
8595 /// there is such a number. Otherwise returns zero.
8596 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
8597   // Figure out whether we're looping over two inputs or just one.
8598   bool IsSingleInput = isSingleInputShuffleMask(Mask);
8599
8600   // The modulus for the shuffle vector entries is based on whether this is
8601   // a single input or not.
8602   int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
8603   assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
8604          "We should only be called with masks with a power-of-2 size!");
8605
8606   uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
8607
8608   // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
8609   // and 2^3 simultaneously. This is because we may have ambiguity with
8610   // partially undef inputs.
8611   bool ViableForN[3] = {true, true, true};
8612
8613   for (int i = 0, e = Mask.size(); i < e; ++i) {
8614     // Ignore undef lanes, we'll optimistically collapse them to the pattern we
8615     // want.
8616     if (Mask[i] == -1)
8617       continue;
8618
8619     bool IsAnyViable = false;
8620     for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8621       if (ViableForN[j]) {
8622         uint64_t N = j + 1;
8623
8624         // The shuffle mask must be equal to (i * 2^N) % M.
8625         if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
8626           IsAnyViable = true;
8627         else
8628           ViableForN[j] = false;
8629       }
8630     // Early exit if we exhaust the possible powers of two.
8631     if (!IsAnyViable)
8632       break;
8633   }
8634
8635   for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8636     if (ViableForN[j])
8637       return j + 1;
8638
8639   // Return 0 as there is no viable power of two.
8640   return 0;
8641 }
8642
8643 /// \brief Generic lowering of v16i8 shuffles.
8644 ///
8645 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
8646 /// detect any complexity reducing interleaving. If that doesn't help, it uses
8647 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
8648 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
8649 /// back together.
8650 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8651                                        const X86Subtarget *Subtarget,
8652                                        SelectionDAG &DAG) {
8653   SDLoc DL(Op);
8654   assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
8655   assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8656   assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8657   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8658   ArrayRef<int> Mask = SVOp->getMask();
8659   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
8660
8661   // Try to use shift instructions.
8662   if (SDValue Shift =
8663           lowerVectorShuffleAsShift(DL, MVT::v16i8, V1, V2, Mask, DAG))
8664     return Shift;
8665
8666   // Try to use byte rotation instructions.
8667   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8668           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
8669     return Rotate;
8670
8671   // Try to use a zext lowering.
8672   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
8673           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
8674     return ZExt;
8675
8676   int NumV2Elements =
8677       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 16; });
8678
8679   // For single-input shuffles, there are some nicer lowering tricks we can use.
8680   if (NumV2Elements == 0) {
8681     // Check for being able to broadcast a single element.
8682     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i8, V1,
8683                                                           Mask, Subtarget, DAG))
8684       return Broadcast;
8685
8686     // Check whether we can widen this to an i16 shuffle by duplicating bytes.
8687     // Notably, this handles splat and partial-splat shuffles more efficiently.
8688     // However, it only makes sense if the pre-duplication shuffle simplifies
8689     // things significantly. Currently, this means we need to be able to
8690     // express the pre-duplication shuffle as an i16 shuffle.
8691     //
8692     // FIXME: We should check for other patterns which can be widened into an
8693     // i16 shuffle as well.
8694     auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
8695       for (int i = 0; i < 16; i += 2)
8696         if (Mask[i] != -1 && Mask[i + 1] != -1 && Mask[i] != Mask[i + 1])
8697           return false;
8698
8699       return true;
8700     };
8701     auto tryToWidenViaDuplication = [&]() -> SDValue {
8702       if (!canWidenViaDuplication(Mask))
8703         return SDValue();
8704       SmallVector<int, 4> LoInputs;
8705       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
8706                    [](int M) { return M >= 0 && M < 8; });
8707       std::sort(LoInputs.begin(), LoInputs.end());
8708       LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
8709                      LoInputs.end());
8710       SmallVector<int, 4> HiInputs;
8711       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
8712                    [](int M) { return M >= 8; });
8713       std::sort(HiInputs.begin(), HiInputs.end());
8714       HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
8715                      HiInputs.end());
8716
8717       bool TargetLo = LoInputs.size() >= HiInputs.size();
8718       ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
8719       ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
8720
8721       int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
8722       SmallDenseMap<int, int, 8> LaneMap;
8723       for (int I : InPlaceInputs) {
8724         PreDupI16Shuffle[I/2] = I/2;
8725         LaneMap[I] = I;
8726       }
8727       int j = TargetLo ? 0 : 4, je = j + 4;
8728       for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
8729         // Check if j is already a shuffle of this input. This happens when
8730         // there are two adjacent bytes after we move the low one.
8731         if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
8732           // If we haven't yet mapped the input, search for a slot into which
8733           // we can map it.
8734           while (j < je && PreDupI16Shuffle[j] != -1)
8735             ++j;
8736
8737           if (j == je)
8738             // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
8739             return SDValue();
8740
8741           // Map this input with the i16 shuffle.
8742           PreDupI16Shuffle[j] = MovingInputs[i] / 2;
8743         }
8744
8745         // Update the lane map based on the mapping we ended up with.
8746         LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
8747       }
8748       V1 = DAG.getBitcast(
8749           MVT::v16i8,
8750           DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
8751                                DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
8752
8753       // Unpack the bytes to form the i16s that will be shuffled into place.
8754       V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
8755                        MVT::v16i8, V1, V1);
8756
8757       int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8758       for (int i = 0; i < 16; ++i)
8759         if (Mask[i] != -1) {
8760           int MappedMask = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
8761           assert(MappedMask < 8 && "Invalid v8 shuffle mask!");
8762           if (PostDupI16Shuffle[i / 2] == -1)
8763             PostDupI16Shuffle[i / 2] = MappedMask;
8764           else
8765             assert(PostDupI16Shuffle[i / 2] == MappedMask &&
8766                    "Conflicting entrties in the original shuffle!");
8767         }
8768       return DAG.getBitcast(
8769           MVT::v16i8,
8770           DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
8771                                DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
8772     };
8773     if (SDValue V = tryToWidenViaDuplication())
8774       return V;
8775   }
8776
8777   // Use dedicated unpack instructions for masks that match their pattern.
8778   if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
8779                                          0, 16, 1, 17, 2, 18, 3, 19,
8780                                          // High half.
8781                                          4, 20, 5, 21, 6, 22, 7, 23}))
8782     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V1, V2);
8783   if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
8784                                          8, 24, 9, 25, 10, 26, 11, 27,
8785                                          // High half.
8786                                          12, 28, 13, 29, 14, 30, 15, 31}))
8787     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V1, V2);
8788
8789   // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
8790   // with PSHUFB. It is important to do this before we attempt to generate any
8791   // blends but after all of the single-input lowerings. If the single input
8792   // lowerings can find an instruction sequence that is faster than a PSHUFB, we
8793   // want to preserve that and we can DAG combine any longer sequences into
8794   // a PSHUFB in the end. But once we start blending from multiple inputs,
8795   // the complexity of DAG combining bad patterns back into PSHUFB is too high,
8796   // and there are *very* few patterns that would actually be faster than the
8797   // PSHUFB approach because of its ability to zero lanes.
8798   //
8799   // FIXME: The only exceptions to the above are blends which are exact
8800   // interleavings with direct instructions supporting them. We currently don't
8801   // handle those well here.
8802   if (Subtarget->hasSSSE3()) {
8803     bool V1InUse = false;
8804     bool V2InUse = false;
8805
8806     SDValue PSHUFB = lowerVectorShuffleAsPSHUFB(DL, MVT::v16i8, V1, V2, Mask,
8807                                                 DAG, V1InUse, V2InUse);
8808
8809     // If both V1 and V2 are in use and we can use a direct blend or an unpack,
8810     // do so. This avoids using them to handle blends-with-zero which is
8811     // important as a single pshufb is significantly faster for that.
8812     if (V1InUse && V2InUse) {
8813       if (Subtarget->hasSSE41())
8814         if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i8, V1, V2,
8815                                                       Mask, Subtarget, DAG))
8816           return Blend;
8817
8818       // We can use an unpack to do the blending rather than an or in some
8819       // cases. Even though the or may be (very minorly) more efficient, we
8820       // preference this lowering because there are common cases where part of
8821       // the complexity of the shuffles goes away when we do the final blend as
8822       // an unpack.
8823       // FIXME: It might be worth trying to detect if the unpack-feeding
8824       // shuffles will both be pshufb, in which case we shouldn't bother with
8825       // this.
8826       if (SDValue Unpack =
8827               lowerVectorShuffleAsUnpack(DL, MVT::v16i8, V1, V2, Mask, DAG))
8828         return Unpack;
8829     }
8830
8831     return PSHUFB;
8832   }
8833
8834   // There are special ways we can lower some single-element blends.
8835   if (NumV2Elements == 1)
8836     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v16i8, V1, V2,
8837                                                          Mask, Subtarget, DAG))
8838       return V;
8839
8840   if (SDValue BitBlend =
8841           lowerVectorShuffleAsBitBlend(DL, MVT::v16i8, V1, V2, Mask, DAG))
8842     return BitBlend;
8843
8844   // Check whether a compaction lowering can be done. This handles shuffles
8845   // which take every Nth element for some even N. See the helper function for
8846   // details.
8847   //
8848   // We special case these as they can be particularly efficiently handled with
8849   // the PACKUSB instruction on x86 and they show up in common patterns of
8850   // rearranging bytes to truncate wide elements.
8851   if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
8852     // NumEvenDrops is the power of two stride of the elements. Another way of
8853     // thinking about it is that we need to drop the even elements this many
8854     // times to get the original input.
8855     bool IsSingleInput = isSingleInputShuffleMask(Mask);
8856
8857     // First we need to zero all the dropped bytes.
8858     assert(NumEvenDrops <= 3 &&
8859            "No support for dropping even elements more than 3 times.");
8860     // We use the mask type to pick which bytes are preserved based on how many
8861     // elements are dropped.
8862     MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
8863     SDValue ByteClearMask = DAG.getBitcast(
8864         MVT::v16i8, DAG.getConstant(0xFF, DL, MaskVTs[NumEvenDrops - 1]));
8865     V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
8866     if (!IsSingleInput)
8867       V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
8868
8869     // Now pack things back together.
8870     V1 = DAG.getBitcast(MVT::v8i16, V1);
8871     V2 = IsSingleInput ? V1 : DAG.getBitcast(MVT::v8i16, V2);
8872     SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
8873     for (int i = 1; i < NumEvenDrops; ++i) {
8874       Result = DAG.getBitcast(MVT::v8i16, Result);
8875       Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
8876     }
8877
8878     return Result;
8879   }
8880
8881   // Handle multi-input cases by blending single-input shuffles.
8882   if (NumV2Elements > 0)
8883     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v16i8, V1, V2,
8884                                                       Mask, DAG);
8885
8886   // The fallback path for single-input shuffles widens this into two v8i16
8887   // vectors with unpacks, shuffles those, and then pulls them back together
8888   // with a pack.
8889   SDValue V = V1;
8890
8891   int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8892   int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8893   for (int i = 0; i < 16; ++i)
8894     if (Mask[i] >= 0)
8895       (i < 8 ? LoBlendMask[i] : HiBlendMask[i % 8]) = Mask[i];
8896
8897   SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
8898
8899   SDValue VLoHalf, VHiHalf;
8900   // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
8901   // them out and avoid using UNPCK{L,H} to extract the elements of V as
8902   // i16s.
8903   if (std::none_of(std::begin(LoBlendMask), std::end(LoBlendMask),
8904                    [](int M) { return M >= 0 && M % 2 == 1; }) &&
8905       std::none_of(std::begin(HiBlendMask), std::end(HiBlendMask),
8906                    [](int M) { return M >= 0 && M % 2 == 1; })) {
8907     // Use a mask to drop the high bytes.
8908     VLoHalf = DAG.getBitcast(MVT::v8i16, V);
8909     VLoHalf = DAG.getNode(ISD::AND, DL, MVT::v8i16, VLoHalf,
8910                      DAG.getConstant(0x00FF, DL, MVT::v8i16));
8911
8912     // This will be a single vector shuffle instead of a blend so nuke VHiHalf.
8913     VHiHalf = DAG.getUNDEF(MVT::v8i16);
8914
8915     // Squash the masks to point directly into VLoHalf.
8916     for (int &M : LoBlendMask)
8917       if (M >= 0)
8918         M /= 2;
8919     for (int &M : HiBlendMask)
8920       if (M >= 0)
8921         M /= 2;
8922   } else {
8923     // Otherwise just unpack the low half of V into VLoHalf and the high half into
8924     // VHiHalf so that we can blend them as i16s.
8925     VLoHalf = DAG.getBitcast(
8926         MVT::v8i16, DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
8927     VHiHalf = DAG.getBitcast(
8928         MVT::v8i16, DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
8929   }
8930
8931   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, LoBlendMask);
8932   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, HiBlendMask);
8933
8934   return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
8935 }
8936
8937 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
8938 ///
8939 /// This routine breaks down the specific type of 128-bit shuffle and
8940 /// dispatches to the lowering routines accordingly.
8941 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8942                                         MVT VT, const X86Subtarget *Subtarget,
8943                                         SelectionDAG &DAG) {
8944   switch (VT.SimpleTy) {
8945   case MVT::v2i64:
8946     return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8947   case MVT::v2f64:
8948     return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8949   case MVT::v4i32:
8950     return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
8951   case MVT::v4f32:
8952     return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
8953   case MVT::v8i16:
8954     return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
8955   case MVT::v16i8:
8956     return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
8957
8958   default:
8959     llvm_unreachable("Unimplemented!");
8960   }
8961 }
8962
8963 /// \brief Helper function to test whether a shuffle mask could be
8964 /// simplified by widening the elements being shuffled.
8965 ///
8966 /// Appends the mask for wider elements in WidenedMask if valid. Otherwise
8967 /// leaves it in an unspecified state.
8968 ///
8969 /// NOTE: This must handle normal vector shuffle masks and *target* vector
8970 /// shuffle masks. The latter have the special property of a '-2' representing
8971 /// a zero-ed lane of a vector.
8972 static bool canWidenShuffleElements(ArrayRef<int> Mask,
8973                                     SmallVectorImpl<int> &WidenedMask) {
8974   for (int i = 0, Size = Mask.size(); i < Size; i += 2) {
8975     // If both elements are undef, its trivial.
8976     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] == SM_SentinelUndef) {
8977       WidenedMask.push_back(SM_SentinelUndef);
8978       continue;
8979     }
8980
8981     // Check for an undef mask and a mask value properly aligned to fit with
8982     // a pair of values. If we find such a case, use the non-undef mask's value.
8983     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] >= 0 && Mask[i + 1] % 2 == 1) {
8984       WidenedMask.push_back(Mask[i + 1] / 2);
8985       continue;
8986     }
8987     if (Mask[i + 1] == SM_SentinelUndef && Mask[i] >= 0 && Mask[i] % 2 == 0) {
8988       WidenedMask.push_back(Mask[i] / 2);
8989       continue;
8990     }
8991
8992     // When zeroing, we need to spread the zeroing across both lanes to widen.
8993     if (Mask[i] == SM_SentinelZero || Mask[i + 1] == SM_SentinelZero) {
8994       if ((Mask[i] == SM_SentinelZero || Mask[i] == SM_SentinelUndef) &&
8995           (Mask[i + 1] == SM_SentinelZero || Mask[i + 1] == SM_SentinelUndef)) {
8996         WidenedMask.push_back(SM_SentinelZero);
8997         continue;
8998       }
8999       return false;
9000     }
9001
9002     // Finally check if the two mask values are adjacent and aligned with
9003     // a pair.
9004     if (Mask[i] != SM_SentinelUndef && Mask[i] % 2 == 0 && Mask[i] + 1 == Mask[i + 1]) {
9005       WidenedMask.push_back(Mask[i] / 2);
9006       continue;
9007     }
9008
9009     // Otherwise we can't safely widen the elements used in this shuffle.
9010     return false;
9011   }
9012   assert(WidenedMask.size() == Mask.size() / 2 &&
9013          "Incorrect size of mask after widening the elements!");
9014
9015   return true;
9016 }
9017
9018 /// \brief Generic routine to split vector shuffle into half-sized shuffles.
9019 ///
9020 /// This routine just extracts two subvectors, shuffles them independently, and
9021 /// then concatenates them back together. This should work effectively with all
9022 /// AVX vector shuffle types.
9023 static SDValue splitAndLowerVectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9024                                           SDValue V2, ArrayRef<int> Mask,
9025                                           SelectionDAG &DAG) {
9026   assert(VT.getSizeInBits() >= 256 &&
9027          "Only for 256-bit or wider vector shuffles!");
9028   assert(V1.getSimpleValueType() == VT && "Bad operand type!");
9029   assert(V2.getSimpleValueType() == VT && "Bad operand type!");
9030
9031   ArrayRef<int> LoMask = Mask.slice(0, Mask.size() / 2);
9032   ArrayRef<int> HiMask = Mask.slice(Mask.size() / 2);
9033
9034   int NumElements = VT.getVectorNumElements();
9035   int SplitNumElements = NumElements / 2;
9036   MVT ScalarVT = VT.getScalarType();
9037   MVT SplitVT = MVT::getVectorVT(ScalarVT, NumElements / 2);
9038
9039   // Rather than splitting build-vectors, just build two narrower build
9040   // vectors. This helps shuffling with splats and zeros.
9041   auto SplitVector = [&](SDValue V) {
9042     while (V.getOpcode() == ISD::BITCAST)
9043       V = V->getOperand(0);
9044
9045     MVT OrigVT = V.getSimpleValueType();
9046     int OrigNumElements = OrigVT.getVectorNumElements();
9047     int OrigSplitNumElements = OrigNumElements / 2;
9048     MVT OrigScalarVT = OrigVT.getScalarType();
9049     MVT OrigSplitVT = MVT::getVectorVT(OrigScalarVT, OrigNumElements / 2);
9050
9051     SDValue LoV, HiV;
9052
9053     auto *BV = dyn_cast<BuildVectorSDNode>(V);
9054     if (!BV) {
9055       LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9056                         DAG.getIntPtrConstant(0, DL));
9057       HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9058                         DAG.getIntPtrConstant(OrigSplitNumElements, DL));
9059     } else {
9060
9061       SmallVector<SDValue, 16> LoOps, HiOps;
9062       for (int i = 0; i < OrigSplitNumElements; ++i) {
9063         LoOps.push_back(BV->getOperand(i));
9064         HiOps.push_back(BV->getOperand(i + OrigSplitNumElements));
9065       }
9066       LoV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, LoOps);
9067       HiV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, HiOps);
9068     }
9069     return std::make_pair(DAG.getBitcast(SplitVT, LoV),
9070                           DAG.getBitcast(SplitVT, HiV));
9071   };
9072
9073   SDValue LoV1, HiV1, LoV2, HiV2;
9074   std::tie(LoV1, HiV1) = SplitVector(V1);
9075   std::tie(LoV2, HiV2) = SplitVector(V2);
9076
9077   // Now create two 4-way blends of these half-width vectors.
9078   auto HalfBlend = [&](ArrayRef<int> HalfMask) {
9079     bool UseLoV1 = false, UseHiV1 = false, UseLoV2 = false, UseHiV2 = false;
9080     SmallVector<int, 32> V1BlendMask, V2BlendMask, BlendMask;
9081     for (int i = 0; i < SplitNumElements; ++i) {
9082       int M = HalfMask[i];
9083       if (M >= NumElements) {
9084         if (M >= NumElements + SplitNumElements)
9085           UseHiV2 = true;
9086         else
9087           UseLoV2 = true;
9088         V2BlendMask.push_back(M - NumElements);
9089         V1BlendMask.push_back(-1);
9090         BlendMask.push_back(SplitNumElements + i);
9091       } else if (M >= 0) {
9092         if (M >= SplitNumElements)
9093           UseHiV1 = true;
9094         else
9095           UseLoV1 = true;
9096         V2BlendMask.push_back(-1);
9097         V1BlendMask.push_back(M);
9098         BlendMask.push_back(i);
9099       } else {
9100         V2BlendMask.push_back(-1);
9101         V1BlendMask.push_back(-1);
9102         BlendMask.push_back(-1);
9103       }
9104     }
9105
9106     // Because the lowering happens after all combining takes place, we need to
9107     // manually combine these blend masks as much as possible so that we create
9108     // a minimal number of high-level vector shuffle nodes.
9109
9110     // First try just blending the halves of V1 or V2.
9111     if (!UseLoV1 && !UseHiV1 && !UseLoV2 && !UseHiV2)
9112       return DAG.getUNDEF(SplitVT);
9113     if (!UseLoV2 && !UseHiV2)
9114       return DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9115     if (!UseLoV1 && !UseHiV1)
9116       return DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9117
9118     SDValue V1Blend, V2Blend;
9119     if (UseLoV1 && UseHiV1) {
9120       V1Blend =
9121         DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9122     } else {
9123       // We only use half of V1 so map the usage down into the final blend mask.
9124       V1Blend = UseLoV1 ? LoV1 : HiV1;
9125       for (int i = 0; i < SplitNumElements; ++i)
9126         if (BlendMask[i] >= 0 && BlendMask[i] < SplitNumElements)
9127           BlendMask[i] = V1BlendMask[i] - (UseLoV1 ? 0 : SplitNumElements);
9128     }
9129     if (UseLoV2 && UseHiV2) {
9130       V2Blend =
9131         DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9132     } else {
9133       // We only use half of V2 so map the usage down into the final blend mask.
9134       V2Blend = UseLoV2 ? LoV2 : HiV2;
9135       for (int i = 0; i < SplitNumElements; ++i)
9136         if (BlendMask[i] >= SplitNumElements)
9137           BlendMask[i] = V2BlendMask[i] + (UseLoV2 ? SplitNumElements : 0);
9138     }
9139     return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
9140   };
9141   SDValue Lo = HalfBlend(LoMask);
9142   SDValue Hi = HalfBlend(HiMask);
9143   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
9144 }
9145
9146 /// \brief Either split a vector in halves or decompose the shuffles and the
9147 /// blend.
9148 ///
9149 /// This is provided as a good fallback for many lowerings of non-single-input
9150 /// shuffles with more than one 128-bit lane. In those cases, we want to select
9151 /// between splitting the shuffle into 128-bit components and stitching those
9152 /// back together vs. extracting the single-input shuffles and blending those
9153 /// results.
9154 static SDValue lowerVectorShuffleAsSplitOrBlend(SDLoc DL, MVT VT, SDValue V1,
9155                                                 SDValue V2, ArrayRef<int> Mask,
9156                                                 SelectionDAG &DAG) {
9157   assert(!isSingleInputShuffleMask(Mask) && "This routine must not be used to "
9158                                             "lower single-input shuffles as it "
9159                                             "could then recurse on itself.");
9160   int Size = Mask.size();
9161
9162   // If this can be modeled as a broadcast of two elements followed by a blend,
9163   // prefer that lowering. This is especially important because broadcasts can
9164   // often fold with memory operands.
9165   auto DoBothBroadcast = [&] {
9166     int V1BroadcastIdx = -1, V2BroadcastIdx = -1;
9167     for (int M : Mask)
9168       if (M >= Size) {
9169         if (V2BroadcastIdx == -1)
9170           V2BroadcastIdx = M - Size;
9171         else if (M - Size != V2BroadcastIdx)
9172           return false;
9173       } else if (M >= 0) {
9174         if (V1BroadcastIdx == -1)
9175           V1BroadcastIdx = M;
9176         else if (M != V1BroadcastIdx)
9177           return false;
9178       }
9179     return true;
9180   };
9181   if (DoBothBroadcast())
9182     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask,
9183                                                       DAG);
9184
9185   // If the inputs all stem from a single 128-bit lane of each input, then we
9186   // split them rather than blending because the split will decompose to
9187   // unusually few instructions.
9188   int LaneCount = VT.getSizeInBits() / 128;
9189   int LaneSize = Size / LaneCount;
9190   SmallBitVector LaneInputs[2];
9191   LaneInputs[0].resize(LaneCount, false);
9192   LaneInputs[1].resize(LaneCount, false);
9193   for (int i = 0; i < Size; ++i)
9194     if (Mask[i] >= 0)
9195       LaneInputs[Mask[i] / Size][(Mask[i] % Size) / LaneSize] = true;
9196   if (LaneInputs[0].count() <= 1 && LaneInputs[1].count() <= 1)
9197     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9198
9199   // Otherwise, just fall back to decomposed shuffles and a blend. This requires
9200   // that the decomposed single-input shuffles don't end up here.
9201   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9202 }
9203
9204 /// \brief Lower a vector shuffle crossing multiple 128-bit lanes as
9205 /// a permutation and blend of those lanes.
9206 ///
9207 /// This essentially blends the out-of-lane inputs to each lane into the lane
9208 /// from a permuted copy of the vector. This lowering strategy results in four
9209 /// instructions in the worst case for a single-input cross lane shuffle which
9210 /// is lower than any other fully general cross-lane shuffle strategy I'm aware
9211 /// of. Special cases for each particular shuffle pattern should be handled
9212 /// prior to trying this lowering.
9213 static SDValue lowerVectorShuffleAsLanePermuteAndBlend(SDLoc DL, MVT VT,
9214                                                        SDValue V1, SDValue V2,
9215                                                        ArrayRef<int> Mask,
9216                                                        SelectionDAG &DAG) {
9217   // FIXME: This should probably be generalized for 512-bit vectors as well.
9218   assert(VT.getSizeInBits() == 256 && "Only for 256-bit vector shuffles!");
9219   int LaneSize = Mask.size() / 2;
9220
9221   // If there are only inputs from one 128-bit lane, splitting will in fact be
9222   // less expensive. The flags track whether the given lane contains an element
9223   // that crosses to another lane.
9224   bool LaneCrossing[2] = {false, false};
9225   for (int i = 0, Size = Mask.size(); i < Size; ++i)
9226     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
9227       LaneCrossing[(Mask[i] % Size) / LaneSize] = true;
9228   if (!LaneCrossing[0] || !LaneCrossing[1])
9229     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9230
9231   if (isSingleInputShuffleMask(Mask)) {
9232     SmallVector<int, 32> FlippedBlendMask;
9233     for (int i = 0, Size = Mask.size(); i < Size; ++i)
9234       FlippedBlendMask.push_back(
9235           Mask[i] < 0 ? -1 : (((Mask[i] % Size) / LaneSize == i / LaneSize)
9236                                   ? Mask[i]
9237                                   : Mask[i] % LaneSize +
9238                                         (i / LaneSize) * LaneSize + Size));
9239
9240     // Flip the vector, and blend the results which should now be in-lane. The
9241     // VPERM2X128 mask uses the low 2 bits for the low source and bits 4 and
9242     // 5 for the high source. The value 3 selects the high half of source 2 and
9243     // the value 2 selects the low half of source 2. We only use source 2 to
9244     // allow folding it into a memory operand.
9245     unsigned PERMMask = 3 | 2 << 4;
9246     SDValue Flipped = DAG.getNode(X86ISD::VPERM2X128, DL, VT, DAG.getUNDEF(VT),
9247                                   V1, DAG.getConstant(PERMMask, DL, MVT::i8));
9248     return DAG.getVectorShuffle(VT, DL, V1, Flipped, FlippedBlendMask);
9249   }
9250
9251   // This now reduces to two single-input shuffles of V1 and V2 which at worst
9252   // will be handled by the above logic and a blend of the results, much like
9253   // other patterns in AVX.
9254   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9255 }
9256
9257 /// \brief Handle lowering 2-lane 128-bit shuffles.
9258 static SDValue lowerV2X128VectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9259                                         SDValue V2, ArrayRef<int> Mask,
9260                                         const X86Subtarget *Subtarget,
9261                                         SelectionDAG &DAG) {
9262   // TODO: If minimizing size and one of the inputs is a zero vector and the
9263   // the zero vector has only one use, we could use a VPERM2X128 to save the
9264   // instruction bytes needed to explicitly generate the zero vector.
9265
9266   // Blends are faster and handle all the non-lane-crossing cases.
9267   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, VT, V1, V2, Mask,
9268                                                 Subtarget, DAG))
9269     return Blend;
9270
9271   bool IsV1Zero = ISD::isBuildVectorAllZeros(V1.getNode());
9272   bool IsV2Zero = ISD::isBuildVectorAllZeros(V2.getNode());
9273
9274   // If either input operand is a zero vector, use VPERM2X128 because its mask
9275   // allows us to replace the zero input with an implicit zero.
9276   if (!IsV1Zero && !IsV2Zero) {
9277     // Check for patterns which can be matched with a single insert of a 128-bit
9278     // subvector.
9279     bool OnlyUsesV1 = isShuffleEquivalent(V1, V2, Mask, {0, 1, 0, 1});
9280     if (OnlyUsesV1 || isShuffleEquivalent(V1, V2, Mask, {0, 1, 4, 5})) {
9281       MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(),
9282                                    VT.getVectorNumElements() / 2);
9283       SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
9284                                 DAG.getIntPtrConstant(0, DL));
9285       SDValue HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT,
9286                                 OnlyUsesV1 ? V1 : V2,
9287                                 DAG.getIntPtrConstant(0, DL));
9288       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoV, HiV);
9289     }
9290   }
9291
9292   // Otherwise form a 128-bit permutation. After accounting for undefs,
9293   // convert the 64-bit shuffle mask selection values into 128-bit
9294   // selection bits by dividing the indexes by 2 and shifting into positions
9295   // defined by a vperm2*128 instruction's immediate control byte.
9296
9297   // The immediate permute control byte looks like this:
9298   //    [1:0] - select 128 bits from sources for low half of destination
9299   //    [2]   - ignore
9300   //    [3]   - zero low half of destination
9301   //    [5:4] - select 128 bits from sources for high half of destination
9302   //    [6]   - ignore
9303   //    [7]   - zero high half of destination
9304
9305   int MaskLO = Mask[0];
9306   if (MaskLO == SM_SentinelUndef)
9307     MaskLO = Mask[1] == SM_SentinelUndef ? 0 : Mask[1];
9308
9309   int MaskHI = Mask[2];
9310   if (MaskHI == SM_SentinelUndef)
9311     MaskHI = Mask[3] == SM_SentinelUndef ? 0 : Mask[3];
9312
9313   unsigned PermMask = MaskLO / 2 | (MaskHI / 2) << 4;
9314
9315   // If either input is a zero vector, replace it with an undef input.
9316   // Shuffle mask values <  4 are selecting elements of V1.
9317   // Shuffle mask values >= 4 are selecting elements of V2.
9318   // Adjust each half of the permute mask by clearing the half that was
9319   // selecting the zero vector and setting the zero mask bit.
9320   if (IsV1Zero) {
9321     V1 = DAG.getUNDEF(VT);
9322     if (MaskLO < 4)
9323       PermMask = (PermMask & 0xf0) | 0x08;
9324     if (MaskHI < 4)
9325       PermMask = (PermMask & 0x0f) | 0x80;
9326   }
9327   if (IsV2Zero) {
9328     V2 = DAG.getUNDEF(VT);
9329     if (MaskLO >= 4)
9330       PermMask = (PermMask & 0xf0) | 0x08;
9331     if (MaskHI >= 4)
9332       PermMask = (PermMask & 0x0f) | 0x80;
9333   }
9334
9335   return DAG.getNode(X86ISD::VPERM2X128, DL, VT, V1, V2,
9336                      DAG.getConstant(PermMask, DL, MVT::i8));
9337 }
9338
9339 /// \brief Lower a vector shuffle by first fixing the 128-bit lanes and then
9340 /// shuffling each lane.
9341 ///
9342 /// This will only succeed when the result of fixing the 128-bit lanes results
9343 /// in a single-input non-lane-crossing shuffle with a repeating shuffle mask in
9344 /// each 128-bit lanes. This handles many cases where we can quickly blend away
9345 /// the lane crosses early and then use simpler shuffles within each lane.
9346 ///
9347 /// FIXME: It might be worthwhile at some point to support this without
9348 /// requiring the 128-bit lane-relative shuffles to be repeating, but currently
9349 /// in x86 only floating point has interesting non-repeating shuffles, and even
9350 /// those are still *marginally* more expensive.
9351 static SDValue lowerVectorShuffleByMerging128BitLanes(
9352     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
9353     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
9354   assert(!isSingleInputShuffleMask(Mask) &&
9355          "This is only useful with multiple inputs.");
9356
9357   int Size = Mask.size();
9358   int LaneSize = 128 / VT.getScalarSizeInBits();
9359   int NumLanes = Size / LaneSize;
9360   assert(NumLanes > 1 && "Only handles 256-bit and wider shuffles.");
9361
9362   // See if we can build a hypothetical 128-bit lane-fixing shuffle mask. Also
9363   // check whether the in-128-bit lane shuffles share a repeating pattern.
9364   SmallVector<int, 4> Lanes;
9365   Lanes.resize(NumLanes, -1);
9366   SmallVector<int, 4> InLaneMask;
9367   InLaneMask.resize(LaneSize, -1);
9368   for (int i = 0; i < Size; ++i) {
9369     if (Mask[i] < 0)
9370       continue;
9371
9372     int j = i / LaneSize;
9373
9374     if (Lanes[j] < 0) {
9375       // First entry we've seen for this lane.
9376       Lanes[j] = Mask[i] / LaneSize;
9377     } else if (Lanes[j] != Mask[i] / LaneSize) {
9378       // This doesn't match the lane selected previously!
9379       return SDValue();
9380     }
9381
9382     // Check that within each lane we have a consistent shuffle mask.
9383     int k = i % LaneSize;
9384     if (InLaneMask[k] < 0) {
9385       InLaneMask[k] = Mask[i] % LaneSize;
9386     } else if (InLaneMask[k] != Mask[i] % LaneSize) {
9387       // This doesn't fit a repeating in-lane mask.
9388       return SDValue();
9389     }
9390   }
9391
9392   // First shuffle the lanes into place.
9393   MVT LaneVT = MVT::getVectorVT(VT.isFloatingPoint() ? MVT::f64 : MVT::i64,
9394                                 VT.getSizeInBits() / 64);
9395   SmallVector<int, 8> LaneMask;
9396   LaneMask.resize(NumLanes * 2, -1);
9397   for (int i = 0; i < NumLanes; ++i)
9398     if (Lanes[i] >= 0) {
9399       LaneMask[2 * i + 0] = 2*Lanes[i] + 0;
9400       LaneMask[2 * i + 1] = 2*Lanes[i] + 1;
9401     }
9402
9403   V1 = DAG.getBitcast(LaneVT, V1);
9404   V2 = DAG.getBitcast(LaneVT, V2);
9405   SDValue LaneShuffle = DAG.getVectorShuffle(LaneVT, DL, V1, V2, LaneMask);
9406
9407   // Cast it back to the type we actually want.
9408   LaneShuffle = DAG.getBitcast(VT, LaneShuffle);
9409
9410   // Now do a simple shuffle that isn't lane crossing.
9411   SmallVector<int, 8> NewMask;
9412   NewMask.resize(Size, -1);
9413   for (int i = 0; i < Size; ++i)
9414     if (Mask[i] >= 0)
9415       NewMask[i] = (i / LaneSize) * LaneSize + Mask[i] % LaneSize;
9416   assert(!is128BitLaneCrossingShuffleMask(VT, NewMask) &&
9417          "Must not introduce lane crosses at this point!");
9418
9419   return DAG.getVectorShuffle(VT, DL, LaneShuffle, DAG.getUNDEF(VT), NewMask);
9420 }
9421
9422 /// \brief Test whether the specified input (0 or 1) is in-place blended by the
9423 /// given mask.
9424 ///
9425 /// This returns true if the elements from a particular input are already in the
9426 /// slot required by the given mask and require no permutation.
9427 static bool isShuffleMaskInputInPlace(int Input, ArrayRef<int> Mask) {
9428   assert((Input == 0 || Input == 1) && "Only two inputs to shuffles.");
9429   int Size = Mask.size();
9430   for (int i = 0; i < Size; ++i)
9431     if (Mask[i] >= 0 && Mask[i] / Size == Input && Mask[i] % Size != i)
9432       return false;
9433
9434   return true;
9435 }
9436
9437 static SDValue lowerVectorShuffleWithSHUFPD(SDLoc DL, MVT VT,
9438                                             ArrayRef<int> Mask, SDValue V1,
9439                                             SDValue V2, SelectionDAG &DAG) {
9440
9441   // Mask for V8F64: 0/1,  8/9,  2/3,  10/11, 4/5, ..
9442   // Mask for V4F64; 0/1,  4/5,  2/3,  6/7..
9443   assert(VT.getScalarSizeInBits() == 64 && "Unexpected data type for VSHUFPD");
9444   int NumElts = VT.getVectorNumElements();
9445   bool ShufpdMask = true;
9446   bool CommutableMask = true;
9447   unsigned Immediate = 0;
9448   for (int i = 0; i < NumElts; ++i) {
9449     if (Mask[i] < 0)
9450       continue;
9451     int Val = (i & 6) + NumElts * (i & 1);
9452     int CommutVal = (i & 0xe) + NumElts * ((i & 1)^1);
9453     if (Mask[i] < Val ||  Mask[i] > Val + 1)
9454       ShufpdMask = false;
9455     if (Mask[i] < CommutVal ||  Mask[i] > CommutVal + 1)
9456       CommutableMask = false;
9457     Immediate |= (Mask[i] % 2) << i;
9458   }
9459   if (ShufpdMask)
9460     return DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
9461                        DAG.getConstant(Immediate, DL, MVT::i8));
9462   if (CommutableMask)
9463     return DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
9464                        DAG.getConstant(Immediate, DL, MVT::i8));
9465   return SDValue();
9466 }
9467
9468 /// \brief Handle lowering of 4-lane 64-bit floating point shuffles.
9469 ///
9470 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
9471 /// isn't available.
9472 static SDValue lowerV4F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9473                                        const X86Subtarget *Subtarget,
9474                                        SelectionDAG &DAG) {
9475   SDLoc DL(Op);
9476   assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9477   assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9478   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9479   ArrayRef<int> Mask = SVOp->getMask();
9480   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9481
9482   SmallVector<int, 4> WidenedMask;
9483   if (canWidenShuffleElements(Mask, WidenedMask))
9484     return lowerV2X128VectorShuffle(DL, MVT::v4f64, V1, V2, Mask, Subtarget,
9485                                     DAG);
9486
9487   if (isSingleInputShuffleMask(Mask)) {
9488     // Check for being able to broadcast a single element.
9489     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f64, V1,
9490                                                           Mask, Subtarget, DAG))
9491       return Broadcast;
9492
9493     // Use low duplicate instructions for masks that match their pattern.
9494     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
9495       return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v4f64, V1);
9496
9497     if (!is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask)) {
9498       // Non-half-crossing single input shuffles can be lowerid with an
9499       // interleaved permutation.
9500       unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
9501                               ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
9502       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f64, V1,
9503                          DAG.getConstant(VPERMILPMask, DL, MVT::i8));
9504     }
9505
9506     // With AVX2 we have direct support for this permutation.
9507     if (Subtarget->hasAVX2())
9508       return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4f64, V1,
9509                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
9510
9511     // Otherwise, fall back.
9512     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v4f64, V1, V2, Mask,
9513                                                    DAG);
9514   }
9515
9516   // X86 has dedicated unpack instructions that can handle specific blend
9517   // operations: UNPCKH and UNPCKL.
9518   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9519     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V1, V2);
9520   if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9521     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V1, V2);
9522   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9523     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V2, V1);
9524   if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9525     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V2, V1);
9526
9527   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f64, V1, V2, Mask,
9528                                                 Subtarget, DAG))
9529     return Blend;
9530
9531   // Check if the blend happens to exactly fit that of SHUFPD.
9532   if (SDValue Op =
9533       lowerVectorShuffleWithSHUFPD(DL, MVT::v4f64, Mask, V1, V2, DAG))
9534     return Op;
9535
9536   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9537   // shuffle. However, if we have AVX2 and either inputs are already in place,
9538   // we will be able to shuffle even across lanes the other input in a single
9539   // instruction so skip this pattern.
9540   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9541                                  isShuffleMaskInputInPlace(1, Mask))))
9542     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9543             DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
9544       return Result;
9545
9546   // If we have AVX2 then we always want to lower with a blend because an v4 we
9547   // can fully permute the elements.
9548   if (Subtarget->hasAVX2())
9549     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4f64, V1, V2,
9550                                                       Mask, DAG);
9551
9552   // Otherwise fall back on generic lowering.
9553   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v4f64, V1, V2, Mask, DAG);
9554 }
9555
9556 /// \brief Handle lowering of 4-lane 64-bit integer shuffles.
9557 ///
9558 /// This routine is only called when we have AVX2 and thus a reasonable
9559 /// instruction set for v4i64 shuffling..
9560 static SDValue lowerV4I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9561                                        const X86Subtarget *Subtarget,
9562                                        SelectionDAG &DAG) {
9563   SDLoc DL(Op);
9564   assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9565   assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9566   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9567   ArrayRef<int> Mask = SVOp->getMask();
9568   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9569   assert(Subtarget->hasAVX2() && "We can only lower v4i64 with AVX2!");
9570
9571   SmallVector<int, 4> WidenedMask;
9572   if (canWidenShuffleElements(Mask, WidenedMask))
9573     return lowerV2X128VectorShuffle(DL, MVT::v4i64, V1, V2, Mask, Subtarget,
9574                                     DAG);
9575
9576   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i64, V1, V2, Mask,
9577                                                 Subtarget, DAG))
9578     return Blend;
9579
9580   // Check for being able to broadcast a single element.
9581   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i64, V1,
9582                                                         Mask, Subtarget, DAG))
9583     return Broadcast;
9584
9585   // When the shuffle is mirrored between the 128-bit lanes of the unit, we can
9586   // use lower latency instructions that will operate on both 128-bit lanes.
9587   SmallVector<int, 2> RepeatedMask;
9588   if (is128BitLaneRepeatedShuffleMask(MVT::v4i64, Mask, RepeatedMask)) {
9589     if (isSingleInputShuffleMask(Mask)) {
9590       int PSHUFDMask[] = {-1, -1, -1, -1};
9591       for (int i = 0; i < 2; ++i)
9592         if (RepeatedMask[i] >= 0) {
9593           PSHUFDMask[2 * i] = 2 * RepeatedMask[i];
9594           PSHUFDMask[2 * i + 1] = 2 * RepeatedMask[i] + 1;
9595         }
9596       return DAG.getBitcast(
9597           MVT::v4i64,
9598           DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32,
9599                       DAG.getBitcast(MVT::v8i32, V1),
9600                       getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
9601     }
9602   }
9603
9604   // AVX2 provides a direct instruction for permuting a single input across
9605   // lanes.
9606   if (isSingleInputShuffleMask(Mask))
9607     return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4i64, V1,
9608                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
9609
9610   // Try to use shift instructions.
9611   if (SDValue Shift =
9612           lowerVectorShuffleAsShift(DL, MVT::v4i64, V1, V2, Mask, DAG))
9613     return Shift;
9614
9615   // Use dedicated unpack instructions for masks that match their pattern.
9616   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9617     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V1, V2);
9618   if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9619     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V1, V2);
9620   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9621     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V2, V1);
9622   if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9623     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V2, V1);
9624
9625   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9626   // shuffle. However, if we have AVX2 and either inputs are already in place,
9627   // we will be able to shuffle even across lanes the other input in a single
9628   // instruction so skip this pattern.
9629   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9630                                  isShuffleMaskInputInPlace(1, Mask))))
9631     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9632             DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
9633       return Result;
9634
9635   // Otherwise fall back on generic blend lowering.
9636   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i64, V1, V2,
9637                                                     Mask, DAG);
9638 }
9639
9640 /// \brief Handle lowering of 8-lane 32-bit floating point shuffles.
9641 ///
9642 /// Also ends up handling lowering of 8-lane 32-bit integer shuffles when AVX2
9643 /// isn't available.
9644 static SDValue lowerV8F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9645                                        const X86Subtarget *Subtarget,
9646                                        SelectionDAG &DAG) {
9647   SDLoc DL(Op);
9648   assert(V1.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
9649   assert(V2.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
9650   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9651   ArrayRef<int> Mask = SVOp->getMask();
9652   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9653
9654   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8f32, V1, V2, Mask,
9655                                                 Subtarget, DAG))
9656     return Blend;
9657
9658   // Check for being able to broadcast a single element.
9659   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8f32, V1,
9660                                                         Mask, Subtarget, DAG))
9661     return Broadcast;
9662
9663   // If the shuffle mask is repeated in each 128-bit lane, we have many more
9664   // options to efficiently lower the shuffle.
9665   SmallVector<int, 4> RepeatedMask;
9666   if (is128BitLaneRepeatedShuffleMask(MVT::v8f32, Mask, RepeatedMask)) {
9667     assert(RepeatedMask.size() == 4 &&
9668            "Repeated masks must be half the mask width!");
9669
9670     // Use even/odd duplicate instructions for masks that match their pattern.
9671     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2, 4, 4, 6, 6}))
9672       return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v8f32, V1);
9673     if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3, 5, 5, 7, 7}))
9674       return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v8f32, V1);
9675
9676     if (isSingleInputShuffleMask(Mask))
9677       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, V1,
9678                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
9679
9680     // Use dedicated unpack instructions for masks that match their pattern.
9681     if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
9682       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V1, V2);
9683     if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
9684       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V1, V2);
9685     if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
9686       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V2, V1);
9687     if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
9688       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V2, V1);
9689
9690     // Otherwise, fall back to a SHUFPS sequence. Here it is important that we
9691     // have already handled any direct blends. We also need to squash the
9692     // repeated mask into a simulated v4f32 mask.
9693     for (int i = 0; i < 4; ++i)
9694       if (RepeatedMask[i] >= 8)
9695         RepeatedMask[i] -= 4;
9696     return lowerVectorShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask, V1, V2, DAG);
9697   }
9698
9699   // If we have a single input shuffle with different shuffle patterns in the
9700   // two 128-bit lanes use the variable mask to VPERMILPS.
9701   if (isSingleInputShuffleMask(Mask)) {
9702     SDValue VPermMask[8];
9703     for (int i = 0; i < 8; ++i)
9704       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
9705                                  : DAG.getConstant(Mask[i], DL, MVT::i32);
9706     if (!is128BitLaneCrossingShuffleMask(MVT::v8f32, Mask))
9707       return DAG.getNode(
9708           X86ISD::VPERMILPV, DL, MVT::v8f32, V1,
9709           DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask));
9710
9711     if (Subtarget->hasAVX2())
9712       return DAG.getNode(
9713           X86ISD::VPERMV, DL, MVT::v8f32,
9714           DAG.getBitcast(MVT::v8f32, DAG.getNode(ISD::BUILD_VECTOR, DL,
9715                                                  MVT::v8i32, VPermMask)),
9716           V1);
9717
9718     // Otherwise, fall back.
9719     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v8f32, V1, V2, Mask,
9720                                                    DAG);
9721   }
9722
9723   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9724   // shuffle.
9725   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9726           DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
9727     return Result;
9728
9729   // If we have AVX2 then we always want to lower with a blend because at v8 we
9730   // can fully permute the elements.
9731   if (Subtarget->hasAVX2())
9732     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8f32, V1, V2,
9733                                                       Mask, DAG);
9734
9735   // Otherwise fall back on generic lowering.
9736   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask, DAG);
9737 }
9738
9739 /// \brief Handle lowering of 8-lane 32-bit integer shuffles.
9740 ///
9741 /// This routine is only called when we have AVX2 and thus a reasonable
9742 /// instruction set for v8i32 shuffling..
9743 static SDValue lowerV8I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9744                                        const X86Subtarget *Subtarget,
9745                                        SelectionDAG &DAG) {
9746   SDLoc DL(Op);
9747   assert(V1.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
9748   assert(V2.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
9749   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9750   ArrayRef<int> Mask = SVOp->getMask();
9751   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9752   assert(Subtarget->hasAVX2() && "We can only lower v8i32 with AVX2!");
9753
9754   // Whenever we can lower this as a zext, that instruction is strictly faster
9755   // than any alternative. It also allows us to fold memory operands into the
9756   // shuffle in many cases.
9757   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v8i32, V1, V2,
9758                                                          Mask, Subtarget, DAG))
9759     return ZExt;
9760
9761   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i32, V1, V2, Mask,
9762                                                 Subtarget, DAG))
9763     return Blend;
9764
9765   // Check for being able to broadcast a single element.
9766   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i32, V1,
9767                                                         Mask, Subtarget, DAG))
9768     return Broadcast;
9769
9770   // If the shuffle mask is repeated in each 128-bit lane we can use more
9771   // efficient instructions that mirror the shuffles across the two 128-bit
9772   // lanes.
9773   SmallVector<int, 4> RepeatedMask;
9774   if (is128BitLaneRepeatedShuffleMask(MVT::v8i32, Mask, RepeatedMask)) {
9775     assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
9776     if (isSingleInputShuffleMask(Mask))
9777       return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32, V1,
9778                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
9779
9780     // Use dedicated unpack instructions for masks that match their pattern.
9781     if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
9782       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V1, V2);
9783     if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
9784       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V1, V2);
9785     if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
9786       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V2, V1);
9787     if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
9788       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V2, V1);
9789   }
9790
9791   // Try to use shift instructions.
9792   if (SDValue Shift =
9793           lowerVectorShuffleAsShift(DL, MVT::v8i32, V1, V2, Mask, DAG))
9794     return Shift;
9795
9796   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9797           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
9798     return Rotate;
9799
9800   // If the shuffle patterns aren't repeated but it is a single input, directly
9801   // generate a cross-lane VPERMD instruction.
9802   if (isSingleInputShuffleMask(Mask)) {
9803     SDValue VPermMask[8];
9804     for (int i = 0; i < 8; ++i)
9805       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
9806                                  : DAG.getConstant(Mask[i], DL, MVT::i32);
9807     return DAG.getNode(
9808         X86ISD::VPERMV, DL, MVT::v8i32,
9809         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask), V1);
9810   }
9811
9812   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9813   // shuffle.
9814   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9815           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
9816     return Result;
9817
9818   // Otherwise fall back on generic blend lowering.
9819   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i32, V1, V2,
9820                                                     Mask, DAG);
9821 }
9822
9823 /// \brief Handle lowering of 16-lane 16-bit integer shuffles.
9824 ///
9825 /// This routine is only called when we have AVX2 and thus a reasonable
9826 /// instruction set for v16i16 shuffling..
9827 static SDValue lowerV16I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9828                                         const X86Subtarget *Subtarget,
9829                                         SelectionDAG &DAG) {
9830   SDLoc DL(Op);
9831   assert(V1.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
9832   assert(V2.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
9833   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9834   ArrayRef<int> Mask = SVOp->getMask();
9835   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
9836   assert(Subtarget->hasAVX2() && "We can only lower v16i16 with AVX2!");
9837
9838   // Whenever we can lower this as a zext, that instruction is strictly faster
9839   // than any alternative. It also allows us to fold memory operands into the
9840   // shuffle in many cases.
9841   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v16i16, V1, V2,
9842                                                          Mask, Subtarget, DAG))
9843     return ZExt;
9844
9845   // Check for being able to broadcast a single element.
9846   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i16, V1,
9847                                                         Mask, Subtarget, DAG))
9848     return Broadcast;
9849
9850   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i16, V1, V2, Mask,
9851                                                 Subtarget, DAG))
9852     return Blend;
9853
9854   // Use dedicated unpack instructions for masks that match their pattern.
9855   if (isShuffleEquivalent(V1, V2, Mask,
9856                           {// First 128-bit lane:
9857                            0, 16, 1, 17, 2, 18, 3, 19,
9858                            // Second 128-bit lane:
9859                            8, 24, 9, 25, 10, 26, 11, 27}))
9860     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i16, V1, V2);
9861   if (isShuffleEquivalent(V1, V2, Mask,
9862                           {// First 128-bit lane:
9863                            4, 20, 5, 21, 6, 22, 7, 23,
9864                            // Second 128-bit lane:
9865                            12, 28, 13, 29, 14, 30, 15, 31}))
9866     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i16, V1, V2);
9867
9868   // Try to use shift instructions.
9869   if (SDValue Shift =
9870           lowerVectorShuffleAsShift(DL, MVT::v16i16, V1, V2, Mask, DAG))
9871     return Shift;
9872
9873   // Try to use byte rotation instructions.
9874   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9875           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
9876     return Rotate;
9877
9878   if (isSingleInputShuffleMask(Mask)) {
9879     // There are no generalized cross-lane shuffle operations available on i16
9880     // element types.
9881     if (is128BitLaneCrossingShuffleMask(MVT::v16i16, Mask))
9882       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v16i16, V1, V2,
9883                                                      Mask, DAG);
9884
9885     SmallVector<int, 8> RepeatedMask;
9886     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
9887       // As this is a single-input shuffle, the repeated mask should be
9888       // a strictly valid v8i16 mask that we can pass through to the v8i16
9889       // lowering to handle even the v16 case.
9890       return lowerV8I16GeneralSingleInputVectorShuffle(
9891           DL, MVT::v16i16, V1, RepeatedMask, Subtarget, DAG);
9892     }
9893
9894     SDValue PSHUFBMask[32];
9895     for (int i = 0; i < 16; ++i) {
9896       if (Mask[i] == -1) {
9897         PSHUFBMask[2 * i] = PSHUFBMask[2 * i + 1] = DAG.getUNDEF(MVT::i8);
9898         continue;
9899       }
9900
9901       int M = i < 8 ? Mask[i] : Mask[i] - 8;
9902       assert(M >= 0 && M < 8 && "Invalid single-input mask!");
9903       PSHUFBMask[2 * i] = DAG.getConstant(2 * M, DL, MVT::i8);
9904       PSHUFBMask[2 * i + 1] = DAG.getConstant(2 * M + 1, DL, MVT::i8);
9905     }
9906     return DAG.getBitcast(MVT::v16i16,
9907                           DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8,
9908                                       DAG.getBitcast(MVT::v32i8, V1),
9909                                       DAG.getNode(ISD::BUILD_VECTOR, DL,
9910                                                   MVT::v32i8, PSHUFBMask)));
9911   }
9912
9913   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9914   // shuffle.
9915   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9916           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
9917     return Result;
9918
9919   // Otherwise fall back on generic lowering.
9920   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v16i16, V1, V2, Mask, DAG);
9921 }
9922
9923 /// \brief Handle lowering of 32-lane 8-bit integer shuffles.
9924 ///
9925 /// This routine is only called when we have AVX2 and thus a reasonable
9926 /// instruction set for v32i8 shuffling..
9927 static SDValue lowerV32I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9928                                        const X86Subtarget *Subtarget,
9929                                        SelectionDAG &DAG) {
9930   SDLoc DL(Op);
9931   assert(V1.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
9932   assert(V2.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
9933   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9934   ArrayRef<int> Mask = SVOp->getMask();
9935   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
9936   assert(Subtarget->hasAVX2() && "We can only lower v32i8 with AVX2!");
9937
9938   // Whenever we can lower this as a zext, that instruction is strictly faster
9939   // than any alternative. It also allows us to fold memory operands into the
9940   // shuffle in many cases.
9941   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v32i8, V1, V2,
9942                                                          Mask, Subtarget, DAG))
9943     return ZExt;
9944
9945   // Check for being able to broadcast a single element.
9946   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v32i8, V1,
9947                                                         Mask, Subtarget, DAG))
9948     return Broadcast;
9949
9950   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v32i8, V1, V2, Mask,
9951                                                 Subtarget, DAG))
9952     return Blend;
9953
9954   // Use dedicated unpack instructions for masks that match their pattern.
9955   // Note that these are repeated 128-bit lane unpacks, not unpacks across all
9956   // 256-bit lanes.
9957   if (isShuffleEquivalent(
9958           V1, V2, Mask,
9959           {// First 128-bit lane:
9960            0, 32, 1, 33, 2, 34, 3, 35, 4, 36, 5, 37, 6, 38, 7, 39,
9961            // Second 128-bit lane:
9962            16, 48, 17, 49, 18, 50, 19, 51, 20, 52, 21, 53, 22, 54, 23, 55}))
9963     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v32i8, V1, V2);
9964   if (isShuffleEquivalent(
9965           V1, V2, Mask,
9966           {// First 128-bit lane:
9967            8, 40, 9, 41, 10, 42, 11, 43, 12, 44, 13, 45, 14, 46, 15, 47,
9968            // Second 128-bit lane:
9969            24, 56, 25, 57, 26, 58, 27, 59, 28, 60, 29, 61, 30, 62, 31, 63}))
9970     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v32i8, V1, V2);
9971
9972   // Try to use shift instructions.
9973   if (SDValue Shift =
9974           lowerVectorShuffleAsShift(DL, MVT::v32i8, V1, V2, Mask, DAG))
9975     return Shift;
9976
9977   // Try to use byte rotation instructions.
9978   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9979           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
9980     return Rotate;
9981
9982   if (isSingleInputShuffleMask(Mask)) {
9983     // There are no generalized cross-lane shuffle operations available on i8
9984     // element types.
9985     if (is128BitLaneCrossingShuffleMask(MVT::v32i8, Mask))
9986       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v32i8, V1, V2,
9987                                                      Mask, DAG);
9988
9989     SDValue PSHUFBMask[32];
9990     for (int i = 0; i < 32; ++i)
9991       PSHUFBMask[i] =
9992           Mask[i] < 0
9993               ? DAG.getUNDEF(MVT::i8)
9994               : DAG.getConstant(Mask[i] < 16 ? Mask[i] : Mask[i] - 16, DL,
9995                                 MVT::i8);
9996
9997     return DAG.getNode(
9998         X86ISD::PSHUFB, DL, MVT::v32i8, V1,
9999         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask));
10000   }
10001
10002   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10003   // shuffle.
10004   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10005           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
10006     return Result;
10007
10008   // Otherwise fall back on generic lowering.
10009   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v32i8, V1, V2, Mask, DAG);
10010 }
10011
10012 /// \brief High-level routine to lower various 256-bit x86 vector shuffles.
10013 ///
10014 /// This routine either breaks down the specific type of a 256-bit x86 vector
10015 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
10016 /// together based on the available instructions.
10017 static SDValue lower256BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10018                                         MVT VT, const X86Subtarget *Subtarget,
10019                                         SelectionDAG &DAG) {
10020   SDLoc DL(Op);
10021   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10022   ArrayRef<int> Mask = SVOp->getMask();
10023
10024   // If we have a single input to the zero element, insert that into V1 if we
10025   // can do so cheaply.
10026   int NumElts = VT.getVectorNumElements();
10027   int NumV2Elements = std::count_if(Mask.begin(), Mask.end(), [NumElts](int M) {
10028     return M >= NumElts;
10029   });
10030
10031   if (NumV2Elements == 1 && Mask[0] >= NumElts)
10032     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
10033                               DL, VT, V1, V2, Mask, Subtarget, DAG))
10034       return Insertion;
10035
10036   // There is a really nice hard cut-over between AVX1 and AVX2 that means we can
10037   // check for those subtargets here and avoid much of the subtarget querying in
10038   // the per-vector-type lowering routines. With AVX1 we have essentially *zero*
10039   // ability to manipulate a 256-bit vector with integer types. Since we'll use
10040   // floating point types there eventually, just immediately cast everything to
10041   // a float and operate entirely in that domain.
10042   if (VT.isInteger() && !Subtarget->hasAVX2()) {
10043     int ElementBits = VT.getScalarSizeInBits();
10044     if (ElementBits < 32)
10045       // No floating point type available, decompose into 128-bit vectors.
10046       return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10047
10048     MVT FpVT = MVT::getVectorVT(MVT::getFloatingPointVT(ElementBits),
10049                                 VT.getVectorNumElements());
10050     V1 = DAG.getBitcast(FpVT, V1);
10051     V2 = DAG.getBitcast(FpVT, V2);
10052     return DAG.getBitcast(VT, DAG.getVectorShuffle(FpVT, DL, V1, V2, Mask));
10053   }
10054
10055   switch (VT.SimpleTy) {
10056   case MVT::v4f64:
10057     return lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10058   case MVT::v4i64:
10059     return lowerV4I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10060   case MVT::v8f32:
10061     return lowerV8F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10062   case MVT::v8i32:
10063     return lowerV8I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10064   case MVT::v16i16:
10065     return lowerV16I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10066   case MVT::v32i8:
10067     return lowerV32I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10068
10069   default:
10070     llvm_unreachable("Not a valid 256-bit x86 vector type!");
10071   }
10072 }
10073
10074 /// \brief Handle lowering of 8-lane 64-bit floating point shuffles.
10075 static SDValue lowerV8F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10076                                        const X86Subtarget *Subtarget,
10077                                        SelectionDAG &DAG) {
10078   SDLoc DL(Op);
10079   assert(V1.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10080   assert(V2.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10081   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10082   ArrayRef<int> Mask = SVOp->getMask();
10083   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10084
10085   // X86 has dedicated unpack instructions that can handle specific blend
10086   // operations: UNPCKH and UNPCKL.
10087   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
10088     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f64, V1, V2);
10089   if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
10090     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f64, V1, V2);
10091
10092   // FIXME: Implement direct support for this type!
10093   return splitAndLowerVectorShuffle(DL, MVT::v8f64, V1, V2, Mask, DAG);
10094 }
10095
10096 /// \brief Handle lowering of 16-lane 32-bit floating point shuffles.
10097 static SDValue lowerV16F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10098                                        const X86Subtarget *Subtarget,
10099                                        SelectionDAG &DAG) {
10100   SDLoc DL(Op);
10101   assert(V1.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10102   assert(V2.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10103   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10104   ArrayRef<int> Mask = SVOp->getMask();
10105   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10106
10107   // Use dedicated unpack instructions for masks that match their pattern.
10108   if (isShuffleEquivalent(V1, V2, Mask,
10109                           {// First 128-bit lane.
10110                            0, 16, 1, 17, 4, 20, 5, 21,
10111                            // Second 128-bit lane.
10112                            8, 24, 9, 25, 12, 28, 13, 29}))
10113     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16f32, V1, V2);
10114   if (isShuffleEquivalent(V1, V2, Mask,
10115                           {// First 128-bit lane.
10116                            2, 18, 3, 19, 6, 22, 7, 23,
10117                            // Second 128-bit lane.
10118                            10, 26, 11, 27, 14, 30, 15, 31}))
10119     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16f32, V1, V2);
10120
10121   // FIXME: Implement direct support for this type!
10122   return splitAndLowerVectorShuffle(DL, MVT::v16f32, V1, V2, Mask, DAG);
10123 }
10124
10125 /// \brief Handle lowering of 8-lane 64-bit integer shuffles.
10126 static SDValue lowerV8I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10127                                        const X86Subtarget *Subtarget,
10128                                        SelectionDAG &DAG) {
10129   SDLoc DL(Op);
10130   assert(V1.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10131   assert(V2.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10132   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10133   ArrayRef<int> Mask = SVOp->getMask();
10134   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10135
10136   // X86 has dedicated unpack instructions that can handle specific blend
10137   // operations: UNPCKH and UNPCKL.
10138   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
10139     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i64, V1, V2);
10140   if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
10141     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i64, V1, V2);
10142
10143   // FIXME: Implement direct support for this type!
10144   return splitAndLowerVectorShuffle(DL, MVT::v8i64, V1, V2, Mask, DAG);
10145 }
10146
10147 /// \brief Handle lowering of 16-lane 32-bit integer shuffles.
10148 static SDValue lowerV16I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10149                                        const X86Subtarget *Subtarget,
10150                                        SelectionDAG &DAG) {
10151   SDLoc DL(Op);
10152   assert(V1.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10153   assert(V2.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10154   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10155   ArrayRef<int> Mask = SVOp->getMask();
10156   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10157
10158   // Use dedicated unpack instructions for masks that match their pattern.
10159   if (isShuffleEquivalent(V1, V2, Mask,
10160                           {// First 128-bit lane.
10161                            0, 16, 1, 17, 4, 20, 5, 21,
10162                            // Second 128-bit lane.
10163                            8, 24, 9, 25, 12, 28, 13, 29}))
10164     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i32, V1, V2);
10165   if (isShuffleEquivalent(V1, V2, Mask,
10166                           {// First 128-bit lane.
10167                            2, 18, 3, 19, 6, 22, 7, 23,
10168                            // Second 128-bit lane.
10169                            10, 26, 11, 27, 14, 30, 15, 31}))
10170     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i32, V1, V2);
10171
10172   // FIXME: Implement direct support for this type!
10173   return splitAndLowerVectorShuffle(DL, MVT::v16i32, V1, V2, Mask, DAG);
10174 }
10175
10176 /// \brief Handle lowering of 32-lane 16-bit integer shuffles.
10177 static SDValue lowerV32I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10178                                         const X86Subtarget *Subtarget,
10179                                         SelectionDAG &DAG) {
10180   SDLoc DL(Op);
10181   assert(V1.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10182   assert(V2.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10183   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10184   ArrayRef<int> Mask = SVOp->getMask();
10185   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10186   assert(Subtarget->hasBWI() && "We can only lower v32i16 with AVX-512-BWI!");
10187
10188   // FIXME: Implement direct support for this type!
10189   return splitAndLowerVectorShuffle(DL, MVT::v32i16, V1, V2, Mask, DAG);
10190 }
10191
10192 /// \brief Handle lowering of 64-lane 8-bit integer shuffles.
10193 static SDValue lowerV64I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10194                                        const X86Subtarget *Subtarget,
10195                                        SelectionDAG &DAG) {
10196   SDLoc DL(Op);
10197   assert(V1.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10198   assert(V2.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10199   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10200   ArrayRef<int> Mask = SVOp->getMask();
10201   assert(Mask.size() == 64 && "Unexpected mask size for v64 shuffle!");
10202   assert(Subtarget->hasBWI() && "We can only lower v64i8 with AVX-512-BWI!");
10203
10204   // FIXME: Implement direct support for this type!
10205   return splitAndLowerVectorShuffle(DL, MVT::v64i8, V1, V2, Mask, DAG);
10206 }
10207
10208 /// \brief High-level routine to lower various 512-bit x86 vector shuffles.
10209 ///
10210 /// This routine either breaks down the specific type of a 512-bit x86 vector
10211 /// shuffle or splits it into two 256-bit shuffles and fuses the results back
10212 /// together based on the available instructions.
10213 static SDValue lower512BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10214                                         MVT VT, const X86Subtarget *Subtarget,
10215                                         SelectionDAG &DAG) {
10216   SDLoc DL(Op);
10217   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10218   ArrayRef<int> Mask = SVOp->getMask();
10219   assert(Subtarget->hasAVX512() &&
10220          "Cannot lower 512-bit vectors w/ basic ISA!");
10221
10222   // Check for being able to broadcast a single element.
10223   if (SDValue Broadcast =
10224           lowerVectorShuffleAsBroadcast(DL, VT, V1, Mask, Subtarget, DAG))
10225     return Broadcast;
10226
10227   // Dispatch to each element type for lowering. If we don't have supprot for
10228   // specific element type shuffles at 512 bits, immediately split them and
10229   // lower them. Each lowering routine of a given type is allowed to assume that
10230   // the requisite ISA extensions for that element type are available.
10231   switch (VT.SimpleTy) {
10232   case MVT::v8f64:
10233     return lowerV8F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10234   case MVT::v16f32:
10235     return lowerV16F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10236   case MVT::v8i64:
10237     return lowerV8I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10238   case MVT::v16i32:
10239     return lowerV16I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10240   case MVT::v32i16:
10241     if (Subtarget->hasBWI())
10242       return lowerV32I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10243     break;
10244   case MVT::v64i8:
10245     if (Subtarget->hasBWI())
10246       return lowerV64I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10247     break;
10248
10249   default:
10250     llvm_unreachable("Not a valid 512-bit x86 vector type!");
10251   }
10252
10253   // Otherwise fall back on splitting.
10254   return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10255 }
10256
10257 /// \brief Top-level lowering for x86 vector shuffles.
10258 ///
10259 /// This handles decomposition, canonicalization, and lowering of all x86
10260 /// vector shuffles. Most of the specific lowering strategies are encapsulated
10261 /// above in helper routines. The canonicalization attempts to widen shuffles
10262 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
10263 /// s.t. only one of the two inputs needs to be tested, etc.
10264 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
10265                                   SelectionDAG &DAG) {
10266   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10267   ArrayRef<int> Mask = SVOp->getMask();
10268   SDValue V1 = Op.getOperand(0);
10269   SDValue V2 = Op.getOperand(1);
10270   MVT VT = Op.getSimpleValueType();
10271   int NumElements = VT.getVectorNumElements();
10272   SDLoc dl(Op);
10273
10274   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
10275
10276   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
10277   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
10278   if (V1IsUndef && V2IsUndef)
10279     return DAG.getUNDEF(VT);
10280
10281   // When we create a shuffle node we put the UNDEF node to second operand,
10282   // but in some cases the first operand may be transformed to UNDEF.
10283   // In this case we should just commute the node.
10284   if (V1IsUndef)
10285     return DAG.getCommutedVectorShuffle(*SVOp);
10286
10287   // Check for non-undef masks pointing at an undef vector and make the masks
10288   // undef as well. This makes it easier to match the shuffle based solely on
10289   // the mask.
10290   if (V2IsUndef)
10291     for (int M : Mask)
10292       if (M >= NumElements) {
10293         SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
10294         for (int &M : NewMask)
10295           if (M >= NumElements)
10296             M = -1;
10297         return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
10298       }
10299
10300   // We actually see shuffles that are entirely re-arrangements of a set of
10301   // zero inputs. This mostly happens while decomposing complex shuffles into
10302   // simple ones. Directly lower these as a buildvector of zeros.
10303   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
10304   if (Zeroable.all())
10305     return getZeroVector(VT, Subtarget, DAG, dl);
10306
10307   // Try to collapse shuffles into using a vector type with fewer elements but
10308   // wider element types. We cap this to not form integers or floating point
10309   // elements wider than 64 bits, but it might be interesting to form i128
10310   // integers to handle flipping the low and high halves of AVX 256-bit vectors.
10311   SmallVector<int, 16> WidenedMask;
10312   if (VT.getScalarSizeInBits() < 64 &&
10313       canWidenShuffleElements(Mask, WidenedMask)) {
10314     MVT NewEltVT = VT.isFloatingPoint()
10315                        ? MVT::getFloatingPointVT(VT.getScalarSizeInBits() * 2)
10316                        : MVT::getIntegerVT(VT.getScalarSizeInBits() * 2);
10317     MVT NewVT = MVT::getVectorVT(NewEltVT, VT.getVectorNumElements() / 2);
10318     // Make sure that the new vector type is legal. For example, v2f64 isn't
10319     // legal on SSE1.
10320     if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
10321       V1 = DAG.getBitcast(NewVT, V1);
10322       V2 = DAG.getBitcast(NewVT, V2);
10323       return DAG.getBitcast(
10324           VT, DAG.getVectorShuffle(NewVT, dl, V1, V2, WidenedMask));
10325     }
10326   }
10327
10328   int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
10329   for (int M : SVOp->getMask())
10330     if (M < 0)
10331       ++NumUndefElements;
10332     else if (M < NumElements)
10333       ++NumV1Elements;
10334     else
10335       ++NumV2Elements;
10336
10337   // Commute the shuffle as needed such that more elements come from V1 than
10338   // V2. This allows us to match the shuffle pattern strictly on how many
10339   // elements come from V1 without handling the symmetric cases.
10340   if (NumV2Elements > NumV1Elements)
10341     return DAG.getCommutedVectorShuffle(*SVOp);
10342
10343   // When the number of V1 and V2 elements are the same, try to minimize the
10344   // number of uses of V2 in the low half of the vector. When that is tied,
10345   // ensure that the sum of indices for V1 is equal to or lower than the sum
10346   // indices for V2. When those are equal, try to ensure that the number of odd
10347   // indices for V1 is lower than the number of odd indices for V2.
10348   if (NumV1Elements == NumV2Elements) {
10349     int LowV1Elements = 0, LowV2Elements = 0;
10350     for (int M : SVOp->getMask().slice(0, NumElements / 2))
10351       if (M >= NumElements)
10352         ++LowV2Elements;
10353       else if (M >= 0)
10354         ++LowV1Elements;
10355     if (LowV2Elements > LowV1Elements) {
10356       return DAG.getCommutedVectorShuffle(*SVOp);
10357     } else if (LowV2Elements == LowV1Elements) {
10358       int SumV1Indices = 0, SumV2Indices = 0;
10359       for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10360         if (SVOp->getMask()[i] >= NumElements)
10361           SumV2Indices += i;
10362         else if (SVOp->getMask()[i] >= 0)
10363           SumV1Indices += i;
10364       if (SumV2Indices < SumV1Indices) {
10365         return DAG.getCommutedVectorShuffle(*SVOp);
10366       } else if (SumV2Indices == SumV1Indices) {
10367         int NumV1OddIndices = 0, NumV2OddIndices = 0;
10368         for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10369           if (SVOp->getMask()[i] >= NumElements)
10370             NumV2OddIndices += i % 2;
10371           else if (SVOp->getMask()[i] >= 0)
10372             NumV1OddIndices += i % 2;
10373         if (NumV2OddIndices < NumV1OddIndices)
10374           return DAG.getCommutedVectorShuffle(*SVOp);
10375       }
10376     }
10377   }
10378
10379   // For each vector width, delegate to a specialized lowering routine.
10380   if (VT.getSizeInBits() == 128)
10381     return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10382
10383   if (VT.getSizeInBits() == 256)
10384     return lower256BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10385
10386   // Force AVX-512 vectors to be scalarized for now.
10387   // FIXME: Implement AVX-512 support!
10388   if (VT.getSizeInBits() == 512)
10389     return lower512BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10390
10391   llvm_unreachable("Unimplemented!");
10392 }
10393
10394 // This function assumes its argument is a BUILD_VECTOR of constants or
10395 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
10396 // true.
10397 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
10398                                     unsigned &MaskValue) {
10399   MaskValue = 0;
10400   unsigned NumElems = BuildVector->getNumOperands();
10401   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
10402   unsigned NumLanes = (NumElems - 1) / 8 + 1;
10403   unsigned NumElemsInLane = NumElems / NumLanes;
10404
10405   // Blend for v16i16 should be symetric for the both lanes.
10406   for (unsigned i = 0; i < NumElemsInLane; ++i) {
10407     SDValue EltCond = BuildVector->getOperand(i);
10408     SDValue SndLaneEltCond =
10409         (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
10410
10411     int Lane1Cond = -1, Lane2Cond = -1;
10412     if (isa<ConstantSDNode>(EltCond))
10413       Lane1Cond = !isZero(EltCond);
10414     if (isa<ConstantSDNode>(SndLaneEltCond))
10415       Lane2Cond = !isZero(SndLaneEltCond);
10416
10417     if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
10418       // Lane1Cond != 0, means we want the first argument.
10419       // Lane1Cond == 0, means we want the second argument.
10420       // The encoding of this argument is 0 for the first argument, 1
10421       // for the second. Therefore, invert the condition.
10422       MaskValue |= !Lane1Cond << i;
10423     else if (Lane1Cond < 0)
10424       MaskValue |= !Lane2Cond << i;
10425     else
10426       return false;
10427   }
10428   return true;
10429 }
10430
10431 /// \brief Try to lower a VSELECT instruction to a vector shuffle.
10432 static SDValue lowerVSELECTtoVectorShuffle(SDValue Op,
10433                                            const X86Subtarget *Subtarget,
10434                                            SelectionDAG &DAG) {
10435   SDValue Cond = Op.getOperand(0);
10436   SDValue LHS = Op.getOperand(1);
10437   SDValue RHS = Op.getOperand(2);
10438   SDLoc dl(Op);
10439   MVT VT = Op.getSimpleValueType();
10440
10441   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
10442     return SDValue();
10443   auto *CondBV = cast<BuildVectorSDNode>(Cond);
10444
10445   // Only non-legal VSELECTs reach this lowering, convert those into generic
10446   // shuffles and re-use the shuffle lowering path for blends.
10447   SmallVector<int, 32> Mask;
10448   for (int i = 0, Size = VT.getVectorNumElements(); i < Size; ++i) {
10449     SDValue CondElt = CondBV->getOperand(i);
10450     Mask.push_back(
10451         isa<ConstantSDNode>(CondElt) ? i + (isZero(CondElt) ? Size : 0) : -1);
10452   }
10453   return DAG.getVectorShuffle(VT, dl, LHS, RHS, Mask);
10454 }
10455
10456 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
10457   // A vselect where all conditions and data are constants can be optimized into
10458   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
10459   if (ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(0).getNode()) &&
10460       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(1).getNode()) &&
10461       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(2).getNode()))
10462     return SDValue();
10463
10464   // Try to lower this to a blend-style vector shuffle. This can handle all
10465   // constant condition cases.
10466   if (SDValue BlendOp = lowerVSELECTtoVectorShuffle(Op, Subtarget, DAG))
10467     return BlendOp;
10468
10469   // Variable blends are only legal from SSE4.1 onward.
10470   if (!Subtarget->hasSSE41())
10471     return SDValue();
10472
10473   // Only some types will be legal on some subtargets. If we can emit a legal
10474   // VSELECT-matching blend, return Op, and but if we need to expand, return
10475   // a null value.
10476   switch (Op.getSimpleValueType().SimpleTy) {
10477   default:
10478     // Most of the vector types have blends past SSE4.1.
10479     return Op;
10480
10481   case MVT::v32i8:
10482     // The byte blends for AVX vectors were introduced only in AVX2.
10483     if (Subtarget->hasAVX2())
10484       return Op;
10485
10486     return SDValue();
10487
10488   case MVT::v8i16:
10489   case MVT::v16i16:
10490     // AVX-512 BWI and VLX features support VSELECT with i16 elements.
10491     if (Subtarget->hasBWI() && Subtarget->hasVLX())
10492       return Op;
10493
10494     // FIXME: We should custom lower this by fixing the condition and using i8
10495     // blends.
10496     return SDValue();
10497   }
10498 }
10499
10500 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
10501   MVT VT = Op.getSimpleValueType();
10502   SDLoc dl(Op);
10503
10504   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
10505     return SDValue();
10506
10507   if (VT.getSizeInBits() == 8) {
10508     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
10509                                   Op.getOperand(0), Op.getOperand(1));
10510     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10511                                   DAG.getValueType(VT));
10512     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10513   }
10514
10515   if (VT.getSizeInBits() == 16) {
10516     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10517     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
10518     if (Idx == 0)
10519       return DAG.getNode(
10520           ISD::TRUNCATE, dl, MVT::i16,
10521           DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10522                       DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
10523                       Op.getOperand(1)));
10524     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
10525                                   Op.getOperand(0), Op.getOperand(1));
10526     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10527                                   DAG.getValueType(VT));
10528     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10529   }
10530
10531   if (VT == MVT::f32) {
10532     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
10533     // the result back to FR32 register. It's only worth matching if the
10534     // result has a single use which is a store or a bitcast to i32.  And in
10535     // the case of a store, it's not worth it if the index is a constant 0,
10536     // because a MOVSSmr can be used instead, which is smaller and faster.
10537     if (!Op.hasOneUse())
10538       return SDValue();
10539     SDNode *User = *Op.getNode()->use_begin();
10540     if ((User->getOpcode() != ISD::STORE ||
10541          (isa<ConstantSDNode>(Op.getOperand(1)) &&
10542           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
10543         (User->getOpcode() != ISD::BITCAST ||
10544          User->getValueType(0) != MVT::i32))
10545       return SDValue();
10546     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10547                                   DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
10548                                   Op.getOperand(1));
10549     return DAG.getBitcast(MVT::f32, Extract);
10550   }
10551
10552   if (VT == MVT::i32 || VT == MVT::i64) {
10553     // ExtractPS/pextrq works with constant index.
10554     if (isa<ConstantSDNode>(Op.getOperand(1)))
10555       return Op;
10556   }
10557   return SDValue();
10558 }
10559
10560 /// Extract one bit from mask vector, like v16i1 or v8i1.
10561 /// AVX-512 feature.
10562 SDValue
10563 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
10564   SDValue Vec = Op.getOperand(0);
10565   SDLoc dl(Vec);
10566   MVT VecVT = Vec.getSimpleValueType();
10567   SDValue Idx = Op.getOperand(1);
10568   MVT EltVT = Op.getSimpleValueType();
10569
10570   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
10571   assert((VecVT.getVectorNumElements() <= 16 || Subtarget->hasBWI()) &&
10572          "Unexpected vector type in ExtractBitFromMaskVector");
10573
10574   // variable index can't be handled in mask registers,
10575   // extend vector to VR512
10576   if (!isa<ConstantSDNode>(Idx)) {
10577     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
10578     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
10579     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
10580                               ExtVT.getVectorElementType(), Ext, Idx);
10581     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
10582   }
10583
10584   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10585   const TargetRegisterClass* rc = getRegClassFor(VecVT);
10586   if (!Subtarget->hasDQI() && (VecVT.getVectorNumElements() <= 8))
10587     rc = getRegClassFor(MVT::v16i1);
10588   unsigned MaxSift = rc->getSize()*8 - 1;
10589   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
10590                     DAG.getConstant(MaxSift - IdxVal, dl, MVT::i8));
10591   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
10592                     DAG.getConstant(MaxSift, dl, MVT::i8));
10593   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
10594                        DAG.getIntPtrConstant(0, dl));
10595 }
10596
10597 SDValue
10598 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
10599                                            SelectionDAG &DAG) const {
10600   SDLoc dl(Op);
10601   SDValue Vec = Op.getOperand(0);
10602   MVT VecVT = Vec.getSimpleValueType();
10603   SDValue Idx = Op.getOperand(1);
10604
10605   if (Op.getSimpleValueType() == MVT::i1)
10606     return ExtractBitFromMaskVector(Op, DAG);
10607
10608   if (!isa<ConstantSDNode>(Idx)) {
10609     if (VecVT.is512BitVector() ||
10610         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
10611          VecVT.getVectorElementType().getSizeInBits() == 32)) {
10612
10613       MVT MaskEltVT =
10614         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
10615       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
10616                                     MaskEltVT.getSizeInBits());
10617
10618       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
10619       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
10620                                 getZeroVector(MaskVT, Subtarget, DAG, dl),
10621                                 Idx, DAG.getConstant(0, dl, getPointerTy()));
10622       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
10623       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
10624                         Perm, DAG.getConstant(0, dl, getPointerTy()));
10625     }
10626     return SDValue();
10627   }
10628
10629   // If this is a 256-bit vector result, first extract the 128-bit vector and
10630   // then extract the element from the 128-bit vector.
10631   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
10632
10633     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10634     // Get the 128-bit vector.
10635     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
10636     MVT EltVT = VecVT.getVectorElementType();
10637
10638     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
10639
10640     //if (IdxVal >= NumElems/2)
10641     //  IdxVal -= NumElems/2;
10642     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
10643     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
10644                        DAG.getConstant(IdxVal, dl, MVT::i32));
10645   }
10646
10647   assert(VecVT.is128BitVector() && "Unexpected vector length");
10648
10649   if (Subtarget->hasSSE41())
10650     if (SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG))
10651       return Res;
10652
10653   MVT VT = Op.getSimpleValueType();
10654   // TODO: handle v16i8.
10655   if (VT.getSizeInBits() == 16) {
10656     SDValue Vec = Op.getOperand(0);
10657     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10658     if (Idx == 0)
10659       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
10660                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10661                                      DAG.getBitcast(MVT::v4i32, Vec),
10662                                      Op.getOperand(1)));
10663     // Transform it so it match pextrw which produces a 32-bit result.
10664     MVT EltVT = MVT::i32;
10665     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
10666                                   Op.getOperand(0), Op.getOperand(1));
10667     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
10668                                   DAG.getValueType(VT));
10669     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10670   }
10671
10672   if (VT.getSizeInBits() == 32) {
10673     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10674     if (Idx == 0)
10675       return Op;
10676
10677     // SHUFPS the element to the lowest double word, then movss.
10678     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
10679     MVT VVT = Op.getOperand(0).getSimpleValueType();
10680     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10681                                        DAG.getUNDEF(VVT), Mask);
10682     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10683                        DAG.getIntPtrConstant(0, dl));
10684   }
10685
10686   if (VT.getSizeInBits() == 64) {
10687     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
10688     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
10689     //        to match extract_elt for f64.
10690     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10691     if (Idx == 0)
10692       return Op;
10693
10694     // UNPCKHPD the element to the lowest double word, then movsd.
10695     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
10696     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
10697     int Mask[2] = { 1, -1 };
10698     MVT VVT = Op.getOperand(0).getSimpleValueType();
10699     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10700                                        DAG.getUNDEF(VVT), Mask);
10701     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10702                        DAG.getIntPtrConstant(0, dl));
10703   }
10704
10705   return SDValue();
10706 }
10707
10708 /// Insert one bit to mask vector, like v16i1 or v8i1.
10709 /// AVX-512 feature.
10710 SDValue
10711 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
10712   SDLoc dl(Op);
10713   SDValue Vec = Op.getOperand(0);
10714   SDValue Elt = Op.getOperand(1);
10715   SDValue Idx = Op.getOperand(2);
10716   MVT VecVT = Vec.getSimpleValueType();
10717
10718   if (!isa<ConstantSDNode>(Idx)) {
10719     // Non constant index. Extend source and destination,
10720     // insert element and then truncate the result.
10721     MVT ExtVecVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
10722     MVT ExtEltVT = (VecVT == MVT::v8i1 ?  MVT::i64 : MVT::i32);
10723     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
10724       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
10725       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
10726     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
10727   }
10728
10729   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10730   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
10731   if (IdxVal)
10732     EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
10733                            DAG.getConstant(IdxVal, dl, MVT::i8));
10734   if (Vec.getOpcode() == ISD::UNDEF)
10735     return EltInVec;
10736   return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
10737 }
10738
10739 SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
10740                                                   SelectionDAG &DAG) const {
10741   MVT VT = Op.getSimpleValueType();
10742   MVT EltVT = VT.getVectorElementType();
10743
10744   if (EltVT == MVT::i1)
10745     return InsertBitToMaskVector(Op, DAG);
10746
10747   SDLoc dl(Op);
10748   SDValue N0 = Op.getOperand(0);
10749   SDValue N1 = Op.getOperand(1);
10750   SDValue N2 = Op.getOperand(2);
10751   if (!isa<ConstantSDNode>(N2))
10752     return SDValue();
10753   auto *N2C = cast<ConstantSDNode>(N2);
10754   unsigned IdxVal = N2C->getZExtValue();
10755
10756   // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
10757   // into that, and then insert the subvector back into the result.
10758   if (VT.is256BitVector() || VT.is512BitVector()) {
10759     // With a 256-bit vector, we can insert into the zero element efficiently
10760     // using a blend if we have AVX or AVX2 and the right data type.
10761     if (VT.is256BitVector() && IdxVal == 0) {
10762       // TODO: It is worthwhile to cast integer to floating point and back
10763       // and incur a domain crossing penalty if that's what we'll end up
10764       // doing anyway after extracting to a 128-bit vector.
10765       if ((Subtarget->hasAVX() && (EltVT == MVT::f64 || EltVT == MVT::f32)) ||
10766           (Subtarget->hasAVX2() && EltVT == MVT::i32)) {
10767         SDValue N1Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, N1);
10768         N2 = DAG.getIntPtrConstant(1, dl);
10769         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1Vec, N2);
10770       }
10771     }
10772
10773     // Get the desired 128-bit vector chunk.
10774     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
10775
10776     // Insert the element into the desired chunk.
10777     unsigned NumEltsIn128 = 128 / EltVT.getSizeInBits();
10778     unsigned IdxIn128 = IdxVal - (IdxVal / NumEltsIn128) * NumEltsIn128;
10779
10780     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
10781                     DAG.getConstant(IdxIn128, dl, MVT::i32));
10782
10783     // Insert the changed part back into the bigger vector
10784     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
10785   }
10786   assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
10787
10788   if (Subtarget->hasSSE41()) {
10789     if (EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) {
10790       unsigned Opc;
10791       if (VT == MVT::v8i16) {
10792         Opc = X86ISD::PINSRW;
10793       } else {
10794         assert(VT == MVT::v16i8);
10795         Opc = X86ISD::PINSRB;
10796       }
10797
10798       // Transform it so it match pinsr{b,w} which expects a GR32 as its second
10799       // argument.
10800       if (N1.getValueType() != MVT::i32)
10801         N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
10802       if (N2.getValueType() != MVT::i32)
10803         N2 = DAG.getIntPtrConstant(IdxVal, dl);
10804       return DAG.getNode(Opc, dl, VT, N0, N1, N2);
10805     }
10806
10807     if (EltVT == MVT::f32) {
10808       // Bits [7:6] of the constant are the source select. This will always be
10809       //   zero here. The DAG Combiner may combine an extract_elt index into
10810       //   these bits. For example (insert (extract, 3), 2) could be matched by
10811       //   putting the '3' into bits [7:6] of X86ISD::INSERTPS.
10812       // Bits [5:4] of the constant are the destination select. This is the
10813       //   value of the incoming immediate.
10814       // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
10815       //   combine either bitwise AND or insert of float 0.0 to set these bits.
10816
10817       const Function *F = DAG.getMachineFunction().getFunction();
10818       bool MinSize = F->hasFnAttribute(Attribute::MinSize);
10819       if (IdxVal == 0 && (!MinSize || !MayFoldLoad(N1))) {
10820         // If this is an insertion of 32-bits into the low 32-bits of
10821         // a vector, we prefer to generate a blend with immediate rather
10822         // than an insertps. Blends are simpler operations in hardware and so
10823         // will always have equal or better performance than insertps.
10824         // But if optimizing for size and there's a load folding opportunity,
10825         // generate insertps because blendps does not have a 32-bit memory
10826         // operand form.
10827         N2 = DAG.getIntPtrConstant(1, dl);
10828         N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
10829         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1, N2);
10830       }
10831       N2 = DAG.getIntPtrConstant(IdxVal << 4, dl);
10832       // Create this as a scalar to vector..
10833       N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
10834       return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
10835     }
10836
10837     if (EltVT == MVT::i32 || EltVT == MVT::i64) {
10838       // PINSR* works with constant index.
10839       return Op;
10840     }
10841   }
10842
10843   if (EltVT == MVT::i8)
10844     return SDValue();
10845
10846   if (EltVT.getSizeInBits() == 16) {
10847     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
10848     // as its second argument.
10849     if (N1.getValueType() != MVT::i32)
10850       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
10851     if (N2.getValueType() != MVT::i32)
10852       N2 = DAG.getIntPtrConstant(IdxVal, dl);
10853     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
10854   }
10855   return SDValue();
10856 }
10857
10858 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
10859   SDLoc dl(Op);
10860   MVT OpVT = Op.getSimpleValueType();
10861
10862   // If this is a 256-bit vector result, first insert into a 128-bit
10863   // vector and then insert into the 256-bit vector.
10864   if (!OpVT.is128BitVector()) {
10865     // Insert into a 128-bit vector.
10866     unsigned SizeFactor = OpVT.getSizeInBits()/128;
10867     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
10868                                  OpVT.getVectorNumElements() / SizeFactor);
10869
10870     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
10871
10872     // Insert the 128-bit vector.
10873     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
10874   }
10875
10876   if (OpVT == MVT::v1i64 &&
10877       Op.getOperand(0).getValueType() == MVT::i64)
10878     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
10879
10880   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
10881   assert(OpVT.is128BitVector() && "Expected an SSE type!");
10882   return DAG.getBitcast(
10883       OpVT, DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, AnyExt));
10884 }
10885
10886 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
10887 // a simple subregister reference or explicit instructions to grab
10888 // upper bits of a vector.
10889 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10890                                       SelectionDAG &DAG) {
10891   SDLoc dl(Op);
10892   SDValue In =  Op.getOperand(0);
10893   SDValue Idx = Op.getOperand(1);
10894   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10895   MVT ResVT   = Op.getSimpleValueType();
10896   MVT InVT    = In.getSimpleValueType();
10897
10898   if (Subtarget->hasFp256()) {
10899     if (ResVT.is128BitVector() &&
10900         (InVT.is256BitVector() || InVT.is512BitVector()) &&
10901         isa<ConstantSDNode>(Idx)) {
10902       return Extract128BitVector(In, IdxVal, DAG, dl);
10903     }
10904     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
10905         isa<ConstantSDNode>(Idx)) {
10906       return Extract256BitVector(In, IdxVal, DAG, dl);
10907     }
10908   }
10909   return SDValue();
10910 }
10911
10912 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
10913 // simple superregister reference or explicit instructions to insert
10914 // the upper bits of a vector.
10915 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10916                                      SelectionDAG &DAG) {
10917   if (!Subtarget->hasAVX())
10918     return SDValue();
10919
10920   SDLoc dl(Op);
10921   SDValue Vec = Op.getOperand(0);
10922   SDValue SubVec = Op.getOperand(1);
10923   SDValue Idx = Op.getOperand(2);
10924
10925   if (!isa<ConstantSDNode>(Idx))
10926     return SDValue();
10927
10928   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10929   MVT OpVT = Op.getSimpleValueType();
10930   MVT SubVecVT = SubVec.getSimpleValueType();
10931
10932   // Fold two 16-byte subvector loads into one 32-byte load:
10933   // (insert_subvector (insert_subvector undef, (load addr), 0),
10934   //                   (load addr + 16), Elts/2)
10935   // --> load32 addr
10936   if ((IdxVal == OpVT.getVectorNumElements() / 2) &&
10937       Vec.getOpcode() == ISD::INSERT_SUBVECTOR &&
10938       OpVT.is256BitVector() && SubVecVT.is128BitVector() &&
10939       !Subtarget->isUnalignedMem32Slow()) {
10940     SDValue SubVec2 = Vec.getOperand(1);
10941     if (auto *Idx2 = dyn_cast<ConstantSDNode>(Vec.getOperand(2))) {
10942       if (Idx2->getZExtValue() == 0) {
10943         SDValue Ops[] = { SubVec2, SubVec };
10944         if (SDValue Ld = EltsFromConsecutiveLoads(OpVT, Ops, dl, DAG, false))
10945           return Ld;
10946       }
10947     }
10948   }
10949
10950   if ((OpVT.is256BitVector() || OpVT.is512BitVector()) &&
10951       SubVecVT.is128BitVector())
10952     return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
10953
10954   if (OpVT.is512BitVector() && SubVecVT.is256BitVector())
10955     return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
10956
10957   if (OpVT.getVectorElementType() == MVT::i1) {
10958     if (IdxVal == 0  && Vec.getOpcode() == ISD::UNDEF) // the operation is legal
10959       return Op;
10960     SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
10961     SDValue Undef = DAG.getUNDEF(OpVT);
10962     unsigned NumElems = OpVT.getVectorNumElements();
10963     SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
10964
10965     if (IdxVal == OpVT.getVectorNumElements() / 2) {
10966       // Zero upper bits of the Vec
10967       Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
10968       Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
10969
10970       SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
10971                                  SubVec, ZeroIdx);
10972       Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
10973       return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
10974     }
10975     if (IdxVal == 0) {
10976       SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
10977                                  SubVec, ZeroIdx);
10978       // Zero upper bits of the Vec2
10979       Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
10980       Vec2 = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec2, ShiftBits);
10981       // Zero lower bits of the Vec
10982       Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
10983       Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
10984       // Merge them together
10985       return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
10986     }
10987   }
10988   return SDValue();
10989 }
10990
10991 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
10992 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
10993 // one of the above mentioned nodes. It has to be wrapped because otherwise
10994 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
10995 // be used to form addressing mode. These wrapped nodes will be selected
10996 // into MOV32ri.
10997 SDValue
10998 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
10999   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
11000
11001   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11002   // global base reg.
11003   unsigned char OpFlag = 0;
11004   unsigned WrapperKind = X86ISD::Wrapper;
11005   CodeModel::Model M = DAG.getTarget().getCodeModel();
11006
11007   if (Subtarget->isPICStyleRIPRel() &&
11008       (M == CodeModel::Small || M == CodeModel::Kernel))
11009     WrapperKind = X86ISD::WrapperRIP;
11010   else if (Subtarget->isPICStyleGOT())
11011     OpFlag = X86II::MO_GOTOFF;
11012   else if (Subtarget->isPICStyleStubPIC())
11013     OpFlag = X86II::MO_PIC_BASE_OFFSET;
11014
11015   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
11016                                              CP->getAlignment(),
11017                                              CP->getOffset(), OpFlag);
11018   SDLoc DL(CP);
11019   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
11020   // With PIC, the address is actually $g + Offset.
11021   if (OpFlag) {
11022     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11023                          DAG.getNode(X86ISD::GlobalBaseReg,
11024                                      SDLoc(), getPointerTy()),
11025                          Result);
11026   }
11027
11028   return Result;
11029 }
11030
11031 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
11032   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
11033
11034   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11035   // global base reg.
11036   unsigned char OpFlag = 0;
11037   unsigned WrapperKind = X86ISD::Wrapper;
11038   CodeModel::Model M = DAG.getTarget().getCodeModel();
11039
11040   if (Subtarget->isPICStyleRIPRel() &&
11041       (M == CodeModel::Small || M == CodeModel::Kernel))
11042     WrapperKind = X86ISD::WrapperRIP;
11043   else if (Subtarget->isPICStyleGOT())
11044     OpFlag = X86II::MO_GOTOFF;
11045   else if (Subtarget->isPICStyleStubPIC())
11046     OpFlag = X86II::MO_PIC_BASE_OFFSET;
11047
11048   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
11049                                           OpFlag);
11050   SDLoc DL(JT);
11051   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
11052
11053   // With PIC, the address is actually $g + Offset.
11054   if (OpFlag)
11055     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11056                          DAG.getNode(X86ISD::GlobalBaseReg,
11057                                      SDLoc(), getPointerTy()),
11058                          Result);
11059
11060   return Result;
11061 }
11062
11063 SDValue
11064 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
11065   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
11066
11067   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11068   // global base reg.
11069   unsigned char OpFlag = 0;
11070   unsigned WrapperKind = X86ISD::Wrapper;
11071   CodeModel::Model M = DAG.getTarget().getCodeModel();
11072
11073   if (Subtarget->isPICStyleRIPRel() &&
11074       (M == CodeModel::Small || M == CodeModel::Kernel)) {
11075     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
11076       OpFlag = X86II::MO_GOTPCREL;
11077     WrapperKind = X86ISD::WrapperRIP;
11078   } else if (Subtarget->isPICStyleGOT()) {
11079     OpFlag = X86II::MO_GOT;
11080   } else if (Subtarget->isPICStyleStubPIC()) {
11081     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
11082   } else if (Subtarget->isPICStyleStubNoDynamic()) {
11083     OpFlag = X86II::MO_DARWIN_NONLAZY;
11084   }
11085
11086   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
11087
11088   SDLoc DL(Op);
11089   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
11090
11091   // With PIC, the address is actually $g + Offset.
11092   if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
11093       !Subtarget->is64Bit()) {
11094     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11095                          DAG.getNode(X86ISD::GlobalBaseReg,
11096                                      SDLoc(), getPointerTy()),
11097                          Result);
11098   }
11099
11100   // For symbols that require a load from a stub to get the address, emit the
11101   // load.
11102   if (isGlobalStubReference(OpFlag))
11103     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
11104                          MachinePointerInfo::getGOT(), false, false, false, 0);
11105
11106   return Result;
11107 }
11108
11109 SDValue
11110 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
11111   // Create the TargetBlockAddressAddress node.
11112   unsigned char OpFlags =
11113     Subtarget->ClassifyBlockAddressReference();
11114   CodeModel::Model M = DAG.getTarget().getCodeModel();
11115   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
11116   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
11117   SDLoc dl(Op);
11118   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
11119                                              OpFlags);
11120
11121   if (Subtarget->isPICStyleRIPRel() &&
11122       (M == CodeModel::Small || M == CodeModel::Kernel))
11123     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
11124   else
11125     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
11126
11127   // With PIC, the address is actually $g + Offset.
11128   if (isGlobalRelativeToPICBase(OpFlags)) {
11129     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
11130                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
11131                          Result);
11132   }
11133
11134   return Result;
11135 }
11136
11137 SDValue
11138 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
11139                                       int64_t Offset, SelectionDAG &DAG) const {
11140   // Create the TargetGlobalAddress node, folding in the constant
11141   // offset if it is legal.
11142   unsigned char OpFlags =
11143       Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
11144   CodeModel::Model M = DAG.getTarget().getCodeModel();
11145   SDValue Result;
11146   if (OpFlags == X86II::MO_NO_FLAG &&
11147       X86::isOffsetSuitableForCodeModel(Offset, M)) {
11148     // A direct static reference to a global.
11149     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
11150     Offset = 0;
11151   } else {
11152     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
11153   }
11154
11155   if (Subtarget->isPICStyleRIPRel() &&
11156       (M == CodeModel::Small || M == CodeModel::Kernel))
11157     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
11158   else
11159     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
11160
11161   // With PIC, the address is actually $g + Offset.
11162   if (isGlobalRelativeToPICBase(OpFlags)) {
11163     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
11164                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
11165                          Result);
11166   }
11167
11168   // For globals that require a load from a stub to get the address, emit the
11169   // load.
11170   if (isGlobalStubReference(OpFlags))
11171     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
11172                          MachinePointerInfo::getGOT(), false, false, false, 0);
11173
11174   // If there was a non-zero offset that we didn't fold, create an explicit
11175   // addition for it.
11176   if (Offset != 0)
11177     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
11178                          DAG.getConstant(Offset, dl, getPointerTy()));
11179
11180   return Result;
11181 }
11182
11183 SDValue
11184 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
11185   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
11186   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
11187   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
11188 }
11189
11190 static SDValue
11191 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
11192            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
11193            unsigned char OperandFlags, bool LocalDynamic = false) {
11194   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11195   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11196   SDLoc dl(GA);
11197   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11198                                            GA->getValueType(0),
11199                                            GA->getOffset(),
11200                                            OperandFlags);
11201
11202   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
11203                                            : X86ISD::TLSADDR;
11204
11205   if (InFlag) {
11206     SDValue Ops[] = { Chain,  TGA, *InFlag };
11207     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11208   } else {
11209     SDValue Ops[]  = { Chain, TGA };
11210     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11211   }
11212
11213   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
11214   MFI->setAdjustsStack(true);
11215   MFI->setHasCalls(true);
11216
11217   SDValue Flag = Chain.getValue(1);
11218   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
11219 }
11220
11221 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
11222 static SDValue
11223 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11224                                 const EVT PtrVT) {
11225   SDValue InFlag;
11226   SDLoc dl(GA);  // ? function entry point might be better
11227   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11228                                    DAG.getNode(X86ISD::GlobalBaseReg,
11229                                                SDLoc(), PtrVT), InFlag);
11230   InFlag = Chain.getValue(1);
11231
11232   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
11233 }
11234
11235 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
11236 static SDValue
11237 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11238                                 const EVT PtrVT) {
11239   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
11240                     X86::RAX, X86II::MO_TLSGD);
11241 }
11242
11243 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
11244                                            SelectionDAG &DAG,
11245                                            const EVT PtrVT,
11246                                            bool is64Bit) {
11247   SDLoc dl(GA);
11248
11249   // Get the start address of the TLS block for this module.
11250   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
11251       .getInfo<X86MachineFunctionInfo>();
11252   MFI->incNumLocalDynamicTLSAccesses();
11253
11254   SDValue Base;
11255   if (is64Bit) {
11256     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
11257                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
11258   } else {
11259     SDValue InFlag;
11260     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11261         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
11262     InFlag = Chain.getValue(1);
11263     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
11264                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
11265   }
11266
11267   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
11268   // of Base.
11269
11270   // Build x@dtpoff.
11271   unsigned char OperandFlags = X86II::MO_DTPOFF;
11272   unsigned WrapperKind = X86ISD::Wrapper;
11273   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11274                                            GA->getValueType(0),
11275                                            GA->getOffset(), OperandFlags);
11276   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11277
11278   // Add x@dtpoff with the base.
11279   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
11280 }
11281
11282 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
11283 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11284                                    const EVT PtrVT, TLSModel::Model model,
11285                                    bool is64Bit, bool isPIC) {
11286   SDLoc dl(GA);
11287
11288   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
11289   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
11290                                                          is64Bit ? 257 : 256));
11291
11292   SDValue ThreadPointer =
11293       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0, dl),
11294                   MachinePointerInfo(Ptr), false, false, false, 0);
11295
11296   unsigned char OperandFlags = 0;
11297   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
11298   // initialexec.
11299   unsigned WrapperKind = X86ISD::Wrapper;
11300   if (model == TLSModel::LocalExec) {
11301     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
11302   } else if (model == TLSModel::InitialExec) {
11303     if (is64Bit) {
11304       OperandFlags = X86II::MO_GOTTPOFF;
11305       WrapperKind = X86ISD::WrapperRIP;
11306     } else {
11307       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
11308     }
11309   } else {
11310     llvm_unreachable("Unexpected model");
11311   }
11312
11313   // emit "addl x@ntpoff,%eax" (local exec)
11314   // or "addl x@indntpoff,%eax" (initial exec)
11315   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
11316   SDValue TGA =
11317       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
11318                                  GA->getOffset(), OperandFlags);
11319   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11320
11321   if (model == TLSModel::InitialExec) {
11322     if (isPIC && !is64Bit) {
11323       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
11324                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
11325                            Offset);
11326     }
11327
11328     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
11329                          MachinePointerInfo::getGOT(), false, false, false, 0);
11330   }
11331
11332   // The address of the thread local variable is the add of the thread
11333   // pointer with the offset of the variable.
11334   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
11335 }
11336
11337 SDValue
11338 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
11339
11340   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
11341   const GlobalValue *GV = GA->getGlobal();
11342
11343   if (Subtarget->isTargetELF()) {
11344     TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
11345     switch (model) {
11346       case TLSModel::GeneralDynamic:
11347         if (Subtarget->is64Bit())
11348           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
11349         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
11350       case TLSModel::LocalDynamic:
11351         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
11352                                            Subtarget->is64Bit());
11353       case TLSModel::InitialExec:
11354       case TLSModel::LocalExec:
11355         return LowerToTLSExecModel(
11356             GA, DAG, getPointerTy(), model, Subtarget->is64Bit(),
11357             DAG.getTarget().getRelocationModel() == Reloc::PIC_);
11358     }
11359     llvm_unreachable("Unknown TLS model.");
11360   }
11361
11362   if (Subtarget->isTargetDarwin()) {
11363     // Darwin only has one model of TLS.  Lower to that.
11364     unsigned char OpFlag = 0;
11365     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
11366                            X86ISD::WrapperRIP : X86ISD::Wrapper;
11367
11368     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11369     // global base reg.
11370     bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
11371                  !Subtarget->is64Bit();
11372     if (PIC32)
11373       OpFlag = X86II::MO_TLVP_PIC_BASE;
11374     else
11375       OpFlag = X86II::MO_TLVP;
11376     SDLoc DL(Op);
11377     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
11378                                                 GA->getValueType(0),
11379                                                 GA->getOffset(), OpFlag);
11380     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
11381
11382     // With PIC32, the address is actually $g + Offset.
11383     if (PIC32)
11384       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11385                            DAG.getNode(X86ISD::GlobalBaseReg,
11386                                        SDLoc(), getPointerTy()),
11387                            Offset);
11388
11389     // Lowering the machine isd will make sure everything is in the right
11390     // location.
11391     SDValue Chain = DAG.getEntryNode();
11392     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11393     SDValue Args[] = { Chain, Offset };
11394     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
11395
11396     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
11397     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11398     MFI->setAdjustsStack(true);
11399
11400     // And our return value (tls address) is in the standard call return value
11401     // location.
11402     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11403     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
11404                               Chain.getValue(1));
11405   }
11406
11407   if (Subtarget->isTargetKnownWindowsMSVC() ||
11408       Subtarget->isTargetWindowsGNU()) {
11409     // Just use the implicit TLS architecture
11410     // Need to generate someting similar to:
11411     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
11412     //                                  ; from TEB
11413     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
11414     //   mov     rcx, qword [rdx+rcx*8]
11415     //   mov     eax, .tls$:tlsvar
11416     //   [rax+rcx] contains the address
11417     // Windows 64bit: gs:0x58
11418     // Windows 32bit: fs:__tls_array
11419
11420     SDLoc dl(GA);
11421     SDValue Chain = DAG.getEntryNode();
11422
11423     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
11424     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
11425     // use its literal value of 0x2C.
11426     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
11427                                         ? Type::getInt8PtrTy(*DAG.getContext(),
11428                                                              256)
11429                                         : Type::getInt32PtrTy(*DAG.getContext(),
11430                                                               257));
11431
11432     SDValue TlsArray =
11433         Subtarget->is64Bit()
11434             ? DAG.getIntPtrConstant(0x58, dl)
11435             : (Subtarget->isTargetWindowsGNU()
11436                    ? DAG.getIntPtrConstant(0x2C, dl)
11437                    : DAG.getExternalSymbol("_tls_array", getPointerTy()));
11438
11439     SDValue ThreadPointer =
11440         DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
11441                     MachinePointerInfo(Ptr), false, false, false, 0);
11442
11443     SDValue res;
11444     if (GV->getThreadLocalMode() == GlobalVariable::LocalExecTLSModel) {
11445       res = ThreadPointer;
11446     } else {
11447       // Load the _tls_index variable
11448       SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
11449       if (Subtarget->is64Bit())
11450         IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain, IDX,
11451                              MachinePointerInfo(), MVT::i32, false, false,
11452                              false, 0);
11453       else
11454         IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
11455                           false, false, false, 0);
11456
11457       SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()), dl,
11458                                       getPointerTy());
11459       IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
11460
11461       res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
11462     }
11463
11464     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
11465                       false, false, false, 0);
11466
11467     // Get the offset of start of .tls section
11468     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11469                                              GA->getValueType(0),
11470                                              GA->getOffset(), X86II::MO_SECREL);
11471     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
11472
11473     // The address of the thread local variable is the add of the thread
11474     // pointer with the offset of the variable.
11475     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
11476   }
11477
11478   llvm_unreachable("TLS not implemented for this target.");
11479 }
11480
11481 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
11482 /// and take a 2 x i32 value to shift plus a shift amount.
11483 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
11484   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
11485   MVT VT = Op.getSimpleValueType();
11486   unsigned VTBits = VT.getSizeInBits();
11487   SDLoc dl(Op);
11488   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
11489   SDValue ShOpLo = Op.getOperand(0);
11490   SDValue ShOpHi = Op.getOperand(1);
11491   SDValue ShAmt  = Op.getOperand(2);
11492   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
11493   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
11494   // during isel.
11495   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11496                                   DAG.getConstant(VTBits - 1, dl, MVT::i8));
11497   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
11498                                      DAG.getConstant(VTBits - 1, dl, MVT::i8))
11499                        : DAG.getConstant(0, dl, VT);
11500
11501   SDValue Tmp2, Tmp3;
11502   if (Op.getOpcode() == ISD::SHL_PARTS) {
11503     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
11504     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
11505   } else {
11506     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
11507     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
11508   }
11509
11510   // If the shift amount is larger or equal than the width of a part we can't
11511   // rely on the results of shld/shrd. Insert a test and select the appropriate
11512   // values for large shift amounts.
11513   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11514                                 DAG.getConstant(VTBits, dl, MVT::i8));
11515   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11516                              AndNode, DAG.getConstant(0, dl, MVT::i8));
11517
11518   SDValue Hi, Lo;
11519   SDValue CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
11520   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
11521   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
11522
11523   if (Op.getOpcode() == ISD::SHL_PARTS) {
11524     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11525     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11526   } else {
11527     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11528     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11529   }
11530
11531   SDValue Ops[2] = { Lo, Hi };
11532   return DAG.getMergeValues(Ops, dl);
11533 }
11534
11535 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
11536                                            SelectionDAG &DAG) const {
11537   SDValue Src = Op.getOperand(0);
11538   MVT SrcVT = Src.getSimpleValueType();
11539   MVT VT = Op.getSimpleValueType();
11540   SDLoc dl(Op);
11541
11542   if (SrcVT.isVector()) {
11543     if (SrcVT == MVT::v2i32 && VT == MVT::v2f64) {
11544       return DAG.getNode(X86ISD::CVTDQ2PD, dl, VT,
11545                          DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i32, Src,
11546                          DAG.getUNDEF(SrcVT)));
11547     }
11548     if (SrcVT.getVectorElementType() == MVT::i1) {
11549       MVT IntegerVT = MVT::getVectorVT(MVT::i32, SrcVT.getVectorNumElements());
11550       return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
11551                          DAG.getNode(ISD::SIGN_EXTEND, dl, IntegerVT, Src));
11552     }
11553     return SDValue();
11554   }
11555
11556   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
11557          "Unknown SINT_TO_FP to lower!");
11558
11559   // These are really Legal; return the operand so the caller accepts it as
11560   // Legal.
11561   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
11562     return Op;
11563   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
11564       Subtarget->is64Bit()) {
11565     return Op;
11566   }
11567
11568   unsigned Size = SrcVT.getSizeInBits()/8;
11569   MachineFunction &MF = DAG.getMachineFunction();
11570   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
11571   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11572   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11573                                StackSlot,
11574                                MachinePointerInfo::getFixedStack(SSFI),
11575                                false, false, 0);
11576   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
11577 }
11578
11579 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
11580                                      SDValue StackSlot,
11581                                      SelectionDAG &DAG) const {
11582   // Build the FILD
11583   SDLoc DL(Op);
11584   SDVTList Tys;
11585   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
11586   if (useSSE)
11587     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
11588   else
11589     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
11590
11591   unsigned ByteSize = SrcVT.getSizeInBits()/8;
11592
11593   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
11594   MachineMemOperand *MMO;
11595   if (FI) {
11596     int SSFI = FI->getIndex();
11597     MMO =
11598       DAG.getMachineFunction()
11599       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11600                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
11601   } else {
11602     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
11603     StackSlot = StackSlot.getOperand(1);
11604   }
11605   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
11606   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
11607                                            X86ISD::FILD, DL,
11608                                            Tys, Ops, SrcVT, MMO);
11609
11610   if (useSSE) {
11611     Chain = Result.getValue(1);
11612     SDValue InFlag = Result.getValue(2);
11613
11614     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
11615     // shouldn't be necessary except that RFP cannot be live across
11616     // multiple blocks. When stackifier is fixed, they can be uncoupled.
11617     MachineFunction &MF = DAG.getMachineFunction();
11618     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
11619     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
11620     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11621     Tys = DAG.getVTList(MVT::Other);
11622     SDValue Ops[] = {
11623       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
11624     };
11625     MachineMemOperand *MMO =
11626       DAG.getMachineFunction()
11627       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11628                             MachineMemOperand::MOStore, SSFISize, SSFISize);
11629
11630     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
11631                                     Ops, Op.getValueType(), MMO);
11632     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
11633                          MachinePointerInfo::getFixedStack(SSFI),
11634                          false, false, false, 0);
11635   }
11636
11637   return Result;
11638 }
11639
11640 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
11641 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
11642                                                SelectionDAG &DAG) const {
11643   // This algorithm is not obvious. Here it is what we're trying to output:
11644   /*
11645      movq       %rax,  %xmm0
11646      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
11647      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
11648      #ifdef __SSE3__
11649        haddpd   %xmm0, %xmm0
11650      #else
11651        pshufd   $0x4e, %xmm0, %xmm1
11652        addpd    %xmm1, %xmm0
11653      #endif
11654   */
11655
11656   SDLoc dl(Op);
11657   LLVMContext *Context = DAG.getContext();
11658
11659   // Build some magic constants.
11660   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
11661   Constant *C0 = ConstantDataVector::get(*Context, CV0);
11662   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
11663
11664   SmallVector<Constant*,2> CV1;
11665   CV1.push_back(
11666     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11667                                       APInt(64, 0x4330000000000000ULL))));
11668   CV1.push_back(
11669     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11670                                       APInt(64, 0x4530000000000000ULL))));
11671   Constant *C1 = ConstantVector::get(CV1);
11672   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
11673
11674   // Load the 64-bit value into an XMM register.
11675   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
11676                             Op.getOperand(0));
11677   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
11678                               MachinePointerInfo::getConstantPool(),
11679                               false, false, false, 16);
11680   SDValue Unpck1 =
11681       getUnpackl(DAG, dl, MVT::v4i32, DAG.getBitcast(MVT::v4i32, XR1), CLod0);
11682
11683   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
11684                               MachinePointerInfo::getConstantPool(),
11685                               false, false, false, 16);
11686   SDValue XR2F = DAG.getBitcast(MVT::v2f64, Unpck1);
11687   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
11688   SDValue Result;
11689
11690   if (Subtarget->hasSSE3()) {
11691     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
11692     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
11693   } else {
11694     SDValue S2F = DAG.getBitcast(MVT::v4i32, Sub);
11695     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
11696                                            S2F, 0x4E, DAG);
11697     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
11698                          DAG.getBitcast(MVT::v2f64, Shuffle), Sub);
11699   }
11700
11701   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
11702                      DAG.getIntPtrConstant(0, dl));
11703 }
11704
11705 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
11706 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
11707                                                SelectionDAG &DAG) const {
11708   SDLoc dl(Op);
11709   // FP constant to bias correct the final result.
11710   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
11711                                    MVT::f64);
11712
11713   // Load the 32-bit value into an XMM register.
11714   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
11715                              Op.getOperand(0));
11716
11717   // Zero out the upper parts of the register.
11718   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
11719
11720   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11721                      DAG.getBitcast(MVT::v2f64, Load),
11722                      DAG.getIntPtrConstant(0, dl));
11723
11724   // Or the load with the bias.
11725   SDValue Or = DAG.getNode(
11726       ISD::OR, dl, MVT::v2i64,
11727       DAG.getBitcast(MVT::v2i64,
11728                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Load)),
11729       DAG.getBitcast(MVT::v2i64,
11730                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Bias)));
11731   Or =
11732       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11733                   DAG.getBitcast(MVT::v2f64, Or), DAG.getIntPtrConstant(0, dl));
11734
11735   // Subtract the bias.
11736   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
11737
11738   // Handle final rounding.
11739   EVT DestVT = Op.getValueType();
11740
11741   if (DestVT.bitsLT(MVT::f64))
11742     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
11743                        DAG.getIntPtrConstant(0, dl));
11744   if (DestVT.bitsGT(MVT::f64))
11745     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
11746
11747   // Handle final rounding.
11748   return Sub;
11749 }
11750
11751 static SDValue lowerUINT_TO_FP_vXi32(SDValue Op, SelectionDAG &DAG,
11752                                      const X86Subtarget &Subtarget) {
11753   // The algorithm is the following:
11754   // #ifdef __SSE4_1__
11755   //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
11756   //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
11757   //                                 (uint4) 0x53000000, 0xaa);
11758   // #else
11759   //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
11760   //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
11761   // #endif
11762   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
11763   //     return (float4) lo + fhi;
11764
11765   SDLoc DL(Op);
11766   SDValue V = Op->getOperand(0);
11767   EVT VecIntVT = V.getValueType();
11768   bool Is128 = VecIntVT == MVT::v4i32;
11769   EVT VecFloatVT = Is128 ? MVT::v4f32 : MVT::v8f32;
11770   // If we convert to something else than the supported type, e.g., to v4f64,
11771   // abort early.
11772   if (VecFloatVT != Op->getValueType(0))
11773     return SDValue();
11774
11775   unsigned NumElts = VecIntVT.getVectorNumElements();
11776   assert((VecIntVT == MVT::v4i32 || VecIntVT == MVT::v8i32) &&
11777          "Unsupported custom type");
11778   assert(NumElts <= 8 && "The size of the constant array must be fixed");
11779
11780   // In the #idef/#else code, we have in common:
11781   // - The vector of constants:
11782   // -- 0x4b000000
11783   // -- 0x53000000
11784   // - A shift:
11785   // -- v >> 16
11786
11787   // Create the splat vector for 0x4b000000.
11788   SDValue CstLow = DAG.getConstant(0x4b000000, DL, MVT::i32);
11789   SDValue CstLowArray[] = {CstLow, CstLow, CstLow, CstLow,
11790                            CstLow, CstLow, CstLow, CstLow};
11791   SDValue VecCstLow = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
11792                                   makeArrayRef(&CstLowArray[0], NumElts));
11793   // Create the splat vector for 0x53000000.
11794   SDValue CstHigh = DAG.getConstant(0x53000000, DL, MVT::i32);
11795   SDValue CstHighArray[] = {CstHigh, CstHigh, CstHigh, CstHigh,
11796                             CstHigh, CstHigh, CstHigh, CstHigh};
11797   SDValue VecCstHigh = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
11798                                    makeArrayRef(&CstHighArray[0], NumElts));
11799
11800   // Create the right shift.
11801   SDValue CstShift = DAG.getConstant(16, DL, MVT::i32);
11802   SDValue CstShiftArray[] = {CstShift, CstShift, CstShift, CstShift,
11803                              CstShift, CstShift, CstShift, CstShift};
11804   SDValue VecCstShift = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
11805                                     makeArrayRef(&CstShiftArray[0], NumElts));
11806   SDValue HighShift = DAG.getNode(ISD::SRL, DL, VecIntVT, V, VecCstShift);
11807
11808   SDValue Low, High;
11809   if (Subtarget.hasSSE41()) {
11810     EVT VecI16VT = Is128 ? MVT::v8i16 : MVT::v16i16;
11811     //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
11812     SDValue VecCstLowBitcast = DAG.getBitcast(VecI16VT, VecCstLow);
11813     SDValue VecBitcast = DAG.getBitcast(VecI16VT, V);
11814     // Low will be bitcasted right away, so do not bother bitcasting back to its
11815     // original type.
11816     Low = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecBitcast,
11817                       VecCstLowBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
11818     //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
11819     //                                 (uint4) 0x53000000, 0xaa);
11820     SDValue VecCstHighBitcast = DAG.getBitcast(VecI16VT, VecCstHigh);
11821     SDValue VecShiftBitcast = DAG.getBitcast(VecI16VT, HighShift);
11822     // High will be bitcasted right away, so do not bother bitcasting back to
11823     // its original type.
11824     High = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecShiftBitcast,
11825                        VecCstHighBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
11826   } else {
11827     SDValue CstMask = DAG.getConstant(0xffff, DL, MVT::i32);
11828     SDValue VecCstMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT, CstMask,
11829                                      CstMask, CstMask, CstMask);
11830     //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
11831     SDValue LowAnd = DAG.getNode(ISD::AND, DL, VecIntVT, V, VecCstMask);
11832     Low = DAG.getNode(ISD::OR, DL, VecIntVT, LowAnd, VecCstLow);
11833
11834     //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
11835     High = DAG.getNode(ISD::OR, DL, VecIntVT, HighShift, VecCstHigh);
11836   }
11837
11838   // Create the vector constant for -(0x1.0p39f + 0x1.0p23f).
11839   SDValue CstFAdd = DAG.getConstantFP(
11840       APFloat(APFloat::IEEEsingle, APInt(32, 0xD3000080)), DL, MVT::f32);
11841   SDValue CstFAddArray[] = {CstFAdd, CstFAdd, CstFAdd, CstFAdd,
11842                             CstFAdd, CstFAdd, CstFAdd, CstFAdd};
11843   SDValue VecCstFAdd = DAG.getNode(ISD::BUILD_VECTOR, DL, VecFloatVT,
11844                                    makeArrayRef(&CstFAddArray[0], NumElts));
11845
11846   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
11847   SDValue HighBitcast = DAG.getBitcast(VecFloatVT, High);
11848   SDValue FHigh =
11849       DAG.getNode(ISD::FADD, DL, VecFloatVT, HighBitcast, VecCstFAdd);
11850   //     return (float4) lo + fhi;
11851   SDValue LowBitcast = DAG.getBitcast(VecFloatVT, Low);
11852   return DAG.getNode(ISD::FADD, DL, VecFloatVT, LowBitcast, FHigh);
11853 }
11854
11855 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
11856                                                SelectionDAG &DAG) const {
11857   SDValue N0 = Op.getOperand(0);
11858   MVT SVT = N0.getSimpleValueType();
11859   SDLoc dl(Op);
11860
11861   switch (SVT.SimpleTy) {
11862   default:
11863     llvm_unreachable("Custom UINT_TO_FP is not supported!");
11864   case MVT::v4i8:
11865   case MVT::v4i16:
11866   case MVT::v8i8:
11867   case MVT::v8i16: {
11868     MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
11869     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
11870                        DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
11871   }
11872   case MVT::v4i32:
11873   case MVT::v8i32:
11874     return lowerUINT_TO_FP_vXi32(Op, DAG, *Subtarget);
11875   case MVT::v16i8:
11876   case MVT::v16i16:
11877     if (Subtarget->hasAVX512())
11878       return DAG.getNode(ISD::UINT_TO_FP, dl, Op.getValueType(),
11879                          DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v16i32, N0));
11880   }
11881   llvm_unreachable(nullptr);
11882 }
11883
11884 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
11885                                            SelectionDAG &DAG) const {
11886   SDValue N0 = Op.getOperand(0);
11887   SDLoc dl(Op);
11888
11889   if (Op.getValueType().isVector())
11890     return lowerUINT_TO_FP_vec(Op, DAG);
11891
11892   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
11893   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
11894   // the optimization here.
11895   if (DAG.SignBitIsZero(N0))
11896     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
11897
11898   MVT SrcVT = N0.getSimpleValueType();
11899   MVT DstVT = Op.getSimpleValueType();
11900   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
11901     return LowerUINT_TO_FP_i64(Op, DAG);
11902   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
11903     return LowerUINT_TO_FP_i32(Op, DAG);
11904   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
11905     return SDValue();
11906
11907   // Make a 64-bit buffer, and use it to build an FILD.
11908   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
11909   if (SrcVT == MVT::i32) {
11910     SDValue WordOff = DAG.getConstant(4, dl, getPointerTy());
11911     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
11912                                      getPointerTy(), StackSlot, WordOff);
11913     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11914                                   StackSlot, MachinePointerInfo(),
11915                                   false, false, 0);
11916     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, dl, MVT::i32),
11917                                   OffsetSlot, MachinePointerInfo(),
11918                                   false, false, 0);
11919     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
11920     return Fild;
11921   }
11922
11923   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
11924   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11925                                StackSlot, MachinePointerInfo(),
11926                                false, false, 0);
11927   // For i64 source, we need to add the appropriate power of 2 if the input
11928   // was negative.  This is the same as the optimization in
11929   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
11930   // we must be careful to do the computation in x87 extended precision, not
11931   // in SSE. (The generic code can't know it's OK to do this, or how to.)
11932   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
11933   MachineMemOperand *MMO =
11934     DAG.getMachineFunction()
11935     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11936                           MachineMemOperand::MOLoad, 8, 8);
11937
11938   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
11939   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
11940   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
11941                                          MVT::i64, MMO);
11942
11943   APInt FF(32, 0x5F800000ULL);
11944
11945   // Check whether the sign bit is set.
11946   SDValue SignSet = DAG.getSetCC(dl,
11947                                  getSetCCResultType(*DAG.getContext(), MVT::i64),
11948                                  Op.getOperand(0),
11949                                  DAG.getConstant(0, dl, MVT::i64), ISD::SETLT);
11950
11951   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
11952   SDValue FudgePtr = DAG.getConstantPool(
11953                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
11954                                          getPointerTy());
11955
11956   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
11957   SDValue Zero = DAG.getIntPtrConstant(0, dl);
11958   SDValue Four = DAG.getIntPtrConstant(4, dl);
11959   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
11960                                Zero, Four);
11961   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
11962
11963   // Load the value out, extending it from f32 to f80.
11964   // FIXME: Avoid the extend by constructing the right constant pool?
11965   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
11966                                  FudgePtr, MachinePointerInfo::getConstantPool(),
11967                                  MVT::f32, false, false, false, 4);
11968   // Extend everything to 80 bits to force it to be done on x87.
11969   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
11970   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add,
11971                      DAG.getIntPtrConstant(0, dl));
11972 }
11973
11974 std::pair<SDValue,SDValue>
11975 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
11976                                     bool IsSigned, bool IsReplace) const {
11977   SDLoc DL(Op);
11978
11979   EVT DstTy = Op.getValueType();
11980
11981   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
11982     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
11983     DstTy = MVT::i64;
11984   }
11985
11986   assert(DstTy.getSimpleVT() <= MVT::i64 &&
11987          DstTy.getSimpleVT() >= MVT::i16 &&
11988          "Unknown FP_TO_INT to lower!");
11989
11990   // These are really Legal.
11991   if (DstTy == MVT::i32 &&
11992       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
11993     return std::make_pair(SDValue(), SDValue());
11994   if (Subtarget->is64Bit() &&
11995       DstTy == MVT::i64 &&
11996       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
11997     return std::make_pair(SDValue(), SDValue());
11998
11999   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
12000   // stack slot, or into the FTOL runtime function.
12001   MachineFunction &MF = DAG.getMachineFunction();
12002   unsigned MemSize = DstTy.getSizeInBits()/8;
12003   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
12004   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
12005
12006   unsigned Opc;
12007   if (!IsSigned && isIntegerTypeFTOL(DstTy))
12008     Opc = X86ISD::WIN_FTOL;
12009   else
12010     switch (DstTy.getSimpleVT().SimpleTy) {
12011     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
12012     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
12013     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
12014     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
12015     }
12016
12017   SDValue Chain = DAG.getEntryNode();
12018   SDValue Value = Op.getOperand(0);
12019   EVT TheVT = Op.getOperand(0).getValueType();
12020   // FIXME This causes a redundant load/store if the SSE-class value is already
12021   // in memory, such as if it is on the callstack.
12022   if (isScalarFPTypeInSSEReg(TheVT)) {
12023     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
12024     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
12025                          MachinePointerInfo::getFixedStack(SSFI),
12026                          false, false, 0);
12027     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
12028     SDValue Ops[] = {
12029       Chain, StackSlot, DAG.getValueType(TheVT)
12030     };
12031
12032     MachineMemOperand *MMO =
12033       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
12034                               MachineMemOperand::MOLoad, MemSize, MemSize);
12035     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
12036     Chain = Value.getValue(1);
12037     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
12038     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
12039   }
12040
12041   MachineMemOperand *MMO =
12042     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
12043                             MachineMemOperand::MOStore, MemSize, MemSize);
12044
12045   if (Opc != X86ISD::WIN_FTOL) {
12046     // Build the FP_TO_INT*_IN_MEM
12047     SDValue Ops[] = { Chain, Value, StackSlot };
12048     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
12049                                            Ops, DstTy, MMO);
12050     return std::make_pair(FIST, StackSlot);
12051   } else {
12052     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
12053       DAG.getVTList(MVT::Other, MVT::Glue),
12054       Chain, Value);
12055     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
12056       MVT::i32, ftol.getValue(1));
12057     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
12058       MVT::i32, eax.getValue(2));
12059     SDValue Ops[] = { eax, edx };
12060     SDValue pair = IsReplace
12061       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
12062       : DAG.getMergeValues(Ops, DL);
12063     return std::make_pair(pair, SDValue());
12064   }
12065 }
12066
12067 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
12068                               const X86Subtarget *Subtarget) {
12069   MVT VT = Op->getSimpleValueType(0);
12070   SDValue In = Op->getOperand(0);
12071   MVT InVT = In.getSimpleValueType();
12072   SDLoc dl(Op);
12073
12074   if (VT.is512BitVector() || InVT.getScalarType() == MVT::i1)
12075     return DAG.getNode(ISD::ZERO_EXTEND, dl, VT, In);
12076
12077   // Optimize vectors in AVX mode:
12078   //
12079   //   v8i16 -> v8i32
12080   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
12081   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
12082   //   Concat upper and lower parts.
12083   //
12084   //   v4i32 -> v4i64
12085   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
12086   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
12087   //   Concat upper and lower parts.
12088   //
12089
12090   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
12091       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
12092       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
12093     return SDValue();
12094
12095   if (Subtarget->hasInt256())
12096     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
12097
12098   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
12099   SDValue Undef = DAG.getUNDEF(InVT);
12100   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
12101   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12102   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12103
12104   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
12105                              VT.getVectorNumElements()/2);
12106
12107   OpLo = DAG.getBitcast(HVT, OpLo);
12108   OpHi = DAG.getBitcast(HVT, OpHi);
12109
12110   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
12111 }
12112
12113 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
12114                   const X86Subtarget *Subtarget, SelectionDAG &DAG) {
12115   MVT VT = Op->getSimpleValueType(0);
12116   SDValue In = Op->getOperand(0);
12117   MVT InVT = In.getSimpleValueType();
12118   SDLoc DL(Op);
12119   unsigned int NumElts = VT.getVectorNumElements();
12120   if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
12121     return SDValue();
12122
12123   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
12124     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
12125
12126   assert(InVT.getVectorElementType() == MVT::i1);
12127   MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
12128   SDValue One =
12129    DAG.getConstant(APInt(ExtVT.getScalarSizeInBits(), 1), DL, ExtVT);
12130   SDValue Zero =
12131    DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), DL, ExtVT);
12132
12133   SDValue V = DAG.getNode(ISD::VSELECT, DL, ExtVT, In, One, Zero);
12134   if (VT.is512BitVector())
12135     return V;
12136   return DAG.getNode(X86ISD::VTRUNC, DL, VT, V);
12137 }
12138
12139 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12140                                SelectionDAG &DAG) {
12141   if (Subtarget->hasFp256())
12142     if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
12143       return Res;
12144
12145   return SDValue();
12146 }
12147
12148 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12149                                 SelectionDAG &DAG) {
12150   SDLoc DL(Op);
12151   MVT VT = Op.getSimpleValueType();
12152   SDValue In = Op.getOperand(0);
12153   MVT SVT = In.getSimpleValueType();
12154
12155   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
12156     return LowerZERO_EXTEND_AVX512(Op, Subtarget, DAG);
12157
12158   if (Subtarget->hasFp256())
12159     if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
12160       return Res;
12161
12162   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
12163          VT.getVectorNumElements() != SVT.getVectorNumElements());
12164   return SDValue();
12165 }
12166
12167 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
12168   SDLoc DL(Op);
12169   MVT VT = Op.getSimpleValueType();
12170   SDValue In = Op.getOperand(0);
12171   MVT InVT = In.getSimpleValueType();
12172
12173   if (VT == MVT::i1) {
12174     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
12175            "Invalid scalar TRUNCATE operation");
12176     if (InVT.getSizeInBits() >= 32)
12177       return SDValue();
12178     In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
12179     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
12180   }
12181   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
12182          "Invalid TRUNCATE operation");
12183
12184   // move vector to mask - truncate solution for SKX
12185   if (VT.getVectorElementType() == MVT::i1) {
12186     if (InVT.is512BitVector() && InVT.getScalarSizeInBits() <= 16 &&
12187         Subtarget->hasBWI())
12188       return Op; // legal, will go to VPMOVB2M, VPMOVW2M
12189     if ((InVT.is256BitVector() || InVT.is128BitVector())
12190         && InVT.getScalarSizeInBits() <= 16 &&
12191         Subtarget->hasBWI() && Subtarget->hasVLX())
12192       return Op; // legal, will go to VPMOVB2M, VPMOVW2M
12193     if (InVT.is512BitVector() && InVT.getScalarSizeInBits() >= 32 &&
12194         Subtarget->hasDQI())
12195       return Op; // legal, will go to VPMOVD2M, VPMOVQ2M
12196     if ((InVT.is256BitVector() || InVT.is128BitVector())
12197         && InVT.getScalarSizeInBits() >= 32 &&
12198         Subtarget->hasDQI() && Subtarget->hasVLX())
12199       return Op; // legal, will go to VPMOVB2M, VPMOVQ2M
12200   }
12201   if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
12202     if (VT.getVectorElementType().getSizeInBits() >=8)
12203       return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
12204
12205     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
12206     unsigned NumElts = InVT.getVectorNumElements();
12207     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
12208     if (InVT.getSizeInBits() < 512) {
12209       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
12210       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
12211       InVT = ExtVT;
12212     }
12213
12214     SDValue OneV =
12215      DAG.getConstant(APInt::getSignBit(InVT.getScalarSizeInBits()), DL, InVT);
12216     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
12217     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
12218   }
12219
12220   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
12221     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
12222     if (Subtarget->hasInt256()) {
12223       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
12224       In = DAG.getBitcast(MVT::v8i32, In);
12225       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
12226                                 ShufMask);
12227       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
12228                          DAG.getIntPtrConstant(0, DL));
12229     }
12230
12231     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12232                                DAG.getIntPtrConstant(0, DL));
12233     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12234                                DAG.getIntPtrConstant(2, DL));
12235     OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
12236     OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
12237     static const int ShufMask[] = {0, 2, 4, 6};
12238     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
12239   }
12240
12241   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
12242     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
12243     if (Subtarget->hasInt256()) {
12244       In = DAG.getBitcast(MVT::v32i8, In);
12245
12246       SmallVector<SDValue,32> pshufbMask;
12247       for (unsigned i = 0; i < 2; ++i) {
12248         pshufbMask.push_back(DAG.getConstant(0x0, DL, MVT::i8));
12249         pshufbMask.push_back(DAG.getConstant(0x1, DL, MVT::i8));
12250         pshufbMask.push_back(DAG.getConstant(0x4, DL, MVT::i8));
12251         pshufbMask.push_back(DAG.getConstant(0x5, DL, MVT::i8));
12252         pshufbMask.push_back(DAG.getConstant(0x8, DL, MVT::i8));
12253         pshufbMask.push_back(DAG.getConstant(0x9, DL, MVT::i8));
12254         pshufbMask.push_back(DAG.getConstant(0xc, DL, MVT::i8));
12255         pshufbMask.push_back(DAG.getConstant(0xd, DL, MVT::i8));
12256         for (unsigned j = 0; j < 8; ++j)
12257           pshufbMask.push_back(DAG.getConstant(0x80, DL, MVT::i8));
12258       }
12259       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
12260       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
12261       In = DAG.getBitcast(MVT::v4i64, In);
12262
12263       static const int ShufMask[] = {0,  2,  -1,  -1};
12264       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
12265                                 &ShufMask[0]);
12266       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12267                        DAG.getIntPtrConstant(0, DL));
12268       return DAG.getBitcast(VT, In);
12269     }
12270
12271     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12272                                DAG.getIntPtrConstant(0, DL));
12273
12274     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12275                                DAG.getIntPtrConstant(4, DL));
12276
12277     OpLo = DAG.getBitcast(MVT::v16i8, OpLo);
12278     OpHi = DAG.getBitcast(MVT::v16i8, OpHi);
12279
12280     // The PSHUFB mask:
12281     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
12282                                    -1, -1, -1, -1, -1, -1, -1, -1};
12283
12284     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
12285     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
12286     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
12287
12288     OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
12289     OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
12290
12291     // The MOVLHPS Mask:
12292     static const int ShufMask2[] = {0, 1, 4, 5};
12293     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
12294     return DAG.getBitcast(MVT::v8i16, res);
12295   }
12296
12297   // Handle truncation of V256 to V128 using shuffles.
12298   if (!VT.is128BitVector() || !InVT.is256BitVector())
12299     return SDValue();
12300
12301   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
12302
12303   unsigned NumElems = VT.getVectorNumElements();
12304   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
12305
12306   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
12307   // Prepare truncation shuffle mask
12308   for (unsigned i = 0; i != NumElems; ++i)
12309     MaskVec[i] = i * 2;
12310   SDValue V = DAG.getVectorShuffle(NVT, DL, DAG.getBitcast(NVT, In),
12311                                    DAG.getUNDEF(NVT), &MaskVec[0]);
12312   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
12313                      DAG.getIntPtrConstant(0, DL));
12314 }
12315
12316 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
12317                                            SelectionDAG &DAG) const {
12318   assert(!Op.getSimpleValueType().isVector());
12319
12320   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12321     /*IsSigned=*/ true, /*IsReplace=*/ false);
12322   SDValue FIST = Vals.first, StackSlot = Vals.second;
12323   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
12324   if (!FIST.getNode()) return Op;
12325
12326   if (StackSlot.getNode())
12327     // Load the result.
12328     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12329                        FIST, StackSlot, MachinePointerInfo(),
12330                        false, false, false, 0);
12331
12332   // The node is the result.
12333   return FIST;
12334 }
12335
12336 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
12337                                            SelectionDAG &DAG) const {
12338   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12339     /*IsSigned=*/ false, /*IsReplace=*/ false);
12340   SDValue FIST = Vals.first, StackSlot = Vals.second;
12341   assert(FIST.getNode() && "Unexpected failure");
12342
12343   if (StackSlot.getNode())
12344     // Load the result.
12345     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12346                        FIST, StackSlot, MachinePointerInfo(),
12347                        false, false, false, 0);
12348
12349   // The node is the result.
12350   return FIST;
12351 }
12352
12353 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
12354   SDLoc DL(Op);
12355   MVT VT = Op.getSimpleValueType();
12356   SDValue In = Op.getOperand(0);
12357   MVT SVT = In.getSimpleValueType();
12358
12359   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
12360
12361   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
12362                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
12363                                  In, DAG.getUNDEF(SVT)));
12364 }
12365
12366 /// The only differences between FABS and FNEG are the mask and the logic op.
12367 /// FNEG also has a folding opportunity for FNEG(FABS(x)).
12368 static SDValue LowerFABSorFNEG(SDValue Op, SelectionDAG &DAG) {
12369   assert((Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) &&
12370          "Wrong opcode for lowering FABS or FNEG.");
12371
12372   bool IsFABS = (Op.getOpcode() == ISD::FABS);
12373
12374   // If this is a FABS and it has an FNEG user, bail out to fold the combination
12375   // into an FNABS. We'll lower the FABS after that if it is still in use.
12376   if (IsFABS)
12377     for (SDNode *User : Op->uses())
12378       if (User->getOpcode() == ISD::FNEG)
12379         return Op;
12380
12381   SDValue Op0 = Op.getOperand(0);
12382   bool IsFNABS = !IsFABS && (Op0.getOpcode() == ISD::FABS);
12383
12384   SDLoc dl(Op);
12385   MVT VT = Op.getSimpleValueType();
12386   // Assume scalar op for initialization; update for vector if needed.
12387   // Note that there are no scalar bitwise logical SSE/AVX instructions, so we
12388   // generate a 16-byte vector constant and logic op even for the scalar case.
12389   // Using a 16-byte mask allows folding the load of the mask with
12390   // the logic op, so it can save (~4 bytes) on code size.
12391   MVT EltVT = VT;
12392   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
12393   // FIXME: Use function attribute "OptimizeForSize" and/or CodeGenOpt::Level to
12394   // decide if we should generate a 16-byte constant mask when we only need 4 or
12395   // 8 bytes for the scalar case.
12396   if (VT.isVector()) {
12397     EltVT = VT.getVectorElementType();
12398     NumElts = VT.getVectorNumElements();
12399   }
12400
12401   unsigned EltBits = EltVT.getSizeInBits();
12402   LLVMContext *Context = DAG.getContext();
12403   // For FABS, mask is 0x7f...; for FNEG, mask is 0x80...
12404   APInt MaskElt =
12405     IsFABS ? APInt::getSignedMaxValue(EltBits) : APInt::getSignBit(EltBits);
12406   Constant *C = ConstantInt::get(*Context, MaskElt);
12407   C = ConstantVector::getSplat(NumElts, C);
12408   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12409   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
12410   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
12411   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
12412                              MachinePointerInfo::getConstantPool(),
12413                              false, false, false, Alignment);
12414
12415   if (VT.isVector()) {
12416     // For a vector, cast operands to a vector type, perform the logic op,
12417     // and cast the result back to the original value type.
12418     MVT VecVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
12419     SDValue MaskCasted = DAG.getBitcast(VecVT, Mask);
12420     SDValue Operand = IsFNABS ? DAG.getBitcast(VecVT, Op0.getOperand(0))
12421                               : DAG.getBitcast(VecVT, Op0);
12422     unsigned BitOp = IsFABS ? ISD::AND : IsFNABS ? ISD::OR : ISD::XOR;
12423     return DAG.getBitcast(VT,
12424                           DAG.getNode(BitOp, dl, VecVT, Operand, MaskCasted));
12425   }
12426
12427   // If not vector, then scalar.
12428   unsigned BitOp = IsFABS ? X86ISD::FAND : IsFNABS ? X86ISD::FOR : X86ISD::FXOR;
12429   SDValue Operand = IsFNABS ? Op0.getOperand(0) : Op0;
12430   return DAG.getNode(BitOp, dl, VT, Operand, Mask);
12431 }
12432
12433 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
12434   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12435   LLVMContext *Context = DAG.getContext();
12436   SDValue Op0 = Op.getOperand(0);
12437   SDValue Op1 = Op.getOperand(1);
12438   SDLoc dl(Op);
12439   MVT VT = Op.getSimpleValueType();
12440   MVT SrcVT = Op1.getSimpleValueType();
12441
12442   // If second operand is smaller, extend it first.
12443   if (SrcVT.bitsLT(VT)) {
12444     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
12445     SrcVT = VT;
12446   }
12447   // And if it is bigger, shrink it first.
12448   if (SrcVT.bitsGT(VT)) {
12449     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1, dl));
12450     SrcVT = VT;
12451   }
12452
12453   // At this point the operands and the result should have the same
12454   // type, and that won't be f80 since that is not custom lowered.
12455
12456   const fltSemantics &Sem =
12457       VT == MVT::f64 ? APFloat::IEEEdouble : APFloat::IEEEsingle;
12458   const unsigned SizeInBits = VT.getSizeInBits();
12459
12460   SmallVector<Constant *, 4> CV(
12461       VT == MVT::f64 ? 2 : 4,
12462       ConstantFP::get(*Context, APFloat(Sem, APInt(SizeInBits, 0))));
12463
12464   // First, clear all bits but the sign bit from the second operand (sign).
12465   CV[0] = ConstantFP::get(*Context,
12466                           APFloat(Sem, APInt::getHighBitsSet(SizeInBits, 1)));
12467   Constant *C = ConstantVector::get(CV);
12468   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
12469   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
12470                               MachinePointerInfo::getConstantPool(),
12471                               false, false, false, 16);
12472   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
12473
12474   // Next, clear the sign bit from the first operand (magnitude).
12475   // If it's a constant, we can clear it here.
12476   if (ConstantFPSDNode *Op0CN = dyn_cast<ConstantFPSDNode>(Op0)) {
12477     APFloat APF = Op0CN->getValueAPF();
12478     // If the magnitude is a positive zero, the sign bit alone is enough.
12479     if (APF.isPosZero())
12480       return SignBit;
12481     APF.clearSign();
12482     CV[0] = ConstantFP::get(*Context, APF);
12483   } else {
12484     CV[0] = ConstantFP::get(
12485         *Context,
12486         APFloat(Sem, APInt::getLowBitsSet(SizeInBits, SizeInBits - 1)));
12487   }
12488   C = ConstantVector::get(CV);
12489   CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
12490   SDValue Val = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
12491                             MachinePointerInfo::getConstantPool(),
12492                             false, false, false, 16);
12493   // If the magnitude operand wasn't a constant, we need to AND out the sign.
12494   if (!isa<ConstantFPSDNode>(Op0))
12495     Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Val);
12496
12497   // OR the magnitude value with the sign bit.
12498   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
12499 }
12500
12501 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
12502   SDValue N0 = Op.getOperand(0);
12503   SDLoc dl(Op);
12504   MVT VT = Op.getSimpleValueType();
12505
12506   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
12507   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
12508                                   DAG.getConstant(1, dl, VT));
12509   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, dl, VT));
12510 }
12511
12512 // Check whether an OR'd tree is PTEST-able.
12513 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
12514                                       SelectionDAG &DAG) {
12515   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
12516
12517   if (!Subtarget->hasSSE41())
12518     return SDValue();
12519
12520   if (!Op->hasOneUse())
12521     return SDValue();
12522
12523   SDNode *N = Op.getNode();
12524   SDLoc DL(N);
12525
12526   SmallVector<SDValue, 8> Opnds;
12527   DenseMap<SDValue, unsigned> VecInMap;
12528   SmallVector<SDValue, 8> VecIns;
12529   EVT VT = MVT::Other;
12530
12531   // Recognize a special case where a vector is casted into wide integer to
12532   // test all 0s.
12533   Opnds.push_back(N->getOperand(0));
12534   Opnds.push_back(N->getOperand(1));
12535
12536   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
12537     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
12538     // BFS traverse all OR'd operands.
12539     if (I->getOpcode() == ISD::OR) {
12540       Opnds.push_back(I->getOperand(0));
12541       Opnds.push_back(I->getOperand(1));
12542       // Re-evaluate the number of nodes to be traversed.
12543       e += 2; // 2 more nodes (LHS and RHS) are pushed.
12544       continue;
12545     }
12546
12547     // Quit if a non-EXTRACT_VECTOR_ELT
12548     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
12549       return SDValue();
12550
12551     // Quit if without a constant index.
12552     SDValue Idx = I->getOperand(1);
12553     if (!isa<ConstantSDNode>(Idx))
12554       return SDValue();
12555
12556     SDValue ExtractedFromVec = I->getOperand(0);
12557     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
12558     if (M == VecInMap.end()) {
12559       VT = ExtractedFromVec.getValueType();
12560       // Quit if not 128/256-bit vector.
12561       if (!VT.is128BitVector() && !VT.is256BitVector())
12562         return SDValue();
12563       // Quit if not the same type.
12564       if (VecInMap.begin() != VecInMap.end() &&
12565           VT != VecInMap.begin()->first.getValueType())
12566         return SDValue();
12567       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
12568       VecIns.push_back(ExtractedFromVec);
12569     }
12570     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
12571   }
12572
12573   assert((VT.is128BitVector() || VT.is256BitVector()) &&
12574          "Not extracted from 128-/256-bit vector.");
12575
12576   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
12577
12578   for (DenseMap<SDValue, unsigned>::const_iterator
12579         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
12580     // Quit if not all elements are used.
12581     if (I->second != FullMask)
12582       return SDValue();
12583   }
12584
12585   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
12586
12587   // Cast all vectors into TestVT for PTEST.
12588   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
12589     VecIns[i] = DAG.getBitcast(TestVT, VecIns[i]);
12590
12591   // If more than one full vectors are evaluated, OR them first before PTEST.
12592   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
12593     // Each iteration will OR 2 nodes and append the result until there is only
12594     // 1 node left, i.e. the final OR'd value of all vectors.
12595     SDValue LHS = VecIns[Slot];
12596     SDValue RHS = VecIns[Slot + 1];
12597     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
12598   }
12599
12600   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
12601                      VecIns.back(), VecIns.back());
12602 }
12603
12604 /// \brief return true if \c Op has a use that doesn't just read flags.
12605 static bool hasNonFlagsUse(SDValue Op) {
12606   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
12607        ++UI) {
12608     SDNode *User = *UI;
12609     unsigned UOpNo = UI.getOperandNo();
12610     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
12611       // Look pass truncate.
12612       UOpNo = User->use_begin().getOperandNo();
12613       User = *User->use_begin();
12614     }
12615
12616     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
12617         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
12618       return true;
12619   }
12620   return false;
12621 }
12622
12623 /// Emit nodes that will be selected as "test Op0,Op0", or something
12624 /// equivalent.
12625 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
12626                                     SelectionDAG &DAG) const {
12627   if (Op.getValueType() == MVT::i1) {
12628     SDValue ExtOp = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i8, Op);
12629     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, ExtOp,
12630                        DAG.getConstant(0, dl, MVT::i8));
12631   }
12632   // CF and OF aren't always set the way we want. Determine which
12633   // of these we need.
12634   bool NeedCF = false;
12635   bool NeedOF = false;
12636   switch (X86CC) {
12637   default: break;
12638   case X86::COND_A: case X86::COND_AE:
12639   case X86::COND_B: case X86::COND_BE:
12640     NeedCF = true;
12641     break;
12642   case X86::COND_G: case X86::COND_GE:
12643   case X86::COND_L: case X86::COND_LE:
12644   case X86::COND_O: case X86::COND_NO: {
12645     // Check if we really need to set the
12646     // Overflow flag. If NoSignedWrap is present
12647     // that is not actually needed.
12648     switch (Op->getOpcode()) {
12649     case ISD::ADD:
12650     case ISD::SUB:
12651     case ISD::MUL:
12652     case ISD::SHL: {
12653       const auto *BinNode = cast<BinaryWithFlagsSDNode>(Op.getNode());
12654       if (BinNode->Flags.hasNoSignedWrap())
12655         break;
12656     }
12657     default:
12658       NeedOF = true;
12659       break;
12660     }
12661     break;
12662   }
12663   }
12664   // See if we can use the EFLAGS value from the operand instead of
12665   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
12666   // we prove that the arithmetic won't overflow, we can't use OF or CF.
12667   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
12668     // Emit a CMP with 0, which is the TEST pattern.
12669     //if (Op.getValueType() == MVT::i1)
12670     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
12671     //                     DAG.getConstant(0, MVT::i1));
12672     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12673                        DAG.getConstant(0, dl, Op.getValueType()));
12674   }
12675   unsigned Opcode = 0;
12676   unsigned NumOperands = 0;
12677
12678   // Truncate operations may prevent the merge of the SETCC instruction
12679   // and the arithmetic instruction before it. Attempt to truncate the operands
12680   // of the arithmetic instruction and use a reduced bit-width instruction.
12681   bool NeedTruncation = false;
12682   SDValue ArithOp = Op;
12683   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
12684     SDValue Arith = Op->getOperand(0);
12685     // Both the trunc and the arithmetic op need to have one user each.
12686     if (Arith->hasOneUse())
12687       switch (Arith.getOpcode()) {
12688         default: break;
12689         case ISD::ADD:
12690         case ISD::SUB:
12691         case ISD::AND:
12692         case ISD::OR:
12693         case ISD::XOR: {
12694           NeedTruncation = true;
12695           ArithOp = Arith;
12696         }
12697       }
12698   }
12699
12700   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
12701   // which may be the result of a CAST.  We use the variable 'Op', which is the
12702   // non-casted variable when we check for possible users.
12703   switch (ArithOp.getOpcode()) {
12704   case ISD::ADD:
12705     // Due to an isel shortcoming, be conservative if this add is likely to be
12706     // selected as part of a load-modify-store instruction. When the root node
12707     // in a match is a store, isel doesn't know how to remap non-chain non-flag
12708     // uses of other nodes in the match, such as the ADD in this case. This
12709     // leads to the ADD being left around and reselected, with the result being
12710     // two adds in the output.  Alas, even if none our users are stores, that
12711     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
12712     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
12713     // climbing the DAG back to the root, and it doesn't seem to be worth the
12714     // effort.
12715     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12716          UE = Op.getNode()->use_end(); UI != UE; ++UI)
12717       if (UI->getOpcode() != ISD::CopyToReg &&
12718           UI->getOpcode() != ISD::SETCC &&
12719           UI->getOpcode() != ISD::STORE)
12720         goto default_case;
12721
12722     if (ConstantSDNode *C =
12723         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
12724       // An add of one will be selected as an INC.
12725       if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
12726         Opcode = X86ISD::INC;
12727         NumOperands = 1;
12728         break;
12729       }
12730
12731       // An add of negative one (subtract of one) will be selected as a DEC.
12732       if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
12733         Opcode = X86ISD::DEC;
12734         NumOperands = 1;
12735         break;
12736       }
12737     }
12738
12739     // Otherwise use a regular EFLAGS-setting add.
12740     Opcode = X86ISD::ADD;
12741     NumOperands = 2;
12742     break;
12743   case ISD::SHL:
12744   case ISD::SRL:
12745     // If we have a constant logical shift that's only used in a comparison
12746     // against zero turn it into an equivalent AND. This allows turning it into
12747     // a TEST instruction later.
12748     if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
12749         isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
12750       EVT VT = Op.getValueType();
12751       unsigned BitWidth = VT.getSizeInBits();
12752       unsigned ShAmt = Op->getConstantOperandVal(1);
12753       if (ShAmt >= BitWidth) // Avoid undefined shifts.
12754         break;
12755       APInt Mask = ArithOp.getOpcode() == ISD::SRL
12756                        ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
12757                        : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
12758       if (!Mask.isSignedIntN(32)) // Avoid large immediates.
12759         break;
12760       SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
12761                                 DAG.getConstant(Mask, dl, VT));
12762       DAG.ReplaceAllUsesWith(Op, New);
12763       Op = New;
12764     }
12765     break;
12766
12767   case ISD::AND:
12768     // If the primary and result isn't used, don't bother using X86ISD::AND,
12769     // because a TEST instruction will be better.
12770     if (!hasNonFlagsUse(Op))
12771       break;
12772     // FALL THROUGH
12773   case ISD::SUB:
12774   case ISD::OR:
12775   case ISD::XOR:
12776     // Due to the ISEL shortcoming noted above, be conservative if this op is
12777     // likely to be selected as part of a load-modify-store instruction.
12778     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12779            UE = Op.getNode()->use_end(); UI != UE; ++UI)
12780       if (UI->getOpcode() == ISD::STORE)
12781         goto default_case;
12782
12783     // Otherwise use a regular EFLAGS-setting instruction.
12784     switch (ArithOp.getOpcode()) {
12785     default: llvm_unreachable("unexpected operator!");
12786     case ISD::SUB: Opcode = X86ISD::SUB; break;
12787     case ISD::XOR: Opcode = X86ISD::XOR; break;
12788     case ISD::AND: Opcode = X86ISD::AND; break;
12789     case ISD::OR: {
12790       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
12791         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
12792         if (EFLAGS.getNode())
12793           return EFLAGS;
12794       }
12795       Opcode = X86ISD::OR;
12796       break;
12797     }
12798     }
12799
12800     NumOperands = 2;
12801     break;
12802   case X86ISD::ADD:
12803   case X86ISD::SUB:
12804   case X86ISD::INC:
12805   case X86ISD::DEC:
12806   case X86ISD::OR:
12807   case X86ISD::XOR:
12808   case X86ISD::AND:
12809     return SDValue(Op.getNode(), 1);
12810   default:
12811   default_case:
12812     break;
12813   }
12814
12815   // If we found that truncation is beneficial, perform the truncation and
12816   // update 'Op'.
12817   if (NeedTruncation) {
12818     EVT VT = Op.getValueType();
12819     SDValue WideVal = Op->getOperand(0);
12820     EVT WideVT = WideVal.getValueType();
12821     unsigned ConvertedOp = 0;
12822     // Use a target machine opcode to prevent further DAGCombine
12823     // optimizations that may separate the arithmetic operations
12824     // from the setcc node.
12825     switch (WideVal.getOpcode()) {
12826       default: break;
12827       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
12828       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
12829       case ISD::AND: ConvertedOp = X86ISD::AND; break;
12830       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
12831       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
12832     }
12833
12834     if (ConvertedOp) {
12835       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12836       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
12837         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
12838         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
12839         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
12840       }
12841     }
12842   }
12843
12844   if (Opcode == 0)
12845     // Emit a CMP with 0, which is the TEST pattern.
12846     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12847                        DAG.getConstant(0, dl, Op.getValueType()));
12848
12849   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12850   SmallVector<SDValue, 4> Ops(Op->op_begin(), Op->op_begin() + NumOperands);
12851
12852   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
12853   DAG.ReplaceAllUsesWith(Op, New);
12854   return SDValue(New.getNode(), 1);
12855 }
12856
12857 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
12858 /// equivalent.
12859 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
12860                                    SDLoc dl, SelectionDAG &DAG) const {
12861   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
12862     if (C->getAPIntValue() == 0)
12863       return EmitTest(Op0, X86CC, dl, DAG);
12864
12865      if (Op0.getValueType() == MVT::i1)
12866        llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
12867   }
12868
12869   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
12870        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
12871     // Do the comparison at i32 if it's smaller, besides the Atom case.
12872     // This avoids subregister aliasing issues. Keep the smaller reference
12873     // if we're optimizing for size, however, as that'll allow better folding
12874     // of memory operations.
12875     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
12876         !DAG.getMachineFunction().getFunction()->hasFnAttribute(
12877             Attribute::MinSize) &&
12878         !Subtarget->isAtom()) {
12879       unsigned ExtendOp =
12880           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
12881       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
12882       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
12883     }
12884     // Use SUB instead of CMP to enable CSE between SUB and CMP.
12885     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
12886     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
12887                               Op0, Op1);
12888     return SDValue(Sub.getNode(), 1);
12889   }
12890   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
12891 }
12892
12893 /// Convert a comparison if required by the subtarget.
12894 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
12895                                                  SelectionDAG &DAG) const {
12896   // If the subtarget does not support the FUCOMI instruction, floating-point
12897   // comparisons have to be converted.
12898   if (Subtarget->hasCMov() ||
12899       Cmp.getOpcode() != X86ISD::CMP ||
12900       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
12901       !Cmp.getOperand(1).getValueType().isFloatingPoint())
12902     return Cmp;
12903
12904   // The instruction selector will select an FUCOM instruction instead of
12905   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
12906   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
12907   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
12908   SDLoc dl(Cmp);
12909   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
12910   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
12911   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
12912                             DAG.getConstant(8, dl, MVT::i8));
12913   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
12914   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
12915 }
12916
12917 /// The minimum architected relative accuracy is 2^-12. We need one
12918 /// Newton-Raphson step to have a good float result (24 bits of precision).
12919 SDValue X86TargetLowering::getRsqrtEstimate(SDValue Op,
12920                                             DAGCombinerInfo &DCI,
12921                                             unsigned &RefinementSteps,
12922                                             bool &UseOneConstNR) const {
12923   EVT VT = Op.getValueType();
12924   const char *RecipOp;
12925
12926   // SSE1 has rsqrtss and rsqrtps. AVX adds a 256-bit variant for rsqrtps.
12927   // TODO: Add support for AVX512 (v16f32).
12928   // It is likely not profitable to do this for f64 because a double-precision
12929   // rsqrt estimate with refinement on x86 prior to FMA requires at least 16
12930   // instructions: convert to single, rsqrtss, convert back to double, refine
12931   // (3 steps = at least 13 insts). If an 'rsqrtsd' variant was added to the ISA
12932   // along with FMA, this could be a throughput win.
12933   if (VT == MVT::f32 && Subtarget->hasSSE1())
12934     RecipOp = "sqrtf";
12935   else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
12936            (VT == MVT::v8f32 && Subtarget->hasAVX()))
12937     RecipOp = "vec-sqrtf";
12938   else
12939     return SDValue();
12940
12941   TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
12942   if (!Recips.isEnabled(RecipOp))
12943     return SDValue();
12944
12945   RefinementSteps = Recips.getRefinementSteps(RecipOp);
12946   UseOneConstNR = false;
12947   return DCI.DAG.getNode(X86ISD::FRSQRT, SDLoc(Op), VT, Op);
12948 }
12949
12950 /// The minimum architected relative accuracy is 2^-12. We need one
12951 /// Newton-Raphson step to have a good float result (24 bits of precision).
12952 SDValue X86TargetLowering::getRecipEstimate(SDValue Op,
12953                                             DAGCombinerInfo &DCI,
12954                                             unsigned &RefinementSteps) const {
12955   EVT VT = Op.getValueType();
12956   const char *RecipOp;
12957
12958   // SSE1 has rcpss and rcpps. AVX adds a 256-bit variant for rcpps.
12959   // TODO: Add support for AVX512 (v16f32).
12960   // It is likely not profitable to do this for f64 because a double-precision
12961   // reciprocal estimate with refinement on x86 prior to FMA requires
12962   // 15 instructions: convert to single, rcpss, convert back to double, refine
12963   // (3 steps = 12 insts). If an 'rcpsd' variant was added to the ISA
12964   // along with FMA, this could be a throughput win.
12965   if (VT == MVT::f32 && Subtarget->hasSSE1())
12966     RecipOp = "divf";
12967   else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
12968            (VT == MVT::v8f32 && Subtarget->hasAVX()))
12969     RecipOp = "vec-divf";
12970   else
12971     return SDValue();
12972
12973   TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
12974   if (!Recips.isEnabled(RecipOp))
12975     return SDValue();
12976
12977   RefinementSteps = Recips.getRefinementSteps(RecipOp);
12978   return DCI.DAG.getNode(X86ISD::FRCP, SDLoc(Op), VT, Op);
12979 }
12980
12981 /// If we have at least two divisions that use the same divisor, convert to
12982 /// multplication by a reciprocal. This may need to be adjusted for a given
12983 /// CPU if a division's cost is not at least twice the cost of a multiplication.
12984 /// This is because we still need one division to calculate the reciprocal and
12985 /// then we need two multiplies by that reciprocal as replacements for the
12986 /// original divisions.
12987 bool X86TargetLowering::combineRepeatedFPDivisors(unsigned NumUsers) const {
12988   return NumUsers > 1;
12989 }
12990
12991 static bool isAllOnes(SDValue V) {
12992   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
12993   return C && C->isAllOnesValue();
12994 }
12995
12996 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
12997 /// if it's possible.
12998 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
12999                                      SDLoc dl, SelectionDAG &DAG) const {
13000   SDValue Op0 = And.getOperand(0);
13001   SDValue Op1 = And.getOperand(1);
13002   if (Op0.getOpcode() == ISD::TRUNCATE)
13003     Op0 = Op0.getOperand(0);
13004   if (Op1.getOpcode() == ISD::TRUNCATE)
13005     Op1 = Op1.getOperand(0);
13006
13007   SDValue LHS, RHS;
13008   if (Op1.getOpcode() == ISD::SHL)
13009     std::swap(Op0, Op1);
13010   if (Op0.getOpcode() == ISD::SHL) {
13011     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
13012       if (And00C->getZExtValue() == 1) {
13013         // If we looked past a truncate, check that it's only truncating away
13014         // known zeros.
13015         unsigned BitWidth = Op0.getValueSizeInBits();
13016         unsigned AndBitWidth = And.getValueSizeInBits();
13017         if (BitWidth > AndBitWidth) {
13018           APInt Zeros, Ones;
13019           DAG.computeKnownBits(Op0, Zeros, Ones);
13020           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
13021             return SDValue();
13022         }
13023         LHS = Op1;
13024         RHS = Op0.getOperand(1);
13025       }
13026   } else if (Op1.getOpcode() == ISD::Constant) {
13027     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
13028     uint64_t AndRHSVal = AndRHS->getZExtValue();
13029     SDValue AndLHS = Op0;
13030
13031     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
13032       LHS = AndLHS.getOperand(0);
13033       RHS = AndLHS.getOperand(1);
13034     }
13035
13036     // Use BT if the immediate can't be encoded in a TEST instruction.
13037     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
13038       LHS = AndLHS;
13039       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), dl, LHS.getValueType());
13040     }
13041   }
13042
13043   if (LHS.getNode()) {
13044     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
13045     // instruction.  Since the shift amount is in-range-or-undefined, we know
13046     // that doing a bittest on the i32 value is ok.  We extend to i32 because
13047     // the encoding for the i16 version is larger than the i32 version.
13048     // Also promote i16 to i32 for performance / code size reason.
13049     if (LHS.getValueType() == MVT::i8 ||
13050         LHS.getValueType() == MVT::i16)
13051       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
13052
13053     // If the operand types disagree, extend the shift amount to match.  Since
13054     // BT ignores high bits (like shifts) we can use anyextend.
13055     if (LHS.getValueType() != RHS.getValueType())
13056       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
13057
13058     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
13059     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
13060     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13061                        DAG.getConstant(Cond, dl, MVT::i8), BT);
13062   }
13063
13064   return SDValue();
13065 }
13066
13067 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
13068 /// mask CMPs.
13069 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
13070                               SDValue &Op1) {
13071   unsigned SSECC;
13072   bool Swap = false;
13073
13074   // SSE Condition code mapping:
13075   //  0 - EQ
13076   //  1 - LT
13077   //  2 - LE
13078   //  3 - UNORD
13079   //  4 - NEQ
13080   //  5 - NLT
13081   //  6 - NLE
13082   //  7 - ORD
13083   switch (SetCCOpcode) {
13084   default: llvm_unreachable("Unexpected SETCC condition");
13085   case ISD::SETOEQ:
13086   case ISD::SETEQ:  SSECC = 0; break;
13087   case ISD::SETOGT:
13088   case ISD::SETGT:  Swap = true; // Fallthrough
13089   case ISD::SETLT:
13090   case ISD::SETOLT: SSECC = 1; break;
13091   case ISD::SETOGE:
13092   case ISD::SETGE:  Swap = true; // Fallthrough
13093   case ISD::SETLE:
13094   case ISD::SETOLE: SSECC = 2; break;
13095   case ISD::SETUO:  SSECC = 3; break;
13096   case ISD::SETUNE:
13097   case ISD::SETNE:  SSECC = 4; break;
13098   case ISD::SETULE: Swap = true; // Fallthrough
13099   case ISD::SETUGE: SSECC = 5; break;
13100   case ISD::SETULT: Swap = true; // Fallthrough
13101   case ISD::SETUGT: SSECC = 6; break;
13102   case ISD::SETO:   SSECC = 7; break;
13103   case ISD::SETUEQ:
13104   case ISD::SETONE: SSECC = 8; break;
13105   }
13106   if (Swap)
13107     std::swap(Op0, Op1);
13108
13109   return SSECC;
13110 }
13111
13112 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
13113 // ones, and then concatenate the result back.
13114 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
13115   MVT VT = Op.getSimpleValueType();
13116
13117   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
13118          "Unsupported value type for operation");
13119
13120   unsigned NumElems = VT.getVectorNumElements();
13121   SDLoc dl(Op);
13122   SDValue CC = Op.getOperand(2);
13123
13124   // Extract the LHS vectors
13125   SDValue LHS = Op.getOperand(0);
13126   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13127   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13128
13129   // Extract the RHS vectors
13130   SDValue RHS = Op.getOperand(1);
13131   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
13132   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
13133
13134   // Issue the operation on the smaller types and concatenate the result back
13135   MVT EltVT = VT.getVectorElementType();
13136   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13137   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
13138                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
13139                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
13140 }
13141
13142 static SDValue LowerBoolVSETCC_AVX512(SDValue Op, SelectionDAG &DAG) {
13143   SDValue Op0 = Op.getOperand(0);
13144   SDValue Op1 = Op.getOperand(1);
13145   SDValue CC = Op.getOperand(2);
13146   MVT VT = Op.getSimpleValueType();
13147   SDLoc dl(Op);
13148
13149   assert(Op0.getValueType().getVectorElementType() == MVT::i1 &&
13150          "Unexpected type for boolean compare operation");
13151   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13152   SDValue NotOp0 = DAG.getNode(ISD::XOR, dl, VT, Op0,
13153                                DAG.getConstant(-1, dl, VT));
13154   SDValue NotOp1 = DAG.getNode(ISD::XOR, dl, VT, Op1,
13155                                DAG.getConstant(-1, dl, VT));
13156   switch (SetCCOpcode) {
13157   default: llvm_unreachable("Unexpected SETCC condition");
13158   case ISD::SETEQ:
13159     // (x == y) -> ~(x ^ y)
13160     return DAG.getNode(ISD::XOR, dl, VT,
13161                        DAG.getNode(ISD::XOR, dl, VT, Op0, Op1),
13162                        DAG.getConstant(-1, dl, VT));
13163   case ISD::SETNE:
13164     // (x != y) -> (x ^ y)
13165     return DAG.getNode(ISD::XOR, dl, VT, Op0, Op1);
13166   case ISD::SETUGT:
13167   case ISD::SETGT:
13168     // (x > y) -> (x & ~y)
13169     return DAG.getNode(ISD::AND, dl, VT, Op0, NotOp1);
13170   case ISD::SETULT:
13171   case ISD::SETLT:
13172     // (x < y) -> (~x & y)
13173     return DAG.getNode(ISD::AND, dl, VT, NotOp0, Op1);
13174   case ISD::SETULE:
13175   case ISD::SETLE:
13176     // (x <= y) -> (~x | y)
13177     return DAG.getNode(ISD::OR, dl, VT, NotOp0, Op1);
13178   case ISD::SETUGE:
13179   case ISD::SETGE:
13180     // (x >=y) -> (x | ~y)
13181     return DAG.getNode(ISD::OR, dl, VT, Op0, NotOp1);
13182   }
13183 }
13184
13185 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
13186                                      const X86Subtarget *Subtarget) {
13187   SDValue Op0 = Op.getOperand(0);
13188   SDValue Op1 = Op.getOperand(1);
13189   SDValue CC = Op.getOperand(2);
13190   MVT VT = Op.getSimpleValueType();
13191   SDLoc dl(Op);
13192
13193   assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 8 &&
13194          Op.getValueType().getScalarType() == MVT::i1 &&
13195          "Cannot set masked compare for this operation");
13196
13197   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13198   unsigned  Opc = 0;
13199   bool Unsigned = false;
13200   bool Swap = false;
13201   unsigned SSECC;
13202   switch (SetCCOpcode) {
13203   default: llvm_unreachable("Unexpected SETCC condition");
13204   case ISD::SETNE:  SSECC = 4; break;
13205   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
13206   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
13207   case ISD::SETLT:  Swap = true; //fall-through
13208   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
13209   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
13210   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
13211   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
13212   case ISD::SETULE: Unsigned = true; //fall-through
13213   case ISD::SETLE:  SSECC = 2; break;
13214   }
13215
13216   if (Swap)
13217     std::swap(Op0, Op1);
13218   if (Opc)
13219     return DAG.getNode(Opc, dl, VT, Op0, Op1);
13220   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
13221   return DAG.getNode(Opc, dl, VT, Op0, Op1,
13222                      DAG.getConstant(SSECC, dl, MVT::i8));
13223 }
13224
13225 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
13226 /// operand \p Op1.  If non-trivial (for example because it's not constant)
13227 /// return an empty value.
13228 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
13229 {
13230   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
13231   if (!BV)
13232     return SDValue();
13233
13234   MVT VT = Op1.getSimpleValueType();
13235   MVT EVT = VT.getVectorElementType();
13236   unsigned n = VT.getVectorNumElements();
13237   SmallVector<SDValue, 8> ULTOp1;
13238
13239   for (unsigned i = 0; i < n; ++i) {
13240     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
13241     if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
13242       return SDValue();
13243
13244     // Avoid underflow.
13245     APInt Val = Elt->getAPIntValue();
13246     if (Val == 0)
13247       return SDValue();
13248
13249     ULTOp1.push_back(DAG.getConstant(Val - 1, dl, EVT));
13250   }
13251
13252   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
13253 }
13254
13255 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
13256                            SelectionDAG &DAG) {
13257   SDValue Op0 = Op.getOperand(0);
13258   SDValue Op1 = Op.getOperand(1);
13259   SDValue CC = Op.getOperand(2);
13260   MVT VT = Op.getSimpleValueType();
13261   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13262   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
13263   SDLoc dl(Op);
13264
13265   if (isFP) {
13266 #ifndef NDEBUG
13267     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
13268     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
13269 #endif
13270
13271     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
13272     unsigned Opc = X86ISD::CMPP;
13273     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
13274       assert(VT.getVectorNumElements() <= 16);
13275       Opc = X86ISD::CMPM;
13276     }
13277     // In the two special cases we can't handle, emit two comparisons.
13278     if (SSECC == 8) {
13279       unsigned CC0, CC1;
13280       unsigned CombineOpc;
13281       if (SetCCOpcode == ISD::SETUEQ) {
13282         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
13283       } else {
13284         assert(SetCCOpcode == ISD::SETONE);
13285         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
13286       }
13287
13288       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13289                                  DAG.getConstant(CC0, dl, MVT::i8));
13290       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13291                                  DAG.getConstant(CC1, dl, MVT::i8));
13292       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
13293     }
13294     // Handle all other FP comparisons here.
13295     return DAG.getNode(Opc, dl, VT, Op0, Op1,
13296                        DAG.getConstant(SSECC, dl, MVT::i8));
13297   }
13298
13299   // Break 256-bit integer vector compare into smaller ones.
13300   if (VT.is256BitVector() && !Subtarget->hasInt256())
13301     return Lower256IntVSETCC(Op, DAG);
13302
13303   EVT OpVT = Op1.getValueType();
13304   if (OpVT.getVectorElementType() == MVT::i1)
13305     return LowerBoolVSETCC_AVX512(Op, DAG);
13306
13307   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
13308   if (Subtarget->hasAVX512()) {
13309     if (Op1.getValueType().is512BitVector() ||
13310         (Subtarget->hasBWI() && Subtarget->hasVLX()) ||
13311         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
13312       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
13313
13314     // In AVX-512 architecture setcc returns mask with i1 elements,
13315     // But there is no compare instruction for i8 and i16 elements in KNL.
13316     // We are not talking about 512-bit operands in this case, these
13317     // types are illegal.
13318     if (MaskResult &&
13319         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
13320          OpVT.getVectorElementType().getSizeInBits() >= 8))
13321       return DAG.getNode(ISD::TRUNCATE, dl, VT,
13322                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
13323   }
13324
13325   // We are handling one of the integer comparisons here.  Since SSE only has
13326   // GT and EQ comparisons for integer, swapping operands and multiple
13327   // operations may be required for some comparisons.
13328   unsigned Opc;
13329   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
13330   bool Subus = false;
13331
13332   switch (SetCCOpcode) {
13333   default: llvm_unreachable("Unexpected SETCC condition");
13334   case ISD::SETNE:  Invert = true;
13335   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
13336   case ISD::SETLT:  Swap = true;
13337   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
13338   case ISD::SETGE:  Swap = true;
13339   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
13340                     Invert = true; break;
13341   case ISD::SETULT: Swap = true;
13342   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
13343                     FlipSigns = true; break;
13344   case ISD::SETUGE: Swap = true;
13345   case ISD::SETULE: Opc = X86ISD::PCMPGT;
13346                     FlipSigns = true; Invert = true; break;
13347   }
13348
13349   // Special case: Use min/max operations for SETULE/SETUGE
13350   MVT VET = VT.getVectorElementType();
13351   bool hasMinMax =
13352        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
13353     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
13354
13355   if (hasMinMax) {
13356     switch (SetCCOpcode) {
13357     default: break;
13358     case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
13359     case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
13360     }
13361
13362     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
13363   }
13364
13365   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
13366   if (!MinMax && hasSubus) {
13367     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
13368     // Op0 u<= Op1:
13369     //   t = psubus Op0, Op1
13370     //   pcmpeq t, <0..0>
13371     switch (SetCCOpcode) {
13372     default: break;
13373     case ISD::SETULT: {
13374       // If the comparison is against a constant we can turn this into a
13375       // setule.  With psubus, setule does not require a swap.  This is
13376       // beneficial because the constant in the register is no longer
13377       // destructed as the destination so it can be hoisted out of a loop.
13378       // Only do this pre-AVX since vpcmp* is no longer destructive.
13379       if (Subtarget->hasAVX())
13380         break;
13381       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
13382       if (ULEOp1.getNode()) {
13383         Op1 = ULEOp1;
13384         Subus = true; Invert = false; Swap = false;
13385       }
13386       break;
13387     }
13388     // Psubus is better than flip-sign because it requires no inversion.
13389     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
13390     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
13391     }
13392
13393     if (Subus) {
13394       Opc = X86ISD::SUBUS;
13395       FlipSigns = false;
13396     }
13397   }
13398
13399   if (Swap)
13400     std::swap(Op0, Op1);
13401
13402   // Check that the operation in question is available (most are plain SSE2,
13403   // but PCMPGTQ and PCMPEQQ have different requirements).
13404   if (VT == MVT::v2i64) {
13405     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
13406       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
13407
13408       // First cast everything to the right type.
13409       Op0 = DAG.getBitcast(MVT::v4i32, Op0);
13410       Op1 = DAG.getBitcast(MVT::v4i32, Op1);
13411
13412       // Since SSE has no unsigned integer comparisons, we need to flip the sign
13413       // bits of the inputs before performing those operations. The lower
13414       // compare is always unsigned.
13415       SDValue SB;
13416       if (FlipSigns) {
13417         SB = DAG.getConstant(0x80000000U, dl, MVT::v4i32);
13418       } else {
13419         SDValue Sign = DAG.getConstant(0x80000000U, dl, MVT::i32);
13420         SDValue Zero = DAG.getConstant(0x00000000U, dl, MVT::i32);
13421         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
13422                          Sign, Zero, Sign, Zero);
13423       }
13424       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
13425       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
13426
13427       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
13428       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
13429       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
13430
13431       // Create masks for only the low parts/high parts of the 64 bit integers.
13432       static const int MaskHi[] = { 1, 1, 3, 3 };
13433       static const int MaskLo[] = { 0, 0, 2, 2 };
13434       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
13435       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
13436       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
13437
13438       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
13439       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
13440
13441       if (Invert)
13442         Result = DAG.getNOT(dl, Result, MVT::v4i32);
13443
13444       return DAG.getBitcast(VT, Result);
13445     }
13446
13447     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
13448       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
13449       // pcmpeqd + pshufd + pand.
13450       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
13451
13452       // First cast everything to the right type.
13453       Op0 = DAG.getBitcast(MVT::v4i32, Op0);
13454       Op1 = DAG.getBitcast(MVT::v4i32, Op1);
13455
13456       // Do the compare.
13457       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
13458
13459       // Make sure the lower and upper halves are both all-ones.
13460       static const int Mask[] = { 1, 0, 3, 2 };
13461       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
13462       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
13463
13464       if (Invert)
13465         Result = DAG.getNOT(dl, Result, MVT::v4i32);
13466
13467       return DAG.getBitcast(VT, Result);
13468     }
13469   }
13470
13471   // Since SSE has no unsigned integer comparisons, we need to flip the sign
13472   // bits of the inputs before performing those operations.
13473   if (FlipSigns) {
13474     EVT EltVT = VT.getVectorElementType();
13475     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), dl,
13476                                  VT);
13477     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
13478     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
13479   }
13480
13481   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
13482
13483   // If the logical-not of the result is required, perform that now.
13484   if (Invert)
13485     Result = DAG.getNOT(dl, Result, VT);
13486
13487   if (MinMax)
13488     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
13489
13490   if (Subus)
13491     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
13492                          getZeroVector(VT, Subtarget, DAG, dl));
13493
13494   return Result;
13495 }
13496
13497 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
13498
13499   MVT VT = Op.getSimpleValueType();
13500
13501   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
13502
13503   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
13504          && "SetCC type must be 8-bit or 1-bit integer");
13505   SDValue Op0 = Op.getOperand(0);
13506   SDValue Op1 = Op.getOperand(1);
13507   SDLoc dl(Op);
13508   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
13509
13510   // Optimize to BT if possible.
13511   // Lower (X & (1 << N)) == 0 to BT(X, N).
13512   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
13513   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
13514   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
13515       Op1.getOpcode() == ISD::Constant &&
13516       cast<ConstantSDNode>(Op1)->isNullValue() &&
13517       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13518     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
13519     if (NewSetCC.getNode()) {
13520       if (VT == MVT::i1)
13521         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewSetCC);
13522       return NewSetCC;
13523     }
13524   }
13525
13526   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
13527   // these.
13528   if (Op1.getOpcode() == ISD::Constant &&
13529       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
13530        cast<ConstantSDNode>(Op1)->isNullValue()) &&
13531       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13532
13533     // If the input is a setcc, then reuse the input setcc or use a new one with
13534     // the inverted condition.
13535     if (Op0.getOpcode() == X86ISD::SETCC) {
13536       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
13537       bool Invert = (CC == ISD::SETNE) ^
13538         cast<ConstantSDNode>(Op1)->isNullValue();
13539       if (!Invert)
13540         return Op0;
13541
13542       CCode = X86::GetOppositeBranchCondition(CCode);
13543       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13544                                   DAG.getConstant(CCode, dl, MVT::i8),
13545                                   Op0.getOperand(1));
13546       if (VT == MVT::i1)
13547         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13548       return SetCC;
13549     }
13550   }
13551   if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
13552       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
13553       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13554
13555     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
13556     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, dl, MVT::i1), NewCC);
13557   }
13558
13559   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
13560   unsigned X86CC = TranslateX86CC(CC, dl, isFP, Op0, Op1, DAG);
13561   if (X86CC == X86::COND_INVALID)
13562     return SDValue();
13563
13564   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
13565   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
13566   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13567                               DAG.getConstant(X86CC, dl, MVT::i8), EFLAGS);
13568   if (VT == MVT::i1)
13569     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13570   return SetCC;
13571 }
13572
13573 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
13574 static bool isX86LogicalCmp(SDValue Op) {
13575   unsigned Opc = Op.getNode()->getOpcode();
13576   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
13577       Opc == X86ISD::SAHF)
13578     return true;
13579   if (Op.getResNo() == 1 &&
13580       (Opc == X86ISD::ADD ||
13581        Opc == X86ISD::SUB ||
13582        Opc == X86ISD::ADC ||
13583        Opc == X86ISD::SBB ||
13584        Opc == X86ISD::SMUL ||
13585        Opc == X86ISD::UMUL ||
13586        Opc == X86ISD::INC ||
13587        Opc == X86ISD::DEC ||
13588        Opc == X86ISD::OR ||
13589        Opc == X86ISD::XOR ||
13590        Opc == X86ISD::AND))
13591     return true;
13592
13593   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
13594     return true;
13595
13596   return false;
13597 }
13598
13599 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
13600   if (V.getOpcode() != ISD::TRUNCATE)
13601     return false;
13602
13603   SDValue VOp0 = V.getOperand(0);
13604   unsigned InBits = VOp0.getValueSizeInBits();
13605   unsigned Bits = V.getValueSizeInBits();
13606   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
13607 }
13608
13609 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
13610   bool addTest = true;
13611   SDValue Cond  = Op.getOperand(0);
13612   SDValue Op1 = Op.getOperand(1);
13613   SDValue Op2 = Op.getOperand(2);
13614   SDLoc DL(Op);
13615   EVT VT = Op1.getValueType();
13616   SDValue CC;
13617
13618   // Lower FP selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
13619   // are available or VBLENDV if AVX is available.
13620   // Otherwise FP cmovs get lowered into a less efficient branch sequence later.
13621   if (Cond.getOpcode() == ISD::SETCC &&
13622       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
13623        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
13624       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
13625     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
13626     int SSECC = translateX86FSETCC(
13627         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
13628
13629     if (SSECC != 8) {
13630       if (Subtarget->hasAVX512()) {
13631         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
13632                                   DAG.getConstant(SSECC, DL, MVT::i8));
13633         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
13634       }
13635
13636       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
13637                                 DAG.getConstant(SSECC, DL, MVT::i8));
13638
13639       // If we have AVX, we can use a variable vector select (VBLENDV) instead
13640       // of 3 logic instructions for size savings and potentially speed.
13641       // Unfortunately, there is no scalar form of VBLENDV.
13642
13643       // If either operand is a constant, don't try this. We can expect to
13644       // optimize away at least one of the logic instructions later in that
13645       // case, so that sequence would be faster than a variable blend.
13646
13647       // BLENDV was introduced with SSE 4.1, but the 2 register form implicitly
13648       // uses XMM0 as the selection register. That may need just as many
13649       // instructions as the AND/ANDN/OR sequence due to register moves, so
13650       // don't bother.
13651
13652       if (Subtarget->hasAVX() &&
13653           !isa<ConstantFPSDNode>(Op1) && !isa<ConstantFPSDNode>(Op2)) {
13654
13655         // Convert to vectors, do a VSELECT, and convert back to scalar.
13656         // All of the conversions should be optimized away.
13657
13658         EVT VecVT = VT == MVT::f32 ? MVT::v4f32 : MVT::v2f64;
13659         SDValue VOp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op1);
13660         SDValue VOp2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op2);
13661         SDValue VCmp = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Cmp);
13662
13663         EVT VCmpVT = VT == MVT::f32 ? MVT::v4i32 : MVT::v2i64;
13664         VCmp = DAG.getBitcast(VCmpVT, VCmp);
13665
13666         SDValue VSel = DAG.getNode(ISD::VSELECT, DL, VecVT, VCmp, VOp1, VOp2);
13667
13668         return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
13669                            VSel, DAG.getIntPtrConstant(0, DL));
13670       }
13671       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
13672       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
13673       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
13674     }
13675   }
13676
13677     if (VT.isVector() && VT.getScalarType() == MVT::i1) {
13678       SDValue Op1Scalar;
13679       if (ISD::isBuildVectorOfConstantSDNodes(Op1.getNode()))
13680         Op1Scalar = ConvertI1VectorToInterger(Op1, DAG);
13681       else if (Op1.getOpcode() == ISD::BITCAST && Op1.getOperand(0))
13682         Op1Scalar = Op1.getOperand(0);
13683       SDValue Op2Scalar;
13684       if (ISD::isBuildVectorOfConstantSDNodes(Op2.getNode()))
13685         Op2Scalar = ConvertI1VectorToInterger(Op2, DAG);
13686       else if (Op2.getOpcode() == ISD::BITCAST && Op2.getOperand(0))
13687         Op2Scalar = Op2.getOperand(0);
13688       if (Op1Scalar.getNode() && Op2Scalar.getNode()) {
13689         SDValue newSelect = DAG.getNode(ISD::SELECT, DL,
13690                                         Op1Scalar.getValueType(),
13691                                         Cond, Op1Scalar, Op2Scalar);
13692         if (newSelect.getValueSizeInBits() == VT.getSizeInBits())
13693           return DAG.getBitcast(VT, newSelect);
13694         SDValue ExtVec = DAG.getBitcast(MVT::v8i1, newSelect);
13695         return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, ExtVec,
13696                            DAG.getIntPtrConstant(0, DL));
13697     }
13698   }
13699
13700   if (VT == MVT::v4i1 || VT == MVT::v2i1) {
13701     SDValue zeroConst = DAG.getIntPtrConstant(0, DL);
13702     Op1 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
13703                       DAG.getUNDEF(MVT::v8i1), Op1, zeroConst);
13704     Op2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
13705                       DAG.getUNDEF(MVT::v8i1), Op2, zeroConst);
13706     SDValue newSelect = DAG.getNode(ISD::SELECT, DL, MVT::v8i1,
13707                                     Cond, Op1, Op2);
13708     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, newSelect, zeroConst);
13709   }
13710
13711   if (Cond.getOpcode() == ISD::SETCC) {
13712     SDValue NewCond = LowerSETCC(Cond, DAG);
13713     if (NewCond.getNode())
13714       Cond = NewCond;
13715   }
13716
13717   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
13718   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
13719   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
13720   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
13721   if (Cond.getOpcode() == X86ISD::SETCC &&
13722       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
13723       isZero(Cond.getOperand(1).getOperand(1))) {
13724     SDValue Cmp = Cond.getOperand(1);
13725
13726     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
13727
13728     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
13729         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
13730       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
13731
13732       SDValue CmpOp0 = Cmp.getOperand(0);
13733       // Apply further optimizations for special cases
13734       // (select (x != 0), -1, 0) -> neg & sbb
13735       // (select (x == 0), 0, -1) -> neg & sbb
13736       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
13737         if (YC->isNullValue() &&
13738             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
13739           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
13740           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
13741                                     DAG.getConstant(0, DL,
13742                                                     CmpOp0.getValueType()),
13743                                     CmpOp0);
13744           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13745                                     DAG.getConstant(X86::COND_B, DL, MVT::i8),
13746                                     SDValue(Neg.getNode(), 1));
13747           return Res;
13748         }
13749
13750       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
13751                         CmpOp0, DAG.getConstant(1, DL, CmpOp0.getValueType()));
13752       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
13753
13754       SDValue Res =   // Res = 0 or -1.
13755         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13756                     DAG.getConstant(X86::COND_B, DL, MVT::i8), Cmp);
13757
13758       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
13759         Res = DAG.getNOT(DL, Res, Res.getValueType());
13760
13761       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
13762       if (!N2C || !N2C->isNullValue())
13763         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
13764       return Res;
13765     }
13766   }
13767
13768   // Look past (and (setcc_carry (cmp ...)), 1).
13769   if (Cond.getOpcode() == ISD::AND &&
13770       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
13771     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
13772     if (C && C->getAPIntValue() == 1)
13773       Cond = Cond.getOperand(0);
13774   }
13775
13776   // If condition flag is set by a X86ISD::CMP, then use it as the condition
13777   // setting operand in place of the X86ISD::SETCC.
13778   unsigned CondOpcode = Cond.getOpcode();
13779   if (CondOpcode == X86ISD::SETCC ||
13780       CondOpcode == X86ISD::SETCC_CARRY) {
13781     CC = Cond.getOperand(0);
13782
13783     SDValue Cmp = Cond.getOperand(1);
13784     unsigned Opc = Cmp.getOpcode();
13785     MVT VT = Op.getSimpleValueType();
13786
13787     bool IllegalFPCMov = false;
13788     if (VT.isFloatingPoint() && !VT.isVector() &&
13789         !isScalarFPTypeInSSEReg(VT))  // FPStack?
13790       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
13791
13792     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
13793         Opc == X86ISD::BT) { // FIXME
13794       Cond = Cmp;
13795       addTest = false;
13796     }
13797   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
13798              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
13799              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
13800               Cond.getOperand(0).getValueType() != MVT::i8)) {
13801     SDValue LHS = Cond.getOperand(0);
13802     SDValue RHS = Cond.getOperand(1);
13803     unsigned X86Opcode;
13804     unsigned X86Cond;
13805     SDVTList VTs;
13806     switch (CondOpcode) {
13807     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
13808     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
13809     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
13810     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
13811     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
13812     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
13813     default: llvm_unreachable("unexpected overflowing operator");
13814     }
13815     if (CondOpcode == ISD::UMULO)
13816       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
13817                           MVT::i32);
13818     else
13819       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
13820
13821     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
13822
13823     if (CondOpcode == ISD::UMULO)
13824       Cond = X86Op.getValue(2);
13825     else
13826       Cond = X86Op.getValue(1);
13827
13828     CC = DAG.getConstant(X86Cond, DL, MVT::i8);
13829     addTest = false;
13830   }
13831
13832   if (addTest) {
13833     // Look pass the truncate if the high bits are known zero.
13834     if (isTruncWithZeroHighBitsInput(Cond, DAG))
13835         Cond = Cond.getOperand(0);
13836
13837     // We know the result of AND is compared against zero. Try to match
13838     // it to BT.
13839     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
13840       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
13841       if (NewSetCC.getNode()) {
13842         CC = NewSetCC.getOperand(0);
13843         Cond = NewSetCC.getOperand(1);
13844         addTest = false;
13845       }
13846     }
13847   }
13848
13849   if (addTest) {
13850     CC = DAG.getConstant(X86::COND_NE, DL, MVT::i8);
13851     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
13852   }
13853
13854   // a <  b ? -1 :  0 -> RES = ~setcc_carry
13855   // a <  b ?  0 : -1 -> RES = setcc_carry
13856   // a >= b ? -1 :  0 -> RES = setcc_carry
13857   // a >= b ?  0 : -1 -> RES = ~setcc_carry
13858   if (Cond.getOpcode() == X86ISD::SUB) {
13859     Cond = ConvertCmpIfNecessary(Cond, DAG);
13860     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
13861
13862     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
13863         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
13864       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13865                                 DAG.getConstant(X86::COND_B, DL, MVT::i8),
13866                                 Cond);
13867       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
13868         return DAG.getNOT(DL, Res, Res.getValueType());
13869       return Res;
13870     }
13871   }
13872
13873   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
13874   // widen the cmov and push the truncate through. This avoids introducing a new
13875   // branch during isel and doesn't add any extensions.
13876   if (Op.getValueType() == MVT::i8 &&
13877       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
13878     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
13879     if (T1.getValueType() == T2.getValueType() &&
13880         // Blacklist CopyFromReg to avoid partial register stalls.
13881         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
13882       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
13883       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
13884       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
13885     }
13886   }
13887
13888   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
13889   // condition is true.
13890   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
13891   SDValue Ops[] = { Op2, Op1, CC, Cond };
13892   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
13893 }
13894
13895 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op,
13896                                        const X86Subtarget *Subtarget,
13897                                        SelectionDAG &DAG) {
13898   MVT VT = Op->getSimpleValueType(0);
13899   SDValue In = Op->getOperand(0);
13900   MVT InVT = In.getSimpleValueType();
13901   MVT VTElt = VT.getVectorElementType();
13902   MVT InVTElt = InVT.getVectorElementType();
13903   SDLoc dl(Op);
13904
13905   // SKX processor
13906   if ((InVTElt == MVT::i1) &&
13907       (((Subtarget->hasBWI() && Subtarget->hasVLX() &&
13908         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() <= 16)) ||
13909
13910        ((Subtarget->hasBWI() && VT.is512BitVector() &&
13911         VTElt.getSizeInBits() <= 16)) ||
13912
13913        ((Subtarget->hasDQI() && Subtarget->hasVLX() &&
13914         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() >= 32)) ||
13915
13916        ((Subtarget->hasDQI() && VT.is512BitVector() &&
13917         VTElt.getSizeInBits() >= 32))))
13918     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13919
13920   unsigned int NumElts = VT.getVectorNumElements();
13921
13922   if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
13923     return SDValue();
13924
13925   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1) {
13926     if (In.getOpcode() == X86ISD::VSEXT || In.getOpcode() == X86ISD::VZEXT)
13927       return DAG.getNode(In.getOpcode(), dl, VT, In.getOperand(0));
13928     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13929   }
13930
13931   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
13932   MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
13933   SDValue NegOne =
13934    DAG.getConstant(APInt::getAllOnesValue(ExtVT.getScalarSizeInBits()), dl,
13935                    ExtVT);
13936   SDValue Zero =
13937    DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), dl, ExtVT);
13938
13939   SDValue V = DAG.getNode(ISD::VSELECT, dl, ExtVT, In, NegOne, Zero);
13940   if (VT.is512BitVector())
13941     return V;
13942   return DAG.getNode(X86ISD::VTRUNC, dl, VT, V);
13943 }
13944
13945 static SDValue LowerSIGN_EXTEND_VECTOR_INREG(SDValue Op,
13946                                              const X86Subtarget *Subtarget,
13947                                              SelectionDAG &DAG) {
13948   SDValue In = Op->getOperand(0);
13949   MVT VT = Op->getSimpleValueType(0);
13950   MVT InVT = In.getSimpleValueType();
13951   assert(VT.getSizeInBits() == InVT.getSizeInBits());
13952
13953   MVT InSVT = InVT.getScalarType();
13954   assert(VT.getScalarType().getScalarSizeInBits() > InSVT.getScalarSizeInBits());
13955
13956   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
13957     return SDValue();
13958   if (InSVT != MVT::i32 && InSVT != MVT::i16 && InSVT != MVT::i8)
13959     return SDValue();
13960
13961   SDLoc dl(Op);
13962
13963   // SSE41 targets can use the pmovsx* instructions directly.
13964   if (Subtarget->hasSSE41())
13965     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13966
13967   // pre-SSE41 targets unpack lower lanes and then sign-extend using SRAI.
13968   SDValue Curr = In;
13969   MVT CurrVT = InVT;
13970
13971   // As SRAI is only available on i16/i32 types, we expand only up to i32
13972   // and handle i64 separately.
13973   while (CurrVT != VT && CurrVT.getScalarType() != MVT::i32) {
13974     Curr = DAG.getNode(X86ISD::UNPCKL, dl, CurrVT, DAG.getUNDEF(CurrVT), Curr);
13975     MVT CurrSVT = MVT::getIntegerVT(CurrVT.getScalarSizeInBits() * 2);
13976     CurrVT = MVT::getVectorVT(CurrSVT, CurrVT.getVectorNumElements() / 2);
13977     Curr = DAG.getBitcast(CurrVT, Curr);
13978   }
13979
13980   SDValue SignExt = Curr;
13981   if (CurrVT != InVT) {
13982     unsigned SignExtShift =
13983         CurrVT.getScalarSizeInBits() - InSVT.getScalarSizeInBits();
13984     SignExt = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
13985                           DAG.getConstant(SignExtShift, dl, MVT::i8));
13986   }
13987
13988   if (CurrVT == VT)
13989     return SignExt;
13990
13991   if (VT == MVT::v2i64 && CurrVT == MVT::v4i32) {
13992     SDValue Sign = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
13993                                DAG.getConstant(31, dl, MVT::i8));
13994     SDValue Ext = DAG.getVectorShuffle(CurrVT, dl, SignExt, Sign, {0, 4, 1, 5});
13995     return DAG.getBitcast(VT, Ext);
13996   }
13997
13998   return SDValue();
13999 }
14000
14001 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
14002                                 SelectionDAG &DAG) {
14003   MVT VT = Op->getSimpleValueType(0);
14004   SDValue In = Op->getOperand(0);
14005   MVT InVT = In.getSimpleValueType();
14006   SDLoc dl(Op);
14007
14008   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
14009     return LowerSIGN_EXTEND_AVX512(Op, Subtarget, DAG);
14010
14011   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
14012       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
14013       (VT != MVT::v16i16 || InVT != MVT::v16i8))
14014     return SDValue();
14015
14016   if (Subtarget->hasInt256())
14017     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14018
14019   // Optimize vectors in AVX mode
14020   // Sign extend  v8i16 to v8i32 and
14021   //              v4i32 to v4i64
14022   //
14023   // Divide input vector into two parts
14024   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
14025   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
14026   // concat the vectors to original VT
14027
14028   unsigned NumElems = InVT.getVectorNumElements();
14029   SDValue Undef = DAG.getUNDEF(InVT);
14030
14031   SmallVector<int,8> ShufMask1(NumElems, -1);
14032   for (unsigned i = 0; i != NumElems/2; ++i)
14033     ShufMask1[i] = i;
14034
14035   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
14036
14037   SmallVector<int,8> ShufMask2(NumElems, -1);
14038   for (unsigned i = 0; i != NumElems/2; ++i)
14039     ShufMask2[i] = i + NumElems/2;
14040
14041   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
14042
14043   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
14044                                 VT.getVectorNumElements()/2);
14045
14046   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
14047   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
14048
14049   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
14050 }
14051
14052 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
14053 // may emit an illegal shuffle but the expansion is still better than scalar
14054 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
14055 // we'll emit a shuffle and a arithmetic shift.
14056 // FIXME: Is the expansion actually better than scalar code? It doesn't seem so.
14057 // TODO: It is possible to support ZExt by zeroing the undef values during
14058 // the shuffle phase or after the shuffle.
14059 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
14060                                  SelectionDAG &DAG) {
14061   MVT RegVT = Op.getSimpleValueType();
14062   assert(RegVT.isVector() && "We only custom lower vector sext loads.");
14063   assert(RegVT.isInteger() &&
14064          "We only custom lower integer vector sext loads.");
14065
14066   // Nothing useful we can do without SSE2 shuffles.
14067   assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
14068
14069   LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
14070   SDLoc dl(Ld);
14071   EVT MemVT = Ld->getMemoryVT();
14072   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14073   unsigned RegSz = RegVT.getSizeInBits();
14074
14075   ISD::LoadExtType Ext = Ld->getExtensionType();
14076
14077   assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
14078          && "Only anyext and sext are currently implemented.");
14079   assert(MemVT != RegVT && "Cannot extend to the same type");
14080   assert(MemVT.isVector() && "Must load a vector from memory");
14081
14082   unsigned NumElems = RegVT.getVectorNumElements();
14083   unsigned MemSz = MemVT.getSizeInBits();
14084   assert(RegSz > MemSz && "Register size must be greater than the mem size");
14085
14086   if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
14087     // The only way in which we have a legal 256-bit vector result but not the
14088     // integer 256-bit operations needed to directly lower a sextload is if we
14089     // have AVX1 but not AVX2. In that case, we can always emit a sextload to
14090     // a 128-bit vector and a normal sign_extend to 256-bits that should get
14091     // correctly legalized. We do this late to allow the canonical form of
14092     // sextload to persist throughout the rest of the DAG combiner -- it wants
14093     // to fold together any extensions it can, and so will fuse a sign_extend
14094     // of an sextload into a sextload targeting a wider value.
14095     SDValue Load;
14096     if (MemSz == 128) {
14097       // Just switch this to a normal load.
14098       assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
14099                                        "it must be a legal 128-bit vector "
14100                                        "type!");
14101       Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
14102                   Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
14103                   Ld->isInvariant(), Ld->getAlignment());
14104     } else {
14105       assert(MemSz < 128 &&
14106              "Can't extend a type wider than 128 bits to a 256 bit vector!");
14107       // Do an sext load to a 128-bit vector type. We want to use the same
14108       // number of elements, but elements half as wide. This will end up being
14109       // recursively lowered by this routine, but will succeed as we definitely
14110       // have all the necessary features if we're using AVX1.
14111       EVT HalfEltVT =
14112           EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
14113       EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
14114       Load =
14115           DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
14116                          Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
14117                          Ld->isNonTemporal(), Ld->isInvariant(),
14118                          Ld->getAlignment());
14119     }
14120
14121     // Replace chain users with the new chain.
14122     assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
14123     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
14124
14125     // Finally, do a normal sign-extend to the desired register.
14126     return DAG.getSExtOrTrunc(Load, dl, RegVT);
14127   }
14128
14129   // All sizes must be a power of two.
14130   assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
14131          "Non-power-of-two elements are not custom lowered!");
14132
14133   // Attempt to load the original value using scalar loads.
14134   // Find the largest scalar type that divides the total loaded size.
14135   MVT SclrLoadTy = MVT::i8;
14136   for (MVT Tp : MVT::integer_valuetypes()) {
14137     if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
14138       SclrLoadTy = Tp;
14139     }
14140   }
14141
14142   // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
14143   if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
14144       (64 <= MemSz))
14145     SclrLoadTy = MVT::f64;
14146
14147   // Calculate the number of scalar loads that we need to perform
14148   // in order to load our vector from memory.
14149   unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
14150
14151   assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
14152          "Can only lower sext loads with a single scalar load!");
14153
14154   unsigned loadRegZize = RegSz;
14155   if (Ext == ISD::SEXTLOAD && RegSz >= 256)
14156     loadRegZize = 128;
14157
14158   // Represent our vector as a sequence of elements which are the
14159   // largest scalar that we can load.
14160   EVT LoadUnitVecVT = EVT::getVectorVT(
14161       *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
14162
14163   // Represent the data using the same element type that is stored in
14164   // memory. In practice, we ''widen'' MemVT.
14165   EVT WideVecVT =
14166       EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
14167                        loadRegZize / MemVT.getScalarType().getSizeInBits());
14168
14169   assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
14170          "Invalid vector type");
14171
14172   // We can't shuffle using an illegal type.
14173   assert(TLI.isTypeLegal(WideVecVT) &&
14174          "We only lower types that form legal widened vector types");
14175
14176   SmallVector<SDValue, 8> Chains;
14177   SDValue Ptr = Ld->getBasePtr();
14178   SDValue Increment =
14179       DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, dl, TLI.getPointerTy());
14180   SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
14181
14182   for (unsigned i = 0; i < NumLoads; ++i) {
14183     // Perform a single load.
14184     SDValue ScalarLoad =
14185         DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
14186                     Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
14187                     Ld->getAlignment());
14188     Chains.push_back(ScalarLoad.getValue(1));
14189     // Create the first element type using SCALAR_TO_VECTOR in order to avoid
14190     // another round of DAGCombining.
14191     if (i == 0)
14192       Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
14193     else
14194       Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
14195                         ScalarLoad, DAG.getIntPtrConstant(i, dl));
14196
14197     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
14198   }
14199
14200   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
14201
14202   // Bitcast the loaded value to a vector of the original element type, in
14203   // the size of the target vector type.
14204   SDValue SlicedVec = DAG.getBitcast(WideVecVT, Res);
14205   unsigned SizeRatio = RegSz / MemSz;
14206
14207   if (Ext == ISD::SEXTLOAD) {
14208     // If we have SSE4.1, we can directly emit a VSEXT node.
14209     if (Subtarget->hasSSE41()) {
14210       SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
14211       DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14212       return Sext;
14213     }
14214
14215     // Otherwise we'll shuffle the small elements in the high bits of the
14216     // larger type and perform an arithmetic shift. If the shift is not legal
14217     // it's better to scalarize.
14218     assert(TLI.isOperationLegalOrCustom(ISD::SRA, RegVT) &&
14219            "We can't implement a sext load without an arithmetic right shift!");
14220
14221     // Redistribute the loaded elements into the different locations.
14222     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
14223     for (unsigned i = 0; i != NumElems; ++i)
14224       ShuffleVec[i * SizeRatio + SizeRatio - 1] = i;
14225
14226     SDValue Shuff = DAG.getVectorShuffle(
14227         WideVecVT, dl, SlicedVec, DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
14228
14229     Shuff = DAG.getBitcast(RegVT, Shuff);
14230
14231     // Build the arithmetic shift.
14232     unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
14233                    MemVT.getVectorElementType().getSizeInBits();
14234     Shuff =
14235         DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
14236                     DAG.getConstant(Amt, dl, RegVT));
14237
14238     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14239     return Shuff;
14240   }
14241
14242   // Redistribute the loaded elements into the different locations.
14243   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
14244   for (unsigned i = 0; i != NumElems; ++i)
14245     ShuffleVec[i * SizeRatio] = i;
14246
14247   SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
14248                                        DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
14249
14250   // Bitcast to the requested type.
14251   Shuff = DAG.getBitcast(RegVT, Shuff);
14252   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14253   return Shuff;
14254 }
14255
14256 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
14257 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
14258 // from the AND / OR.
14259 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
14260   Opc = Op.getOpcode();
14261   if (Opc != ISD::OR && Opc != ISD::AND)
14262     return false;
14263   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
14264           Op.getOperand(0).hasOneUse() &&
14265           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
14266           Op.getOperand(1).hasOneUse());
14267 }
14268
14269 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
14270 // 1 and that the SETCC node has a single use.
14271 static bool isXor1OfSetCC(SDValue Op) {
14272   if (Op.getOpcode() != ISD::XOR)
14273     return false;
14274   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
14275   if (N1C && N1C->getAPIntValue() == 1) {
14276     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
14277       Op.getOperand(0).hasOneUse();
14278   }
14279   return false;
14280 }
14281
14282 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
14283   bool addTest = true;
14284   SDValue Chain = Op.getOperand(0);
14285   SDValue Cond  = Op.getOperand(1);
14286   SDValue Dest  = Op.getOperand(2);
14287   SDLoc dl(Op);
14288   SDValue CC;
14289   bool Inverted = false;
14290
14291   if (Cond.getOpcode() == ISD::SETCC) {
14292     // Check for setcc([su]{add,sub,mul}o == 0).
14293     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
14294         isa<ConstantSDNode>(Cond.getOperand(1)) &&
14295         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
14296         Cond.getOperand(0).getResNo() == 1 &&
14297         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
14298          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
14299          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
14300          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
14301          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
14302          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
14303       Inverted = true;
14304       Cond = Cond.getOperand(0);
14305     } else {
14306       SDValue NewCond = LowerSETCC(Cond, DAG);
14307       if (NewCond.getNode())
14308         Cond = NewCond;
14309     }
14310   }
14311 #if 0
14312   // FIXME: LowerXALUO doesn't handle these!!
14313   else if (Cond.getOpcode() == X86ISD::ADD  ||
14314            Cond.getOpcode() == X86ISD::SUB  ||
14315            Cond.getOpcode() == X86ISD::SMUL ||
14316            Cond.getOpcode() == X86ISD::UMUL)
14317     Cond = LowerXALUO(Cond, DAG);
14318 #endif
14319
14320   // Look pass (and (setcc_carry (cmp ...)), 1).
14321   if (Cond.getOpcode() == ISD::AND &&
14322       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
14323     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
14324     if (C && C->getAPIntValue() == 1)
14325       Cond = Cond.getOperand(0);
14326   }
14327
14328   // If condition flag is set by a X86ISD::CMP, then use it as the condition
14329   // setting operand in place of the X86ISD::SETCC.
14330   unsigned CondOpcode = Cond.getOpcode();
14331   if (CondOpcode == X86ISD::SETCC ||
14332       CondOpcode == X86ISD::SETCC_CARRY) {
14333     CC = Cond.getOperand(0);
14334
14335     SDValue Cmp = Cond.getOperand(1);
14336     unsigned Opc = Cmp.getOpcode();
14337     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
14338     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
14339       Cond = Cmp;
14340       addTest = false;
14341     } else {
14342       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
14343       default: break;
14344       case X86::COND_O:
14345       case X86::COND_B:
14346         // These can only come from an arithmetic instruction with overflow,
14347         // e.g. SADDO, UADDO.
14348         Cond = Cond.getNode()->getOperand(1);
14349         addTest = false;
14350         break;
14351       }
14352     }
14353   }
14354   CondOpcode = Cond.getOpcode();
14355   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
14356       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
14357       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
14358        Cond.getOperand(0).getValueType() != MVT::i8)) {
14359     SDValue LHS = Cond.getOperand(0);
14360     SDValue RHS = Cond.getOperand(1);
14361     unsigned X86Opcode;
14362     unsigned X86Cond;
14363     SDVTList VTs;
14364     // Keep this in sync with LowerXALUO, otherwise we might create redundant
14365     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
14366     // X86ISD::INC).
14367     switch (CondOpcode) {
14368     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
14369     case ISD::SADDO:
14370       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14371         if (C->isOne()) {
14372           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
14373           break;
14374         }
14375       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
14376     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
14377     case ISD::SSUBO:
14378       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14379         if (C->isOne()) {
14380           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
14381           break;
14382         }
14383       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
14384     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
14385     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
14386     default: llvm_unreachable("unexpected overflowing operator");
14387     }
14388     if (Inverted)
14389       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
14390     if (CondOpcode == ISD::UMULO)
14391       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
14392                           MVT::i32);
14393     else
14394       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14395
14396     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
14397
14398     if (CondOpcode == ISD::UMULO)
14399       Cond = X86Op.getValue(2);
14400     else
14401       Cond = X86Op.getValue(1);
14402
14403     CC = DAG.getConstant(X86Cond, dl, MVT::i8);
14404     addTest = false;
14405   } else {
14406     unsigned CondOpc;
14407     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
14408       SDValue Cmp = Cond.getOperand(0).getOperand(1);
14409       if (CondOpc == ISD::OR) {
14410         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
14411         // two branches instead of an explicit OR instruction with a
14412         // separate test.
14413         if (Cmp == Cond.getOperand(1).getOperand(1) &&
14414             isX86LogicalCmp(Cmp)) {
14415           CC = Cond.getOperand(0).getOperand(0);
14416           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14417                               Chain, Dest, CC, Cmp);
14418           CC = Cond.getOperand(1).getOperand(0);
14419           Cond = Cmp;
14420           addTest = false;
14421         }
14422       } else { // ISD::AND
14423         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
14424         // two branches instead of an explicit AND instruction with a
14425         // separate test. However, we only do this if this block doesn't
14426         // have a fall-through edge, because this requires an explicit
14427         // jmp when the condition is false.
14428         if (Cmp == Cond.getOperand(1).getOperand(1) &&
14429             isX86LogicalCmp(Cmp) &&
14430             Op.getNode()->hasOneUse()) {
14431           X86::CondCode CCode =
14432             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
14433           CCode = X86::GetOppositeBranchCondition(CCode);
14434           CC = DAG.getConstant(CCode, dl, MVT::i8);
14435           SDNode *User = *Op.getNode()->use_begin();
14436           // Look for an unconditional branch following this conditional branch.
14437           // We need this because we need to reverse the successors in order
14438           // to implement FCMP_OEQ.
14439           if (User->getOpcode() == ISD::BR) {
14440             SDValue FalseBB = User->getOperand(1);
14441             SDNode *NewBR =
14442               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14443             assert(NewBR == User);
14444             (void)NewBR;
14445             Dest = FalseBB;
14446
14447             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14448                                 Chain, Dest, CC, Cmp);
14449             X86::CondCode CCode =
14450               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
14451             CCode = X86::GetOppositeBranchCondition(CCode);
14452             CC = DAG.getConstant(CCode, dl, MVT::i8);
14453             Cond = Cmp;
14454             addTest = false;
14455           }
14456         }
14457       }
14458     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
14459       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
14460       // It should be transformed during dag combiner except when the condition
14461       // is set by a arithmetics with overflow node.
14462       X86::CondCode CCode =
14463         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
14464       CCode = X86::GetOppositeBranchCondition(CCode);
14465       CC = DAG.getConstant(CCode, dl, MVT::i8);
14466       Cond = Cond.getOperand(0).getOperand(1);
14467       addTest = false;
14468     } else if (Cond.getOpcode() == ISD::SETCC &&
14469                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
14470       // For FCMP_OEQ, we can emit
14471       // two branches instead of an explicit AND instruction with a
14472       // separate test. However, we only do this if this block doesn't
14473       // have a fall-through edge, because this requires an explicit
14474       // jmp when the condition is false.
14475       if (Op.getNode()->hasOneUse()) {
14476         SDNode *User = *Op.getNode()->use_begin();
14477         // Look for an unconditional branch following this conditional branch.
14478         // We need this because we need to reverse the successors in order
14479         // to implement FCMP_OEQ.
14480         if (User->getOpcode() == ISD::BR) {
14481           SDValue FalseBB = User->getOperand(1);
14482           SDNode *NewBR =
14483             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14484           assert(NewBR == User);
14485           (void)NewBR;
14486           Dest = FalseBB;
14487
14488           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14489                                     Cond.getOperand(0), Cond.getOperand(1));
14490           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14491           CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
14492           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14493                               Chain, Dest, CC, Cmp);
14494           CC = DAG.getConstant(X86::COND_P, dl, MVT::i8);
14495           Cond = Cmp;
14496           addTest = false;
14497         }
14498       }
14499     } else if (Cond.getOpcode() == ISD::SETCC &&
14500                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
14501       // For FCMP_UNE, we can emit
14502       // two branches instead of an explicit AND instruction with a
14503       // separate test. However, we only do this if this block doesn't
14504       // have a fall-through edge, because this requires an explicit
14505       // jmp when the condition is false.
14506       if (Op.getNode()->hasOneUse()) {
14507         SDNode *User = *Op.getNode()->use_begin();
14508         // Look for an unconditional branch following this conditional branch.
14509         // We need this because we need to reverse the successors in order
14510         // to implement FCMP_UNE.
14511         if (User->getOpcode() == ISD::BR) {
14512           SDValue FalseBB = User->getOperand(1);
14513           SDNode *NewBR =
14514             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14515           assert(NewBR == User);
14516           (void)NewBR;
14517
14518           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14519                                     Cond.getOperand(0), Cond.getOperand(1));
14520           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14521           CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
14522           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14523                               Chain, Dest, CC, Cmp);
14524           CC = DAG.getConstant(X86::COND_NP, dl, MVT::i8);
14525           Cond = Cmp;
14526           addTest = false;
14527           Dest = FalseBB;
14528         }
14529       }
14530     }
14531   }
14532
14533   if (addTest) {
14534     // Look pass the truncate if the high bits are known zero.
14535     if (isTruncWithZeroHighBitsInput(Cond, DAG))
14536         Cond = Cond.getOperand(0);
14537
14538     // We know the result of AND is compared against zero. Try to match
14539     // it to BT.
14540     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
14541       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
14542       if (NewSetCC.getNode()) {
14543         CC = NewSetCC.getOperand(0);
14544         Cond = NewSetCC.getOperand(1);
14545         addTest = false;
14546       }
14547     }
14548   }
14549
14550   if (addTest) {
14551     X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
14552     CC = DAG.getConstant(X86Cond, dl, MVT::i8);
14553     Cond = EmitTest(Cond, X86Cond, dl, DAG);
14554   }
14555   Cond = ConvertCmpIfNecessary(Cond, DAG);
14556   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14557                      Chain, Dest, CC, Cond);
14558 }
14559
14560 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
14561 // Calls to _alloca are needed to probe the stack when allocating more than 4k
14562 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
14563 // that the guard pages used by the OS virtual memory manager are allocated in
14564 // correct sequence.
14565 SDValue
14566 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
14567                                            SelectionDAG &DAG) const {
14568   MachineFunction &MF = DAG.getMachineFunction();
14569   bool SplitStack = MF.shouldSplitStack();
14570   bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMachO()) ||
14571                SplitStack;
14572   SDLoc dl(Op);
14573
14574   if (!Lower) {
14575     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14576     SDNode* Node = Op.getNode();
14577
14578     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
14579     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
14580         " not tell us which reg is the stack pointer!");
14581     EVT VT = Node->getValueType(0);
14582     SDValue Tmp1 = SDValue(Node, 0);
14583     SDValue Tmp2 = SDValue(Node, 1);
14584     SDValue Tmp3 = Node->getOperand(2);
14585     SDValue Chain = Tmp1.getOperand(0);
14586
14587     // Chain the dynamic stack allocation so that it doesn't modify the stack
14588     // pointer when other instructions are using the stack.
14589     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, dl, true),
14590         SDLoc(Node));
14591
14592     SDValue Size = Tmp2.getOperand(1);
14593     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
14594     Chain = SP.getValue(1);
14595     unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
14596     const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
14597     unsigned StackAlign = TFI.getStackAlignment();
14598     Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
14599     if (Align > StackAlign)
14600       Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
14601           DAG.getConstant(-(uint64_t)Align, dl, VT));
14602     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
14603
14604     Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
14605         DAG.getIntPtrConstant(0, dl, true), SDValue(),
14606         SDLoc(Node));
14607
14608     SDValue Ops[2] = { Tmp1, Tmp2 };
14609     return DAG.getMergeValues(Ops, dl);
14610   }
14611
14612   // Get the inputs.
14613   SDValue Chain = Op.getOperand(0);
14614   SDValue Size  = Op.getOperand(1);
14615   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
14616   EVT VT = Op.getNode()->getValueType(0);
14617
14618   bool Is64Bit = Subtarget->is64Bit();
14619   EVT SPTy = getPointerTy();
14620
14621   if (SplitStack) {
14622     MachineRegisterInfo &MRI = MF.getRegInfo();
14623
14624     if (Is64Bit) {
14625       // The 64 bit implementation of segmented stacks needs to clobber both r10
14626       // r11. This makes it impossible to use it along with nested parameters.
14627       const Function *F = MF.getFunction();
14628
14629       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
14630            I != E; ++I)
14631         if (I->hasNestAttr())
14632           report_fatal_error("Cannot use segmented stacks with functions that "
14633                              "have nested arguments.");
14634     }
14635
14636     const TargetRegisterClass *AddrRegClass =
14637       getRegClassFor(getPointerTy());
14638     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
14639     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
14640     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
14641                                 DAG.getRegister(Vreg, SPTy));
14642     SDValue Ops1[2] = { Value, Chain };
14643     return DAG.getMergeValues(Ops1, dl);
14644   } else {
14645     SDValue Flag;
14646     const unsigned Reg = (Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX);
14647
14648     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
14649     Flag = Chain.getValue(1);
14650     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
14651
14652     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
14653
14654     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
14655     unsigned SPReg = RegInfo->getStackRegister();
14656     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
14657     Chain = SP.getValue(1);
14658
14659     if (Align) {
14660       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
14661                        DAG.getConstant(-(uint64_t)Align, dl, VT));
14662       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
14663     }
14664
14665     SDValue Ops1[2] = { SP, Chain };
14666     return DAG.getMergeValues(Ops1, dl);
14667   }
14668 }
14669
14670 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
14671   MachineFunction &MF = DAG.getMachineFunction();
14672   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
14673
14674   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
14675   SDLoc DL(Op);
14676
14677   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
14678     // vastart just stores the address of the VarArgsFrameIndex slot into the
14679     // memory location argument.
14680     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
14681                                    getPointerTy());
14682     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
14683                         MachinePointerInfo(SV), false, false, 0);
14684   }
14685
14686   // __va_list_tag:
14687   //   gp_offset         (0 - 6 * 8)
14688   //   fp_offset         (48 - 48 + 8 * 16)
14689   //   overflow_arg_area (point to parameters coming in memory).
14690   //   reg_save_area
14691   SmallVector<SDValue, 8> MemOps;
14692   SDValue FIN = Op.getOperand(1);
14693   // Store gp_offset
14694   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
14695                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
14696                                                DL, MVT::i32),
14697                                FIN, MachinePointerInfo(SV), false, false, 0);
14698   MemOps.push_back(Store);
14699
14700   // Store fp_offset
14701   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14702                     FIN, DAG.getIntPtrConstant(4, DL));
14703   Store = DAG.getStore(Op.getOperand(0), DL,
14704                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(), DL,
14705                                        MVT::i32),
14706                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
14707   MemOps.push_back(Store);
14708
14709   // Store ptr to overflow_arg_area
14710   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14711                     FIN, DAG.getIntPtrConstant(4, DL));
14712   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
14713                                     getPointerTy());
14714   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
14715                        MachinePointerInfo(SV, 8),
14716                        false, false, 0);
14717   MemOps.push_back(Store);
14718
14719   // Store ptr to reg_save_area.
14720   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14721                     FIN, DAG.getIntPtrConstant(8, DL));
14722   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
14723                                     getPointerTy());
14724   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
14725                        MachinePointerInfo(SV, 16), false, false, 0);
14726   MemOps.push_back(Store);
14727   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
14728 }
14729
14730 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
14731   assert(Subtarget->is64Bit() &&
14732          "LowerVAARG only handles 64-bit va_arg!");
14733   assert((Subtarget->isTargetLinux() ||
14734           Subtarget->isTargetDarwin()) &&
14735           "Unhandled target in LowerVAARG");
14736   assert(Op.getNode()->getNumOperands() == 4);
14737   SDValue Chain = Op.getOperand(0);
14738   SDValue SrcPtr = Op.getOperand(1);
14739   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
14740   unsigned Align = Op.getConstantOperandVal(3);
14741   SDLoc dl(Op);
14742
14743   EVT ArgVT = Op.getNode()->getValueType(0);
14744   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
14745   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
14746   uint8_t ArgMode;
14747
14748   // Decide which area this value should be read from.
14749   // TODO: Implement the AMD64 ABI in its entirety. This simple
14750   // selection mechanism works only for the basic types.
14751   if (ArgVT == MVT::f80) {
14752     llvm_unreachable("va_arg for f80 not yet implemented");
14753   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
14754     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
14755   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
14756     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
14757   } else {
14758     llvm_unreachable("Unhandled argument type in LowerVAARG");
14759   }
14760
14761   if (ArgMode == 2) {
14762     // Sanity Check: Make sure using fp_offset makes sense.
14763     assert(!Subtarget->useSoftFloat() &&
14764            !(DAG.getMachineFunction().getFunction()->hasFnAttribute(
14765                Attribute::NoImplicitFloat)) &&
14766            Subtarget->hasSSE1());
14767   }
14768
14769   // Insert VAARG_64 node into the DAG
14770   // VAARG_64 returns two values: Variable Argument Address, Chain
14771   SDValue InstOps[] = {Chain, SrcPtr, DAG.getConstant(ArgSize, dl, MVT::i32),
14772                        DAG.getConstant(ArgMode, dl, MVT::i8),
14773                        DAG.getConstant(Align, dl, MVT::i32)};
14774   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
14775   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
14776                                           VTs, InstOps, MVT::i64,
14777                                           MachinePointerInfo(SV),
14778                                           /*Align=*/0,
14779                                           /*Volatile=*/false,
14780                                           /*ReadMem=*/true,
14781                                           /*WriteMem=*/true);
14782   Chain = VAARG.getValue(1);
14783
14784   // Load the next argument and return it
14785   return DAG.getLoad(ArgVT, dl,
14786                      Chain,
14787                      VAARG,
14788                      MachinePointerInfo(),
14789                      false, false, false, 0);
14790 }
14791
14792 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
14793                            SelectionDAG &DAG) {
14794   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
14795   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
14796   SDValue Chain = Op.getOperand(0);
14797   SDValue DstPtr = Op.getOperand(1);
14798   SDValue SrcPtr = Op.getOperand(2);
14799   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
14800   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
14801   SDLoc DL(Op);
14802
14803   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
14804                        DAG.getIntPtrConstant(24, DL), 8, /*isVolatile*/false,
14805                        false, false,
14806                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
14807 }
14808
14809 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
14810 // amount is a constant. Takes immediate version of shift as input.
14811 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
14812                                           SDValue SrcOp, uint64_t ShiftAmt,
14813                                           SelectionDAG &DAG) {
14814   MVT ElementType = VT.getVectorElementType();
14815
14816   // Fold this packed shift into its first operand if ShiftAmt is 0.
14817   if (ShiftAmt == 0)
14818     return SrcOp;
14819
14820   // Check for ShiftAmt >= element width
14821   if (ShiftAmt >= ElementType.getSizeInBits()) {
14822     if (Opc == X86ISD::VSRAI)
14823       ShiftAmt = ElementType.getSizeInBits() - 1;
14824     else
14825       return DAG.getConstant(0, dl, VT);
14826   }
14827
14828   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
14829          && "Unknown target vector shift-by-constant node");
14830
14831   // Fold this packed vector shift into a build vector if SrcOp is a
14832   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
14833   if (VT == SrcOp.getSimpleValueType() &&
14834       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
14835     SmallVector<SDValue, 8> Elts;
14836     unsigned NumElts = SrcOp->getNumOperands();
14837     ConstantSDNode *ND;
14838
14839     switch(Opc) {
14840     default: llvm_unreachable(nullptr);
14841     case X86ISD::VSHLI:
14842       for (unsigned i=0; i!=NumElts; ++i) {
14843         SDValue CurrentOp = SrcOp->getOperand(i);
14844         if (CurrentOp->getOpcode() == ISD::UNDEF) {
14845           Elts.push_back(CurrentOp);
14846           continue;
14847         }
14848         ND = cast<ConstantSDNode>(CurrentOp);
14849         const APInt &C = ND->getAPIntValue();
14850         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), dl, ElementType));
14851       }
14852       break;
14853     case X86ISD::VSRLI:
14854       for (unsigned i=0; i!=NumElts; ++i) {
14855         SDValue CurrentOp = SrcOp->getOperand(i);
14856         if (CurrentOp->getOpcode() == ISD::UNDEF) {
14857           Elts.push_back(CurrentOp);
14858           continue;
14859         }
14860         ND = cast<ConstantSDNode>(CurrentOp);
14861         const APInt &C = ND->getAPIntValue();
14862         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), dl, ElementType));
14863       }
14864       break;
14865     case X86ISD::VSRAI:
14866       for (unsigned i=0; i!=NumElts; ++i) {
14867         SDValue CurrentOp = SrcOp->getOperand(i);
14868         if (CurrentOp->getOpcode() == ISD::UNDEF) {
14869           Elts.push_back(CurrentOp);
14870           continue;
14871         }
14872         ND = cast<ConstantSDNode>(CurrentOp);
14873         const APInt &C = ND->getAPIntValue();
14874         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), dl, ElementType));
14875       }
14876       break;
14877     }
14878
14879     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
14880   }
14881
14882   return DAG.getNode(Opc, dl, VT, SrcOp,
14883                      DAG.getConstant(ShiftAmt, dl, MVT::i8));
14884 }
14885
14886 // getTargetVShiftNode - Handle vector element shifts where the shift amount
14887 // may or may not be a constant. Takes immediate version of shift as input.
14888 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
14889                                    SDValue SrcOp, SDValue ShAmt,
14890                                    SelectionDAG &DAG) {
14891   MVT SVT = ShAmt.getSimpleValueType();
14892   assert((SVT == MVT::i32 || SVT == MVT::i64) && "Unexpected value type!");
14893
14894   // Catch shift-by-constant.
14895   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
14896     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
14897                                       CShAmt->getZExtValue(), DAG);
14898
14899   // Change opcode to non-immediate version
14900   switch (Opc) {
14901     default: llvm_unreachable("Unknown target vector shift node");
14902     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
14903     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
14904     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
14905   }
14906
14907   const X86Subtarget &Subtarget =
14908       static_cast<const X86Subtarget &>(DAG.getSubtarget());
14909   if (Subtarget.hasSSE41() && ShAmt.getOpcode() == ISD::ZERO_EXTEND &&
14910       ShAmt.getOperand(0).getSimpleValueType() == MVT::i16) {
14911     // Let the shuffle legalizer expand this shift amount node.
14912     SDValue Op0 = ShAmt.getOperand(0);
14913     Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(Op0), MVT::v8i16, Op0);
14914     ShAmt = getShuffleVectorZeroOrUndef(Op0, 0, true, &Subtarget, DAG);
14915   } else {
14916     // Need to build a vector containing shift amount.
14917     // SSE/AVX packed shifts only use the lower 64-bit of the shift count.
14918     SmallVector<SDValue, 4> ShOps;
14919     ShOps.push_back(ShAmt);
14920     if (SVT == MVT::i32) {
14921       ShOps.push_back(DAG.getConstant(0, dl, SVT));
14922       ShOps.push_back(DAG.getUNDEF(SVT));
14923     }
14924     ShOps.push_back(DAG.getUNDEF(SVT));
14925
14926     MVT BVT = SVT == MVT::i32 ? MVT::v4i32 : MVT::v2i64;
14927     ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, BVT, ShOps);
14928   }
14929
14930   // The return type has to be a 128-bit type with the same element
14931   // type as the input type.
14932   MVT EltVT = VT.getVectorElementType();
14933   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
14934
14935   ShAmt = DAG.getBitcast(ShVT, ShAmt);
14936   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
14937 }
14938
14939 /// \brief Return (and \p Op, \p Mask) for compare instructions or
14940 /// (vselect \p Mask, \p Op, \p PreservedSrc) for others along with the
14941 /// necessary casting for \p Mask when lowering masking intrinsics.
14942 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
14943                                     SDValue PreservedSrc,
14944                                     const X86Subtarget *Subtarget,
14945                                     SelectionDAG &DAG) {
14946     EVT VT = Op.getValueType();
14947     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
14948                                   MVT::i1, VT.getVectorNumElements());
14949     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14950                                      Mask.getValueType().getSizeInBits());
14951     SDLoc dl(Op);
14952
14953     assert(MaskVT.isSimple() && "invalid mask type");
14954
14955     if (isAllOnes(Mask))
14956       return Op;
14957
14958     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
14959     // are extracted by EXTRACT_SUBVECTOR.
14960     SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
14961                                 DAG.getBitcast(BitcastVT, Mask),
14962                                 DAG.getIntPtrConstant(0, dl));
14963
14964     switch (Op.getOpcode()) {
14965       default: break;
14966       case X86ISD::PCMPEQM:
14967       case X86ISD::PCMPGTM:
14968       case X86ISD::CMPM:
14969       case X86ISD::CMPMU:
14970         return DAG.getNode(ISD::AND, dl, VT, Op, VMask);
14971     }
14972     if (PreservedSrc.getOpcode() == ISD::UNDEF)
14973       PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
14974     return DAG.getNode(ISD::VSELECT, dl, VT, VMask, Op, PreservedSrc);
14975 }
14976
14977 /// \brief Creates an SDNode for a predicated scalar operation.
14978 /// \returns (X86vselect \p Mask, \p Op, \p PreservedSrc).
14979 /// The mask is comming as MVT::i8 and it should be truncated
14980 /// to MVT::i1 while lowering masking intrinsics.
14981 /// The main difference between ScalarMaskingNode and VectorMaskingNode is using
14982 /// "X86select" instead of "vselect". We just can't create the "vselect" node for
14983 /// a scalar instruction.
14984 static SDValue getScalarMaskingNode(SDValue Op, SDValue Mask,
14985                                     SDValue PreservedSrc,
14986                                     const X86Subtarget *Subtarget,
14987                                     SelectionDAG &DAG) {
14988     if (isAllOnes(Mask))
14989       return Op;
14990
14991     EVT VT = Op.getValueType();
14992     SDLoc dl(Op);
14993     // The mask should be of type MVT::i1
14994     SDValue IMask = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Mask);
14995
14996     if (PreservedSrc.getOpcode() == ISD::UNDEF)
14997       PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
14998     return DAG.getNode(X86ISD::SELECT, dl, VT, IMask, Op, PreservedSrc);
14999 }
15000
15001 /// When the 32-bit MSVC runtime transfers control to us, either to an outlined
15002 /// function or when returning to a parent frame after catching an exception, we
15003 /// recover the parent frame pointer by doing arithmetic on the incoming EBP.
15004 /// Here's the math:
15005 ///   RegNodeBase = EntryEBP - RegNodeSize
15006 ///   ParentFP = RegNodeBase - RegNodeFrameOffset
15007 /// Subtracting RegNodeSize takes us to the offset of the registration node, and
15008 /// subtracting the offset (negative on x86) takes us back to the parent FP.
15009 static SDValue recoverFramePointer(SelectionDAG &DAG, const Function *Fn,
15010                                    SDValue EntryEBP) {
15011   MachineFunction &MF = DAG.getMachineFunction();
15012   SDLoc dl;
15013
15014   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15015   MVT PtrVT = TLI.getPointerTy();
15016
15017   // It's possible that the parent function no longer has a personality function
15018   // if the exceptional code was optimized away, in which case we just return
15019   // the incoming EBP.
15020   if (!Fn->hasPersonalityFn())
15021     return EntryEBP;
15022
15023   // The RegNodeSize is 6 32-bit words for SEH and 4 for C++ EH. See
15024   // WinEHStatePass for the full struct definition.
15025   int RegNodeSize;
15026   switch (classifyEHPersonality(Fn->getPersonalityFn())) {
15027   default:
15028     report_fatal_error("can only recover FP for MSVC EH personality functions");
15029   case EHPersonality::MSVC_X86SEH: RegNodeSize = 24; break;
15030   case EHPersonality::MSVC_CXX: RegNodeSize = 16; break;
15031   }
15032
15033   // Get an MCSymbol that will ultimately resolve to the frame offset of the EH
15034   // registration.
15035   MCSymbol *OffsetSym =
15036       MF.getMMI().getContext().getOrCreateParentFrameOffsetSymbol(
15037           GlobalValue::getRealLinkageName(Fn->getName()));
15038   SDValue OffsetSymVal = DAG.getMCSymbol(OffsetSym, PtrVT);
15039   SDValue RegNodeFrameOffset =
15040       DAG.getNode(ISD::FRAME_ALLOC_RECOVER, dl, PtrVT, OffsetSymVal);
15041
15042   // RegNodeBase = EntryEBP - RegNodeSize
15043   // ParentFP = RegNodeBase - RegNodeFrameOffset
15044   SDValue RegNodeBase = DAG.getNode(ISD::SUB, dl, PtrVT, EntryEBP,
15045                                     DAG.getConstant(RegNodeSize, dl, PtrVT));
15046   return DAG.getNode(ISD::SUB, dl, PtrVT, RegNodeBase, RegNodeFrameOffset);
15047 }
15048
15049 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
15050                                        SelectionDAG &DAG) {
15051   SDLoc dl(Op);
15052   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15053   EVT VT = Op.getValueType();
15054   const IntrinsicData* IntrData = getIntrinsicWithoutChain(IntNo);
15055   if (IntrData) {
15056     switch(IntrData->Type) {
15057     case INTR_TYPE_1OP:
15058       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1));
15059     case INTR_TYPE_2OP:
15060       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15061         Op.getOperand(2));
15062     case INTR_TYPE_3OP:
15063       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15064         Op.getOperand(2), Op.getOperand(3));
15065     case INTR_TYPE_1OP_MASK_RM: {
15066       SDValue Src = Op.getOperand(1);
15067       SDValue PassThru = Op.getOperand(2);
15068       SDValue Mask = Op.getOperand(3);
15069       SDValue RoundingMode;
15070       if (Op.getNumOperands() == 4)
15071         RoundingMode = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
15072       else
15073         RoundingMode = Op.getOperand(4);
15074       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15075       if (IntrWithRoundingModeOpcode != 0) {
15076         unsigned Round = cast<ConstantSDNode>(RoundingMode)->getZExtValue();
15077         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION)
15078           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15079                                       dl, Op.getValueType(), Src, RoundingMode),
15080                                       Mask, PassThru, Subtarget, DAG);
15081       }
15082       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src,
15083                                               RoundingMode),
15084                                   Mask, PassThru, Subtarget, DAG);
15085     }
15086     case INTR_TYPE_1OP_MASK: {
15087       SDValue Src = Op.getOperand(1);
15088       SDValue Passthru = Op.getOperand(2);
15089       SDValue Mask = Op.getOperand(3);
15090       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src),
15091                                   Mask, Passthru, Subtarget, DAG);
15092     }
15093     case INTR_TYPE_SCALAR_MASK_RM: {
15094       SDValue Src1 = Op.getOperand(1);
15095       SDValue Src2 = Op.getOperand(2);
15096       SDValue Src0 = Op.getOperand(3);
15097       SDValue Mask = Op.getOperand(4);
15098       // There are 2 kinds of intrinsics in this group:
15099       // (1) With supress-all-exceptions (sae) or rounding mode- 6 operands
15100       // (2) With rounding mode and sae - 7 operands.
15101       if (Op.getNumOperands() == 6) {
15102         SDValue Sae  = Op.getOperand(5);
15103         unsigned Opc = IntrData->Opc1 ? IntrData->Opc1 : IntrData->Opc0;
15104         return getScalarMaskingNode(DAG.getNode(Opc, dl, VT, Src1, Src2,
15105                                                 Sae),
15106                                     Mask, Src0, Subtarget, DAG);
15107       }
15108       assert(Op.getNumOperands() == 7 && "Unexpected intrinsic form");
15109       SDValue RoundingMode  = Op.getOperand(5);
15110       SDValue Sae  = Op.getOperand(6);
15111       return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
15112                                               RoundingMode, Sae),
15113                                   Mask, Src0, Subtarget, DAG);
15114     }
15115     case INTR_TYPE_2OP_MASK: {
15116       SDValue Src1 = Op.getOperand(1);
15117       SDValue Src2 = Op.getOperand(2);
15118       SDValue PassThru = Op.getOperand(3);
15119       SDValue Mask = Op.getOperand(4);
15120       // We specify 2 possible opcodes for intrinsics with rounding modes.
15121       // First, we check if the intrinsic may have non-default rounding mode,
15122       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15123       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15124       if (IntrWithRoundingModeOpcode != 0) {
15125         SDValue Rnd = Op.getOperand(5);
15126         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
15127         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
15128           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15129                                       dl, Op.getValueType(),
15130                                       Src1, Src2, Rnd),
15131                                       Mask, PassThru, Subtarget, DAG);
15132         }
15133       }
15134       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15135                                               Src1,Src2),
15136                                   Mask, PassThru, Subtarget, DAG);
15137     }
15138     case INTR_TYPE_2OP_MASK_RM: {
15139       SDValue Src1 = Op.getOperand(1);
15140       SDValue Src2 = Op.getOperand(2);
15141       SDValue PassThru = Op.getOperand(3);
15142       SDValue Mask = Op.getOperand(4);
15143       // We specify 2 possible modes for intrinsics, with/without rounding modes.
15144       // First, we check if the intrinsic have rounding mode (6 operands),
15145       // if not, we set rounding mode to "current".
15146       SDValue Rnd;
15147       if (Op.getNumOperands() == 6)
15148         Rnd = Op.getOperand(5);
15149       else 
15150         Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
15151       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15152                                               Src1, Src2, Rnd),
15153                                   Mask, PassThru, Subtarget, DAG);
15154     }
15155     case INTR_TYPE_3OP_MASK: {
15156       SDValue Src1 = Op.getOperand(1);
15157       SDValue Src2 = Op.getOperand(2);
15158       SDValue Src3 = Op.getOperand(3);
15159       SDValue PassThru = Op.getOperand(4);
15160       SDValue Mask = Op.getOperand(5);
15161       // We specify 2 possible opcodes for intrinsics with rounding modes.
15162       // First, we check if the intrinsic may have non-default rounding mode,
15163       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15164       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15165       if (IntrWithRoundingModeOpcode != 0) {
15166         SDValue Rnd = Op.getOperand(6);
15167         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
15168         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
15169           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15170                                       dl, Op.getValueType(),
15171                                       Src1, Src2, Src3, Rnd),
15172                                       Mask, PassThru, Subtarget, DAG);
15173         }
15174       }
15175       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15176                                               Src1, Src2, Src3),
15177                                   Mask, PassThru, Subtarget, DAG);
15178     }
15179     case VPERM_3OP_MASKZ: 
15180     case VPERM_3OP_MASK:
15181     case FMA_OP_MASK3:
15182     case FMA_OP_MASKZ:
15183     case FMA_OP_MASK: {
15184       SDValue Src1 = Op.getOperand(1);
15185       SDValue Src2 = Op.getOperand(2);
15186       SDValue Src3 = Op.getOperand(3);
15187       SDValue Mask = Op.getOperand(4);
15188       EVT VT = Op.getValueType();
15189       SDValue PassThru = SDValue();
15190
15191       // set PassThru element
15192       if (IntrData->Type == VPERM_3OP_MASKZ || IntrData->Type == FMA_OP_MASKZ)
15193         PassThru = getZeroVector(VT, Subtarget, DAG, dl);
15194       else if (IntrData->Type == FMA_OP_MASK3)
15195         PassThru = Src3;
15196       else
15197         PassThru = Src1;
15198
15199       // We specify 2 possible opcodes for intrinsics with rounding modes.
15200       // First, we check if the intrinsic may have non-default rounding mode,
15201       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15202       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15203       if (IntrWithRoundingModeOpcode != 0) {
15204         SDValue Rnd = Op.getOperand(5);
15205         if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
15206             X86::STATIC_ROUNDING::CUR_DIRECTION)
15207           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15208                                                   dl, Op.getValueType(),
15209                                                   Src1, Src2, Src3, Rnd),
15210                                       Mask, PassThru, Subtarget, DAG);
15211       }
15212       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0,
15213                                               dl, Op.getValueType(),
15214                                               Src1, Src2, Src3),
15215                                   Mask, PassThru, Subtarget, DAG);
15216     }
15217     case CMP_MASK:
15218     case CMP_MASK_CC: {
15219       // Comparison intrinsics with masks.
15220       // Example of transformation:
15221       // (i8 (int_x86_avx512_mask_pcmpeq_q_128
15222       //             (v2i64 %a), (v2i64 %b), (i8 %mask))) ->
15223       // (i8 (bitcast
15224       //   (v8i1 (insert_subvector undef,
15225       //           (v2i1 (and (PCMPEQM %a, %b),
15226       //                      (extract_subvector
15227       //                         (v8i1 (bitcast %mask)), 0))), 0))))
15228       EVT VT = Op.getOperand(1).getValueType();
15229       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15230                                     VT.getVectorNumElements());
15231       SDValue Mask = Op.getOperand((IntrData->Type == CMP_MASK_CC) ? 4 : 3);
15232       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15233                                        Mask.getValueType().getSizeInBits());
15234       SDValue Cmp;
15235       if (IntrData->Type == CMP_MASK_CC) {
15236         SDValue CC = Op.getOperand(3);
15237         CC = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, CC);
15238         // We specify 2 possible opcodes for intrinsics with rounding modes.
15239         // First, we check if the intrinsic may have non-default rounding mode,
15240         // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15241         if (IntrData->Opc1 != 0) {
15242           SDValue Rnd = Op.getOperand(5);
15243           if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
15244               X86::STATIC_ROUNDING::CUR_DIRECTION)
15245             Cmp = DAG.getNode(IntrData->Opc1, dl, MaskVT, Op.getOperand(1),
15246                               Op.getOperand(2), CC, Rnd);
15247         }
15248         //default rounding mode
15249         if(!Cmp.getNode())
15250             Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
15251                               Op.getOperand(2), CC);
15252
15253       } else {
15254         assert(IntrData->Type == CMP_MASK && "Unexpected intrinsic type!");
15255         Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
15256                           Op.getOperand(2));
15257       }
15258       SDValue CmpMask = getVectorMaskingNode(Cmp, Mask,
15259                                              DAG.getTargetConstant(0, dl,
15260                                                                    MaskVT),
15261                                              Subtarget, DAG);
15262       SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
15263                                 DAG.getUNDEF(BitcastVT), CmpMask,
15264                                 DAG.getIntPtrConstant(0, dl));
15265       return DAG.getBitcast(Op.getValueType(), Res);
15266     }
15267     case COMI: { // Comparison intrinsics
15268       ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
15269       SDValue LHS = Op.getOperand(1);
15270       SDValue RHS = Op.getOperand(2);
15271       unsigned X86CC = TranslateX86CC(CC, dl, true, LHS, RHS, DAG);
15272       assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
15273       SDValue Cond = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
15274       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15275                                   DAG.getConstant(X86CC, dl, MVT::i8), Cond);
15276       return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15277     }
15278     case VSHIFT:
15279       return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
15280                                  Op.getOperand(1), Op.getOperand(2), DAG);
15281     case VSHIFT_MASK:
15282       return getVectorMaskingNode(getTargetVShiftNode(IntrData->Opc0, dl,
15283                                                       Op.getSimpleValueType(),
15284                                                       Op.getOperand(1),
15285                                                       Op.getOperand(2), DAG),
15286                                   Op.getOperand(4), Op.getOperand(3), Subtarget,
15287                                   DAG);
15288     case COMPRESS_EXPAND_IN_REG: {
15289       SDValue Mask = Op.getOperand(3);
15290       SDValue DataToCompress = Op.getOperand(1);
15291       SDValue PassThru = Op.getOperand(2);
15292       if (isAllOnes(Mask)) // return data as is
15293         return Op.getOperand(1);
15294
15295       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15296                                               DataToCompress),
15297                                   Mask, PassThru, Subtarget, DAG);
15298     }
15299     case BLEND: {
15300       SDValue Mask = Op.getOperand(3);
15301       EVT VT = Op.getValueType();
15302       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15303                                     VT.getVectorNumElements());
15304       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15305                                        Mask.getValueType().getSizeInBits());
15306       SDLoc dl(Op);
15307       SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15308                                   DAG.getBitcast(BitcastVT, Mask),
15309                                   DAG.getIntPtrConstant(0, dl));
15310       return DAG.getNode(IntrData->Opc0, dl, VT, VMask, Op.getOperand(1),
15311                          Op.getOperand(2));
15312     }
15313     default:
15314       break;
15315     }
15316   }
15317
15318   switch (IntNo) {
15319   default: return SDValue();    // Don't custom lower most intrinsics.
15320
15321   case Intrinsic::x86_avx2_permd:
15322   case Intrinsic::x86_avx2_permps:
15323     // Operands intentionally swapped. Mask is last operand to intrinsic,
15324     // but second operand for node/instruction.
15325     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
15326                        Op.getOperand(2), Op.getOperand(1));
15327
15328   // ptest and testp intrinsics. The intrinsic these come from are designed to
15329   // return an integer value, not just an instruction so lower it to the ptest
15330   // or testp pattern and a setcc for the result.
15331   case Intrinsic::x86_sse41_ptestz:
15332   case Intrinsic::x86_sse41_ptestc:
15333   case Intrinsic::x86_sse41_ptestnzc:
15334   case Intrinsic::x86_avx_ptestz_256:
15335   case Intrinsic::x86_avx_ptestc_256:
15336   case Intrinsic::x86_avx_ptestnzc_256:
15337   case Intrinsic::x86_avx_vtestz_ps:
15338   case Intrinsic::x86_avx_vtestc_ps:
15339   case Intrinsic::x86_avx_vtestnzc_ps:
15340   case Intrinsic::x86_avx_vtestz_pd:
15341   case Intrinsic::x86_avx_vtestc_pd:
15342   case Intrinsic::x86_avx_vtestnzc_pd:
15343   case Intrinsic::x86_avx_vtestz_ps_256:
15344   case Intrinsic::x86_avx_vtestc_ps_256:
15345   case Intrinsic::x86_avx_vtestnzc_ps_256:
15346   case Intrinsic::x86_avx_vtestz_pd_256:
15347   case Intrinsic::x86_avx_vtestc_pd_256:
15348   case Intrinsic::x86_avx_vtestnzc_pd_256: {
15349     bool IsTestPacked = false;
15350     unsigned X86CC;
15351     switch (IntNo) {
15352     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
15353     case Intrinsic::x86_avx_vtestz_ps:
15354     case Intrinsic::x86_avx_vtestz_pd:
15355     case Intrinsic::x86_avx_vtestz_ps_256:
15356     case Intrinsic::x86_avx_vtestz_pd_256:
15357       IsTestPacked = true; // Fallthrough
15358     case Intrinsic::x86_sse41_ptestz:
15359     case Intrinsic::x86_avx_ptestz_256:
15360       // ZF = 1
15361       X86CC = X86::COND_E;
15362       break;
15363     case Intrinsic::x86_avx_vtestc_ps:
15364     case Intrinsic::x86_avx_vtestc_pd:
15365     case Intrinsic::x86_avx_vtestc_ps_256:
15366     case Intrinsic::x86_avx_vtestc_pd_256:
15367       IsTestPacked = true; // Fallthrough
15368     case Intrinsic::x86_sse41_ptestc:
15369     case Intrinsic::x86_avx_ptestc_256:
15370       // CF = 1
15371       X86CC = X86::COND_B;
15372       break;
15373     case Intrinsic::x86_avx_vtestnzc_ps:
15374     case Intrinsic::x86_avx_vtestnzc_pd:
15375     case Intrinsic::x86_avx_vtestnzc_ps_256:
15376     case Intrinsic::x86_avx_vtestnzc_pd_256:
15377       IsTestPacked = true; // Fallthrough
15378     case Intrinsic::x86_sse41_ptestnzc:
15379     case Intrinsic::x86_avx_ptestnzc_256:
15380       // ZF and CF = 0
15381       X86CC = X86::COND_A;
15382       break;
15383     }
15384
15385     SDValue LHS = Op.getOperand(1);
15386     SDValue RHS = Op.getOperand(2);
15387     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
15388     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
15389     SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
15390     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
15391     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15392   }
15393   case Intrinsic::x86_avx512_kortestz_w:
15394   case Intrinsic::x86_avx512_kortestc_w: {
15395     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
15396     SDValue LHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(1));
15397     SDValue RHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(2));
15398     SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
15399     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
15400     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
15401     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15402   }
15403
15404   case Intrinsic::x86_sse42_pcmpistria128:
15405   case Intrinsic::x86_sse42_pcmpestria128:
15406   case Intrinsic::x86_sse42_pcmpistric128:
15407   case Intrinsic::x86_sse42_pcmpestric128:
15408   case Intrinsic::x86_sse42_pcmpistrio128:
15409   case Intrinsic::x86_sse42_pcmpestrio128:
15410   case Intrinsic::x86_sse42_pcmpistris128:
15411   case Intrinsic::x86_sse42_pcmpestris128:
15412   case Intrinsic::x86_sse42_pcmpistriz128:
15413   case Intrinsic::x86_sse42_pcmpestriz128: {
15414     unsigned Opcode;
15415     unsigned X86CC;
15416     switch (IntNo) {
15417     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
15418     case Intrinsic::x86_sse42_pcmpistria128:
15419       Opcode = X86ISD::PCMPISTRI;
15420       X86CC = X86::COND_A;
15421       break;
15422     case Intrinsic::x86_sse42_pcmpestria128:
15423       Opcode = X86ISD::PCMPESTRI;
15424       X86CC = X86::COND_A;
15425       break;
15426     case Intrinsic::x86_sse42_pcmpistric128:
15427       Opcode = X86ISD::PCMPISTRI;
15428       X86CC = X86::COND_B;
15429       break;
15430     case Intrinsic::x86_sse42_pcmpestric128:
15431       Opcode = X86ISD::PCMPESTRI;
15432       X86CC = X86::COND_B;
15433       break;
15434     case Intrinsic::x86_sse42_pcmpistrio128:
15435       Opcode = X86ISD::PCMPISTRI;
15436       X86CC = X86::COND_O;
15437       break;
15438     case Intrinsic::x86_sse42_pcmpestrio128:
15439       Opcode = X86ISD::PCMPESTRI;
15440       X86CC = X86::COND_O;
15441       break;
15442     case Intrinsic::x86_sse42_pcmpistris128:
15443       Opcode = X86ISD::PCMPISTRI;
15444       X86CC = X86::COND_S;
15445       break;
15446     case Intrinsic::x86_sse42_pcmpestris128:
15447       Opcode = X86ISD::PCMPESTRI;
15448       X86CC = X86::COND_S;
15449       break;
15450     case Intrinsic::x86_sse42_pcmpistriz128:
15451       Opcode = X86ISD::PCMPISTRI;
15452       X86CC = X86::COND_E;
15453       break;
15454     case Intrinsic::x86_sse42_pcmpestriz128:
15455       Opcode = X86ISD::PCMPESTRI;
15456       X86CC = X86::COND_E;
15457       break;
15458     }
15459     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
15460     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
15461     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
15462     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15463                                 DAG.getConstant(X86CC, dl, MVT::i8),
15464                                 SDValue(PCMP.getNode(), 1));
15465     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15466   }
15467
15468   case Intrinsic::x86_sse42_pcmpistri128:
15469   case Intrinsic::x86_sse42_pcmpestri128: {
15470     unsigned Opcode;
15471     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
15472       Opcode = X86ISD::PCMPISTRI;
15473     else
15474       Opcode = X86ISD::PCMPESTRI;
15475
15476     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
15477     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
15478     return DAG.getNode(Opcode, dl, VTs, NewOps);
15479   }
15480
15481   case Intrinsic::x86_seh_lsda: {
15482     // Compute the symbol for the LSDA. We know it'll get emitted later.
15483     MachineFunction &MF = DAG.getMachineFunction();
15484     SDValue Op1 = Op.getOperand(1);
15485     auto *Fn = cast<Function>(cast<GlobalAddressSDNode>(Op1)->getGlobal());
15486     MCSymbol *LSDASym = MF.getMMI().getContext().getOrCreateLSDASymbol(
15487         GlobalValue::getRealLinkageName(Fn->getName()));
15488
15489     // Generate a simple absolute symbol reference. This intrinsic is only
15490     // supported on 32-bit Windows, which isn't PIC.
15491     SDValue Result = DAG.getMCSymbol(LSDASym, VT);
15492     return DAG.getNode(X86ISD::Wrapper, dl, VT, Result);
15493   }
15494
15495   case Intrinsic::x86_seh_recoverfp: {
15496     SDValue FnOp = Op.getOperand(1);
15497     SDValue IncomingFPOp = Op.getOperand(2);
15498     GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(FnOp);
15499     auto *Fn = dyn_cast_or_null<Function>(GSD ? GSD->getGlobal() : nullptr);
15500     if (!Fn)
15501       report_fatal_error(
15502           "llvm.x86.seh.recoverfp must take a function as the first argument");
15503     return recoverFramePointer(DAG, Fn, IncomingFPOp);
15504   }
15505   }
15506 }
15507
15508 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15509                               SDValue Src, SDValue Mask, SDValue Base,
15510                               SDValue Index, SDValue ScaleOp, SDValue Chain,
15511                               const X86Subtarget * Subtarget) {
15512   SDLoc dl(Op);
15513   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15514   if (!C)
15515     llvm_unreachable("Invalid scale type");
15516   unsigned ScaleVal = C->getZExtValue();
15517   if (ScaleVal > 2 && ScaleVal != 4 && ScaleVal != 8)
15518     llvm_unreachable("Valid scale values are 1, 2, 4, 8");
15519
15520   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
15521   EVT MaskVT = MVT::getVectorVT(MVT::i1,
15522                              Index.getSimpleValueType().getVectorNumElements());
15523   SDValue MaskInReg;
15524   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15525   if (MaskC)
15526     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
15527   else {
15528     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15529                                      Mask.getValueType().getSizeInBits());
15530
15531     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
15532     // are extracted by EXTRACT_SUBVECTOR.
15533     MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15534                             DAG.getBitcast(BitcastVT, Mask),
15535                             DAG.getIntPtrConstant(0, dl));
15536   }
15537   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
15538   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
15539   SDValue Segment = DAG.getRegister(0, MVT::i32);
15540   if (Src.getOpcode() == ISD::UNDEF)
15541     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
15542   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
15543   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
15544   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
15545   return DAG.getMergeValues(RetOps, dl);
15546 }
15547
15548 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15549                                SDValue Src, SDValue Mask, SDValue Base,
15550                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
15551   SDLoc dl(Op);
15552   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15553   if (!C)
15554     llvm_unreachable("Invalid scale type");
15555   unsigned ScaleVal = C->getZExtValue();
15556   if (ScaleVal > 2 && ScaleVal != 4 && ScaleVal != 8)
15557     llvm_unreachable("Valid scale values are 1, 2, 4, 8");
15558
15559   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
15560   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
15561   SDValue Segment = DAG.getRegister(0, MVT::i32);
15562   EVT MaskVT = MVT::getVectorVT(MVT::i1,
15563                              Index.getSimpleValueType().getVectorNumElements());
15564   SDValue MaskInReg;
15565   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15566   if (MaskC)
15567     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
15568   else {
15569     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15570                                      Mask.getValueType().getSizeInBits());
15571
15572     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
15573     // are extracted by EXTRACT_SUBVECTOR.
15574     MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15575                             DAG.getBitcast(BitcastVT, Mask),
15576                             DAG.getIntPtrConstant(0, dl));
15577   }
15578   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
15579   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
15580   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
15581   return SDValue(Res, 1);
15582 }
15583
15584 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15585                                SDValue Mask, SDValue Base, SDValue Index,
15586                                SDValue ScaleOp, SDValue Chain) {
15587   SDLoc dl(Op);
15588   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15589   assert(C && "Invalid scale type");
15590   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
15591   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
15592   SDValue Segment = DAG.getRegister(0, MVT::i32);
15593   EVT MaskVT =
15594     MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
15595   SDValue MaskInReg;
15596   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15597   if (MaskC)
15598     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
15599   else
15600     MaskInReg = DAG.getBitcast(MaskVT, Mask);
15601   //SDVTList VTs = DAG.getVTList(MVT::Other);
15602   SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
15603   SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
15604   return SDValue(Res, 0);
15605 }
15606
15607 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
15608 // read performance monitor counters (x86_rdpmc).
15609 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
15610                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
15611                               SmallVectorImpl<SDValue> &Results) {
15612   assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
15613   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
15614   SDValue LO, HI;
15615
15616   // The ECX register is used to select the index of the performance counter
15617   // to read.
15618   SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
15619                                    N->getOperand(2));
15620   SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
15621
15622   // Reads the content of a 64-bit performance counter and returns it in the
15623   // registers EDX:EAX.
15624   if (Subtarget->is64Bit()) {
15625     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
15626     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
15627                             LO.getValue(2));
15628   } else {
15629     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
15630     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
15631                             LO.getValue(2));
15632   }
15633   Chain = HI.getValue(1);
15634
15635   if (Subtarget->is64Bit()) {
15636     // The EAX register is loaded with the low-order 32 bits. The EDX register
15637     // is loaded with the supported high-order bits of the counter.
15638     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
15639                               DAG.getConstant(32, DL, MVT::i8));
15640     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
15641     Results.push_back(Chain);
15642     return;
15643   }
15644
15645   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
15646   SDValue Ops[] = { LO, HI };
15647   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
15648   Results.push_back(Pair);
15649   Results.push_back(Chain);
15650 }
15651
15652 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
15653 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
15654 // also used to custom lower READCYCLECOUNTER nodes.
15655 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
15656                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
15657                               SmallVectorImpl<SDValue> &Results) {
15658   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
15659   SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
15660   SDValue LO, HI;
15661
15662   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
15663   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
15664   // and the EAX register is loaded with the low-order 32 bits.
15665   if (Subtarget->is64Bit()) {
15666     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
15667     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
15668                             LO.getValue(2));
15669   } else {
15670     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
15671     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
15672                             LO.getValue(2));
15673   }
15674   SDValue Chain = HI.getValue(1);
15675
15676   if (Opcode == X86ISD::RDTSCP_DAG) {
15677     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
15678
15679     // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
15680     // the ECX register. Add 'ecx' explicitly to the chain.
15681     SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
15682                                      HI.getValue(2));
15683     // Explicitly store the content of ECX at the location passed in input
15684     // to the 'rdtscp' intrinsic.
15685     Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
15686                          MachinePointerInfo(), false, false, 0);
15687   }
15688
15689   if (Subtarget->is64Bit()) {
15690     // The EDX register is loaded with the high-order 32 bits of the MSR, and
15691     // the EAX register is loaded with the low-order 32 bits.
15692     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
15693                               DAG.getConstant(32, DL, MVT::i8));
15694     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
15695     Results.push_back(Chain);
15696     return;
15697   }
15698
15699   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
15700   SDValue Ops[] = { LO, HI };
15701   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
15702   Results.push_back(Pair);
15703   Results.push_back(Chain);
15704 }
15705
15706 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
15707                                      SelectionDAG &DAG) {
15708   SmallVector<SDValue, 2> Results;
15709   SDLoc DL(Op);
15710   getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
15711                           Results);
15712   return DAG.getMergeValues(Results, DL);
15713 }
15714
15715 static SDValue LowerSEHRESTOREFRAME(SDValue Op, const X86Subtarget *Subtarget,
15716                                     SelectionDAG &DAG) {
15717   MachineFunction &MF = DAG.getMachineFunction();
15718   SDLoc dl(Op);
15719   SDValue Chain = Op.getOperand(0);
15720
15721   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15722   MVT VT = TLI.getPointerTy();
15723
15724   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15725   unsigned FrameReg =
15726       RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
15727   unsigned SPReg = RegInfo->getStackRegister();
15728
15729   // Get incoming EBP.
15730   SDValue IncomingEBP =
15731       DAG.getCopyFromReg(Chain, dl, FrameReg, VT);
15732
15733   // Load [EBP-24] into SP.
15734   SDValue SPAddr =
15735       DAG.getNode(ISD::ADD, dl, VT, IncomingEBP, DAG.getConstant(-24, dl, VT));
15736   SDValue NewSP =
15737       DAG.getLoad(VT, dl, Chain, SPAddr, MachinePointerInfo(), false, false,
15738                   false, VT.getScalarSizeInBits() / 8);
15739   Chain = DAG.getCopyToReg(Chain, dl, SPReg, NewSP);
15740
15741   // FIXME: Restore the base pointer in case of stack realignment!
15742
15743   // Adjust EBP to point back to the original frame position.
15744   SDValue NewFP = recoverFramePointer(DAG, MF.getFunction(), IncomingEBP);
15745   Chain = DAG.getCopyToReg(Chain, dl, FrameReg, NewFP);
15746   return Chain;
15747 }
15748
15749 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
15750                                       SelectionDAG &DAG) {
15751   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
15752
15753   const IntrinsicData* IntrData = getIntrinsicWithChain(IntNo);
15754   if (!IntrData) {
15755     if (IntNo == llvm::Intrinsic::x86_seh_restoreframe)
15756       return LowerSEHRESTOREFRAME(Op, Subtarget, DAG);
15757     return SDValue();
15758   }
15759
15760   SDLoc dl(Op);
15761   switch(IntrData->Type) {
15762   default:
15763     llvm_unreachable("Unknown Intrinsic Type");
15764     break;
15765   case RDSEED:
15766   case RDRAND: {
15767     // Emit the node with the right value type.
15768     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
15769     SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
15770
15771     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
15772     // Otherwise return the value from Rand, which is always 0, casted to i32.
15773     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
15774                       DAG.getConstant(1, dl, Op->getValueType(1)),
15775                       DAG.getConstant(X86::COND_B, dl, MVT::i32),
15776                       SDValue(Result.getNode(), 1) };
15777     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
15778                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
15779                                   Ops);
15780
15781     // Return { result, isValid, chain }.
15782     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
15783                        SDValue(Result.getNode(), 2));
15784   }
15785   case GATHER: {
15786   //gather(v1, mask, index, base, scale);
15787     SDValue Chain = Op.getOperand(0);
15788     SDValue Src   = Op.getOperand(2);
15789     SDValue Base  = Op.getOperand(3);
15790     SDValue Index = Op.getOperand(4);
15791     SDValue Mask  = Op.getOperand(5);
15792     SDValue Scale = Op.getOperand(6);
15793     return getGatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale,
15794                          Chain, Subtarget);
15795   }
15796   case SCATTER: {
15797   //scatter(base, mask, index, v1, scale);
15798     SDValue Chain = Op.getOperand(0);
15799     SDValue Base  = Op.getOperand(2);
15800     SDValue Mask  = Op.getOperand(3);
15801     SDValue Index = Op.getOperand(4);
15802     SDValue Src   = Op.getOperand(5);
15803     SDValue Scale = Op.getOperand(6);
15804     return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index,
15805                           Scale, Chain);
15806   }
15807   case PREFETCH: {
15808     SDValue Hint = Op.getOperand(6);
15809     unsigned HintVal = cast<ConstantSDNode>(Hint)->getZExtValue();
15810     assert(HintVal < 2 && "Wrong prefetch hint in intrinsic: should be 0 or 1");
15811     unsigned Opcode = (HintVal ? IntrData->Opc1 : IntrData->Opc0);
15812     SDValue Chain = Op.getOperand(0);
15813     SDValue Mask  = Op.getOperand(2);
15814     SDValue Index = Op.getOperand(3);
15815     SDValue Base  = Op.getOperand(4);
15816     SDValue Scale = Op.getOperand(5);
15817     return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
15818   }
15819   // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
15820   case RDTSC: {
15821     SmallVector<SDValue, 2> Results;
15822     getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget,
15823                             Results);
15824     return DAG.getMergeValues(Results, dl);
15825   }
15826   // Read Performance Monitoring Counters.
15827   case RDPMC: {
15828     SmallVector<SDValue, 2> Results;
15829     getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
15830     return DAG.getMergeValues(Results, dl);
15831   }
15832   // XTEST intrinsics.
15833   case XTEST: {
15834     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
15835     SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
15836     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15837                                 DAG.getConstant(X86::COND_NE, dl, MVT::i8),
15838                                 InTrans);
15839     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
15840     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
15841                        Ret, SDValue(InTrans.getNode(), 1));
15842   }
15843   // ADC/ADCX/SBB
15844   case ADX: {
15845     SmallVector<SDValue, 2> Results;
15846     SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
15847     SDVTList VTs = DAG.getVTList(Op.getOperand(3)->getValueType(0), MVT::Other);
15848     SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(2),
15849                                 DAG.getConstant(-1, dl, MVT::i8));
15850     SDValue Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(3),
15851                               Op.getOperand(4), GenCF.getValue(1));
15852     SDValue Store = DAG.getStore(Op.getOperand(0), dl, Res.getValue(0),
15853                                  Op.getOperand(5), MachinePointerInfo(),
15854                                  false, false, 0);
15855     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15856                                 DAG.getConstant(X86::COND_B, dl, MVT::i8),
15857                                 Res.getValue(1));
15858     Results.push_back(SetCC);
15859     Results.push_back(Store);
15860     return DAG.getMergeValues(Results, dl);
15861   }
15862   case COMPRESS_TO_MEM: {
15863     SDLoc dl(Op);
15864     SDValue Mask = Op.getOperand(4);
15865     SDValue DataToCompress = Op.getOperand(3);
15866     SDValue Addr = Op.getOperand(2);
15867     SDValue Chain = Op.getOperand(0);
15868
15869     EVT VT = DataToCompress.getValueType();
15870     if (isAllOnes(Mask)) // return just a store
15871       return DAG.getStore(Chain, dl, DataToCompress, Addr,
15872                           MachinePointerInfo(), false, false,
15873                           VT.getScalarSizeInBits()/8);
15874
15875     SDValue Compressed =
15876       getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToCompress),
15877                            Mask, DAG.getUNDEF(VT), Subtarget, DAG);
15878     return DAG.getStore(Chain, dl, Compressed, Addr,
15879                         MachinePointerInfo(), false, false,
15880                         VT.getScalarSizeInBits()/8);
15881   }
15882   case EXPAND_FROM_MEM: {
15883     SDLoc dl(Op);
15884     SDValue Mask = Op.getOperand(4);
15885     SDValue PassThru = Op.getOperand(3);
15886     SDValue Addr = Op.getOperand(2);
15887     SDValue Chain = Op.getOperand(0);
15888     EVT VT = Op.getValueType();
15889
15890     if (isAllOnes(Mask)) // return just a load
15891       return DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(), false, false,
15892                          false, VT.getScalarSizeInBits()/8);
15893
15894     SDValue DataToExpand = DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(),
15895                                        false, false, false,
15896                                        VT.getScalarSizeInBits()/8);
15897
15898     SDValue Results[] = {
15899       getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToExpand),
15900                            Mask, PassThru, Subtarget, DAG), Chain};
15901     return DAG.getMergeValues(Results, dl);
15902   }
15903   }
15904 }
15905
15906 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
15907                                            SelectionDAG &DAG) const {
15908   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
15909   MFI->setReturnAddressIsTaken(true);
15910
15911   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
15912     return SDValue();
15913
15914   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15915   SDLoc dl(Op);
15916   EVT PtrVT = getPointerTy();
15917
15918   if (Depth > 0) {
15919     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
15920     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15921     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), dl, PtrVT);
15922     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15923                        DAG.getNode(ISD::ADD, dl, PtrVT,
15924                                    FrameAddr, Offset),
15925                        MachinePointerInfo(), false, false, false, 0);
15926   }
15927
15928   // Just load the return address.
15929   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
15930   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15931                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
15932 }
15933
15934 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
15935   MachineFunction &MF = DAG.getMachineFunction();
15936   MachineFrameInfo *MFI = MF.getFrameInfo();
15937   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
15938   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15939   EVT VT = Op.getValueType();
15940
15941   MFI->setFrameAddressIsTaken(true);
15942
15943   if (MF.getTarget().getMCAsmInfo()->usesWindowsCFI()) {
15944     // Depth > 0 makes no sense on targets which use Windows unwind codes.  It
15945     // is not possible to crawl up the stack without looking at the unwind codes
15946     // simultaneously.
15947     int FrameAddrIndex = FuncInfo->getFAIndex();
15948     if (!FrameAddrIndex) {
15949       // Set up a frame object for the return address.
15950       unsigned SlotSize = RegInfo->getSlotSize();
15951       FrameAddrIndex = MF.getFrameInfo()->CreateFixedObject(
15952           SlotSize, /*Offset=*/0, /*IsImmutable=*/false);
15953       FuncInfo->setFAIndex(FrameAddrIndex);
15954     }
15955     return DAG.getFrameIndex(FrameAddrIndex, VT);
15956   }
15957
15958   unsigned FrameReg =
15959       RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
15960   SDLoc dl(Op);  // FIXME probably not meaningful
15961   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15962   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
15963           (FrameReg == X86::EBP && VT == MVT::i32)) &&
15964          "Invalid Frame Register!");
15965   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
15966   while (Depth--)
15967     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
15968                             MachinePointerInfo(),
15969                             false, false, false, 0);
15970   return FrameAddr;
15971 }
15972
15973 // FIXME? Maybe this could be a TableGen attribute on some registers and
15974 // this table could be generated automatically from RegInfo.
15975 unsigned X86TargetLowering::getRegisterByName(const char* RegName,
15976                                               EVT VT) const {
15977   unsigned Reg = StringSwitch<unsigned>(RegName)
15978                        .Case("esp", X86::ESP)
15979                        .Case("rsp", X86::RSP)
15980                        .Default(0);
15981   if (Reg)
15982     return Reg;
15983   report_fatal_error("Invalid register name global variable");
15984 }
15985
15986 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
15987                                                      SelectionDAG &DAG) const {
15988   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15989   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize(), SDLoc(Op));
15990 }
15991
15992 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
15993   SDValue Chain     = Op.getOperand(0);
15994   SDValue Offset    = Op.getOperand(1);
15995   SDValue Handler   = Op.getOperand(2);
15996   SDLoc dl      (Op);
15997
15998   EVT PtrVT = getPointerTy();
15999   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16000   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
16001   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
16002           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
16003          "Invalid Frame Register!");
16004   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
16005   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
16006
16007   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
16008                                  DAG.getIntPtrConstant(RegInfo->getSlotSize(),
16009                                                        dl));
16010   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
16011   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
16012                        false, false, 0);
16013   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
16014
16015   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
16016                      DAG.getRegister(StoreAddrReg, PtrVT));
16017 }
16018
16019 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
16020                                                SelectionDAG &DAG) const {
16021   SDLoc DL(Op);
16022   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
16023                      DAG.getVTList(MVT::i32, MVT::Other),
16024                      Op.getOperand(0), Op.getOperand(1));
16025 }
16026
16027 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
16028                                                 SelectionDAG &DAG) const {
16029   SDLoc DL(Op);
16030   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
16031                      Op.getOperand(0), Op.getOperand(1));
16032 }
16033
16034 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
16035   return Op.getOperand(0);
16036 }
16037
16038 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
16039                                                 SelectionDAG &DAG) const {
16040   SDValue Root = Op.getOperand(0);
16041   SDValue Trmp = Op.getOperand(1); // trampoline
16042   SDValue FPtr = Op.getOperand(2); // nested function
16043   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
16044   SDLoc dl (Op);
16045
16046   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
16047   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
16048
16049   if (Subtarget->is64Bit()) {
16050     SDValue OutChains[6];
16051
16052     // Large code-model.
16053     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
16054     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
16055
16056     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
16057     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
16058
16059     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
16060
16061     // Load the pointer to the nested function into R11.
16062     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
16063     SDValue Addr = Trmp;
16064     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
16065                                 Addr, MachinePointerInfo(TrmpAddr),
16066                                 false, false, 0);
16067
16068     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16069                        DAG.getConstant(2, dl, MVT::i64));
16070     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
16071                                 MachinePointerInfo(TrmpAddr, 2),
16072                                 false, false, 2);
16073
16074     // Load the 'nest' parameter value into R10.
16075     // R10 is specified in X86CallingConv.td
16076     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
16077     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16078                        DAG.getConstant(10, dl, MVT::i64));
16079     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
16080                                 Addr, MachinePointerInfo(TrmpAddr, 10),
16081                                 false, false, 0);
16082
16083     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16084                        DAG.getConstant(12, dl, MVT::i64));
16085     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
16086                                 MachinePointerInfo(TrmpAddr, 12),
16087                                 false, false, 2);
16088
16089     // Jump to the nested function.
16090     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
16091     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16092                        DAG.getConstant(20, dl, MVT::i64));
16093     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
16094                                 Addr, MachinePointerInfo(TrmpAddr, 20),
16095                                 false, false, 0);
16096
16097     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
16098     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16099                        DAG.getConstant(22, dl, MVT::i64));
16100     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, dl, MVT::i8),
16101                                 Addr, MachinePointerInfo(TrmpAddr, 22),
16102                                 false, false, 0);
16103
16104     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
16105   } else {
16106     const Function *Func =
16107       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
16108     CallingConv::ID CC = Func->getCallingConv();
16109     unsigned NestReg;
16110
16111     switch (CC) {
16112     default:
16113       llvm_unreachable("Unsupported calling convention");
16114     case CallingConv::C:
16115     case CallingConv::X86_StdCall: {
16116       // Pass 'nest' parameter in ECX.
16117       // Must be kept in sync with X86CallingConv.td
16118       NestReg = X86::ECX;
16119
16120       // Check that ECX wasn't needed by an 'inreg' parameter.
16121       FunctionType *FTy = Func->getFunctionType();
16122       const AttributeSet &Attrs = Func->getAttributes();
16123
16124       if (!Attrs.isEmpty() && !Func->isVarArg()) {
16125         unsigned InRegCount = 0;
16126         unsigned Idx = 1;
16127
16128         for (FunctionType::param_iterator I = FTy->param_begin(),
16129              E = FTy->param_end(); I != E; ++I, ++Idx)
16130           if (Attrs.hasAttribute(Idx, Attribute::InReg))
16131             // FIXME: should only count parameters that are lowered to integers.
16132             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
16133
16134         if (InRegCount > 2) {
16135           report_fatal_error("Nest register in use - reduce number of inreg"
16136                              " parameters!");
16137         }
16138       }
16139       break;
16140     }
16141     case CallingConv::X86_FastCall:
16142     case CallingConv::X86_ThisCall:
16143     case CallingConv::Fast:
16144       // Pass 'nest' parameter in EAX.
16145       // Must be kept in sync with X86CallingConv.td
16146       NestReg = X86::EAX;
16147       break;
16148     }
16149
16150     SDValue OutChains[4];
16151     SDValue Addr, Disp;
16152
16153     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16154                        DAG.getConstant(10, dl, MVT::i32));
16155     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
16156
16157     // This is storing the opcode for MOV32ri.
16158     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
16159     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
16160     OutChains[0] = DAG.getStore(Root, dl,
16161                                 DAG.getConstant(MOV32ri|N86Reg, dl, MVT::i8),
16162                                 Trmp, MachinePointerInfo(TrmpAddr),
16163                                 false, false, 0);
16164
16165     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16166                        DAG.getConstant(1, dl, MVT::i32));
16167     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
16168                                 MachinePointerInfo(TrmpAddr, 1),
16169                                 false, false, 1);
16170
16171     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
16172     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16173                        DAG.getConstant(5, dl, MVT::i32));
16174     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, dl, MVT::i8),
16175                                 Addr, MachinePointerInfo(TrmpAddr, 5),
16176                                 false, false, 1);
16177
16178     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16179                        DAG.getConstant(6, dl, MVT::i32));
16180     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
16181                                 MachinePointerInfo(TrmpAddr, 6),
16182                                 false, false, 1);
16183
16184     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
16185   }
16186 }
16187
16188 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
16189                                             SelectionDAG &DAG) const {
16190   /*
16191    The rounding mode is in bits 11:10 of FPSR, and has the following
16192    settings:
16193      00 Round to nearest
16194      01 Round to -inf
16195      10 Round to +inf
16196      11 Round to 0
16197
16198   FLT_ROUNDS, on the other hand, expects the following:
16199     -1 Undefined
16200      0 Round to 0
16201      1 Round to nearest
16202      2 Round to +inf
16203      3 Round to -inf
16204
16205   To perform the conversion, we do:
16206     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
16207   */
16208
16209   MachineFunction &MF = DAG.getMachineFunction();
16210   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
16211   unsigned StackAlignment = TFI.getStackAlignment();
16212   MVT VT = Op.getSimpleValueType();
16213   SDLoc DL(Op);
16214
16215   // Save FP Control Word to stack slot
16216   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
16217   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
16218
16219   MachineMemOperand *MMO =
16220    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
16221                            MachineMemOperand::MOStore, 2, 2);
16222
16223   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
16224   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
16225                                           DAG.getVTList(MVT::Other),
16226                                           Ops, MVT::i16, MMO);
16227
16228   // Load FP Control Word from stack slot
16229   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
16230                             MachinePointerInfo(), false, false, false, 0);
16231
16232   // Transform as necessary
16233   SDValue CWD1 =
16234     DAG.getNode(ISD::SRL, DL, MVT::i16,
16235                 DAG.getNode(ISD::AND, DL, MVT::i16,
16236                             CWD, DAG.getConstant(0x800, DL, MVT::i16)),
16237                 DAG.getConstant(11, DL, MVT::i8));
16238   SDValue CWD2 =
16239     DAG.getNode(ISD::SRL, DL, MVT::i16,
16240                 DAG.getNode(ISD::AND, DL, MVT::i16,
16241                             CWD, DAG.getConstant(0x400, DL, MVT::i16)),
16242                 DAG.getConstant(9, DL, MVT::i8));
16243
16244   SDValue RetVal =
16245     DAG.getNode(ISD::AND, DL, MVT::i16,
16246                 DAG.getNode(ISD::ADD, DL, MVT::i16,
16247                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
16248                             DAG.getConstant(1, DL, MVT::i16)),
16249                 DAG.getConstant(3, DL, MVT::i16));
16250
16251   return DAG.getNode((VT.getSizeInBits() < 16 ?
16252                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
16253 }
16254
16255 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
16256   MVT VT = Op.getSimpleValueType();
16257   EVT OpVT = VT;
16258   unsigned NumBits = VT.getSizeInBits();
16259   SDLoc dl(Op);
16260
16261   Op = Op.getOperand(0);
16262   if (VT == MVT::i8) {
16263     // Zero extend to i32 since there is not an i8 bsr.
16264     OpVT = MVT::i32;
16265     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
16266   }
16267
16268   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
16269   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
16270   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
16271
16272   // If src is zero (i.e. bsr sets ZF), returns NumBits.
16273   SDValue Ops[] = {
16274     Op,
16275     DAG.getConstant(NumBits + NumBits - 1, dl, OpVT),
16276     DAG.getConstant(X86::COND_E, dl, MVT::i8),
16277     Op.getValue(1)
16278   };
16279   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
16280
16281   // Finally xor with NumBits-1.
16282   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
16283                    DAG.getConstant(NumBits - 1, dl, OpVT));
16284
16285   if (VT == MVT::i8)
16286     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
16287   return Op;
16288 }
16289
16290 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
16291   MVT VT = Op.getSimpleValueType();
16292   EVT OpVT = VT;
16293   unsigned NumBits = VT.getSizeInBits();
16294   SDLoc dl(Op);
16295
16296   Op = Op.getOperand(0);
16297   if (VT == MVT::i8) {
16298     // Zero extend to i32 since there is not an i8 bsr.
16299     OpVT = MVT::i32;
16300     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
16301   }
16302
16303   // Issue a bsr (scan bits in reverse).
16304   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
16305   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
16306
16307   // And xor with NumBits-1.
16308   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
16309                    DAG.getConstant(NumBits - 1, dl, OpVT));
16310
16311   if (VT == MVT::i8)
16312     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
16313   return Op;
16314 }
16315
16316 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
16317   MVT VT = Op.getSimpleValueType();
16318   unsigned NumBits = VT.getSizeInBits();
16319   SDLoc dl(Op);
16320   Op = Op.getOperand(0);
16321
16322   // Issue a bsf (scan bits forward) which also sets EFLAGS.
16323   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
16324   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
16325
16326   // If src is zero (i.e. bsf sets ZF), returns NumBits.
16327   SDValue Ops[] = {
16328     Op,
16329     DAG.getConstant(NumBits, dl, VT),
16330     DAG.getConstant(X86::COND_E, dl, MVT::i8),
16331     Op.getValue(1)
16332   };
16333   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
16334 }
16335
16336 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
16337 // ones, and then concatenate the result back.
16338 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
16339   MVT VT = Op.getSimpleValueType();
16340
16341   assert(VT.is256BitVector() && VT.isInteger() &&
16342          "Unsupported value type for operation");
16343
16344   unsigned NumElems = VT.getVectorNumElements();
16345   SDLoc dl(Op);
16346
16347   // Extract the LHS vectors
16348   SDValue LHS = Op.getOperand(0);
16349   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
16350   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
16351
16352   // Extract the RHS vectors
16353   SDValue RHS = Op.getOperand(1);
16354   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
16355   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
16356
16357   MVT EltVT = VT.getVectorElementType();
16358   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16359
16360   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
16361                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
16362                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
16363 }
16364
16365 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
16366   if (Op.getValueType() == MVT::i1)
16367     return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
16368                        Op.getOperand(0), Op.getOperand(1));
16369   assert(Op.getSimpleValueType().is256BitVector() &&
16370          Op.getSimpleValueType().isInteger() &&
16371          "Only handle AVX 256-bit vector integer operation");
16372   return Lower256IntArith(Op, DAG);
16373 }
16374
16375 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
16376   if (Op.getValueType() == MVT::i1)
16377     return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
16378                        Op.getOperand(0), Op.getOperand(1));
16379   assert(Op.getSimpleValueType().is256BitVector() &&
16380          Op.getSimpleValueType().isInteger() &&
16381          "Only handle AVX 256-bit vector integer operation");
16382   return Lower256IntArith(Op, DAG);
16383 }
16384
16385 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
16386                         SelectionDAG &DAG) {
16387   SDLoc dl(Op);
16388   MVT VT = Op.getSimpleValueType();
16389
16390   if (VT == MVT::i1)
16391     return DAG.getNode(ISD::AND, dl, VT, Op.getOperand(0), Op.getOperand(1));
16392
16393   // Decompose 256-bit ops into smaller 128-bit ops.
16394   if (VT.is256BitVector() && !Subtarget->hasInt256())
16395     return Lower256IntArith(Op, DAG);
16396
16397   SDValue A = Op.getOperand(0);
16398   SDValue B = Op.getOperand(1);
16399
16400   // Lower v16i8/v32i8 mul as promotion to v8i16/v16i16 vector
16401   // pairs, multiply and truncate.
16402   if (VT == MVT::v16i8 || VT == MVT::v32i8) {
16403     if (Subtarget->hasInt256()) {
16404       if (VT == MVT::v32i8) {
16405         MVT SubVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() / 2);
16406         SDValue Lo = DAG.getIntPtrConstant(0, dl);
16407         SDValue Hi = DAG.getIntPtrConstant(VT.getVectorNumElements() / 2, dl);
16408         SDValue ALo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Lo);
16409         SDValue BLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Lo);
16410         SDValue AHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Hi);
16411         SDValue BHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Hi);
16412         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
16413                            DAG.getNode(ISD::MUL, dl, SubVT, ALo, BLo),
16414                            DAG.getNode(ISD::MUL, dl, SubVT, AHi, BHi));
16415       }
16416
16417       MVT ExVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements());
16418       return DAG.getNode(
16419           ISD::TRUNCATE, dl, VT,
16420           DAG.getNode(ISD::MUL, dl, ExVT,
16421                       DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, A),
16422                       DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, B)));
16423     }
16424
16425     assert(VT == MVT::v16i8 &&
16426            "Pre-AVX2 support only supports v16i8 multiplication");
16427     MVT ExVT = MVT::v8i16;
16428
16429     // Extract the lo parts and sign extend to i16
16430     SDValue ALo, BLo;
16431     if (Subtarget->hasSSE41()) {
16432       ALo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, A);
16433       BLo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, B);
16434     } else {
16435       const int ShufMask[] = {-1, 0, -1, 1, -1, 2, -1, 3,
16436                               -1, 4, -1, 5, -1, 6, -1, 7};
16437       ALo = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16438       BLo = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16439       ALo = DAG.getBitcast(ExVT, ALo);
16440       BLo = DAG.getBitcast(ExVT, BLo);
16441       ALo = DAG.getNode(ISD::SRA, dl, ExVT, ALo, DAG.getConstant(8, dl, ExVT));
16442       BLo = DAG.getNode(ISD::SRA, dl, ExVT, BLo, DAG.getConstant(8, dl, ExVT));
16443     }
16444
16445     // Extract the hi parts and sign extend to i16
16446     SDValue AHi, BHi;
16447     if (Subtarget->hasSSE41()) {
16448       const int ShufMask[] = {8,  9,  10, 11, 12, 13, 14, 15,
16449                               -1, -1, -1, -1, -1, -1, -1, -1};
16450       AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16451       BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16452       AHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, AHi);
16453       BHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, BHi);
16454     } else {
16455       const int ShufMask[] = {-1, 8,  -1, 9,  -1, 10, -1, 11,
16456                               -1, 12, -1, 13, -1, 14, -1, 15};
16457       AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16458       BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16459       AHi = DAG.getBitcast(ExVT, AHi);
16460       BHi = DAG.getBitcast(ExVT, BHi);
16461       AHi = DAG.getNode(ISD::SRA, dl, ExVT, AHi, DAG.getConstant(8, dl, ExVT));
16462       BHi = DAG.getNode(ISD::SRA, dl, ExVT, BHi, DAG.getConstant(8, dl, ExVT));
16463     }
16464
16465     // Multiply, mask the lower 8bits of the lo/hi results and pack
16466     SDValue RLo = DAG.getNode(ISD::MUL, dl, ExVT, ALo, BLo);
16467     SDValue RHi = DAG.getNode(ISD::MUL, dl, ExVT, AHi, BHi);
16468     RLo = DAG.getNode(ISD::AND, dl, ExVT, RLo, DAG.getConstant(255, dl, ExVT));
16469     RHi = DAG.getNode(ISD::AND, dl, ExVT, RHi, DAG.getConstant(255, dl, ExVT));
16470     return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
16471   }
16472
16473   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
16474   if (VT == MVT::v4i32) {
16475     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
16476            "Should not custom lower when pmuldq is available!");
16477
16478     // Extract the odd parts.
16479     static const int UnpackMask[] = { 1, -1, 3, -1 };
16480     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
16481     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
16482
16483     // Multiply the even parts.
16484     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
16485     // Now multiply odd parts.
16486     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
16487
16488     Evens = DAG.getBitcast(VT, Evens);
16489     Odds = DAG.getBitcast(VT, Odds);
16490
16491     // Merge the two vectors back together with a shuffle. This expands into 2
16492     // shuffles.
16493     static const int ShufMask[] = { 0, 4, 2, 6 };
16494     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
16495   }
16496
16497   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
16498          "Only know how to lower V2I64/V4I64/V8I64 multiply");
16499
16500   //  Ahi = psrlqi(a, 32);
16501   //  Bhi = psrlqi(b, 32);
16502   //
16503   //  AloBlo = pmuludq(a, b);
16504   //  AloBhi = pmuludq(a, Bhi);
16505   //  AhiBlo = pmuludq(Ahi, b);
16506
16507   //  AloBhi = psllqi(AloBhi, 32);
16508   //  AhiBlo = psllqi(AhiBlo, 32);
16509   //  return AloBlo + AloBhi + AhiBlo;
16510
16511   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
16512   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
16513
16514   SDValue AhiBlo = Ahi;
16515   SDValue AloBhi = Bhi;
16516   // Bit cast to 32-bit vectors for MULUDQ
16517   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
16518                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
16519   A = DAG.getBitcast(MulVT, A);
16520   B = DAG.getBitcast(MulVT, B);
16521   Ahi = DAG.getBitcast(MulVT, Ahi);
16522   Bhi = DAG.getBitcast(MulVT, Bhi);
16523
16524   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
16525   // After shifting right const values the result may be all-zero.
16526   if (!ISD::isBuildVectorAllZeros(Ahi.getNode())) {
16527     AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
16528     AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
16529   }
16530   if (!ISD::isBuildVectorAllZeros(Bhi.getNode())) {
16531     AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
16532     AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
16533   }
16534
16535   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
16536   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
16537 }
16538
16539 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
16540   assert(Subtarget->isTargetWin64() && "Unexpected target");
16541   EVT VT = Op.getValueType();
16542   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
16543          "Unexpected return type for lowering");
16544
16545   RTLIB::Libcall LC;
16546   bool isSigned;
16547   switch (Op->getOpcode()) {
16548   default: llvm_unreachable("Unexpected request for libcall!");
16549   case ISD::SDIV:      isSigned = true;  LC = RTLIB::SDIV_I128;    break;
16550   case ISD::UDIV:      isSigned = false; LC = RTLIB::UDIV_I128;    break;
16551   case ISD::SREM:      isSigned = true;  LC = RTLIB::SREM_I128;    break;
16552   case ISD::UREM:      isSigned = false; LC = RTLIB::UREM_I128;    break;
16553   case ISD::SDIVREM:   isSigned = true;  LC = RTLIB::SDIVREM_I128; break;
16554   case ISD::UDIVREM:   isSigned = false; LC = RTLIB::UDIVREM_I128; break;
16555   }
16556
16557   SDLoc dl(Op);
16558   SDValue InChain = DAG.getEntryNode();
16559
16560   TargetLowering::ArgListTy Args;
16561   TargetLowering::ArgListEntry Entry;
16562   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
16563     EVT ArgVT = Op->getOperand(i).getValueType();
16564     assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
16565            "Unexpected argument type for lowering");
16566     SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
16567     Entry.Node = StackPtr;
16568     InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
16569                            false, false, 16);
16570     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
16571     Entry.Ty = PointerType::get(ArgTy,0);
16572     Entry.isSExt = false;
16573     Entry.isZExt = false;
16574     Args.push_back(Entry);
16575   }
16576
16577   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
16578                                          getPointerTy());
16579
16580   TargetLowering::CallLoweringInfo CLI(DAG);
16581   CLI.setDebugLoc(dl).setChain(InChain)
16582     .setCallee(getLibcallCallingConv(LC),
16583                static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
16584                Callee, std::move(Args), 0)
16585     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
16586
16587   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
16588   return DAG.getBitcast(VT, CallInfo.first);
16589 }
16590
16591 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
16592                              SelectionDAG &DAG) {
16593   SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
16594   EVT VT = Op0.getValueType();
16595   SDLoc dl(Op);
16596
16597   assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
16598          (VT == MVT::v8i32 && Subtarget->hasInt256()));
16599
16600   // PMULxD operations multiply each even value (starting at 0) of LHS with
16601   // the related value of RHS and produce a widen result.
16602   // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
16603   // => <2 x i64> <ae|cg>
16604   //
16605   // In other word, to have all the results, we need to perform two PMULxD:
16606   // 1. one with the even values.
16607   // 2. one with the odd values.
16608   // To achieve #2, with need to place the odd values at an even position.
16609   //
16610   // Place the odd value at an even position (basically, shift all values 1
16611   // step to the left):
16612   const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
16613   // <a|b|c|d> => <b|undef|d|undef>
16614   SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
16615   // <e|f|g|h> => <f|undef|h|undef>
16616   SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
16617
16618   // Emit two multiplies, one for the lower 2 ints and one for the higher 2
16619   // ints.
16620   MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
16621   bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
16622   unsigned Opcode =
16623       (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
16624   // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
16625   // => <2 x i64> <ae|cg>
16626   SDValue Mul1 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
16627   // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
16628   // => <2 x i64> <bf|dh>
16629   SDValue Mul2 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
16630
16631   // Shuffle it back into the right order.
16632   SDValue Highs, Lows;
16633   if (VT == MVT::v8i32) {
16634     const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
16635     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
16636     const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
16637     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
16638   } else {
16639     const int HighMask[] = {1, 5, 3, 7};
16640     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
16641     const int LowMask[] = {0, 4, 2, 6};
16642     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
16643   }
16644
16645   // If we have a signed multiply but no PMULDQ fix up the high parts of a
16646   // unsigned multiply.
16647   if (IsSigned && !Subtarget->hasSSE41()) {
16648     SDValue ShAmt =
16649         DAG.getConstant(31, dl,
16650                         DAG.getTargetLoweringInfo().getShiftAmountTy(VT));
16651     SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
16652                              DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
16653     SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
16654                              DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
16655
16656     SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
16657     Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
16658   }
16659
16660   // The first result of MUL_LOHI is actually the low value, followed by the
16661   // high value.
16662   SDValue Ops[] = {Lows, Highs};
16663   return DAG.getMergeValues(Ops, dl);
16664 }
16665
16666 // Return true if the requred (according to Opcode) shift-imm form is natively
16667 // supported by the Subtarget
16668 static bool SupportedVectorShiftWithImm(MVT VT, const X86Subtarget *Subtarget,
16669                                         unsigned Opcode) {
16670   if (VT.getScalarSizeInBits() < 16)
16671     return false;
16672
16673   if (VT.is512BitVector() &&
16674       (VT.getScalarSizeInBits() > 16 || Subtarget->hasBWI()))
16675     return true;
16676
16677   bool LShift = VT.is128BitVector() ||
16678     (VT.is256BitVector() && Subtarget->hasInt256());
16679
16680   bool AShift = LShift && (Subtarget->hasVLX() ||
16681     (VT != MVT::v2i64 && VT != MVT::v4i64));
16682   return (Opcode == ISD::SRA) ? AShift : LShift;
16683 }
16684
16685 // The shift amount is a variable, but it is the same for all vector lanes.
16686 // These instrcutions are defined together with shift-immediate.
16687 static
16688 bool SupportedVectorShiftWithBaseAmnt(MVT VT, const X86Subtarget *Subtarget,
16689                                       unsigned Opcode) {
16690   return SupportedVectorShiftWithImm(VT, Subtarget, Opcode);
16691 }
16692
16693 // Return true if the requred (according to Opcode) variable-shift form is
16694 // natively supported by the Subtarget
16695 static bool SupportedVectorVarShift(MVT VT, const X86Subtarget *Subtarget,
16696                                     unsigned Opcode) {
16697
16698   if (!Subtarget->hasInt256() || VT.getScalarSizeInBits() < 16)
16699     return false;
16700
16701   // vXi16 supported only on AVX-512, BWI
16702   if (VT.getScalarSizeInBits() == 16 && !Subtarget->hasBWI())
16703     return false;
16704
16705   if (VT.is512BitVector() || Subtarget->hasVLX())
16706     return true;
16707
16708   bool LShift = VT.is128BitVector() || VT.is256BitVector();
16709   bool AShift = LShift &&  VT != MVT::v2i64 && VT != MVT::v4i64;
16710   return (Opcode == ISD::SRA) ? AShift : LShift;
16711 }
16712
16713 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
16714                                          const X86Subtarget *Subtarget) {
16715   MVT VT = Op.getSimpleValueType();
16716   SDLoc dl(Op);
16717   SDValue R = Op.getOperand(0);
16718   SDValue Amt = Op.getOperand(1);
16719
16720   unsigned X86Opc = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
16721     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
16722
16723   // Optimize shl/srl/sra with constant shift amount.
16724   if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
16725     if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
16726       uint64_t ShiftAmt = ShiftConst->getZExtValue();
16727
16728       if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
16729         return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
16730
16731       if (VT == MVT::v16i8 || (Subtarget->hasInt256() && VT == MVT::v32i8)) {
16732         unsigned NumElts = VT.getVectorNumElements();
16733         MVT ShiftVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
16734
16735         if (Op.getOpcode() == ISD::SHL) {
16736           // Simple i8 add case
16737           if (ShiftAmt == 1)
16738             return DAG.getNode(ISD::ADD, dl, VT, R, R);
16739
16740           // Make a large shift.
16741           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ShiftVT,
16742                                                    R, ShiftAmt, DAG);
16743           SHL = DAG.getBitcast(VT, SHL);
16744           // Zero out the rightmost bits.
16745           SmallVector<SDValue, 32> V(
16746               NumElts, DAG.getConstant(uint8_t(-1U << ShiftAmt), dl, MVT::i8));
16747           return DAG.getNode(ISD::AND, dl, VT, SHL,
16748                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
16749         }
16750         if (Op.getOpcode() == ISD::SRL) {
16751           // Make a large shift.
16752           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ShiftVT,
16753                                                    R, ShiftAmt, DAG);
16754           SRL = DAG.getBitcast(VT, SRL);
16755           // Zero out the leftmost bits.
16756           SmallVector<SDValue, 32> V(
16757               NumElts, DAG.getConstant(uint8_t(-1U) >> ShiftAmt, dl, MVT::i8));
16758           return DAG.getNode(ISD::AND, dl, VT, SRL,
16759                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
16760         }
16761         if (Op.getOpcode() == ISD::SRA) {
16762           if (ShiftAmt == 7) {
16763             // R s>> 7  ===  R s< 0
16764             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
16765             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
16766           }
16767
16768           // R s>> a === ((R u>> a) ^ m) - m
16769           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
16770           SmallVector<SDValue, 32> V(NumElts,
16771                                      DAG.getConstant(128 >> ShiftAmt, dl,
16772                                                      MVT::i8));
16773           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
16774           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
16775           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
16776           return Res;
16777         }
16778         llvm_unreachable("Unknown shift opcode.");
16779       }
16780     }
16781   }
16782
16783   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
16784   if (!Subtarget->is64Bit() &&
16785       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
16786       Amt.getOpcode() == ISD::BITCAST &&
16787       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
16788     Amt = Amt.getOperand(0);
16789     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
16790                      VT.getVectorNumElements();
16791     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
16792     uint64_t ShiftAmt = 0;
16793     for (unsigned i = 0; i != Ratio; ++i) {
16794       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
16795       if (!C)
16796         return SDValue();
16797       // 6 == Log2(64)
16798       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
16799     }
16800     // Check remaining shift amounts.
16801     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
16802       uint64_t ShAmt = 0;
16803       for (unsigned j = 0; j != Ratio; ++j) {
16804         ConstantSDNode *C =
16805           dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
16806         if (!C)
16807           return SDValue();
16808         // 6 == Log2(64)
16809         ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
16810       }
16811       if (ShAmt != ShiftAmt)
16812         return SDValue();
16813     }
16814     return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
16815   }
16816
16817   return SDValue();
16818 }
16819
16820 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
16821                                         const X86Subtarget* Subtarget) {
16822   MVT VT = Op.getSimpleValueType();
16823   SDLoc dl(Op);
16824   SDValue R = Op.getOperand(0);
16825   SDValue Amt = Op.getOperand(1);
16826
16827   unsigned X86OpcI = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
16828     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
16829
16830   unsigned X86OpcV = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHL :
16831     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRL : X86ISD::VSRA;
16832
16833   if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode())) {
16834     SDValue BaseShAmt;
16835     EVT EltVT = VT.getVectorElementType();
16836
16837     if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Amt)) {
16838       // Check if this build_vector node is doing a splat.
16839       // If so, then set BaseShAmt equal to the splat value.
16840       BaseShAmt = BV->getSplatValue();
16841       if (BaseShAmt && BaseShAmt.getOpcode() == ISD::UNDEF)
16842         BaseShAmt = SDValue();
16843     } else {
16844       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
16845         Amt = Amt.getOperand(0);
16846
16847       ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt);
16848       if (SVN && SVN->isSplat()) {
16849         unsigned SplatIdx = (unsigned)SVN->getSplatIndex();
16850         SDValue InVec = Amt.getOperand(0);
16851         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
16852           assert((SplatIdx < InVec.getValueType().getVectorNumElements()) &&
16853                  "Unexpected shuffle index found!");
16854           BaseShAmt = InVec.getOperand(SplatIdx);
16855         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
16856            if (ConstantSDNode *C =
16857                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
16858              if (C->getZExtValue() == SplatIdx)
16859                BaseShAmt = InVec.getOperand(1);
16860            }
16861         }
16862
16863         if (!BaseShAmt)
16864           // Avoid introducing an extract element from a shuffle.
16865           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InVec,
16866                                   DAG.getIntPtrConstant(SplatIdx, dl));
16867       }
16868     }
16869
16870     if (BaseShAmt.getNode()) {
16871       assert(EltVT.bitsLE(MVT::i64) && "Unexpected element type!");
16872       if (EltVT != MVT::i64 && EltVT.bitsGT(MVT::i32))
16873         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, BaseShAmt);
16874       else if (EltVT.bitsLT(MVT::i32))
16875         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
16876
16877       return getTargetVShiftNode(X86OpcI, dl, VT, R, BaseShAmt, DAG);
16878     }
16879   }
16880
16881   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
16882   if (!Subtarget->is64Bit() && VT == MVT::v2i64  &&
16883       Amt.getOpcode() == ISD::BITCAST &&
16884       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
16885     Amt = Amt.getOperand(0);
16886     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
16887                      VT.getVectorNumElements();
16888     std::vector<SDValue> Vals(Ratio);
16889     for (unsigned i = 0; i != Ratio; ++i)
16890       Vals[i] = Amt.getOperand(i);
16891     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
16892       for (unsigned j = 0; j != Ratio; ++j)
16893         if (Vals[j] != Amt.getOperand(i + j))
16894           return SDValue();
16895     }
16896     return DAG.getNode(X86OpcV, dl, VT, R, Op.getOperand(1));
16897   }
16898   return SDValue();
16899 }
16900
16901 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
16902                           SelectionDAG &DAG) {
16903   MVT VT = Op.getSimpleValueType();
16904   SDLoc dl(Op);
16905   SDValue R = Op.getOperand(0);
16906   SDValue Amt = Op.getOperand(1);
16907
16908   assert(VT.isVector() && "Custom lowering only for vector shifts!");
16909   assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
16910
16911   if (SDValue V = LowerScalarImmediateShift(Op, DAG, Subtarget))
16912     return V;
16913
16914   if (SDValue V = LowerScalarVariableShift(Op, DAG, Subtarget))
16915       return V;
16916
16917   if (SupportedVectorVarShift(VT, Subtarget, Op.getOpcode()))
16918     return Op;
16919
16920   // 2i64 vector logical shifts can efficiently avoid scalarization - do the
16921   // shifts per-lane and then shuffle the partial results back together.
16922   if (VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) {
16923     // Splat the shift amounts so the scalar shifts above will catch it.
16924     SDValue Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {0, 0});
16925     SDValue Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {1, 1});
16926     SDValue R0 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt0);
16927     SDValue R1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt1);
16928     return DAG.getVectorShuffle(VT, dl, R0, R1, {0, 3});
16929   }
16930
16931   // If possible, lower this packed shift into a vector multiply instead of
16932   // expanding it into a sequence of scalar shifts.
16933   // Do this only if the vector shift count is a constant build_vector.
16934   if (Op.getOpcode() == ISD::SHL &&
16935       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
16936        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
16937       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
16938     SmallVector<SDValue, 8> Elts;
16939     EVT SVT = VT.getScalarType();
16940     unsigned SVTBits = SVT.getSizeInBits();
16941     const APInt &One = APInt(SVTBits, 1);
16942     unsigned NumElems = VT.getVectorNumElements();
16943
16944     for (unsigned i=0; i !=NumElems; ++i) {
16945       SDValue Op = Amt->getOperand(i);
16946       if (Op->getOpcode() == ISD::UNDEF) {
16947         Elts.push_back(Op);
16948         continue;
16949       }
16950
16951       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
16952       const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
16953       uint64_t ShAmt = C.getZExtValue();
16954       if (ShAmt >= SVTBits) {
16955         Elts.push_back(DAG.getUNDEF(SVT));
16956         continue;
16957       }
16958       Elts.push_back(DAG.getConstant(One.shl(ShAmt), dl, SVT));
16959     }
16960     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
16961     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
16962   }
16963
16964   // Lower SHL with variable shift amount.
16965   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
16966     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, dl, VT));
16967
16968     Op = DAG.getNode(ISD::ADD, dl, VT, Op,
16969                      DAG.getConstant(0x3f800000U, dl, VT));
16970     Op = DAG.getBitcast(MVT::v4f32, Op);
16971     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
16972     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
16973   }
16974
16975   // If possible, lower this shift as a sequence of two shifts by
16976   // constant plus a MOVSS/MOVSD instead of scalarizing it.
16977   // Example:
16978   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
16979   //
16980   // Could be rewritten as:
16981   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
16982   //
16983   // The advantage is that the two shifts from the example would be
16984   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
16985   // the vector shift into four scalar shifts plus four pairs of vector
16986   // insert/extract.
16987   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
16988       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
16989     unsigned TargetOpcode = X86ISD::MOVSS;
16990     bool CanBeSimplified;
16991     // The splat value for the first packed shift (the 'X' from the example).
16992     SDValue Amt1 = Amt->getOperand(0);
16993     // The splat value for the second packed shift (the 'Y' from the example).
16994     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
16995                                         Amt->getOperand(2);
16996
16997     // See if it is possible to replace this node with a sequence of
16998     // two shifts followed by a MOVSS/MOVSD
16999     if (VT == MVT::v4i32) {
17000       // Check if it is legal to use a MOVSS.
17001       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
17002                         Amt2 == Amt->getOperand(3);
17003       if (!CanBeSimplified) {
17004         // Otherwise, check if we can still simplify this node using a MOVSD.
17005         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
17006                           Amt->getOperand(2) == Amt->getOperand(3);
17007         TargetOpcode = X86ISD::MOVSD;
17008         Amt2 = Amt->getOperand(2);
17009       }
17010     } else {
17011       // Do similar checks for the case where the machine value type
17012       // is MVT::v8i16.
17013       CanBeSimplified = Amt1 == Amt->getOperand(1);
17014       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
17015         CanBeSimplified = Amt2 == Amt->getOperand(i);
17016
17017       if (!CanBeSimplified) {
17018         TargetOpcode = X86ISD::MOVSD;
17019         CanBeSimplified = true;
17020         Amt2 = Amt->getOperand(4);
17021         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
17022           CanBeSimplified = Amt1 == Amt->getOperand(i);
17023         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
17024           CanBeSimplified = Amt2 == Amt->getOperand(j);
17025       }
17026     }
17027
17028     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
17029         isa<ConstantSDNode>(Amt2)) {
17030       // Replace this node with two shifts followed by a MOVSS/MOVSD.
17031       EVT CastVT = MVT::v4i32;
17032       SDValue Splat1 =
17033         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), dl, VT);
17034       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
17035       SDValue Splat2 =
17036         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), dl, VT);
17037       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
17038       if (TargetOpcode == X86ISD::MOVSD)
17039         CastVT = MVT::v2i64;
17040       SDValue BitCast1 = DAG.getBitcast(CastVT, Shift1);
17041       SDValue BitCast2 = DAG.getBitcast(CastVT, Shift2);
17042       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
17043                                             BitCast1, DAG);
17044       return DAG.getBitcast(VT, Result);
17045     }
17046   }
17047
17048   if (VT == MVT::v16i8 || (VT == MVT::v32i8 && Subtarget->hasInt256())) {
17049     MVT ExtVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements() / 2);
17050     unsigned ShiftOpcode = Op->getOpcode();
17051
17052     auto SignBitSelect = [&](MVT SelVT, SDValue Sel, SDValue V0, SDValue V1) {
17053       // On SSE41 targets we make use of the fact that VSELECT lowers
17054       // to PBLENDVB which selects bytes based just on the sign bit.
17055       if (Subtarget->hasSSE41()) {
17056         V0 = DAG.getBitcast(VT, V0);
17057         V1 = DAG.getBitcast(VT, V1);
17058         Sel = DAG.getBitcast(VT, Sel);
17059         return DAG.getBitcast(SelVT,
17060                               DAG.getNode(ISD::VSELECT, dl, VT, Sel, V0, V1));
17061       }
17062       // On pre-SSE41 targets we test for the sign bit by comparing to
17063       // zero - a negative value will set all bits of the lanes to true
17064       // and VSELECT uses that in its OR(AND(V0,C),AND(V1,~C)) lowering.
17065       SDValue Z = getZeroVector(SelVT, Subtarget, DAG, dl);
17066       SDValue C = DAG.getNode(X86ISD::PCMPGT, dl, SelVT, Z, Sel);
17067       return DAG.getNode(ISD::VSELECT, dl, SelVT, C, V0, V1);
17068     };
17069
17070     // Turn 'a' into a mask suitable for VSELECT: a = a << 5;
17071     // We can safely do this using i16 shifts as we're only interested in
17072     // the 3 lower bits of each byte.
17073     Amt = DAG.getBitcast(ExtVT, Amt);
17074     Amt = DAG.getNode(ISD::SHL, dl, ExtVT, Amt, DAG.getConstant(5, dl, ExtVT));
17075     Amt = DAG.getBitcast(VT, Amt);
17076
17077     if (Op->getOpcode() == ISD::SHL || Op->getOpcode() == ISD::SRL) {
17078       // r = VSELECT(r, shift(r, 4), a);
17079       SDValue M =
17080           DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
17081       R = SignBitSelect(VT, Amt, M, R);
17082
17083       // a += a
17084       Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17085
17086       // r = VSELECT(r, shift(r, 2), a);
17087       M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
17088       R = SignBitSelect(VT, Amt, M, R);
17089
17090       // a += a
17091       Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17092
17093       // return VSELECT(r, shift(r, 1), a);
17094       M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
17095       R = SignBitSelect(VT, Amt, M, R);
17096       return R;
17097     }
17098
17099     if (Op->getOpcode() == ISD::SRA) {
17100       // For SRA we need to unpack each byte to the higher byte of a i16 vector
17101       // so we can correctly sign extend. We don't care what happens to the
17102       // lower byte.
17103       SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), Amt);
17104       SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), Amt);
17105       SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), R);
17106       SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), R);
17107       ALo = DAG.getBitcast(ExtVT, ALo);
17108       AHi = DAG.getBitcast(ExtVT, AHi);
17109       RLo = DAG.getBitcast(ExtVT, RLo);
17110       RHi = DAG.getBitcast(ExtVT, RHi);
17111
17112       // r = VSELECT(r, shift(r, 4), a);
17113       SDValue MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
17114                                 DAG.getConstant(4, dl, ExtVT));
17115       SDValue MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
17116                                 DAG.getConstant(4, dl, ExtVT));
17117       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
17118       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
17119
17120       // a += a
17121       ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
17122       AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
17123
17124       // r = VSELECT(r, shift(r, 2), a);
17125       MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
17126                         DAG.getConstant(2, dl, ExtVT));
17127       MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
17128                         DAG.getConstant(2, dl, ExtVT));
17129       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
17130       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
17131
17132       // a += a
17133       ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
17134       AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
17135
17136       // r = VSELECT(r, shift(r, 1), a);
17137       MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
17138                         DAG.getConstant(1, dl, ExtVT));
17139       MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
17140                         DAG.getConstant(1, dl, ExtVT));
17141       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
17142       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
17143
17144       // Logical shift the result back to the lower byte, leaving a zero upper
17145       // byte
17146       // meaning that we can safely pack with PACKUSWB.
17147       RLo =
17148           DAG.getNode(ISD::SRL, dl, ExtVT, RLo, DAG.getConstant(8, dl, ExtVT));
17149       RHi =
17150           DAG.getNode(ISD::SRL, dl, ExtVT, RHi, DAG.getConstant(8, dl, ExtVT));
17151       return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
17152     }
17153   }
17154
17155   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
17156   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
17157   // solution better.
17158   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
17159     MVT ExtVT = MVT::v8i32;
17160     unsigned ExtOpc =
17161         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
17162     R = DAG.getNode(ExtOpc, dl, ExtVT, R);
17163     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, ExtVT, Amt);
17164     return DAG.getNode(ISD::TRUNCATE, dl, VT,
17165                        DAG.getNode(Op.getOpcode(), dl, ExtVT, R, Amt));
17166   }
17167
17168   if (Subtarget->hasInt256() && VT == MVT::v16i16) {
17169     MVT ExtVT = MVT::v8i32;
17170     SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
17171     SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, Amt, Z);
17172     SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, Amt, Z);
17173     SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, R, R);
17174     SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, R, R);
17175     ALo = DAG.getBitcast(ExtVT, ALo);
17176     AHi = DAG.getBitcast(ExtVT, AHi);
17177     RLo = DAG.getBitcast(ExtVT, RLo);
17178     RHi = DAG.getBitcast(ExtVT, RHi);
17179     SDValue Lo = DAG.getNode(Op.getOpcode(), dl, ExtVT, RLo, ALo);
17180     SDValue Hi = DAG.getNode(Op.getOpcode(), dl, ExtVT, RHi, AHi);
17181     Lo = DAG.getNode(ISD::SRL, dl, ExtVT, Lo, DAG.getConstant(16, dl, ExtVT));
17182     Hi = DAG.getNode(ISD::SRL, dl, ExtVT, Hi, DAG.getConstant(16, dl, ExtVT));
17183     return DAG.getNode(X86ISD::PACKUS, dl, VT, Lo, Hi);
17184   }
17185
17186   if (VT == MVT::v8i16) {
17187     unsigned ShiftOpcode = Op->getOpcode();
17188
17189     auto SignBitSelect = [&](SDValue Sel, SDValue V0, SDValue V1) {
17190       // On SSE41 targets we make use of the fact that VSELECT lowers
17191       // to PBLENDVB which selects bytes based just on the sign bit.
17192       if (Subtarget->hasSSE41()) {
17193         MVT ExtVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() * 2);
17194         V0 = DAG.getBitcast(ExtVT, V0);
17195         V1 = DAG.getBitcast(ExtVT, V1);
17196         Sel = DAG.getBitcast(ExtVT, Sel);
17197         return DAG.getBitcast(
17198             VT, DAG.getNode(ISD::VSELECT, dl, ExtVT, Sel, V0, V1));
17199       }
17200       // On pre-SSE41 targets we splat the sign bit - a negative value will
17201       // set all bits of the lanes to true and VSELECT uses that in
17202       // its OR(AND(V0,C),AND(V1,~C)) lowering.
17203       SDValue C =
17204           DAG.getNode(ISD::SRA, dl, VT, Sel, DAG.getConstant(15, dl, VT));
17205       return DAG.getNode(ISD::VSELECT, dl, VT, C, V0, V1);
17206     };
17207
17208     // Turn 'a' into a mask suitable for VSELECT: a = a << 12;
17209     if (Subtarget->hasSSE41()) {
17210       // On SSE41 targets we need to replicate the shift mask in both
17211       // bytes for PBLENDVB.
17212       Amt = DAG.getNode(
17213           ISD::OR, dl, VT,
17214           DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(4, dl, VT)),
17215           DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT)));
17216     } else {
17217       Amt = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT));
17218     }
17219
17220     // r = VSELECT(r, shift(r, 8), a);
17221     SDValue M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(8, dl, VT));
17222     R = SignBitSelect(Amt, M, R);
17223
17224     // a += a
17225     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17226
17227     // r = VSELECT(r, shift(r, 4), a);
17228     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
17229     R = SignBitSelect(Amt, M, R);
17230
17231     // a += a
17232     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17233
17234     // r = VSELECT(r, shift(r, 2), a);
17235     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
17236     R = SignBitSelect(Amt, M, R);
17237
17238     // a += a
17239     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17240
17241     // return VSELECT(r, shift(r, 1), a);
17242     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
17243     R = SignBitSelect(Amt, M, R);
17244     return R;
17245   }
17246
17247   // Decompose 256-bit shifts into smaller 128-bit shifts.
17248   if (VT.is256BitVector()) {
17249     unsigned NumElems = VT.getVectorNumElements();
17250     MVT EltVT = VT.getVectorElementType();
17251     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
17252
17253     // Extract the two vectors
17254     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
17255     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
17256
17257     // Recreate the shift amount vectors
17258     SDValue Amt1, Amt2;
17259     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
17260       // Constant shift amount
17261       SmallVector<SDValue, 8> Ops(Amt->op_begin(), Amt->op_begin() + NumElems);
17262       ArrayRef<SDValue> Amt1Csts = makeArrayRef(Ops).slice(0, NumElems / 2);
17263       ArrayRef<SDValue> Amt2Csts = makeArrayRef(Ops).slice(NumElems / 2);
17264
17265       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
17266       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
17267     } else {
17268       // Variable shift amount
17269       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
17270       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
17271     }
17272
17273     // Issue new vector shifts for the smaller types
17274     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
17275     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
17276
17277     // Concatenate the result back
17278     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
17279   }
17280
17281   return SDValue();
17282 }
17283
17284 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
17285   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
17286   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
17287   // looks for this combo and may remove the "setcc" instruction if the "setcc"
17288   // has only one use.
17289   SDNode *N = Op.getNode();
17290   SDValue LHS = N->getOperand(0);
17291   SDValue RHS = N->getOperand(1);
17292   unsigned BaseOp = 0;
17293   unsigned Cond = 0;
17294   SDLoc DL(Op);
17295   switch (Op.getOpcode()) {
17296   default: llvm_unreachable("Unknown ovf instruction!");
17297   case ISD::SADDO:
17298     // A subtract of one will be selected as a INC. Note that INC doesn't
17299     // set CF, so we can't do this for UADDO.
17300     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
17301       if (C->isOne()) {
17302         BaseOp = X86ISD::INC;
17303         Cond = X86::COND_O;
17304         break;
17305       }
17306     BaseOp = X86ISD::ADD;
17307     Cond = X86::COND_O;
17308     break;
17309   case ISD::UADDO:
17310     BaseOp = X86ISD::ADD;
17311     Cond = X86::COND_B;
17312     break;
17313   case ISD::SSUBO:
17314     // A subtract of one will be selected as a DEC. Note that DEC doesn't
17315     // set CF, so we can't do this for USUBO.
17316     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
17317       if (C->isOne()) {
17318         BaseOp = X86ISD::DEC;
17319         Cond = X86::COND_O;
17320         break;
17321       }
17322     BaseOp = X86ISD::SUB;
17323     Cond = X86::COND_O;
17324     break;
17325   case ISD::USUBO:
17326     BaseOp = X86ISD::SUB;
17327     Cond = X86::COND_B;
17328     break;
17329   case ISD::SMULO:
17330     BaseOp = N->getValueType(0) == MVT::i8 ? X86ISD::SMUL8 : X86ISD::SMUL;
17331     Cond = X86::COND_O;
17332     break;
17333   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
17334     if (N->getValueType(0) == MVT::i8) {
17335       BaseOp = X86ISD::UMUL8;
17336       Cond = X86::COND_O;
17337       break;
17338     }
17339     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
17340                                  MVT::i32);
17341     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
17342
17343     SDValue SetCC =
17344       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
17345                   DAG.getConstant(X86::COND_O, DL, MVT::i32),
17346                   SDValue(Sum.getNode(), 2));
17347
17348     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
17349   }
17350   }
17351
17352   // Also sets EFLAGS.
17353   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
17354   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
17355
17356   SDValue SetCC =
17357     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
17358                 DAG.getConstant(Cond, DL, MVT::i32),
17359                 SDValue(Sum.getNode(), 1));
17360
17361   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
17362 }
17363
17364 /// Returns true if the operand type is exactly twice the native width, and
17365 /// the corresponding cmpxchg8b or cmpxchg16b instruction is available.
17366 /// Used to know whether to use cmpxchg8/16b when expanding atomic operations
17367 /// (otherwise we leave them alone to become __sync_fetch_and_... calls).
17368 bool X86TargetLowering::needsCmpXchgNb(const Type *MemType) const {
17369   unsigned OpWidth = MemType->getPrimitiveSizeInBits();
17370
17371   if (OpWidth == 64)
17372     return !Subtarget->is64Bit(); // FIXME this should be Subtarget.hasCmpxchg8b
17373   else if (OpWidth == 128)
17374     return Subtarget->hasCmpxchg16b();
17375   else
17376     return false;
17377 }
17378
17379 bool X86TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
17380   return needsCmpXchgNb(SI->getValueOperand()->getType());
17381 }
17382
17383 // Note: this turns large loads into lock cmpxchg8b/16b.
17384 // FIXME: On 32 bits x86, fild/movq might be faster than lock cmpxchg8b.
17385 bool X86TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
17386   auto PTy = cast<PointerType>(LI->getPointerOperand()->getType());
17387   return needsCmpXchgNb(PTy->getElementType());
17388 }
17389
17390 TargetLoweringBase::AtomicRMWExpansionKind
17391 X86TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
17392   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
17393   const Type *MemType = AI->getType();
17394
17395   // If the operand is too big, we must see if cmpxchg8/16b is available
17396   // and default to library calls otherwise.
17397   if (MemType->getPrimitiveSizeInBits() > NativeWidth) {
17398     return needsCmpXchgNb(MemType) ? AtomicRMWExpansionKind::CmpXChg
17399                                    : AtomicRMWExpansionKind::None;
17400   }
17401
17402   AtomicRMWInst::BinOp Op = AI->getOperation();
17403   switch (Op) {
17404   default:
17405     llvm_unreachable("Unknown atomic operation");
17406   case AtomicRMWInst::Xchg:
17407   case AtomicRMWInst::Add:
17408   case AtomicRMWInst::Sub:
17409     // It's better to use xadd, xsub or xchg for these in all cases.
17410     return AtomicRMWExpansionKind::None;
17411   case AtomicRMWInst::Or:
17412   case AtomicRMWInst::And:
17413   case AtomicRMWInst::Xor:
17414     // If the atomicrmw's result isn't actually used, we can just add a "lock"
17415     // prefix to a normal instruction for these operations.
17416     return !AI->use_empty() ? AtomicRMWExpansionKind::CmpXChg
17417                             : AtomicRMWExpansionKind::None;
17418   case AtomicRMWInst::Nand:
17419   case AtomicRMWInst::Max:
17420   case AtomicRMWInst::Min:
17421   case AtomicRMWInst::UMax:
17422   case AtomicRMWInst::UMin:
17423     // These always require a non-trivial set of data operations on x86. We must
17424     // use a cmpxchg loop.
17425     return AtomicRMWExpansionKind::CmpXChg;
17426   }
17427 }
17428
17429 static bool hasMFENCE(const X86Subtarget& Subtarget) {
17430   // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
17431   // no-sse2). There isn't any reason to disable it if the target processor
17432   // supports it.
17433   return Subtarget.hasSSE2() || Subtarget.is64Bit();
17434 }
17435
17436 LoadInst *
17437 X86TargetLowering::lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *AI) const {
17438   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
17439   const Type *MemType = AI->getType();
17440   // Accesses larger than the native width are turned into cmpxchg/libcalls, so
17441   // there is no benefit in turning such RMWs into loads, and it is actually
17442   // harmful as it introduces a mfence.
17443   if (MemType->getPrimitiveSizeInBits() > NativeWidth)
17444     return nullptr;
17445
17446   auto Builder = IRBuilder<>(AI);
17447   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
17448   auto SynchScope = AI->getSynchScope();
17449   // We must restrict the ordering to avoid generating loads with Release or
17450   // ReleaseAcquire orderings.
17451   auto Order = AtomicCmpXchgInst::getStrongestFailureOrdering(AI->getOrdering());
17452   auto Ptr = AI->getPointerOperand();
17453
17454   // Before the load we need a fence. Here is an example lifted from
17455   // http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf showing why a fence
17456   // is required:
17457   // Thread 0:
17458   //   x.store(1, relaxed);
17459   //   r1 = y.fetch_add(0, release);
17460   // Thread 1:
17461   //   y.fetch_add(42, acquire);
17462   //   r2 = x.load(relaxed);
17463   // r1 = r2 = 0 is impossible, but becomes possible if the idempotent rmw is
17464   // lowered to just a load without a fence. A mfence flushes the store buffer,
17465   // making the optimization clearly correct.
17466   // FIXME: it is required if isAtLeastRelease(Order) but it is not clear
17467   // otherwise, we might be able to be more agressive on relaxed idempotent
17468   // rmw. In practice, they do not look useful, so we don't try to be
17469   // especially clever.
17470   if (SynchScope == SingleThread)
17471     // FIXME: we could just insert an X86ISD::MEMBARRIER here, except we are at
17472     // the IR level, so we must wrap it in an intrinsic.
17473     return nullptr;
17474
17475   if (!hasMFENCE(*Subtarget))
17476     // FIXME: it might make sense to use a locked operation here but on a
17477     // different cache-line to prevent cache-line bouncing. In practice it
17478     // is probably a small win, and x86 processors without mfence are rare
17479     // enough that we do not bother.
17480     return nullptr;
17481
17482   Function *MFence =
17483       llvm::Intrinsic::getDeclaration(M, Intrinsic::x86_sse2_mfence);
17484   Builder.CreateCall(MFence, {});
17485
17486   // Finally we can emit the atomic load.
17487   LoadInst *Loaded = Builder.CreateAlignedLoad(Ptr,
17488           AI->getType()->getPrimitiveSizeInBits());
17489   Loaded->setAtomic(Order, SynchScope);
17490   AI->replaceAllUsesWith(Loaded);
17491   AI->eraseFromParent();
17492   return Loaded;
17493 }
17494
17495 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
17496                                  SelectionDAG &DAG) {
17497   SDLoc dl(Op);
17498   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
17499     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
17500   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
17501     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
17502
17503   // The only fence that needs an instruction is a sequentially-consistent
17504   // cross-thread fence.
17505   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
17506     if (hasMFENCE(*Subtarget))
17507       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
17508
17509     SDValue Chain = Op.getOperand(0);
17510     SDValue Zero = DAG.getConstant(0, dl, MVT::i32);
17511     SDValue Ops[] = {
17512       DAG.getRegister(X86::ESP, MVT::i32),     // Base
17513       DAG.getTargetConstant(1, dl, MVT::i8),   // Scale
17514       DAG.getRegister(0, MVT::i32),            // Index
17515       DAG.getTargetConstant(0, dl, MVT::i32),  // Disp
17516       DAG.getRegister(0, MVT::i32),            // Segment.
17517       Zero,
17518       Chain
17519     };
17520     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
17521     return SDValue(Res, 0);
17522   }
17523
17524   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
17525   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
17526 }
17527
17528 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
17529                              SelectionDAG &DAG) {
17530   MVT T = Op.getSimpleValueType();
17531   SDLoc DL(Op);
17532   unsigned Reg = 0;
17533   unsigned size = 0;
17534   switch(T.SimpleTy) {
17535   default: llvm_unreachable("Invalid value type!");
17536   case MVT::i8:  Reg = X86::AL;  size = 1; break;
17537   case MVT::i16: Reg = X86::AX;  size = 2; break;
17538   case MVT::i32: Reg = X86::EAX; size = 4; break;
17539   case MVT::i64:
17540     assert(Subtarget->is64Bit() && "Node not type legal!");
17541     Reg = X86::RAX; size = 8;
17542     break;
17543   }
17544   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
17545                                   Op.getOperand(2), SDValue());
17546   SDValue Ops[] = { cpIn.getValue(0),
17547                     Op.getOperand(1),
17548                     Op.getOperand(3),
17549                     DAG.getTargetConstant(size, DL, MVT::i8),
17550                     cpIn.getValue(1) };
17551   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
17552   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
17553   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
17554                                            Ops, T, MMO);
17555
17556   SDValue cpOut =
17557     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
17558   SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
17559                                       MVT::i32, cpOut.getValue(2));
17560   SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
17561                                 DAG.getConstant(X86::COND_E, DL, MVT::i8),
17562                                 EFLAGS);
17563
17564   DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
17565   DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
17566   DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
17567   return SDValue();
17568 }
17569
17570 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
17571                             SelectionDAG &DAG) {
17572   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
17573   MVT DstVT = Op.getSimpleValueType();
17574
17575   if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
17576     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
17577     if (DstVT != MVT::f64)
17578       // This conversion needs to be expanded.
17579       return SDValue();
17580
17581     SDValue InVec = Op->getOperand(0);
17582     SDLoc dl(Op);
17583     unsigned NumElts = SrcVT.getVectorNumElements();
17584     EVT SVT = SrcVT.getVectorElementType();
17585
17586     // Widen the vector in input in the case of MVT::v2i32.
17587     // Example: from MVT::v2i32 to MVT::v4i32.
17588     SmallVector<SDValue, 16> Elts;
17589     for (unsigned i = 0, e = NumElts; i != e; ++i)
17590       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
17591                                  DAG.getIntPtrConstant(i, dl)));
17592
17593     // Explicitly mark the extra elements as Undef.
17594     Elts.append(NumElts, DAG.getUNDEF(SVT));
17595
17596     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
17597     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
17598     SDValue ToV2F64 = DAG.getBitcast(MVT::v2f64, BV);
17599     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
17600                        DAG.getIntPtrConstant(0, dl));
17601   }
17602
17603   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
17604          Subtarget->hasMMX() && "Unexpected custom BITCAST");
17605   assert((DstVT == MVT::i64 ||
17606           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
17607          "Unexpected custom BITCAST");
17608   // i64 <=> MMX conversions are Legal.
17609   if (SrcVT==MVT::i64 && DstVT.isVector())
17610     return Op;
17611   if (DstVT==MVT::i64 && SrcVT.isVector())
17612     return Op;
17613   // MMX <=> MMX conversions are Legal.
17614   if (SrcVT.isVector() && DstVT.isVector())
17615     return Op;
17616   // All other conversions need to be expanded.
17617   return SDValue();
17618 }
17619
17620 /// Compute the horizontal sum of bytes in V for the elements of VT.
17621 ///
17622 /// Requires V to be a byte vector and VT to be an integer vector type with
17623 /// wider elements than V's type. The width of the elements of VT determines
17624 /// how many bytes of V are summed horizontally to produce each element of the
17625 /// result.
17626 static SDValue LowerHorizontalByteSum(SDValue V, MVT VT,
17627                                       const X86Subtarget *Subtarget,
17628                                       SelectionDAG &DAG) {
17629   SDLoc DL(V);
17630   MVT ByteVecVT = V.getSimpleValueType();
17631   MVT EltVT = VT.getVectorElementType();
17632   int NumElts = VT.getVectorNumElements();
17633   assert(ByteVecVT.getVectorElementType() == MVT::i8 &&
17634          "Expected value to have byte element type.");
17635   assert(EltVT != MVT::i8 &&
17636          "Horizontal byte sum only makes sense for wider elements!");
17637   unsigned VecSize = VT.getSizeInBits();
17638   assert(ByteVecVT.getSizeInBits() == VecSize && "Cannot change vector size!");
17639
17640   // PSADBW instruction horizontally add all bytes and leave the result in i64
17641   // chunks, thus directly computes the pop count for v2i64 and v4i64.
17642   if (EltVT == MVT::i64) {
17643     SDValue Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
17644     V = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT, V, Zeros);
17645     return DAG.getBitcast(VT, V);
17646   }
17647
17648   if (EltVT == MVT::i32) {
17649     // We unpack the low half and high half into i32s interleaved with zeros so
17650     // that we can use PSADBW to horizontally sum them. The most useful part of
17651     // this is that it lines up the results of two PSADBW instructions to be
17652     // two v2i64 vectors which concatenated are the 4 population counts. We can
17653     // then use PACKUSWB to shrink and concatenate them into a v4i32 again.
17654     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, DL);
17655     SDValue Low = DAG.getNode(X86ISD::UNPCKL, DL, VT, V, Zeros);
17656     SDValue High = DAG.getNode(X86ISD::UNPCKH, DL, VT, V, Zeros);
17657
17658     // Do the horizontal sums into two v2i64s.
17659     Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
17660     Low = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT,
17661                       DAG.getBitcast(ByteVecVT, Low), Zeros);
17662     High = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT,
17663                        DAG.getBitcast(ByteVecVT, High), Zeros);
17664
17665     // Merge them together.
17666     MVT ShortVecVT = MVT::getVectorVT(MVT::i16, VecSize / 16);
17667     V = DAG.getNode(X86ISD::PACKUS, DL, ByteVecVT,
17668                     DAG.getBitcast(ShortVecVT, Low),
17669                     DAG.getBitcast(ShortVecVT, High));
17670
17671     return DAG.getBitcast(VT, V);
17672   }
17673
17674   // The only element type left is i16.
17675   assert(EltVT == MVT::i16 && "Unknown how to handle type");
17676
17677   // To obtain pop count for each i16 element starting from the pop count for
17678   // i8 elements, shift the i16s left by 8, sum as i8s, and then shift as i16s
17679   // right by 8. It is important to shift as i16s as i8 vector shift isn't
17680   // directly supported.
17681   SmallVector<SDValue, 16> Shifters(NumElts, DAG.getConstant(8, DL, EltVT));
17682   SDValue Shifter = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters);
17683   SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, DAG.getBitcast(VT, V), Shifter);
17684   V = DAG.getNode(ISD::ADD, DL, ByteVecVT, DAG.getBitcast(ByteVecVT, Shl),
17685                   DAG.getBitcast(ByteVecVT, V));
17686   return DAG.getNode(ISD::SRL, DL, VT, DAG.getBitcast(VT, V), Shifter);
17687 }
17688
17689 static SDValue LowerVectorCTPOPInRegLUT(SDValue Op, SDLoc DL,
17690                                         const X86Subtarget *Subtarget,
17691                                         SelectionDAG &DAG) {
17692   MVT VT = Op.getSimpleValueType();
17693   MVT EltVT = VT.getVectorElementType();
17694   unsigned VecSize = VT.getSizeInBits();
17695
17696   // Implement a lookup table in register by using an algorithm based on:
17697   // http://wm.ite.pl/articles/sse-popcount.html
17698   //
17699   // The general idea is that every lower byte nibble in the input vector is an
17700   // index into a in-register pre-computed pop count table. We then split up the
17701   // input vector in two new ones: (1) a vector with only the shifted-right
17702   // higher nibbles for each byte and (2) a vector with the lower nibbles (and
17703   // masked out higher ones) for each byte. PSHUB is used separately with both
17704   // to index the in-register table. Next, both are added and the result is a
17705   // i8 vector where each element contains the pop count for input byte.
17706   //
17707   // To obtain the pop count for elements != i8, we follow up with the same
17708   // approach and use additional tricks as described below.
17709   //
17710   const int LUT[16] = {/* 0 */ 0, /* 1 */ 1, /* 2 */ 1, /* 3 */ 2,
17711                        /* 4 */ 1, /* 5 */ 2, /* 6 */ 2, /* 7 */ 3,
17712                        /* 8 */ 1, /* 9 */ 2, /* a */ 2, /* b */ 3,
17713                        /* c */ 2, /* d */ 3, /* e */ 3, /* f */ 4};
17714
17715   int NumByteElts = VecSize / 8;
17716   MVT ByteVecVT = MVT::getVectorVT(MVT::i8, NumByteElts);
17717   SDValue In = DAG.getBitcast(ByteVecVT, Op);
17718   SmallVector<SDValue, 16> LUTVec;
17719   for (int i = 0; i < NumByteElts; ++i)
17720     LUTVec.push_back(DAG.getConstant(LUT[i % 16], DL, MVT::i8));
17721   SDValue InRegLUT = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, LUTVec);
17722   SmallVector<SDValue, 16> Mask0F(NumByteElts,
17723                                   DAG.getConstant(0x0F, DL, MVT::i8));
17724   SDValue M0F = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Mask0F);
17725
17726   // High nibbles
17727   SmallVector<SDValue, 16> Four(NumByteElts, DAG.getConstant(4, DL, MVT::i8));
17728   SDValue FourV = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Four);
17729   SDValue HighNibbles = DAG.getNode(ISD::SRL, DL, ByteVecVT, In, FourV);
17730
17731   // Low nibbles
17732   SDValue LowNibbles = DAG.getNode(ISD::AND, DL, ByteVecVT, In, M0F);
17733
17734   // The input vector is used as the shuffle mask that index elements into the
17735   // LUT. After counting low and high nibbles, add the vector to obtain the
17736   // final pop count per i8 element.
17737   SDValue HighPopCnt =
17738       DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, HighNibbles);
17739   SDValue LowPopCnt =
17740       DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, LowNibbles);
17741   SDValue PopCnt = DAG.getNode(ISD::ADD, DL, ByteVecVT, HighPopCnt, LowPopCnt);
17742
17743   if (EltVT == MVT::i8)
17744     return PopCnt;
17745
17746   return LowerHorizontalByteSum(PopCnt, VT, Subtarget, DAG);
17747 }
17748
17749 static SDValue LowerVectorCTPOPBitmath(SDValue Op, SDLoc DL,
17750                                        const X86Subtarget *Subtarget,
17751                                        SelectionDAG &DAG) {
17752   MVT VT = Op.getSimpleValueType();
17753   assert(VT.is128BitVector() &&
17754          "Only 128-bit vector bitmath lowering supported.");
17755
17756   int VecSize = VT.getSizeInBits();
17757   MVT EltVT = VT.getVectorElementType();
17758   int Len = EltVT.getSizeInBits();
17759
17760   // This is the vectorized version of the "best" algorithm from
17761   // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
17762   // with a minor tweak to use a series of adds + shifts instead of vector
17763   // multiplications. Implemented for all integer vector types. We only use
17764   // this when we don't have SSSE3 which allows a LUT-based lowering that is
17765   // much faster, even faster than using native popcnt instructions.
17766
17767   auto GetShift = [&](unsigned OpCode, SDValue V, int Shifter) {
17768     MVT VT = V.getSimpleValueType();
17769     SmallVector<SDValue, 32> Shifters(
17770         VT.getVectorNumElements(),
17771         DAG.getConstant(Shifter, DL, VT.getVectorElementType()));
17772     return DAG.getNode(OpCode, DL, VT, V,
17773                        DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters));
17774   };
17775   auto GetMask = [&](SDValue V, APInt Mask) {
17776     MVT VT = V.getSimpleValueType();
17777     SmallVector<SDValue, 32> Masks(
17778         VT.getVectorNumElements(),
17779         DAG.getConstant(Mask, DL, VT.getVectorElementType()));
17780     return DAG.getNode(ISD::AND, DL, VT, V,
17781                        DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Masks));
17782   };
17783
17784   // We don't want to incur the implicit masks required to SRL vNi8 vectors on
17785   // x86, so set the SRL type to have elements at least i16 wide. This is
17786   // correct because all of our SRLs are followed immediately by a mask anyways
17787   // that handles any bits that sneak into the high bits of the byte elements.
17788   MVT SrlVT = Len > 8 ? VT : MVT::getVectorVT(MVT::i16, VecSize / 16);
17789
17790   SDValue V = Op;
17791
17792   // v = v - ((v >> 1) & 0x55555555...)
17793   SDValue Srl =
17794       DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 1));
17795   SDValue And = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x55)));
17796   V = DAG.getNode(ISD::SUB, DL, VT, V, And);
17797
17798   // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
17799   SDValue AndLHS = GetMask(V, APInt::getSplat(Len, APInt(8, 0x33)));
17800   Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 2));
17801   SDValue AndRHS = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x33)));
17802   V = DAG.getNode(ISD::ADD, DL, VT, AndLHS, AndRHS);
17803
17804   // v = (v + (v >> 4)) & 0x0F0F0F0F...
17805   Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 4));
17806   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, V, Srl);
17807   V = GetMask(Add, APInt::getSplat(Len, APInt(8, 0x0F)));
17808
17809   // At this point, V contains the byte-wise population count, and we are
17810   // merely doing a horizontal sum if necessary to get the wider element
17811   // counts.
17812   if (EltVT == MVT::i8)
17813     return V;
17814
17815   return LowerHorizontalByteSum(
17816       DAG.getBitcast(MVT::getVectorVT(MVT::i8, VecSize / 8), V), VT, Subtarget,
17817       DAG);
17818 }
17819
17820 static SDValue LowerVectorCTPOP(SDValue Op, const X86Subtarget *Subtarget,
17821                                 SelectionDAG &DAG) {
17822   MVT VT = Op.getSimpleValueType();
17823   // FIXME: Need to add AVX-512 support here!
17824   assert((VT.is256BitVector() || VT.is128BitVector()) &&
17825          "Unknown CTPOP type to handle");
17826   SDLoc DL(Op.getNode());
17827   SDValue Op0 = Op.getOperand(0);
17828
17829   if (!Subtarget->hasSSSE3()) {
17830     // We can't use the fast LUT approach, so fall back on vectorized bitmath.
17831     assert(VT.is128BitVector() && "Only 128-bit vectors supported in SSE!");
17832     return LowerVectorCTPOPBitmath(Op0, DL, Subtarget, DAG);
17833   }
17834
17835   if (VT.is256BitVector() && !Subtarget->hasInt256()) {
17836     unsigned NumElems = VT.getVectorNumElements();
17837
17838     // Extract each 128-bit vector, compute pop count and concat the result.
17839     SDValue LHS = Extract128BitVector(Op0, 0, DAG, DL);
17840     SDValue RHS = Extract128BitVector(Op0, NumElems/2, DAG, DL);
17841
17842     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT,
17843                        LowerVectorCTPOPInRegLUT(LHS, DL, Subtarget, DAG),
17844                        LowerVectorCTPOPInRegLUT(RHS, DL, Subtarget, DAG));
17845   }
17846
17847   return LowerVectorCTPOPInRegLUT(Op0, DL, Subtarget, DAG);
17848 }
17849
17850 static SDValue LowerCTPOP(SDValue Op, const X86Subtarget *Subtarget,
17851                           SelectionDAG &DAG) {
17852   assert(Op.getValueType().isVector() &&
17853          "We only do custom lowering for vector population count.");
17854   return LowerVectorCTPOP(Op, Subtarget, DAG);
17855 }
17856
17857 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
17858   SDNode *Node = Op.getNode();
17859   SDLoc dl(Node);
17860   EVT T = Node->getValueType(0);
17861   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
17862                               DAG.getConstant(0, dl, T), Node->getOperand(2));
17863   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
17864                        cast<AtomicSDNode>(Node)->getMemoryVT(),
17865                        Node->getOperand(0),
17866                        Node->getOperand(1), negOp,
17867                        cast<AtomicSDNode>(Node)->getMemOperand(),
17868                        cast<AtomicSDNode>(Node)->getOrdering(),
17869                        cast<AtomicSDNode>(Node)->getSynchScope());
17870 }
17871
17872 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
17873   SDNode *Node = Op.getNode();
17874   SDLoc dl(Node);
17875   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
17876
17877   // Convert seq_cst store -> xchg
17878   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
17879   // FIXME: On 32-bit, store -> fist or movq would be more efficient
17880   //        (The only way to get a 16-byte store is cmpxchg16b)
17881   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
17882   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
17883       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
17884     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
17885                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
17886                                  Node->getOperand(0),
17887                                  Node->getOperand(1), Node->getOperand(2),
17888                                  cast<AtomicSDNode>(Node)->getMemOperand(),
17889                                  cast<AtomicSDNode>(Node)->getOrdering(),
17890                                  cast<AtomicSDNode>(Node)->getSynchScope());
17891     return Swap.getValue(1);
17892   }
17893   // Other atomic stores have a simple pattern.
17894   return Op;
17895 }
17896
17897 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
17898   EVT VT = Op.getNode()->getSimpleValueType(0);
17899
17900   // Let legalize expand this if it isn't a legal type yet.
17901   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
17902     return SDValue();
17903
17904   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
17905
17906   unsigned Opc;
17907   bool ExtraOp = false;
17908   switch (Op.getOpcode()) {
17909   default: llvm_unreachable("Invalid code");
17910   case ISD::ADDC: Opc = X86ISD::ADD; break;
17911   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
17912   case ISD::SUBC: Opc = X86ISD::SUB; break;
17913   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
17914   }
17915
17916   if (!ExtraOp)
17917     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
17918                        Op.getOperand(1));
17919   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
17920                      Op.getOperand(1), Op.getOperand(2));
17921 }
17922
17923 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
17924                             SelectionDAG &DAG) {
17925   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
17926
17927   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
17928   // which returns the values as { float, float } (in XMM0) or
17929   // { double, double } (which is returned in XMM0, XMM1).
17930   SDLoc dl(Op);
17931   SDValue Arg = Op.getOperand(0);
17932   EVT ArgVT = Arg.getValueType();
17933   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
17934
17935   TargetLowering::ArgListTy Args;
17936   TargetLowering::ArgListEntry Entry;
17937
17938   Entry.Node = Arg;
17939   Entry.Ty = ArgTy;
17940   Entry.isSExt = false;
17941   Entry.isZExt = false;
17942   Args.push_back(Entry);
17943
17944   bool isF64 = ArgVT == MVT::f64;
17945   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
17946   // the small struct {f32, f32} is returned in (eax, edx). For f64,
17947   // the results are returned via SRet in memory.
17948   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
17949   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17950   SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
17951
17952   Type *RetTy = isF64
17953     ? (Type*)StructType::get(ArgTy, ArgTy, nullptr)
17954     : (Type*)VectorType::get(ArgTy, 4);
17955
17956   TargetLowering::CallLoweringInfo CLI(DAG);
17957   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
17958     .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
17959
17960   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
17961
17962   if (isF64)
17963     // Returned in xmm0 and xmm1.
17964     return CallResult.first;
17965
17966   // Returned in bits 0:31 and 32:64 xmm0.
17967   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
17968                                CallResult.first, DAG.getIntPtrConstant(0, dl));
17969   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
17970                                CallResult.first, DAG.getIntPtrConstant(1, dl));
17971   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
17972   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
17973 }
17974
17975 static SDValue LowerMSCATTER(SDValue Op, const X86Subtarget *Subtarget,
17976                              SelectionDAG &DAG) {
17977   assert(Subtarget->hasAVX512() &&
17978          "MGATHER/MSCATTER are supported on AVX-512 arch only");
17979
17980   MaskedScatterSDNode *N = cast<MaskedScatterSDNode>(Op.getNode());
17981   EVT VT = N->getValue().getValueType();
17982   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported scatter op");
17983   SDLoc dl(Op);
17984
17985   // X86 scatter kills mask register, so its type should be added to
17986   // the list of return values
17987   if (N->getNumValues() == 1) {
17988     SDValue Index = N->getIndex();
17989     if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
17990         !Index.getValueType().is512BitVector())
17991       Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
17992
17993     SDVTList VTs = DAG.getVTList(N->getMask().getValueType(), MVT::Other);
17994     SDValue Ops[] = { N->getOperand(0), N->getOperand(1),  N->getOperand(2),
17995                       N->getOperand(3), Index };
17996
17997     SDValue NewScatter = DAG.getMaskedScatter(VTs, VT, dl, Ops, N->getMemOperand());
17998     DAG.ReplaceAllUsesWith(Op, SDValue(NewScatter.getNode(), 1));
17999     return SDValue(NewScatter.getNode(), 0);
18000   }
18001   return Op;
18002 }
18003
18004 static SDValue LowerMGATHER(SDValue Op, const X86Subtarget *Subtarget,
18005                             SelectionDAG &DAG) {
18006   assert(Subtarget->hasAVX512() &&
18007          "MGATHER/MSCATTER are supported on AVX-512 arch only");
18008
18009   MaskedGatherSDNode *N = cast<MaskedGatherSDNode>(Op.getNode());
18010   EVT VT = Op.getValueType();
18011   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported gather op");
18012   SDLoc dl(Op);
18013
18014   SDValue Index = N->getIndex();
18015   if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
18016       !Index.getValueType().is512BitVector()) {
18017     Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
18018     SDValue Ops[] = { N->getOperand(0), N->getOperand(1),  N->getOperand(2),
18019                       N->getOperand(3), Index };
18020     DAG.UpdateNodeOperands(N, Ops);
18021   }
18022   return Op;
18023 }
18024
18025 SDValue X86TargetLowering::LowerGC_TRANSITION_START(SDValue Op,
18026                                                     SelectionDAG &DAG) const {
18027   // TODO: Eventually, the lowering of these nodes should be informed by or
18028   // deferred to the GC strategy for the function in which they appear. For
18029   // now, however, they must be lowered to something. Since they are logically
18030   // no-ops in the case of a null GC strategy (or a GC strategy which does not
18031   // require special handling for these nodes), lower them as literal NOOPs for
18032   // the time being.
18033   SmallVector<SDValue, 2> Ops;
18034
18035   Ops.push_back(Op.getOperand(0));
18036   if (Op->getGluedNode())
18037     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
18038
18039   SDLoc OpDL(Op);
18040   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
18041   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
18042
18043   return NOOP;
18044 }
18045
18046 SDValue X86TargetLowering::LowerGC_TRANSITION_END(SDValue Op,
18047                                                   SelectionDAG &DAG) const {
18048   // TODO: Eventually, the lowering of these nodes should be informed by or
18049   // deferred to the GC strategy for the function in which they appear. For
18050   // now, however, they must be lowered to something. Since they are logically
18051   // no-ops in the case of a null GC strategy (or a GC strategy which does not
18052   // require special handling for these nodes), lower them as literal NOOPs for
18053   // the time being.
18054   SmallVector<SDValue, 2> Ops;
18055
18056   Ops.push_back(Op.getOperand(0));
18057   if (Op->getGluedNode())
18058     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
18059
18060   SDLoc OpDL(Op);
18061   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
18062   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
18063
18064   return NOOP;
18065 }
18066
18067 /// LowerOperation - Provide custom lowering hooks for some operations.
18068 ///
18069 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
18070   switch (Op.getOpcode()) {
18071   default: llvm_unreachable("Should not custom lower this!");
18072   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
18073   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
18074     return LowerCMP_SWAP(Op, Subtarget, DAG);
18075   case ISD::CTPOP:              return LowerCTPOP(Op, Subtarget, DAG);
18076   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
18077   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
18078   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
18079   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, Subtarget, DAG);
18080   case ISD::VECTOR_SHUFFLE:     return lowerVectorShuffle(Op, Subtarget, DAG);
18081   case ISD::VSELECT:            return LowerVSELECT(Op, DAG);
18082   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
18083   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
18084   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
18085   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
18086   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
18087   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
18088   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
18089   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
18090   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
18091   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
18092   case ISD::SHL_PARTS:
18093   case ISD::SRA_PARTS:
18094   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
18095   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
18096   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
18097   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
18098   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
18099   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
18100   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
18101   case ISD::SIGN_EXTEND_VECTOR_INREG:
18102     return LowerSIGN_EXTEND_VECTOR_INREG(Op, Subtarget, DAG);
18103   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
18104   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
18105   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
18106   case ISD::LOAD:               return LowerExtendedLoad(Op, Subtarget, DAG);
18107   case ISD::FABS:
18108   case ISD::FNEG:               return LowerFABSorFNEG(Op, DAG);
18109   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
18110   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
18111   case ISD::SETCC:              return LowerSETCC(Op, DAG);
18112   case ISD::SELECT:             return LowerSELECT(Op, DAG);
18113   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
18114   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
18115   case ISD::VASTART:            return LowerVASTART(Op, DAG);
18116   case ISD::VAARG:              return LowerVAARG(Op, DAG);
18117   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
18118   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, Subtarget, DAG);
18119   case ISD::INTRINSIC_VOID:
18120   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
18121   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
18122   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
18123   case ISD::FRAME_TO_ARGS_OFFSET:
18124                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
18125   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
18126   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
18127   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
18128   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
18129   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
18130   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
18131   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
18132   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
18133   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
18134   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
18135   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
18136   case ISD::UMUL_LOHI:
18137   case ISD::SMUL_LOHI:          return LowerMUL_LOHI(Op, Subtarget, DAG);
18138   case ISD::SRA:
18139   case ISD::SRL:
18140   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
18141   case ISD::SADDO:
18142   case ISD::UADDO:
18143   case ISD::SSUBO:
18144   case ISD::USUBO:
18145   case ISD::SMULO:
18146   case ISD::UMULO:              return LowerXALUO(Op, DAG);
18147   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
18148   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
18149   case ISD::ADDC:
18150   case ISD::ADDE:
18151   case ISD::SUBC:
18152   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
18153   case ISD::ADD:                return LowerADD(Op, DAG);
18154   case ISD::SUB:                return LowerSUB(Op, DAG);
18155   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
18156   case ISD::MGATHER:            return LowerMGATHER(Op, Subtarget, DAG);
18157   case ISD::MSCATTER:           return LowerMSCATTER(Op, Subtarget, DAG);
18158   case ISD::GC_TRANSITION_START:
18159                                 return LowerGC_TRANSITION_START(Op, DAG);
18160   case ISD::GC_TRANSITION_END:  return LowerGC_TRANSITION_END(Op, DAG);
18161   }
18162 }
18163
18164 /// ReplaceNodeResults - Replace a node with an illegal result type
18165 /// with a new node built out of custom code.
18166 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
18167                                            SmallVectorImpl<SDValue>&Results,
18168                                            SelectionDAG &DAG) const {
18169   SDLoc dl(N);
18170   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18171   switch (N->getOpcode()) {
18172   default:
18173     llvm_unreachable("Do not know how to custom type legalize this operation!");
18174   // We might have generated v2f32 FMIN/FMAX operations. Widen them to v4f32.
18175   case X86ISD::FMINC:
18176   case X86ISD::FMIN:
18177   case X86ISD::FMAXC:
18178   case X86ISD::FMAX: {
18179     EVT VT = N->getValueType(0);
18180     if (VT != MVT::v2f32)
18181       llvm_unreachable("Unexpected type (!= v2f32) on FMIN/FMAX.");
18182     SDValue UNDEF = DAG.getUNDEF(VT);
18183     SDValue LHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
18184                               N->getOperand(0), UNDEF);
18185     SDValue RHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
18186                               N->getOperand(1), UNDEF);
18187     Results.push_back(DAG.getNode(N->getOpcode(), dl, MVT::v4f32, LHS, RHS));
18188     return;
18189   }
18190   case ISD::SIGN_EXTEND_INREG:
18191   case ISD::ADDC:
18192   case ISD::ADDE:
18193   case ISD::SUBC:
18194   case ISD::SUBE:
18195     // We don't want to expand or promote these.
18196     return;
18197   case ISD::SDIV:
18198   case ISD::UDIV:
18199   case ISD::SREM:
18200   case ISD::UREM:
18201   case ISD::SDIVREM:
18202   case ISD::UDIVREM: {
18203     SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
18204     Results.push_back(V);
18205     return;
18206   }
18207   case ISD::FP_TO_SINT:
18208     // FP_TO_INT*_IN_MEM is not legal for f16 inputs.  Do not convert
18209     // (FP_TO_SINT (load f16)) to FP_TO_INT*.
18210     if (N->getOperand(0).getValueType() == MVT::f16)
18211       break;
18212     // fallthrough
18213   case ISD::FP_TO_UINT: {
18214     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
18215
18216     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
18217       return;
18218
18219     std::pair<SDValue,SDValue> Vals =
18220         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
18221     SDValue FIST = Vals.first, StackSlot = Vals.second;
18222     if (FIST.getNode()) {
18223       EVT VT = N->getValueType(0);
18224       // Return a load from the stack slot.
18225       if (StackSlot.getNode())
18226         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
18227                                       MachinePointerInfo(),
18228                                       false, false, false, 0));
18229       else
18230         Results.push_back(FIST);
18231     }
18232     return;
18233   }
18234   case ISD::UINT_TO_FP: {
18235     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
18236     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
18237         N->getValueType(0) != MVT::v2f32)
18238       return;
18239     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
18240                                  N->getOperand(0));
18241     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
18242                                      MVT::f64);
18243     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
18244     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
18245                              DAG.getBitcast(MVT::v2i64, VBias));
18246     Or = DAG.getBitcast(MVT::v2f64, Or);
18247     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
18248     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
18249     return;
18250   }
18251   case ISD::FP_ROUND: {
18252     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
18253         return;
18254     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
18255     Results.push_back(V);
18256     return;
18257   }
18258   case ISD::FP_EXTEND: {
18259     // Right now, only MVT::v2f32 has OperationAction for FP_EXTEND.
18260     // No other ValueType for FP_EXTEND should reach this point.
18261     assert(N->getValueType(0) == MVT::v2f32 &&
18262            "Do not know how to legalize this Node");
18263     return;
18264   }
18265   case ISD::INTRINSIC_W_CHAIN: {
18266     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
18267     switch (IntNo) {
18268     default : llvm_unreachable("Do not know how to custom type "
18269                                "legalize this intrinsic operation!");
18270     case Intrinsic::x86_rdtsc:
18271       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
18272                                      Results);
18273     case Intrinsic::x86_rdtscp:
18274       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
18275                                      Results);
18276     case Intrinsic::x86_rdpmc:
18277       return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
18278     }
18279   }
18280   case ISD::READCYCLECOUNTER: {
18281     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
18282                                    Results);
18283   }
18284   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
18285     EVT T = N->getValueType(0);
18286     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
18287     bool Regs64bit = T == MVT::i128;
18288     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
18289     SDValue cpInL, cpInH;
18290     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
18291                         DAG.getConstant(0, dl, HalfT));
18292     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
18293                         DAG.getConstant(1, dl, HalfT));
18294     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
18295                              Regs64bit ? X86::RAX : X86::EAX,
18296                              cpInL, SDValue());
18297     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
18298                              Regs64bit ? X86::RDX : X86::EDX,
18299                              cpInH, cpInL.getValue(1));
18300     SDValue swapInL, swapInH;
18301     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
18302                           DAG.getConstant(0, dl, HalfT));
18303     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
18304                           DAG.getConstant(1, dl, HalfT));
18305     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
18306                                Regs64bit ? X86::RBX : X86::EBX,
18307                                swapInL, cpInH.getValue(1));
18308     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
18309                                Regs64bit ? X86::RCX : X86::ECX,
18310                                swapInH, swapInL.getValue(1));
18311     SDValue Ops[] = { swapInH.getValue(0),
18312                       N->getOperand(1),
18313                       swapInH.getValue(1) };
18314     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
18315     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
18316     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
18317                                   X86ISD::LCMPXCHG8_DAG;
18318     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
18319     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
18320                                         Regs64bit ? X86::RAX : X86::EAX,
18321                                         HalfT, Result.getValue(1));
18322     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
18323                                         Regs64bit ? X86::RDX : X86::EDX,
18324                                         HalfT, cpOutL.getValue(2));
18325     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
18326
18327     SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
18328                                         MVT::i32, cpOutH.getValue(2));
18329     SDValue Success =
18330         DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
18331                     DAG.getConstant(X86::COND_E, dl, MVT::i8), EFLAGS);
18332     Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
18333
18334     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
18335     Results.push_back(Success);
18336     Results.push_back(EFLAGS.getValue(1));
18337     return;
18338   }
18339   case ISD::ATOMIC_SWAP:
18340   case ISD::ATOMIC_LOAD_ADD:
18341   case ISD::ATOMIC_LOAD_SUB:
18342   case ISD::ATOMIC_LOAD_AND:
18343   case ISD::ATOMIC_LOAD_OR:
18344   case ISD::ATOMIC_LOAD_XOR:
18345   case ISD::ATOMIC_LOAD_NAND:
18346   case ISD::ATOMIC_LOAD_MIN:
18347   case ISD::ATOMIC_LOAD_MAX:
18348   case ISD::ATOMIC_LOAD_UMIN:
18349   case ISD::ATOMIC_LOAD_UMAX:
18350   case ISD::ATOMIC_LOAD: {
18351     // Delegate to generic TypeLegalization. Situations we can really handle
18352     // should have already been dealt with by AtomicExpandPass.cpp.
18353     break;
18354   }
18355   case ISD::BITCAST: {
18356     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
18357     EVT DstVT = N->getValueType(0);
18358     EVT SrcVT = N->getOperand(0)->getValueType(0);
18359
18360     if (SrcVT != MVT::f64 ||
18361         (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
18362       return;
18363
18364     unsigned NumElts = DstVT.getVectorNumElements();
18365     EVT SVT = DstVT.getVectorElementType();
18366     EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
18367     SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
18368                                    MVT::v2f64, N->getOperand(0));
18369     SDValue ToVecInt = DAG.getBitcast(WiderVT, Expanded);
18370
18371     if (ExperimentalVectorWideningLegalization) {
18372       // If we are legalizing vectors by widening, we already have the desired
18373       // legal vector type, just return it.
18374       Results.push_back(ToVecInt);
18375       return;
18376     }
18377
18378     SmallVector<SDValue, 8> Elts;
18379     for (unsigned i = 0, e = NumElts; i != e; ++i)
18380       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
18381                                    ToVecInt, DAG.getIntPtrConstant(i, dl)));
18382
18383     Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
18384   }
18385   }
18386 }
18387
18388 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
18389   switch ((X86ISD::NodeType)Opcode) {
18390   case X86ISD::FIRST_NUMBER:       break;
18391   case X86ISD::BSF:                return "X86ISD::BSF";
18392   case X86ISD::BSR:                return "X86ISD::BSR";
18393   case X86ISD::SHLD:               return "X86ISD::SHLD";
18394   case X86ISD::SHRD:               return "X86ISD::SHRD";
18395   case X86ISD::FAND:               return "X86ISD::FAND";
18396   case X86ISD::FANDN:              return "X86ISD::FANDN";
18397   case X86ISD::FOR:                return "X86ISD::FOR";
18398   case X86ISD::FXOR:               return "X86ISD::FXOR";
18399   case X86ISD::FILD:               return "X86ISD::FILD";
18400   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
18401   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
18402   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
18403   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
18404   case X86ISD::FLD:                return "X86ISD::FLD";
18405   case X86ISD::FST:                return "X86ISD::FST";
18406   case X86ISD::CALL:               return "X86ISD::CALL";
18407   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
18408   case X86ISD::RDTSCP_DAG:         return "X86ISD::RDTSCP_DAG";
18409   case X86ISD::RDPMC_DAG:          return "X86ISD::RDPMC_DAG";
18410   case X86ISD::BT:                 return "X86ISD::BT";
18411   case X86ISD::CMP:                return "X86ISD::CMP";
18412   case X86ISD::COMI:               return "X86ISD::COMI";
18413   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
18414   case X86ISD::CMPM:               return "X86ISD::CMPM";
18415   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
18416   case X86ISD::CMPM_RND:           return "X86ISD::CMPM_RND";
18417   case X86ISD::SETCC:              return "X86ISD::SETCC";
18418   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
18419   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
18420   case X86ISD::FGETSIGNx86:        return "X86ISD::FGETSIGNx86";
18421   case X86ISD::CMOV:               return "X86ISD::CMOV";
18422   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
18423   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
18424   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
18425   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
18426   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
18427   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
18428   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
18429   case X86ISD::MOVDQ2Q:            return "X86ISD::MOVDQ2Q";
18430   case X86ISD::MMX_MOVD2W:         return "X86ISD::MMX_MOVD2W";
18431   case X86ISD::MMX_MOVW2D:         return "X86ISD::MMX_MOVW2D";
18432   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
18433   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
18434   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
18435   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
18436   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
18437   case X86ISD::MMX_PINSRW:         return "X86ISD::MMX_PINSRW";
18438   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
18439   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
18440   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
18441   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
18442   case X86ISD::SHRUNKBLEND:        return "X86ISD::SHRUNKBLEND";
18443   case X86ISD::ADDUS:              return "X86ISD::ADDUS";
18444   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
18445   case X86ISD::HADD:               return "X86ISD::HADD";
18446   case X86ISD::HSUB:               return "X86ISD::HSUB";
18447   case X86ISD::FHADD:              return "X86ISD::FHADD";
18448   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
18449   case X86ISD::UMAX:               return "X86ISD::UMAX";
18450   case X86ISD::UMIN:               return "X86ISD::UMIN";
18451   case X86ISD::SMAX:               return "X86ISD::SMAX";
18452   case X86ISD::SMIN:               return "X86ISD::SMIN";
18453   case X86ISD::ABS:                return "X86ISD::ABS";
18454   case X86ISD::FMAX:               return "X86ISD::FMAX";
18455   case X86ISD::FMAX_RND:           return "X86ISD::FMAX_RND";
18456   case X86ISD::FMIN:               return "X86ISD::FMIN";
18457   case X86ISD::FMIN_RND:           return "X86ISD::FMIN_RND";
18458   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
18459   case X86ISD::FMINC:              return "X86ISD::FMINC";
18460   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
18461   case X86ISD::FRCP:               return "X86ISD::FRCP";
18462   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
18463   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
18464   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
18465   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
18466   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
18467   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
18468   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
18469   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
18470   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
18471   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
18472   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
18473   case X86ISD::LCMPXCHG16_DAG:     return "X86ISD::LCMPXCHG16_DAG";
18474   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
18475   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
18476   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
18477   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
18478   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
18479   case X86ISD::VTRUNCM:            return "X86ISD::VTRUNCM";
18480   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
18481   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
18482   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
18483   case X86ISD::CVTDQ2PD:           return "X86ISD::CVTDQ2PD";
18484   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
18485   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
18486   case X86ISD::VSHL:               return "X86ISD::VSHL";
18487   case X86ISD::VSRL:               return "X86ISD::VSRL";
18488   case X86ISD::VSRA:               return "X86ISD::VSRA";
18489   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
18490   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
18491   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
18492   case X86ISD::CMPP:               return "X86ISD::CMPP";
18493   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
18494   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
18495   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
18496   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
18497   case X86ISD::ADD:                return "X86ISD::ADD";
18498   case X86ISD::SUB:                return "X86ISD::SUB";
18499   case X86ISD::ADC:                return "X86ISD::ADC";
18500   case X86ISD::SBB:                return "X86ISD::SBB";
18501   case X86ISD::SMUL:               return "X86ISD::SMUL";
18502   case X86ISD::UMUL:               return "X86ISD::UMUL";
18503   case X86ISD::SMUL8:              return "X86ISD::SMUL8";
18504   case X86ISD::UMUL8:              return "X86ISD::UMUL8";
18505   case X86ISD::SDIVREM8_SEXT_HREG: return "X86ISD::SDIVREM8_SEXT_HREG";
18506   case X86ISD::UDIVREM8_ZEXT_HREG: return "X86ISD::UDIVREM8_ZEXT_HREG";
18507   case X86ISD::INC:                return "X86ISD::INC";
18508   case X86ISD::DEC:                return "X86ISD::DEC";
18509   case X86ISD::OR:                 return "X86ISD::OR";
18510   case X86ISD::XOR:                return "X86ISD::XOR";
18511   case X86ISD::AND:                return "X86ISD::AND";
18512   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
18513   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
18514   case X86ISD::PTEST:              return "X86ISD::PTEST";
18515   case X86ISD::TESTP:              return "X86ISD::TESTP";
18516   case X86ISD::TESTM:              return "X86ISD::TESTM";
18517   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
18518   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
18519   case X86ISD::PACKSS:             return "X86ISD::PACKSS";
18520   case X86ISD::PACKUS:             return "X86ISD::PACKUS";
18521   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
18522   case X86ISD::VALIGN:             return "X86ISD::VALIGN";
18523   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
18524   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
18525   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
18526   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
18527   case X86ISD::SHUF128:            return "X86ISD::SHUF128";
18528   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
18529   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
18530   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
18531   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
18532   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
18533   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
18534   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
18535   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
18536   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
18537   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
18538   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
18539   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
18540   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
18541   case X86ISD::SUBV_BROADCAST:     return "X86ISD::SUBV_BROADCAST";
18542   case X86ISD::VEXTRACT:           return "X86ISD::VEXTRACT";
18543   case X86ISD::VPERMILPV:          return "X86ISD::VPERMILPV";
18544   case X86ISD::VPERMILPI:          return "X86ISD::VPERMILPI";
18545   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
18546   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
18547   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
18548   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
18549   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
18550   case X86ISD::VFIXUPIMM:          return "X86ISD::VFIXUPIMM";
18551   case X86ISD::VRANGE:             return "X86ISD::VRANGE";
18552   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
18553   case X86ISD::PMULDQ:             return "X86ISD::PMULDQ";
18554   case X86ISD::PSADBW:             return "X86ISD::PSADBW";
18555   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
18556   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
18557   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
18558   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
18559   case X86ISD::MFENCE:             return "X86ISD::MFENCE";
18560   case X86ISD::SFENCE:             return "X86ISD::SFENCE";
18561   case X86ISD::LFENCE:             return "X86ISD::LFENCE";
18562   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
18563   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
18564   case X86ISD::SAHF:               return "X86ISD::SAHF";
18565   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
18566   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
18567   case X86ISD::FMADD:              return "X86ISD::FMADD";
18568   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
18569   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
18570   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
18571   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
18572   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
18573   case X86ISD::FMADD_RND:          return "X86ISD::FMADD_RND";
18574   case X86ISD::FNMADD_RND:         return "X86ISD::FNMADD_RND";
18575   case X86ISD::FMSUB_RND:          return "X86ISD::FMSUB_RND";
18576   case X86ISD::FNMSUB_RND:         return "X86ISD::FNMSUB_RND";
18577   case X86ISD::FMADDSUB_RND:       return "X86ISD::FMADDSUB_RND";
18578   case X86ISD::FMSUBADD_RND:       return "X86ISD::FMSUBADD_RND";
18579   case X86ISD::RNDSCALE:           return "X86ISD::RNDSCALE";
18580   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
18581   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
18582   case X86ISD::XTEST:              return "X86ISD::XTEST";
18583   case X86ISD::COMPRESS:           return "X86ISD::COMPRESS";
18584   case X86ISD::EXPAND:             return "X86ISD::EXPAND";
18585   case X86ISD::SELECT:             return "X86ISD::SELECT";
18586   case X86ISD::ADDSUB:             return "X86ISD::ADDSUB";
18587   case X86ISD::RCP28:              return "X86ISD::RCP28";
18588   case X86ISD::EXP2:               return "X86ISD::EXP2";
18589   case X86ISD::RSQRT28:            return "X86ISD::RSQRT28";
18590   case X86ISD::FADD_RND:           return "X86ISD::FADD_RND";
18591   case X86ISD::FSUB_RND:           return "X86ISD::FSUB_RND";
18592   case X86ISD::FMUL_RND:           return "X86ISD::FMUL_RND";
18593   case X86ISD::FDIV_RND:           return "X86ISD::FDIV_RND";
18594   case X86ISD::FSQRT_RND:          return "X86ISD::FSQRT_RND";
18595   case X86ISD::FGETEXP_RND:        return "X86ISD::FGETEXP_RND";
18596   case X86ISD::SCALEF:             return "X86ISD::SCALEF";
18597   case X86ISD::ADDS:               return "X86ISD::ADDS";
18598   case X86ISD::SUBS:               return "X86ISD::SUBS";
18599   case X86ISD::AVG:                return "X86ISD::AVG";
18600   case X86ISD::SINT_TO_FP_RND:     return "X86ISD::SINT_TO_FP_RND";
18601   case X86ISD::UINT_TO_FP_RND:     return "X86ISD::UINT_TO_FP_RND";
18602   }
18603   return nullptr;
18604 }
18605
18606 // isLegalAddressingMode - Return true if the addressing mode represented
18607 // by AM is legal for this target, for a load/store of the specified type.
18608 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
18609                                               Type *Ty,
18610                                               unsigned AS) const {
18611   // X86 supports extremely general addressing modes.
18612   CodeModel::Model M = getTargetMachine().getCodeModel();
18613   Reloc::Model R = getTargetMachine().getRelocationModel();
18614
18615   // X86 allows a sign-extended 32-bit immediate field as a displacement.
18616   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
18617     return false;
18618
18619   if (AM.BaseGV) {
18620     unsigned GVFlags =
18621       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
18622
18623     // If a reference to this global requires an extra load, we can't fold it.
18624     if (isGlobalStubReference(GVFlags))
18625       return false;
18626
18627     // If BaseGV requires a register for the PIC base, we cannot also have a
18628     // BaseReg specified.
18629     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
18630       return false;
18631
18632     // If lower 4G is not available, then we must use rip-relative addressing.
18633     if ((M != CodeModel::Small || R != Reloc::Static) &&
18634         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
18635       return false;
18636   }
18637
18638   switch (AM.Scale) {
18639   case 0:
18640   case 1:
18641   case 2:
18642   case 4:
18643   case 8:
18644     // These scales always work.
18645     break;
18646   case 3:
18647   case 5:
18648   case 9:
18649     // These scales are formed with basereg+scalereg.  Only accept if there is
18650     // no basereg yet.
18651     if (AM.HasBaseReg)
18652       return false;
18653     break;
18654   default:  // Other stuff never works.
18655     return false;
18656   }
18657
18658   return true;
18659 }
18660
18661 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
18662   unsigned Bits = Ty->getScalarSizeInBits();
18663
18664   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
18665   // particularly cheaper than those without.
18666   if (Bits == 8)
18667     return false;
18668
18669   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
18670   // variable shifts just as cheap as scalar ones.
18671   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
18672     return false;
18673
18674   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
18675   // fully general vector.
18676   return true;
18677 }
18678
18679 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
18680   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
18681     return false;
18682   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
18683   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
18684   return NumBits1 > NumBits2;
18685 }
18686
18687 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
18688   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
18689     return false;
18690
18691   if (!isTypeLegal(EVT::getEVT(Ty1)))
18692     return false;
18693
18694   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
18695
18696   // Assuming the caller doesn't have a zeroext or signext return parameter,
18697   // truncation all the way down to i1 is valid.
18698   return true;
18699 }
18700
18701 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
18702   return isInt<32>(Imm);
18703 }
18704
18705 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
18706   // Can also use sub to handle negated immediates.
18707   return isInt<32>(Imm);
18708 }
18709
18710 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
18711   if (!VT1.isInteger() || !VT2.isInteger())
18712     return false;
18713   unsigned NumBits1 = VT1.getSizeInBits();
18714   unsigned NumBits2 = VT2.getSizeInBits();
18715   return NumBits1 > NumBits2;
18716 }
18717
18718 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
18719   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
18720   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
18721 }
18722
18723 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
18724   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
18725   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
18726 }
18727
18728 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
18729   EVT VT1 = Val.getValueType();
18730   if (isZExtFree(VT1, VT2))
18731     return true;
18732
18733   if (Val.getOpcode() != ISD::LOAD)
18734     return false;
18735
18736   if (!VT1.isSimple() || !VT1.isInteger() ||
18737       !VT2.isSimple() || !VT2.isInteger())
18738     return false;
18739
18740   switch (VT1.getSimpleVT().SimpleTy) {
18741   default: break;
18742   case MVT::i8:
18743   case MVT::i16:
18744   case MVT::i32:
18745     // X86 has 8, 16, and 32-bit zero-extending loads.
18746     return true;
18747   }
18748
18749   return false;
18750 }
18751
18752 bool X86TargetLowering::isVectorLoadExtDesirable(SDValue) const { return true; }
18753
18754 bool
18755 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
18756   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4() || Subtarget->hasAVX512()))
18757     return false;
18758
18759   VT = VT.getScalarType();
18760
18761   if (!VT.isSimple())
18762     return false;
18763
18764   switch (VT.getSimpleVT().SimpleTy) {
18765   case MVT::f32:
18766   case MVT::f64:
18767     return true;
18768   default:
18769     break;
18770   }
18771
18772   return false;
18773 }
18774
18775 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
18776   // i16 instructions are longer (0x66 prefix) and potentially slower.
18777   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
18778 }
18779
18780 /// isShuffleMaskLegal - Targets can use this to indicate that they only
18781 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
18782 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
18783 /// are assumed to be legal.
18784 bool
18785 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
18786                                       EVT VT) const {
18787   if (!VT.isSimple())
18788     return false;
18789
18790   // Not for i1 vectors
18791   if (VT.getScalarType() == MVT::i1)
18792     return false;
18793
18794   // Very little shuffling can be done for 64-bit vectors right now.
18795   if (VT.getSizeInBits() == 64)
18796     return false;
18797
18798   // We only care that the types being shuffled are legal. The lowering can
18799   // handle any possible shuffle mask that results.
18800   return isTypeLegal(VT.getSimpleVT());
18801 }
18802
18803 bool
18804 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
18805                                           EVT VT) const {
18806   // Just delegate to the generic legality, clear masks aren't special.
18807   return isShuffleMaskLegal(Mask, VT);
18808 }
18809
18810 //===----------------------------------------------------------------------===//
18811 //                           X86 Scheduler Hooks
18812 //===----------------------------------------------------------------------===//
18813
18814 /// Utility function to emit xbegin specifying the start of an RTM region.
18815 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
18816                                      const TargetInstrInfo *TII) {
18817   DebugLoc DL = MI->getDebugLoc();
18818
18819   const BasicBlock *BB = MBB->getBasicBlock();
18820   MachineFunction::iterator I = MBB;
18821   ++I;
18822
18823   // For the v = xbegin(), we generate
18824   //
18825   // thisMBB:
18826   //  xbegin sinkMBB
18827   //
18828   // mainMBB:
18829   //  eax = -1
18830   //
18831   // sinkMBB:
18832   //  v = eax
18833
18834   MachineBasicBlock *thisMBB = MBB;
18835   MachineFunction *MF = MBB->getParent();
18836   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
18837   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
18838   MF->insert(I, mainMBB);
18839   MF->insert(I, sinkMBB);
18840
18841   // Transfer the remainder of BB and its successor edges to sinkMBB.
18842   sinkMBB->splice(sinkMBB->begin(), MBB,
18843                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
18844   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
18845
18846   // thisMBB:
18847   //  xbegin sinkMBB
18848   //  # fallthrough to mainMBB
18849   //  # abortion to sinkMBB
18850   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
18851   thisMBB->addSuccessor(mainMBB);
18852   thisMBB->addSuccessor(sinkMBB);
18853
18854   // mainMBB:
18855   //  EAX = -1
18856   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
18857   mainMBB->addSuccessor(sinkMBB);
18858
18859   // sinkMBB:
18860   // EAX is live into the sinkMBB
18861   sinkMBB->addLiveIn(X86::EAX);
18862   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
18863           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
18864     .addReg(X86::EAX);
18865
18866   MI->eraseFromParent();
18867   return sinkMBB;
18868 }
18869
18870 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
18871 // or XMM0_V32I8 in AVX all of this code can be replaced with that
18872 // in the .td file.
18873 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
18874                                        const TargetInstrInfo *TII) {
18875   unsigned Opc;
18876   switch (MI->getOpcode()) {
18877   default: llvm_unreachable("illegal opcode!");
18878   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
18879   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
18880   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
18881   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
18882   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
18883   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
18884   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
18885   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
18886   }
18887
18888   DebugLoc dl = MI->getDebugLoc();
18889   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
18890
18891   unsigned NumArgs = MI->getNumOperands();
18892   for (unsigned i = 1; i < NumArgs; ++i) {
18893     MachineOperand &Op = MI->getOperand(i);
18894     if (!(Op.isReg() && Op.isImplicit()))
18895       MIB.addOperand(Op);
18896   }
18897   if (MI->hasOneMemOperand())
18898     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
18899
18900   BuildMI(*BB, MI, dl,
18901     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
18902     .addReg(X86::XMM0);
18903
18904   MI->eraseFromParent();
18905   return BB;
18906 }
18907
18908 // FIXME: Custom handling because TableGen doesn't support multiple implicit
18909 // defs in an instruction pattern
18910 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
18911                                        const TargetInstrInfo *TII) {
18912   unsigned Opc;
18913   switch (MI->getOpcode()) {
18914   default: llvm_unreachable("illegal opcode!");
18915   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
18916   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
18917   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
18918   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
18919   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
18920   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
18921   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
18922   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
18923   }
18924
18925   DebugLoc dl = MI->getDebugLoc();
18926   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
18927
18928   unsigned NumArgs = MI->getNumOperands(); // remove the results
18929   for (unsigned i = 1; i < NumArgs; ++i) {
18930     MachineOperand &Op = MI->getOperand(i);
18931     if (!(Op.isReg() && Op.isImplicit()))
18932       MIB.addOperand(Op);
18933   }
18934   if (MI->hasOneMemOperand())
18935     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
18936
18937   BuildMI(*BB, MI, dl,
18938     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
18939     .addReg(X86::ECX);
18940
18941   MI->eraseFromParent();
18942   return BB;
18943 }
18944
18945 static MachineBasicBlock *EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
18946                                       const X86Subtarget *Subtarget) {
18947   DebugLoc dl = MI->getDebugLoc();
18948   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18949   // Address into RAX/EAX, other two args into ECX, EDX.
18950   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
18951   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
18952   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
18953   for (int i = 0; i < X86::AddrNumOperands; ++i)
18954     MIB.addOperand(MI->getOperand(i));
18955
18956   unsigned ValOps = X86::AddrNumOperands;
18957   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
18958     .addReg(MI->getOperand(ValOps).getReg());
18959   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
18960     .addReg(MI->getOperand(ValOps+1).getReg());
18961
18962   // The instruction doesn't actually take any operands though.
18963   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
18964
18965   MI->eraseFromParent(); // The pseudo is gone now.
18966   return BB;
18967 }
18968
18969 MachineBasicBlock *
18970 X86TargetLowering::EmitVAARG64WithCustomInserter(MachineInstr *MI,
18971                                                  MachineBasicBlock *MBB) const {
18972   // Emit va_arg instruction on X86-64.
18973
18974   // Operands to this pseudo-instruction:
18975   // 0  ) Output        : destination address (reg)
18976   // 1-5) Input         : va_list address (addr, i64mem)
18977   // 6  ) ArgSize       : Size (in bytes) of vararg type
18978   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
18979   // 8  ) Align         : Alignment of type
18980   // 9  ) EFLAGS (implicit-def)
18981
18982   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
18983   static_assert(X86::AddrNumOperands == 5,
18984                 "VAARG_64 assumes 5 address operands");
18985
18986   unsigned DestReg = MI->getOperand(0).getReg();
18987   MachineOperand &Base = MI->getOperand(1);
18988   MachineOperand &Scale = MI->getOperand(2);
18989   MachineOperand &Index = MI->getOperand(3);
18990   MachineOperand &Disp = MI->getOperand(4);
18991   MachineOperand &Segment = MI->getOperand(5);
18992   unsigned ArgSize = MI->getOperand(6).getImm();
18993   unsigned ArgMode = MI->getOperand(7).getImm();
18994   unsigned Align = MI->getOperand(8).getImm();
18995
18996   // Memory Reference
18997   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
18998   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
18999   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
19000
19001   // Machine Information
19002   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19003   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
19004   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
19005   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
19006   DebugLoc DL = MI->getDebugLoc();
19007
19008   // struct va_list {
19009   //   i32   gp_offset
19010   //   i32   fp_offset
19011   //   i64   overflow_area (address)
19012   //   i64   reg_save_area (address)
19013   // }
19014   // sizeof(va_list) = 24
19015   // alignment(va_list) = 8
19016
19017   unsigned TotalNumIntRegs = 6;
19018   unsigned TotalNumXMMRegs = 8;
19019   bool UseGPOffset = (ArgMode == 1);
19020   bool UseFPOffset = (ArgMode == 2);
19021   unsigned MaxOffset = TotalNumIntRegs * 8 +
19022                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
19023
19024   /* Align ArgSize to a multiple of 8 */
19025   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
19026   bool NeedsAlign = (Align > 8);
19027
19028   MachineBasicBlock *thisMBB = MBB;
19029   MachineBasicBlock *overflowMBB;
19030   MachineBasicBlock *offsetMBB;
19031   MachineBasicBlock *endMBB;
19032
19033   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
19034   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
19035   unsigned OffsetReg = 0;
19036
19037   if (!UseGPOffset && !UseFPOffset) {
19038     // If we only pull from the overflow region, we don't create a branch.
19039     // We don't need to alter control flow.
19040     OffsetDestReg = 0; // unused
19041     OverflowDestReg = DestReg;
19042
19043     offsetMBB = nullptr;
19044     overflowMBB = thisMBB;
19045     endMBB = thisMBB;
19046   } else {
19047     // First emit code to check if gp_offset (or fp_offset) is below the bound.
19048     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
19049     // If not, pull from overflow_area. (branch to overflowMBB)
19050     //
19051     //       thisMBB
19052     //         |     .
19053     //         |        .
19054     //     offsetMBB   overflowMBB
19055     //         |        .
19056     //         |     .
19057     //        endMBB
19058
19059     // Registers for the PHI in endMBB
19060     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
19061     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
19062
19063     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
19064     MachineFunction *MF = MBB->getParent();
19065     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19066     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19067     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19068
19069     MachineFunction::iterator MBBIter = MBB;
19070     ++MBBIter;
19071
19072     // Insert the new basic blocks
19073     MF->insert(MBBIter, offsetMBB);
19074     MF->insert(MBBIter, overflowMBB);
19075     MF->insert(MBBIter, endMBB);
19076
19077     // Transfer the remainder of MBB and its successor edges to endMBB.
19078     endMBB->splice(endMBB->begin(), thisMBB,
19079                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
19080     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
19081
19082     // Make offsetMBB and overflowMBB successors of thisMBB
19083     thisMBB->addSuccessor(offsetMBB);
19084     thisMBB->addSuccessor(overflowMBB);
19085
19086     // endMBB is a successor of both offsetMBB and overflowMBB
19087     offsetMBB->addSuccessor(endMBB);
19088     overflowMBB->addSuccessor(endMBB);
19089
19090     // Load the offset value into a register
19091     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
19092     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
19093       .addOperand(Base)
19094       .addOperand(Scale)
19095       .addOperand(Index)
19096       .addDisp(Disp, UseFPOffset ? 4 : 0)
19097       .addOperand(Segment)
19098       .setMemRefs(MMOBegin, MMOEnd);
19099
19100     // Check if there is enough room left to pull this argument.
19101     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
19102       .addReg(OffsetReg)
19103       .addImm(MaxOffset + 8 - ArgSizeA8);
19104
19105     // Branch to "overflowMBB" if offset >= max
19106     // Fall through to "offsetMBB" otherwise
19107     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
19108       .addMBB(overflowMBB);
19109   }
19110
19111   // In offsetMBB, emit code to use the reg_save_area.
19112   if (offsetMBB) {
19113     assert(OffsetReg != 0);
19114
19115     // Read the reg_save_area address.
19116     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
19117     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
19118       .addOperand(Base)
19119       .addOperand(Scale)
19120       .addOperand(Index)
19121       .addDisp(Disp, 16)
19122       .addOperand(Segment)
19123       .setMemRefs(MMOBegin, MMOEnd);
19124
19125     // Zero-extend the offset
19126     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
19127       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
19128         .addImm(0)
19129         .addReg(OffsetReg)
19130         .addImm(X86::sub_32bit);
19131
19132     // Add the offset to the reg_save_area to get the final address.
19133     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
19134       .addReg(OffsetReg64)
19135       .addReg(RegSaveReg);
19136
19137     // Compute the offset for the next argument
19138     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
19139     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
19140       .addReg(OffsetReg)
19141       .addImm(UseFPOffset ? 16 : 8);
19142
19143     // Store it back into the va_list.
19144     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
19145       .addOperand(Base)
19146       .addOperand(Scale)
19147       .addOperand(Index)
19148       .addDisp(Disp, UseFPOffset ? 4 : 0)
19149       .addOperand(Segment)
19150       .addReg(NextOffsetReg)
19151       .setMemRefs(MMOBegin, MMOEnd);
19152
19153     // Jump to endMBB
19154     BuildMI(offsetMBB, DL, TII->get(X86::JMP_1))
19155       .addMBB(endMBB);
19156   }
19157
19158   //
19159   // Emit code to use overflow area
19160   //
19161
19162   // Load the overflow_area address into a register.
19163   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
19164   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
19165     .addOperand(Base)
19166     .addOperand(Scale)
19167     .addOperand(Index)
19168     .addDisp(Disp, 8)
19169     .addOperand(Segment)
19170     .setMemRefs(MMOBegin, MMOEnd);
19171
19172   // If we need to align it, do so. Otherwise, just copy the address
19173   // to OverflowDestReg.
19174   if (NeedsAlign) {
19175     // Align the overflow address
19176     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
19177     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
19178
19179     // aligned_addr = (addr + (align-1)) & ~(align-1)
19180     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
19181       .addReg(OverflowAddrReg)
19182       .addImm(Align-1);
19183
19184     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
19185       .addReg(TmpReg)
19186       .addImm(~(uint64_t)(Align-1));
19187   } else {
19188     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
19189       .addReg(OverflowAddrReg);
19190   }
19191
19192   // Compute the next overflow address after this argument.
19193   // (the overflow address should be kept 8-byte aligned)
19194   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
19195   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
19196     .addReg(OverflowDestReg)
19197     .addImm(ArgSizeA8);
19198
19199   // Store the new overflow address.
19200   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
19201     .addOperand(Base)
19202     .addOperand(Scale)
19203     .addOperand(Index)
19204     .addDisp(Disp, 8)
19205     .addOperand(Segment)
19206     .addReg(NextAddrReg)
19207     .setMemRefs(MMOBegin, MMOEnd);
19208
19209   // If we branched, emit the PHI to the front of endMBB.
19210   if (offsetMBB) {
19211     BuildMI(*endMBB, endMBB->begin(), DL,
19212             TII->get(X86::PHI), DestReg)
19213       .addReg(OffsetDestReg).addMBB(offsetMBB)
19214       .addReg(OverflowDestReg).addMBB(overflowMBB);
19215   }
19216
19217   // Erase the pseudo instruction
19218   MI->eraseFromParent();
19219
19220   return endMBB;
19221 }
19222
19223 MachineBasicBlock *
19224 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
19225                                                  MachineInstr *MI,
19226                                                  MachineBasicBlock *MBB) const {
19227   // Emit code to save XMM registers to the stack. The ABI says that the
19228   // number of registers to save is given in %al, so it's theoretically
19229   // possible to do an indirect jump trick to avoid saving all of them,
19230   // however this code takes a simpler approach and just executes all
19231   // of the stores if %al is non-zero. It's less code, and it's probably
19232   // easier on the hardware branch predictor, and stores aren't all that
19233   // expensive anyway.
19234
19235   // Create the new basic blocks. One block contains all the XMM stores,
19236   // and one block is the final destination regardless of whether any
19237   // stores were performed.
19238   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
19239   MachineFunction *F = MBB->getParent();
19240   MachineFunction::iterator MBBIter = MBB;
19241   ++MBBIter;
19242   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
19243   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
19244   F->insert(MBBIter, XMMSaveMBB);
19245   F->insert(MBBIter, EndMBB);
19246
19247   // Transfer the remainder of MBB and its successor edges to EndMBB.
19248   EndMBB->splice(EndMBB->begin(), MBB,
19249                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
19250   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
19251
19252   // The original block will now fall through to the XMM save block.
19253   MBB->addSuccessor(XMMSaveMBB);
19254   // The XMMSaveMBB will fall through to the end block.
19255   XMMSaveMBB->addSuccessor(EndMBB);
19256
19257   // Now add the instructions.
19258   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19259   DebugLoc DL = MI->getDebugLoc();
19260
19261   unsigned CountReg = MI->getOperand(0).getReg();
19262   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
19263   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
19264
19265   if (!Subtarget->isTargetWin64()) {
19266     // If %al is 0, branch around the XMM save block.
19267     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
19268     BuildMI(MBB, DL, TII->get(X86::JE_1)).addMBB(EndMBB);
19269     MBB->addSuccessor(EndMBB);
19270   }
19271
19272   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
19273   // that was just emitted, but clearly shouldn't be "saved".
19274   assert((MI->getNumOperands() <= 3 ||
19275           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
19276           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
19277          && "Expected last argument to be EFLAGS");
19278   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
19279   // In the XMM save block, save all the XMM argument registers.
19280   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
19281     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
19282     MachineMemOperand *MMO =
19283       F->getMachineMemOperand(
19284           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
19285         MachineMemOperand::MOStore,
19286         /*Size=*/16, /*Align=*/16);
19287     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
19288       .addFrameIndex(RegSaveFrameIndex)
19289       .addImm(/*Scale=*/1)
19290       .addReg(/*IndexReg=*/0)
19291       .addImm(/*Disp=*/Offset)
19292       .addReg(/*Segment=*/0)
19293       .addReg(MI->getOperand(i).getReg())
19294       .addMemOperand(MMO);
19295   }
19296
19297   MI->eraseFromParent();   // The pseudo instruction is gone now.
19298
19299   return EndMBB;
19300 }
19301
19302 // The EFLAGS operand of SelectItr might be missing a kill marker
19303 // because there were multiple uses of EFLAGS, and ISel didn't know
19304 // which to mark. Figure out whether SelectItr should have had a
19305 // kill marker, and set it if it should. Returns the correct kill
19306 // marker value.
19307 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
19308                                      MachineBasicBlock* BB,
19309                                      const TargetRegisterInfo* TRI) {
19310   // Scan forward through BB for a use/def of EFLAGS.
19311   MachineBasicBlock::iterator miI(std::next(SelectItr));
19312   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
19313     const MachineInstr& mi = *miI;
19314     if (mi.readsRegister(X86::EFLAGS))
19315       return false;
19316     if (mi.definesRegister(X86::EFLAGS))
19317       break; // Should have kill-flag - update below.
19318   }
19319
19320   // If we hit the end of the block, check whether EFLAGS is live into a
19321   // successor.
19322   if (miI == BB->end()) {
19323     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
19324                                           sEnd = BB->succ_end();
19325          sItr != sEnd; ++sItr) {
19326       MachineBasicBlock* succ = *sItr;
19327       if (succ->isLiveIn(X86::EFLAGS))
19328         return false;
19329     }
19330   }
19331
19332   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
19333   // out. SelectMI should have a kill flag on EFLAGS.
19334   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
19335   return true;
19336 }
19337
19338 MachineBasicBlock *
19339 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
19340                                      MachineBasicBlock *BB) const {
19341   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19342   DebugLoc DL = MI->getDebugLoc();
19343
19344   // To "insert" a SELECT_CC instruction, we actually have to insert the
19345   // diamond control-flow pattern.  The incoming instruction knows the
19346   // destination vreg to set, the condition code register to branch on, the
19347   // true/false values to select between, and a branch opcode to use.
19348   const BasicBlock *LLVM_BB = BB->getBasicBlock();
19349   MachineFunction::iterator It = BB;
19350   ++It;
19351
19352   //  thisMBB:
19353   //  ...
19354   //   TrueVal = ...
19355   //   cmpTY ccX, r1, r2
19356   //   bCC copy1MBB
19357   //   fallthrough --> copy0MBB
19358   MachineBasicBlock *thisMBB = BB;
19359   MachineFunction *F = BB->getParent();
19360
19361   // We also lower double CMOVs:
19362   //   (CMOV (CMOV F, T, cc1), T, cc2)
19363   // to two successives branches.  For that, we look for another CMOV as the
19364   // following instruction.
19365   //
19366   // Without this, we would add a PHI between the two jumps, which ends up
19367   // creating a few copies all around. For instance, for
19368   //
19369   //    (sitofp (zext (fcmp une)))
19370   //
19371   // we would generate:
19372   //
19373   //         ucomiss %xmm1, %xmm0
19374   //         movss  <1.0f>, %xmm0
19375   //         movaps  %xmm0, %xmm1
19376   //         jne     .LBB5_2
19377   //         xorps   %xmm1, %xmm1
19378   // .LBB5_2:
19379   //         jp      .LBB5_4
19380   //         movaps  %xmm1, %xmm0
19381   // .LBB5_4:
19382   //         retq
19383   //
19384   // because this custom-inserter would have generated:
19385   //
19386   //   A
19387   //   | \
19388   //   |  B
19389   //   | /
19390   //   C
19391   //   | \
19392   //   |  D
19393   //   | /
19394   //   E
19395   //
19396   // A: X = ...; Y = ...
19397   // B: empty
19398   // C: Z = PHI [X, A], [Y, B]
19399   // D: empty
19400   // E: PHI [X, C], [Z, D]
19401   //
19402   // If we lower both CMOVs in a single step, we can instead generate:
19403   //
19404   //   A
19405   //   | \
19406   //   |  C
19407   //   | /|
19408   //   |/ |
19409   //   |  |
19410   //   |  D
19411   //   | /
19412   //   E
19413   //
19414   // A: X = ...; Y = ...
19415   // D: empty
19416   // E: PHI [X, A], [X, C], [Y, D]
19417   //
19418   // Which, in our sitofp/fcmp example, gives us something like:
19419   //
19420   //         ucomiss %xmm1, %xmm0
19421   //         movss  <1.0f>, %xmm0
19422   //         jne     .LBB5_4
19423   //         jp      .LBB5_4
19424   //         xorps   %xmm0, %xmm0
19425   // .LBB5_4:
19426   //         retq
19427   //
19428   MachineInstr *NextCMOV = nullptr;
19429   MachineBasicBlock::iterator NextMIIt =
19430       std::next(MachineBasicBlock::iterator(MI));
19431   if (NextMIIt != BB->end() && NextMIIt->getOpcode() == MI->getOpcode() &&
19432       NextMIIt->getOperand(2).getReg() == MI->getOperand(2).getReg() &&
19433       NextMIIt->getOperand(1).getReg() == MI->getOperand(0).getReg())
19434     NextCMOV = &*NextMIIt;
19435
19436   MachineBasicBlock *jcc1MBB = nullptr;
19437
19438   // If we have a double CMOV, we lower it to two successive branches to
19439   // the same block.  EFLAGS is used by both, so mark it as live in the second.
19440   if (NextCMOV) {
19441     jcc1MBB = F->CreateMachineBasicBlock(LLVM_BB);
19442     F->insert(It, jcc1MBB);
19443     jcc1MBB->addLiveIn(X86::EFLAGS);
19444   }
19445
19446   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
19447   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
19448   F->insert(It, copy0MBB);
19449   F->insert(It, sinkMBB);
19450
19451   // If the EFLAGS register isn't dead in the terminator, then claim that it's
19452   // live into the sink and copy blocks.
19453   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
19454
19455   MachineInstr *LastEFLAGSUser = NextCMOV ? NextCMOV : MI;
19456   if (!LastEFLAGSUser->killsRegister(X86::EFLAGS) &&
19457       !checkAndUpdateEFLAGSKill(LastEFLAGSUser, BB, TRI)) {
19458     copy0MBB->addLiveIn(X86::EFLAGS);
19459     sinkMBB->addLiveIn(X86::EFLAGS);
19460   }
19461
19462   // Transfer the remainder of BB and its successor edges to sinkMBB.
19463   sinkMBB->splice(sinkMBB->begin(), BB,
19464                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
19465   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
19466
19467   // Add the true and fallthrough blocks as its successors.
19468   if (NextCMOV) {
19469     // The fallthrough block may be jcc1MBB, if we have a double CMOV.
19470     BB->addSuccessor(jcc1MBB);
19471
19472     // In that case, jcc1MBB will itself fallthrough the copy0MBB, and
19473     // jump to the sinkMBB.
19474     jcc1MBB->addSuccessor(copy0MBB);
19475     jcc1MBB->addSuccessor(sinkMBB);
19476   } else {
19477     BB->addSuccessor(copy0MBB);
19478   }
19479
19480   // The true block target of the first (or only) branch is always sinkMBB.
19481   BB->addSuccessor(sinkMBB);
19482
19483   // Create the conditional branch instruction.
19484   unsigned Opc =
19485     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
19486   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
19487
19488   if (NextCMOV) {
19489     unsigned Opc2 = X86::GetCondBranchFromCond(
19490         (X86::CondCode)NextCMOV->getOperand(3).getImm());
19491     BuildMI(jcc1MBB, DL, TII->get(Opc2)).addMBB(sinkMBB);
19492   }
19493
19494   //  copy0MBB:
19495   //   %FalseValue = ...
19496   //   # fallthrough to sinkMBB
19497   copy0MBB->addSuccessor(sinkMBB);
19498
19499   //  sinkMBB:
19500   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
19501   //  ...
19502   MachineInstrBuilder MIB =
19503       BuildMI(*sinkMBB, sinkMBB->begin(), DL, TII->get(X86::PHI),
19504               MI->getOperand(0).getReg())
19505           .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
19506           .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
19507
19508   // If we have a double CMOV, the second Jcc provides the same incoming
19509   // value as the first Jcc (the True operand of the SELECT_CC/CMOV nodes).
19510   if (NextCMOV) {
19511     MIB.addReg(MI->getOperand(2).getReg()).addMBB(jcc1MBB);
19512     // Copy the PHI result to the register defined by the second CMOV.
19513     BuildMI(*sinkMBB, std::next(MachineBasicBlock::iterator(MIB.getInstr())),
19514             DL, TII->get(TargetOpcode::COPY), NextCMOV->getOperand(0).getReg())
19515         .addReg(MI->getOperand(0).getReg());
19516     NextCMOV->eraseFromParent();
19517   }
19518
19519   MI->eraseFromParent();   // The pseudo instruction is gone now.
19520   return sinkMBB;
19521 }
19522
19523 MachineBasicBlock *
19524 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI,
19525                                         MachineBasicBlock *BB) const {
19526   MachineFunction *MF = BB->getParent();
19527   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19528   DebugLoc DL = MI->getDebugLoc();
19529   const BasicBlock *LLVM_BB = BB->getBasicBlock();
19530
19531   assert(MF->shouldSplitStack());
19532
19533   const bool Is64Bit = Subtarget->is64Bit();
19534   const bool IsLP64 = Subtarget->isTarget64BitLP64();
19535
19536   const unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
19537   const unsigned TlsOffset = IsLP64 ? 0x70 : Is64Bit ? 0x40 : 0x30;
19538
19539   // BB:
19540   //  ... [Till the alloca]
19541   // If stacklet is not large enough, jump to mallocMBB
19542   //
19543   // bumpMBB:
19544   //  Allocate by subtracting from RSP
19545   //  Jump to continueMBB
19546   //
19547   // mallocMBB:
19548   //  Allocate by call to runtime
19549   //
19550   // continueMBB:
19551   //  ...
19552   //  [rest of original BB]
19553   //
19554
19555   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19556   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19557   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19558
19559   MachineRegisterInfo &MRI = MF->getRegInfo();
19560   const TargetRegisterClass *AddrRegClass =
19561     getRegClassFor(getPointerTy());
19562
19563   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
19564     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
19565     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
19566     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
19567     sizeVReg = MI->getOperand(1).getReg(),
19568     physSPReg = IsLP64 || Subtarget->isTargetNaCl64() ? X86::RSP : X86::ESP;
19569
19570   MachineFunction::iterator MBBIter = BB;
19571   ++MBBIter;
19572
19573   MF->insert(MBBIter, bumpMBB);
19574   MF->insert(MBBIter, mallocMBB);
19575   MF->insert(MBBIter, continueMBB);
19576
19577   continueMBB->splice(continueMBB->begin(), BB,
19578                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
19579   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
19580
19581   // Add code to the main basic block to check if the stack limit has been hit,
19582   // and if so, jump to mallocMBB otherwise to bumpMBB.
19583   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
19584   BuildMI(BB, DL, TII->get(IsLP64 ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
19585     .addReg(tmpSPVReg).addReg(sizeVReg);
19586   BuildMI(BB, DL, TII->get(IsLP64 ? X86::CMP64mr:X86::CMP32mr))
19587     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
19588     .addReg(SPLimitVReg);
19589   BuildMI(BB, DL, TII->get(X86::JG_1)).addMBB(mallocMBB);
19590
19591   // bumpMBB simply decreases the stack pointer, since we know the current
19592   // stacklet has enough space.
19593   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
19594     .addReg(SPLimitVReg);
19595   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
19596     .addReg(SPLimitVReg);
19597   BuildMI(bumpMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
19598
19599   // Calls into a routine in libgcc to allocate more space from the heap.
19600   const uint32_t *RegMask =
19601       Subtarget->getRegisterInfo()->getCallPreservedMask(*MF, CallingConv::C);
19602   if (IsLP64) {
19603     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
19604       .addReg(sizeVReg);
19605     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
19606       .addExternalSymbol("__morestack_allocate_stack_space")
19607       .addRegMask(RegMask)
19608       .addReg(X86::RDI, RegState::Implicit)
19609       .addReg(X86::RAX, RegState::ImplicitDefine);
19610   } else if (Is64Bit) {
19611     BuildMI(mallocMBB, DL, TII->get(X86::MOV32rr), X86::EDI)
19612       .addReg(sizeVReg);
19613     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
19614       .addExternalSymbol("__morestack_allocate_stack_space")
19615       .addRegMask(RegMask)
19616       .addReg(X86::EDI, RegState::Implicit)
19617       .addReg(X86::EAX, RegState::ImplicitDefine);
19618   } else {
19619     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
19620       .addImm(12);
19621     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
19622     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
19623       .addExternalSymbol("__morestack_allocate_stack_space")
19624       .addRegMask(RegMask)
19625       .addReg(X86::EAX, RegState::ImplicitDefine);
19626   }
19627
19628   if (!Is64Bit)
19629     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
19630       .addImm(16);
19631
19632   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
19633     .addReg(IsLP64 ? X86::RAX : X86::EAX);
19634   BuildMI(mallocMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
19635
19636   // Set up the CFG correctly.
19637   BB->addSuccessor(bumpMBB);
19638   BB->addSuccessor(mallocMBB);
19639   mallocMBB->addSuccessor(continueMBB);
19640   bumpMBB->addSuccessor(continueMBB);
19641
19642   // Take care of the PHI nodes.
19643   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
19644           MI->getOperand(0).getReg())
19645     .addReg(mallocPtrVReg).addMBB(mallocMBB)
19646     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
19647
19648   // Delete the original pseudo instruction.
19649   MI->eraseFromParent();
19650
19651   // And we're done.
19652   return continueMBB;
19653 }
19654
19655 MachineBasicBlock *
19656 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
19657                                         MachineBasicBlock *BB) const {
19658   DebugLoc DL = MI->getDebugLoc();
19659
19660   assert(!Subtarget->isTargetMachO());
19661
19662   Subtarget->getFrameLowering()->emitStackProbeCall(*BB->getParent(), *BB, MI,
19663                                                     DL);
19664
19665   MI->eraseFromParent();   // The pseudo instruction is gone now.
19666   return BB;
19667 }
19668
19669 MachineBasicBlock *
19670 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
19671                                       MachineBasicBlock *BB) const {
19672   // This is pretty easy.  We're taking the value that we received from
19673   // our load from the relocation, sticking it in either RDI (x86-64)
19674   // or EAX and doing an indirect call.  The return value will then
19675   // be in the normal return register.
19676   MachineFunction *F = BB->getParent();
19677   const X86InstrInfo *TII = Subtarget->getInstrInfo();
19678   DebugLoc DL = MI->getDebugLoc();
19679
19680   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
19681   assert(MI->getOperand(3).isGlobal() && "This should be a global");
19682
19683   // Get a register mask for the lowered call.
19684   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
19685   // proper register mask.
19686   const uint32_t *RegMask =
19687       Subtarget->getRegisterInfo()->getCallPreservedMask(*F, CallingConv::C);
19688   if (Subtarget->is64Bit()) {
19689     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
19690                                       TII->get(X86::MOV64rm), X86::RDI)
19691     .addReg(X86::RIP)
19692     .addImm(0).addReg(0)
19693     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
19694                       MI->getOperand(3).getTargetFlags())
19695     .addReg(0);
19696     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
19697     addDirectMem(MIB, X86::RDI);
19698     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
19699   } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
19700     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
19701                                       TII->get(X86::MOV32rm), X86::EAX)
19702     .addReg(0)
19703     .addImm(0).addReg(0)
19704     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
19705                       MI->getOperand(3).getTargetFlags())
19706     .addReg(0);
19707     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
19708     addDirectMem(MIB, X86::EAX);
19709     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
19710   } else {
19711     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
19712                                       TII->get(X86::MOV32rm), X86::EAX)
19713     .addReg(TII->getGlobalBaseReg(F))
19714     .addImm(0).addReg(0)
19715     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
19716                       MI->getOperand(3).getTargetFlags())
19717     .addReg(0);
19718     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
19719     addDirectMem(MIB, X86::EAX);
19720     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
19721   }
19722
19723   MI->eraseFromParent(); // The pseudo instruction is gone now.
19724   return BB;
19725 }
19726
19727 MachineBasicBlock *
19728 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
19729                                     MachineBasicBlock *MBB) const {
19730   DebugLoc DL = MI->getDebugLoc();
19731   MachineFunction *MF = MBB->getParent();
19732   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19733   MachineRegisterInfo &MRI = MF->getRegInfo();
19734
19735   const BasicBlock *BB = MBB->getBasicBlock();
19736   MachineFunction::iterator I = MBB;
19737   ++I;
19738
19739   // Memory Reference
19740   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
19741   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
19742
19743   unsigned DstReg;
19744   unsigned MemOpndSlot = 0;
19745
19746   unsigned CurOp = 0;
19747
19748   DstReg = MI->getOperand(CurOp++).getReg();
19749   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
19750   assert(RC->hasType(MVT::i32) && "Invalid destination!");
19751   unsigned mainDstReg = MRI.createVirtualRegister(RC);
19752   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
19753
19754   MemOpndSlot = CurOp;
19755
19756   MVT PVT = getPointerTy();
19757   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
19758          "Invalid Pointer Size!");
19759
19760   // For v = setjmp(buf), we generate
19761   //
19762   // thisMBB:
19763   //  buf[LabelOffset] = restoreMBB
19764   //  SjLjSetup restoreMBB
19765   //
19766   // mainMBB:
19767   //  v_main = 0
19768   //
19769   // sinkMBB:
19770   //  v = phi(main, restore)
19771   //
19772   // restoreMBB:
19773   //  if base pointer being used, load it from frame
19774   //  v_restore = 1
19775
19776   MachineBasicBlock *thisMBB = MBB;
19777   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
19778   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
19779   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
19780   MF->insert(I, mainMBB);
19781   MF->insert(I, sinkMBB);
19782   MF->push_back(restoreMBB);
19783
19784   MachineInstrBuilder MIB;
19785
19786   // Transfer the remainder of BB and its successor edges to sinkMBB.
19787   sinkMBB->splice(sinkMBB->begin(), MBB,
19788                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
19789   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
19790
19791   // thisMBB:
19792   unsigned PtrStoreOpc = 0;
19793   unsigned LabelReg = 0;
19794   const int64_t LabelOffset = 1 * PVT.getStoreSize();
19795   Reloc::Model RM = MF->getTarget().getRelocationModel();
19796   bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
19797                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
19798
19799   // Prepare IP either in reg or imm.
19800   if (!UseImmLabel) {
19801     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
19802     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
19803     LabelReg = MRI.createVirtualRegister(PtrRC);
19804     if (Subtarget->is64Bit()) {
19805       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
19806               .addReg(X86::RIP)
19807               .addImm(0)
19808               .addReg(0)
19809               .addMBB(restoreMBB)
19810               .addReg(0);
19811     } else {
19812       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
19813       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
19814               .addReg(XII->getGlobalBaseReg(MF))
19815               .addImm(0)
19816               .addReg(0)
19817               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
19818               .addReg(0);
19819     }
19820   } else
19821     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
19822   // Store IP
19823   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
19824   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
19825     if (i == X86::AddrDisp)
19826       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
19827     else
19828       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
19829   }
19830   if (!UseImmLabel)
19831     MIB.addReg(LabelReg);
19832   else
19833     MIB.addMBB(restoreMBB);
19834   MIB.setMemRefs(MMOBegin, MMOEnd);
19835   // Setup
19836   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
19837           .addMBB(restoreMBB);
19838
19839   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
19840   MIB.addRegMask(RegInfo->getNoPreservedMask());
19841   thisMBB->addSuccessor(mainMBB);
19842   thisMBB->addSuccessor(restoreMBB);
19843
19844   // mainMBB:
19845   //  EAX = 0
19846   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
19847   mainMBB->addSuccessor(sinkMBB);
19848
19849   // sinkMBB:
19850   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
19851           TII->get(X86::PHI), DstReg)
19852     .addReg(mainDstReg).addMBB(mainMBB)
19853     .addReg(restoreDstReg).addMBB(restoreMBB);
19854
19855   // restoreMBB:
19856   if (RegInfo->hasBasePointer(*MF)) {
19857     const bool Uses64BitFramePtr =
19858         Subtarget->isTarget64BitLP64() || Subtarget->isTargetNaCl64();
19859     X86MachineFunctionInfo *X86FI = MF->getInfo<X86MachineFunctionInfo>();
19860     X86FI->setRestoreBasePointer(MF);
19861     unsigned FramePtr = RegInfo->getFrameRegister(*MF);
19862     unsigned BasePtr = RegInfo->getBaseRegister();
19863     unsigned Opm = Uses64BitFramePtr ? X86::MOV64rm : X86::MOV32rm;
19864     addRegOffset(BuildMI(restoreMBB, DL, TII->get(Opm), BasePtr),
19865                  FramePtr, true, X86FI->getRestoreBasePointerOffset())
19866       .setMIFlag(MachineInstr::FrameSetup);
19867   }
19868   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
19869   BuildMI(restoreMBB, DL, TII->get(X86::JMP_1)).addMBB(sinkMBB);
19870   restoreMBB->addSuccessor(sinkMBB);
19871
19872   MI->eraseFromParent();
19873   return sinkMBB;
19874 }
19875
19876 MachineBasicBlock *
19877 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
19878                                      MachineBasicBlock *MBB) const {
19879   DebugLoc DL = MI->getDebugLoc();
19880   MachineFunction *MF = MBB->getParent();
19881   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19882   MachineRegisterInfo &MRI = MF->getRegInfo();
19883
19884   // Memory Reference
19885   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
19886   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
19887
19888   MVT PVT = getPointerTy();
19889   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
19890          "Invalid Pointer Size!");
19891
19892   const TargetRegisterClass *RC =
19893     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
19894   unsigned Tmp = MRI.createVirtualRegister(RC);
19895   // Since FP is only updated here but NOT referenced, it's treated as GPR.
19896   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
19897   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
19898   unsigned SP = RegInfo->getStackRegister();
19899
19900   MachineInstrBuilder MIB;
19901
19902   const int64_t LabelOffset = 1 * PVT.getStoreSize();
19903   const int64_t SPOffset = 2 * PVT.getStoreSize();
19904
19905   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
19906   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
19907
19908   // Reload FP
19909   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
19910   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
19911     MIB.addOperand(MI->getOperand(i));
19912   MIB.setMemRefs(MMOBegin, MMOEnd);
19913   // Reload IP
19914   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
19915   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
19916     if (i == X86::AddrDisp)
19917       MIB.addDisp(MI->getOperand(i), LabelOffset);
19918     else
19919       MIB.addOperand(MI->getOperand(i));
19920   }
19921   MIB.setMemRefs(MMOBegin, MMOEnd);
19922   // Reload SP
19923   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
19924   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
19925     if (i == X86::AddrDisp)
19926       MIB.addDisp(MI->getOperand(i), SPOffset);
19927     else
19928       MIB.addOperand(MI->getOperand(i));
19929   }
19930   MIB.setMemRefs(MMOBegin, MMOEnd);
19931   // Jump
19932   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
19933
19934   MI->eraseFromParent();
19935   return MBB;
19936 }
19937
19938 // Replace 213-type (isel default) FMA3 instructions with 231-type for
19939 // accumulator loops. Writing back to the accumulator allows the coalescer
19940 // to remove extra copies in the loop.
19941 // FIXME: Do this on AVX512.  We don't support 231 variants yet (PR23937).
19942 MachineBasicBlock *
19943 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
19944                                  MachineBasicBlock *MBB) const {
19945   MachineOperand &AddendOp = MI->getOperand(3);
19946
19947   // Bail out early if the addend isn't a register - we can't switch these.
19948   if (!AddendOp.isReg())
19949     return MBB;
19950
19951   MachineFunction &MF = *MBB->getParent();
19952   MachineRegisterInfo &MRI = MF.getRegInfo();
19953
19954   // Check whether the addend is defined by a PHI:
19955   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
19956   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
19957   if (!AddendDef.isPHI())
19958     return MBB;
19959
19960   // Look for the following pattern:
19961   // loop:
19962   //   %addend = phi [%entry, 0], [%loop, %result]
19963   //   ...
19964   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
19965
19966   // Replace with:
19967   //   loop:
19968   //   %addend = phi [%entry, 0], [%loop, %result]
19969   //   ...
19970   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
19971
19972   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
19973     assert(AddendDef.getOperand(i).isReg());
19974     MachineOperand PHISrcOp = AddendDef.getOperand(i);
19975     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
19976     if (&PHISrcInst == MI) {
19977       // Found a matching instruction.
19978       unsigned NewFMAOpc = 0;
19979       switch (MI->getOpcode()) {
19980         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
19981         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
19982         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
19983         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
19984         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
19985         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
19986         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
19987         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
19988         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
19989         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
19990         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
19991         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
19992         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
19993         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
19994         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
19995         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
19996         case X86::VFMADDSUBPDr213r: NewFMAOpc = X86::VFMADDSUBPDr231r; break;
19997         case X86::VFMADDSUBPSr213r: NewFMAOpc = X86::VFMADDSUBPSr231r; break;
19998         case X86::VFMSUBADDPDr213r: NewFMAOpc = X86::VFMSUBADDPDr231r; break;
19999         case X86::VFMSUBADDPSr213r: NewFMAOpc = X86::VFMSUBADDPSr231r; break;
20000
20001         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
20002         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
20003         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
20004         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
20005         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
20006         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
20007         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
20008         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
20009         case X86::VFMADDSUBPDr213rY: NewFMAOpc = X86::VFMADDSUBPDr231rY; break;
20010         case X86::VFMADDSUBPSr213rY: NewFMAOpc = X86::VFMADDSUBPSr231rY; break;
20011         case X86::VFMSUBADDPDr213rY: NewFMAOpc = X86::VFMSUBADDPDr231rY; break;
20012         case X86::VFMSUBADDPSr213rY: NewFMAOpc = X86::VFMSUBADDPSr231rY; break;
20013         default: llvm_unreachable("Unrecognized FMA variant.");
20014       }
20015
20016       const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
20017       MachineInstrBuilder MIB =
20018         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
20019         .addOperand(MI->getOperand(0))
20020         .addOperand(MI->getOperand(3))
20021         .addOperand(MI->getOperand(2))
20022         .addOperand(MI->getOperand(1));
20023       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
20024       MI->eraseFromParent();
20025     }
20026   }
20027
20028   return MBB;
20029 }
20030
20031 MachineBasicBlock *
20032 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
20033                                                MachineBasicBlock *BB) const {
20034   switch (MI->getOpcode()) {
20035   default: llvm_unreachable("Unexpected instr type to insert");
20036   case X86::TAILJMPd64:
20037   case X86::TAILJMPr64:
20038   case X86::TAILJMPm64:
20039   case X86::TAILJMPd64_REX:
20040   case X86::TAILJMPr64_REX:
20041   case X86::TAILJMPm64_REX:
20042     llvm_unreachable("TAILJMP64 would not be touched here.");
20043   case X86::TCRETURNdi64:
20044   case X86::TCRETURNri64:
20045   case X86::TCRETURNmi64:
20046     return BB;
20047   case X86::WIN_ALLOCA:
20048     return EmitLoweredWinAlloca(MI, BB);
20049   case X86::SEG_ALLOCA_32:
20050   case X86::SEG_ALLOCA_64:
20051     return EmitLoweredSegAlloca(MI, BB);
20052   case X86::TLSCall_32:
20053   case X86::TLSCall_64:
20054     return EmitLoweredTLSCall(MI, BB);
20055   case X86::CMOV_GR8:
20056   case X86::CMOV_FR32:
20057   case X86::CMOV_FR64:
20058   case X86::CMOV_V4F32:
20059   case X86::CMOV_V2F64:
20060   case X86::CMOV_V2I64:
20061   case X86::CMOV_V8F32:
20062   case X86::CMOV_V4F64:
20063   case X86::CMOV_V4I64:
20064   case X86::CMOV_V16F32:
20065   case X86::CMOV_V8F64:
20066   case X86::CMOV_V8I64:
20067   case X86::CMOV_GR16:
20068   case X86::CMOV_GR32:
20069   case X86::CMOV_RFP32:
20070   case X86::CMOV_RFP64:
20071   case X86::CMOV_RFP80:
20072   case X86::CMOV_V8I1:
20073   case X86::CMOV_V16I1:
20074   case X86::CMOV_V32I1:
20075   case X86::CMOV_V64I1:
20076     return EmitLoweredSelect(MI, BB);
20077
20078   case X86::FP32_TO_INT16_IN_MEM:
20079   case X86::FP32_TO_INT32_IN_MEM:
20080   case X86::FP32_TO_INT64_IN_MEM:
20081   case X86::FP64_TO_INT16_IN_MEM:
20082   case X86::FP64_TO_INT32_IN_MEM:
20083   case X86::FP64_TO_INT64_IN_MEM:
20084   case X86::FP80_TO_INT16_IN_MEM:
20085   case X86::FP80_TO_INT32_IN_MEM:
20086   case X86::FP80_TO_INT64_IN_MEM: {
20087     MachineFunction *F = BB->getParent();
20088     const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20089     DebugLoc DL = MI->getDebugLoc();
20090
20091     // Change the floating point control register to use "round towards zero"
20092     // mode when truncating to an integer value.
20093     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
20094     addFrameReference(BuildMI(*BB, MI, DL,
20095                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
20096
20097     // Load the old value of the high byte of the control word...
20098     unsigned OldCW =
20099       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
20100     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
20101                       CWFrameIdx);
20102
20103     // Set the high part to be round to zero...
20104     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
20105       .addImm(0xC7F);
20106
20107     // Reload the modified control word now...
20108     addFrameReference(BuildMI(*BB, MI, DL,
20109                               TII->get(X86::FLDCW16m)), CWFrameIdx);
20110
20111     // Restore the memory image of control word to original value
20112     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
20113       .addReg(OldCW);
20114
20115     // Get the X86 opcode to use.
20116     unsigned Opc;
20117     switch (MI->getOpcode()) {
20118     default: llvm_unreachable("illegal opcode!");
20119     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
20120     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
20121     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
20122     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
20123     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
20124     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
20125     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
20126     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
20127     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
20128     }
20129
20130     X86AddressMode AM;
20131     MachineOperand &Op = MI->getOperand(0);
20132     if (Op.isReg()) {
20133       AM.BaseType = X86AddressMode::RegBase;
20134       AM.Base.Reg = Op.getReg();
20135     } else {
20136       AM.BaseType = X86AddressMode::FrameIndexBase;
20137       AM.Base.FrameIndex = Op.getIndex();
20138     }
20139     Op = MI->getOperand(1);
20140     if (Op.isImm())
20141       AM.Scale = Op.getImm();
20142     Op = MI->getOperand(2);
20143     if (Op.isImm())
20144       AM.IndexReg = Op.getImm();
20145     Op = MI->getOperand(3);
20146     if (Op.isGlobal()) {
20147       AM.GV = Op.getGlobal();
20148     } else {
20149       AM.Disp = Op.getImm();
20150     }
20151     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
20152                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
20153
20154     // Reload the original control word now.
20155     addFrameReference(BuildMI(*BB, MI, DL,
20156                               TII->get(X86::FLDCW16m)), CWFrameIdx);
20157
20158     MI->eraseFromParent();   // The pseudo instruction is gone now.
20159     return BB;
20160   }
20161     // String/text processing lowering.
20162   case X86::PCMPISTRM128REG:
20163   case X86::VPCMPISTRM128REG:
20164   case X86::PCMPISTRM128MEM:
20165   case X86::VPCMPISTRM128MEM:
20166   case X86::PCMPESTRM128REG:
20167   case X86::VPCMPESTRM128REG:
20168   case X86::PCMPESTRM128MEM:
20169   case X86::VPCMPESTRM128MEM:
20170     assert(Subtarget->hasSSE42() &&
20171            "Target must have SSE4.2 or AVX features enabled");
20172     return EmitPCMPSTRM(MI, BB, Subtarget->getInstrInfo());
20173
20174   // String/text processing lowering.
20175   case X86::PCMPISTRIREG:
20176   case X86::VPCMPISTRIREG:
20177   case X86::PCMPISTRIMEM:
20178   case X86::VPCMPISTRIMEM:
20179   case X86::PCMPESTRIREG:
20180   case X86::VPCMPESTRIREG:
20181   case X86::PCMPESTRIMEM:
20182   case X86::VPCMPESTRIMEM:
20183     assert(Subtarget->hasSSE42() &&
20184            "Target must have SSE4.2 or AVX features enabled");
20185     return EmitPCMPSTRI(MI, BB, Subtarget->getInstrInfo());
20186
20187   // Thread synchronization.
20188   case X86::MONITOR:
20189     return EmitMonitor(MI, BB, Subtarget);
20190
20191   // xbegin
20192   case X86::XBEGIN:
20193     return EmitXBegin(MI, BB, Subtarget->getInstrInfo());
20194
20195   case X86::VASTART_SAVE_XMM_REGS:
20196     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
20197
20198   case X86::VAARG_64:
20199     return EmitVAARG64WithCustomInserter(MI, BB);
20200
20201   case X86::EH_SjLj_SetJmp32:
20202   case X86::EH_SjLj_SetJmp64:
20203     return emitEHSjLjSetJmp(MI, BB);
20204
20205   case X86::EH_SjLj_LongJmp32:
20206   case X86::EH_SjLj_LongJmp64:
20207     return emitEHSjLjLongJmp(MI, BB);
20208
20209   case TargetOpcode::STATEPOINT:
20210     // As an implementation detail, STATEPOINT shares the STACKMAP format at
20211     // this point in the process.  We diverge later.
20212     return emitPatchPoint(MI, BB);
20213
20214   case TargetOpcode::STACKMAP:
20215   case TargetOpcode::PATCHPOINT:
20216     return emitPatchPoint(MI, BB);
20217
20218   case X86::VFMADDPDr213r:
20219   case X86::VFMADDPSr213r:
20220   case X86::VFMADDSDr213r:
20221   case X86::VFMADDSSr213r:
20222   case X86::VFMSUBPDr213r:
20223   case X86::VFMSUBPSr213r:
20224   case X86::VFMSUBSDr213r:
20225   case X86::VFMSUBSSr213r:
20226   case X86::VFNMADDPDr213r:
20227   case X86::VFNMADDPSr213r:
20228   case X86::VFNMADDSDr213r:
20229   case X86::VFNMADDSSr213r:
20230   case X86::VFNMSUBPDr213r:
20231   case X86::VFNMSUBPSr213r:
20232   case X86::VFNMSUBSDr213r:
20233   case X86::VFNMSUBSSr213r:
20234   case X86::VFMADDSUBPDr213r:
20235   case X86::VFMADDSUBPSr213r:
20236   case X86::VFMSUBADDPDr213r:
20237   case X86::VFMSUBADDPSr213r:
20238   case X86::VFMADDPDr213rY:
20239   case X86::VFMADDPSr213rY:
20240   case X86::VFMSUBPDr213rY:
20241   case X86::VFMSUBPSr213rY:
20242   case X86::VFNMADDPDr213rY:
20243   case X86::VFNMADDPSr213rY:
20244   case X86::VFNMSUBPDr213rY:
20245   case X86::VFNMSUBPSr213rY:
20246   case X86::VFMADDSUBPDr213rY:
20247   case X86::VFMADDSUBPSr213rY:
20248   case X86::VFMSUBADDPDr213rY:
20249   case X86::VFMSUBADDPSr213rY:
20250     return emitFMA3Instr(MI, BB);
20251   }
20252 }
20253
20254 //===----------------------------------------------------------------------===//
20255 //                           X86 Optimization Hooks
20256 //===----------------------------------------------------------------------===//
20257
20258 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
20259                                                       APInt &KnownZero,
20260                                                       APInt &KnownOne,
20261                                                       const SelectionDAG &DAG,
20262                                                       unsigned Depth) const {
20263   unsigned BitWidth = KnownZero.getBitWidth();
20264   unsigned Opc = Op.getOpcode();
20265   assert((Opc >= ISD::BUILTIN_OP_END ||
20266           Opc == ISD::INTRINSIC_WO_CHAIN ||
20267           Opc == ISD::INTRINSIC_W_CHAIN ||
20268           Opc == ISD::INTRINSIC_VOID) &&
20269          "Should use MaskedValueIsZero if you don't know whether Op"
20270          " is a target node!");
20271
20272   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
20273   switch (Opc) {
20274   default: break;
20275   case X86ISD::ADD:
20276   case X86ISD::SUB:
20277   case X86ISD::ADC:
20278   case X86ISD::SBB:
20279   case X86ISD::SMUL:
20280   case X86ISD::UMUL:
20281   case X86ISD::INC:
20282   case X86ISD::DEC:
20283   case X86ISD::OR:
20284   case X86ISD::XOR:
20285   case X86ISD::AND:
20286     // These nodes' second result is a boolean.
20287     if (Op.getResNo() == 0)
20288       break;
20289     // Fallthrough
20290   case X86ISD::SETCC:
20291     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
20292     break;
20293   case ISD::INTRINSIC_WO_CHAIN: {
20294     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
20295     unsigned NumLoBits = 0;
20296     switch (IntId) {
20297     default: break;
20298     case Intrinsic::x86_sse_movmsk_ps:
20299     case Intrinsic::x86_avx_movmsk_ps_256:
20300     case Intrinsic::x86_sse2_movmsk_pd:
20301     case Intrinsic::x86_avx_movmsk_pd_256:
20302     case Intrinsic::x86_mmx_pmovmskb:
20303     case Intrinsic::x86_sse2_pmovmskb_128:
20304     case Intrinsic::x86_avx2_pmovmskb: {
20305       // High bits of movmskp{s|d}, pmovmskb are known zero.
20306       switch (IntId) {
20307         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
20308         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
20309         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
20310         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
20311         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
20312         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
20313         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
20314         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
20315       }
20316       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
20317       break;
20318     }
20319     }
20320     break;
20321   }
20322   }
20323 }
20324
20325 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
20326   SDValue Op,
20327   const SelectionDAG &,
20328   unsigned Depth) const {
20329   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
20330   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
20331     return Op.getValueType().getScalarType().getSizeInBits();
20332
20333   // Fallback case.
20334   return 1;
20335 }
20336
20337 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
20338 /// node is a GlobalAddress + offset.
20339 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
20340                                        const GlobalValue* &GA,
20341                                        int64_t &Offset) const {
20342   if (N->getOpcode() == X86ISD::Wrapper) {
20343     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
20344       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
20345       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
20346       return true;
20347     }
20348   }
20349   return TargetLowering::isGAPlusOffset(N, GA, Offset);
20350 }
20351
20352 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
20353 /// same as extracting the high 128-bit part of 256-bit vector and then
20354 /// inserting the result into the low part of a new 256-bit vector
20355 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
20356   EVT VT = SVOp->getValueType(0);
20357   unsigned NumElems = VT.getVectorNumElements();
20358
20359   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
20360   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
20361     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
20362         SVOp->getMaskElt(j) >= 0)
20363       return false;
20364
20365   return true;
20366 }
20367
20368 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
20369 /// same as extracting the low 128-bit part of 256-bit vector and then
20370 /// inserting the result into the high part of a new 256-bit vector
20371 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
20372   EVT VT = SVOp->getValueType(0);
20373   unsigned NumElems = VT.getVectorNumElements();
20374
20375   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
20376   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
20377     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
20378         SVOp->getMaskElt(j) >= 0)
20379       return false;
20380
20381   return true;
20382 }
20383
20384 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
20385 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
20386                                         TargetLowering::DAGCombinerInfo &DCI,
20387                                         const X86Subtarget* Subtarget) {
20388   SDLoc dl(N);
20389   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
20390   SDValue V1 = SVOp->getOperand(0);
20391   SDValue V2 = SVOp->getOperand(1);
20392   EVT VT = SVOp->getValueType(0);
20393   unsigned NumElems = VT.getVectorNumElements();
20394
20395   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
20396       V2.getOpcode() == ISD::CONCAT_VECTORS) {
20397     //
20398     //                   0,0,0,...
20399     //                      |
20400     //    V      UNDEF    BUILD_VECTOR    UNDEF
20401     //     \      /           \           /
20402     //  CONCAT_VECTOR         CONCAT_VECTOR
20403     //         \                  /
20404     //          \                /
20405     //          RESULT: V + zero extended
20406     //
20407     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
20408         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
20409         V1.getOperand(1).getOpcode() != ISD::UNDEF)
20410       return SDValue();
20411
20412     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
20413       return SDValue();
20414
20415     // To match the shuffle mask, the first half of the mask should
20416     // be exactly the first vector, and all the rest a splat with the
20417     // first element of the second one.
20418     for (unsigned i = 0; i != NumElems/2; ++i)
20419       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
20420           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
20421         return SDValue();
20422
20423     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
20424     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
20425       if (Ld->hasNUsesOfValue(1, 0)) {
20426         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
20427         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
20428         SDValue ResNode =
20429           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
20430                                   Ld->getMemoryVT(),
20431                                   Ld->getPointerInfo(),
20432                                   Ld->getAlignment(),
20433                                   false/*isVolatile*/, true/*ReadMem*/,
20434                                   false/*WriteMem*/);
20435
20436         // Make sure the newly-created LOAD is in the same position as Ld in
20437         // terms of dependency. We create a TokenFactor for Ld and ResNode,
20438         // and update uses of Ld's output chain to use the TokenFactor.
20439         if (Ld->hasAnyUseOfValue(1)) {
20440           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
20441                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
20442           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
20443           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
20444                                  SDValue(ResNode.getNode(), 1));
20445         }
20446
20447         return DAG.getBitcast(VT, ResNode);
20448       }
20449     }
20450
20451     // Emit a zeroed vector and insert the desired subvector on its
20452     // first half.
20453     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
20454     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
20455     return DCI.CombineTo(N, InsV);
20456   }
20457
20458   //===--------------------------------------------------------------------===//
20459   // Combine some shuffles into subvector extracts and inserts:
20460   //
20461
20462   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
20463   if (isShuffleHigh128VectorInsertLow(SVOp)) {
20464     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
20465     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
20466     return DCI.CombineTo(N, InsV);
20467   }
20468
20469   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
20470   if (isShuffleLow128VectorInsertHigh(SVOp)) {
20471     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
20472     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
20473     return DCI.CombineTo(N, InsV);
20474   }
20475
20476   return SDValue();
20477 }
20478
20479 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
20480 /// possible.
20481 ///
20482 /// This is the leaf of the recursive combinine below. When we have found some
20483 /// chain of single-use x86 shuffle instructions and accumulated the combined
20484 /// shuffle mask represented by them, this will try to pattern match that mask
20485 /// into either a single instruction if there is a special purpose instruction
20486 /// for this operation, or into a PSHUFB instruction which is a fully general
20487 /// instruction but should only be used to replace chains over a certain depth.
20488 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
20489                                    int Depth, bool HasPSHUFB, SelectionDAG &DAG,
20490                                    TargetLowering::DAGCombinerInfo &DCI,
20491                                    const X86Subtarget *Subtarget) {
20492   assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
20493
20494   // Find the operand that enters the chain. Note that multiple uses are OK
20495   // here, we're not going to remove the operand we find.
20496   SDValue Input = Op.getOperand(0);
20497   while (Input.getOpcode() == ISD::BITCAST)
20498     Input = Input.getOperand(0);
20499
20500   MVT VT = Input.getSimpleValueType();
20501   MVT RootVT = Root.getSimpleValueType();
20502   SDLoc DL(Root);
20503
20504   // Just remove no-op shuffle masks.
20505   if (Mask.size() == 1) {
20506     DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Input),
20507                   /*AddTo*/ true);
20508     return true;
20509   }
20510
20511   // Use the float domain if the operand type is a floating point type.
20512   bool FloatDomain = VT.isFloatingPoint();
20513
20514   // For floating point shuffles, we don't have free copies in the shuffle
20515   // instructions or the ability to load as part of the instruction, so
20516   // canonicalize their shuffles to UNPCK or MOV variants.
20517   //
20518   // Note that even with AVX we prefer the PSHUFD form of shuffle for integer
20519   // vectors because it can have a load folded into it that UNPCK cannot. This
20520   // doesn't preclude something switching to the shorter encoding post-RA.
20521   //
20522   // FIXME: Should teach these routines about AVX vector widths.
20523   if (FloatDomain && VT.getSizeInBits() == 128) {
20524     if (Mask.equals({0, 0}) || Mask.equals({1, 1})) {
20525       bool Lo = Mask.equals({0, 0});
20526       unsigned Shuffle;
20527       MVT ShuffleVT;
20528       // Check if we have SSE3 which will let us use MOVDDUP. That instruction
20529       // is no slower than UNPCKLPD but has the option to fold the input operand
20530       // into even an unaligned memory load.
20531       if (Lo && Subtarget->hasSSE3()) {
20532         Shuffle = X86ISD::MOVDDUP;
20533         ShuffleVT = MVT::v2f64;
20534       } else {
20535         // We have MOVLHPS and MOVHLPS throughout SSE and they encode smaller
20536         // than the UNPCK variants.
20537         Shuffle = Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS;
20538         ShuffleVT = MVT::v4f32;
20539       }
20540       if (Depth == 1 && Root->getOpcode() == Shuffle)
20541         return false; // Nothing to do!
20542       Op = DAG.getBitcast(ShuffleVT, Input);
20543       DCI.AddToWorklist(Op.getNode());
20544       if (Shuffle == X86ISD::MOVDDUP)
20545         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
20546       else
20547         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
20548       DCI.AddToWorklist(Op.getNode());
20549       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
20550                     /*AddTo*/ true);
20551       return true;
20552     }
20553     if (Subtarget->hasSSE3() &&
20554         (Mask.equals({0, 0, 2, 2}) || Mask.equals({1, 1, 3, 3}))) {
20555       bool Lo = Mask.equals({0, 0, 2, 2});
20556       unsigned Shuffle = Lo ? X86ISD::MOVSLDUP : X86ISD::MOVSHDUP;
20557       MVT ShuffleVT = MVT::v4f32;
20558       if (Depth == 1 && Root->getOpcode() == Shuffle)
20559         return false; // Nothing to do!
20560       Op = DAG.getBitcast(ShuffleVT, Input);
20561       DCI.AddToWorklist(Op.getNode());
20562       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
20563       DCI.AddToWorklist(Op.getNode());
20564       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
20565                     /*AddTo*/ true);
20566       return true;
20567     }
20568     if (Mask.equals({0, 0, 1, 1}) || Mask.equals({2, 2, 3, 3})) {
20569       bool Lo = Mask.equals({0, 0, 1, 1});
20570       unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
20571       MVT ShuffleVT = MVT::v4f32;
20572       if (Depth == 1 && Root->getOpcode() == Shuffle)
20573         return false; // Nothing to do!
20574       Op = DAG.getBitcast(ShuffleVT, Input);
20575       DCI.AddToWorklist(Op.getNode());
20576       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
20577       DCI.AddToWorklist(Op.getNode());
20578       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
20579                     /*AddTo*/ true);
20580       return true;
20581     }
20582   }
20583
20584   // We always canonicalize the 8 x i16 and 16 x i8 shuffles into their UNPCK
20585   // variants as none of these have single-instruction variants that are
20586   // superior to the UNPCK formulation.
20587   if (!FloatDomain && VT.getSizeInBits() == 128 &&
20588       (Mask.equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
20589        Mask.equals({4, 4, 5, 5, 6, 6, 7, 7}) ||
20590        Mask.equals({0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7}) ||
20591        Mask.equals(
20592            {8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15}))) {
20593     bool Lo = Mask[0] == 0;
20594     unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
20595     if (Depth == 1 && Root->getOpcode() == Shuffle)
20596       return false; // Nothing to do!
20597     MVT ShuffleVT;
20598     switch (Mask.size()) {
20599     case 8:
20600       ShuffleVT = MVT::v8i16;
20601       break;
20602     case 16:
20603       ShuffleVT = MVT::v16i8;
20604       break;
20605     default:
20606       llvm_unreachable("Impossible mask size!");
20607     };
20608     Op = DAG.getBitcast(ShuffleVT, Input);
20609     DCI.AddToWorklist(Op.getNode());
20610     Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
20611     DCI.AddToWorklist(Op.getNode());
20612     DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
20613                   /*AddTo*/ true);
20614     return true;
20615   }
20616
20617   // Don't try to re-form single instruction chains under any circumstances now
20618   // that we've done encoding canonicalization for them.
20619   if (Depth < 2)
20620     return false;
20621
20622   // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
20623   // can replace them with a single PSHUFB instruction profitably. Intel's
20624   // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
20625   // in practice PSHUFB tends to be *very* fast so we're more aggressive.
20626   if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
20627     SmallVector<SDValue, 16> PSHUFBMask;
20628     int NumBytes = VT.getSizeInBits() / 8;
20629     int Ratio = NumBytes / Mask.size();
20630     for (int i = 0; i < NumBytes; ++i) {
20631       if (Mask[i / Ratio] == SM_SentinelUndef) {
20632         PSHUFBMask.push_back(DAG.getUNDEF(MVT::i8));
20633         continue;
20634       }
20635       int M = Mask[i / Ratio] != SM_SentinelZero
20636                   ? Ratio * Mask[i / Ratio] + i % Ratio
20637                   : 255;
20638       PSHUFBMask.push_back(DAG.getConstant(M, DL, MVT::i8));
20639     }
20640     MVT ByteVT = MVT::getVectorVT(MVT::i8, NumBytes);
20641     Op = DAG.getBitcast(ByteVT, Input);
20642     DCI.AddToWorklist(Op.getNode());
20643     SDValue PSHUFBMaskOp =
20644         DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVT, PSHUFBMask);
20645     DCI.AddToWorklist(PSHUFBMaskOp.getNode());
20646     Op = DAG.getNode(X86ISD::PSHUFB, DL, ByteVT, Op, PSHUFBMaskOp);
20647     DCI.AddToWorklist(Op.getNode());
20648     DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
20649                   /*AddTo*/ true);
20650     return true;
20651   }
20652
20653   // Failed to find any combines.
20654   return false;
20655 }
20656
20657 /// \brief Fully generic combining of x86 shuffle instructions.
20658 ///
20659 /// This should be the last combine run over the x86 shuffle instructions. Once
20660 /// they have been fully optimized, this will recursively consider all chains
20661 /// of single-use shuffle instructions, build a generic model of the cumulative
20662 /// shuffle operation, and check for simpler instructions which implement this
20663 /// operation. We use this primarily for two purposes:
20664 ///
20665 /// 1) Collapse generic shuffles to specialized single instructions when
20666 ///    equivalent. In most cases, this is just an encoding size win, but
20667 ///    sometimes we will collapse multiple generic shuffles into a single
20668 ///    special-purpose shuffle.
20669 /// 2) Look for sequences of shuffle instructions with 3 or more total
20670 ///    instructions, and replace them with the slightly more expensive SSSE3
20671 ///    PSHUFB instruction if available. We do this as the last combining step
20672 ///    to ensure we avoid using PSHUFB if we can implement the shuffle with
20673 ///    a suitable short sequence of other instructions. The PHUFB will either
20674 ///    use a register or have to read from memory and so is slightly (but only
20675 ///    slightly) more expensive than the other shuffle instructions.
20676 ///
20677 /// Because this is inherently a quadratic operation (for each shuffle in
20678 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
20679 /// This should never be an issue in practice as the shuffle lowering doesn't
20680 /// produce sequences of more than 8 instructions.
20681 ///
20682 /// FIXME: We will currently miss some cases where the redundant shuffling
20683 /// would simplify under the threshold for PSHUFB formation because of
20684 /// combine-ordering. To fix this, we should do the redundant instruction
20685 /// combining in this recursive walk.
20686 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
20687                                           ArrayRef<int> RootMask,
20688                                           int Depth, bool HasPSHUFB,
20689                                           SelectionDAG &DAG,
20690                                           TargetLowering::DAGCombinerInfo &DCI,
20691                                           const X86Subtarget *Subtarget) {
20692   // Bound the depth of our recursive combine because this is ultimately
20693   // quadratic in nature.
20694   if (Depth > 8)
20695     return false;
20696
20697   // Directly rip through bitcasts to find the underlying operand.
20698   while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
20699     Op = Op.getOperand(0);
20700
20701   MVT VT = Op.getSimpleValueType();
20702   if (!VT.isVector())
20703     return false; // Bail if we hit a non-vector.
20704
20705   assert(Root.getSimpleValueType().isVector() &&
20706          "Shuffles operate on vector types!");
20707   assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
20708          "Can only combine shuffles of the same vector register size.");
20709
20710   if (!isTargetShuffle(Op.getOpcode()))
20711     return false;
20712   SmallVector<int, 16> OpMask;
20713   bool IsUnary;
20714   bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, OpMask, IsUnary);
20715   // We only can combine unary shuffles which we can decode the mask for.
20716   if (!HaveMask || !IsUnary)
20717     return false;
20718
20719   assert(VT.getVectorNumElements() == OpMask.size() &&
20720          "Different mask size from vector size!");
20721   assert(((RootMask.size() > OpMask.size() &&
20722            RootMask.size() % OpMask.size() == 0) ||
20723           (OpMask.size() > RootMask.size() &&
20724            OpMask.size() % RootMask.size() == 0) ||
20725           OpMask.size() == RootMask.size()) &&
20726          "The smaller number of elements must divide the larger.");
20727   int RootRatio = std::max<int>(1, OpMask.size() / RootMask.size());
20728   int OpRatio = std::max<int>(1, RootMask.size() / OpMask.size());
20729   assert(((RootRatio == 1 && OpRatio == 1) ||
20730           (RootRatio == 1) != (OpRatio == 1)) &&
20731          "Must not have a ratio for both incoming and op masks!");
20732
20733   SmallVector<int, 16> Mask;
20734   Mask.reserve(std::max(OpMask.size(), RootMask.size()));
20735
20736   // Merge this shuffle operation's mask into our accumulated mask. Note that
20737   // this shuffle's mask will be the first applied to the input, followed by the
20738   // root mask to get us all the way to the root value arrangement. The reason
20739   // for this order is that we are recursing up the operation chain.
20740   for (int i = 0, e = std::max(OpMask.size(), RootMask.size()); i < e; ++i) {
20741     int RootIdx = i / RootRatio;
20742     if (RootMask[RootIdx] < 0) {
20743       // This is a zero or undef lane, we're done.
20744       Mask.push_back(RootMask[RootIdx]);
20745       continue;
20746     }
20747
20748     int RootMaskedIdx = RootMask[RootIdx] * RootRatio + i % RootRatio;
20749     int OpIdx = RootMaskedIdx / OpRatio;
20750     if (OpMask[OpIdx] < 0) {
20751       // The incoming lanes are zero or undef, it doesn't matter which ones we
20752       // are using.
20753       Mask.push_back(OpMask[OpIdx]);
20754       continue;
20755     }
20756
20757     // Ok, we have non-zero lanes, map them through.
20758     Mask.push_back(OpMask[OpIdx] * OpRatio +
20759                    RootMaskedIdx % OpRatio);
20760   }
20761
20762   // See if we can recurse into the operand to combine more things.
20763   switch (Op.getOpcode()) {
20764     case X86ISD::PSHUFB:
20765       HasPSHUFB = true;
20766     case X86ISD::PSHUFD:
20767     case X86ISD::PSHUFHW:
20768     case X86ISD::PSHUFLW:
20769       if (Op.getOperand(0).hasOneUse() &&
20770           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
20771                                         HasPSHUFB, DAG, DCI, Subtarget))
20772         return true;
20773       break;
20774
20775     case X86ISD::UNPCKL:
20776     case X86ISD::UNPCKH:
20777       assert(Op.getOperand(0) == Op.getOperand(1) && "We only combine unary shuffles!");
20778       // We can't check for single use, we have to check that this shuffle is the only user.
20779       if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
20780           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
20781                                         HasPSHUFB, DAG, DCI, Subtarget))
20782           return true;
20783       break;
20784   }
20785
20786   // Minor canonicalization of the accumulated shuffle mask to make it easier
20787   // to match below. All this does is detect masks with squential pairs of
20788   // elements, and shrink them to the half-width mask. It does this in a loop
20789   // so it will reduce the size of the mask to the minimal width mask which
20790   // performs an equivalent shuffle.
20791   SmallVector<int, 16> WidenedMask;
20792   while (Mask.size() > 1 && canWidenShuffleElements(Mask, WidenedMask)) {
20793     Mask = std::move(WidenedMask);
20794     WidenedMask.clear();
20795   }
20796
20797   return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
20798                                 Subtarget);
20799 }
20800
20801 /// \brief Get the PSHUF-style mask from PSHUF node.
20802 ///
20803 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
20804 /// PSHUF-style masks that can be reused with such instructions.
20805 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
20806   MVT VT = N.getSimpleValueType();
20807   SmallVector<int, 4> Mask;
20808   bool IsUnary;
20809   bool HaveMask = getTargetShuffleMask(N.getNode(), VT, Mask, IsUnary);
20810   (void)HaveMask;
20811   assert(HaveMask);
20812
20813   // If we have more than 128-bits, only the low 128-bits of shuffle mask
20814   // matter. Check that the upper masks are repeats and remove them.
20815   if (VT.getSizeInBits() > 128) {
20816     int LaneElts = 128 / VT.getScalarSizeInBits();
20817 #ifndef NDEBUG
20818     for (int i = 1, NumLanes = VT.getSizeInBits() / 128; i < NumLanes; ++i)
20819       for (int j = 0; j < LaneElts; ++j)
20820         assert(Mask[j] == Mask[i * LaneElts + j] - (LaneElts * i) &&
20821                "Mask doesn't repeat in high 128-bit lanes!");
20822 #endif
20823     Mask.resize(LaneElts);
20824   }
20825
20826   switch (N.getOpcode()) {
20827   case X86ISD::PSHUFD:
20828     return Mask;
20829   case X86ISD::PSHUFLW:
20830     Mask.resize(4);
20831     return Mask;
20832   case X86ISD::PSHUFHW:
20833     Mask.erase(Mask.begin(), Mask.begin() + 4);
20834     for (int &M : Mask)
20835       M -= 4;
20836     return Mask;
20837   default:
20838     llvm_unreachable("No valid shuffle instruction found!");
20839   }
20840 }
20841
20842 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
20843 ///
20844 /// We walk up the chain and look for a combinable shuffle, skipping over
20845 /// shuffles that we could hoist this shuffle's transformation past without
20846 /// altering anything.
20847 static SDValue
20848 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
20849                              SelectionDAG &DAG,
20850                              TargetLowering::DAGCombinerInfo &DCI) {
20851   assert(N.getOpcode() == X86ISD::PSHUFD &&
20852          "Called with something other than an x86 128-bit half shuffle!");
20853   SDLoc DL(N);
20854
20855   // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
20856   // of the shuffles in the chain so that we can form a fresh chain to replace
20857   // this one.
20858   SmallVector<SDValue, 8> Chain;
20859   SDValue V = N.getOperand(0);
20860   for (; V.hasOneUse(); V = V.getOperand(0)) {
20861     switch (V.getOpcode()) {
20862     default:
20863       return SDValue(); // Nothing combined!
20864
20865     case ISD::BITCAST:
20866       // Skip bitcasts as we always know the type for the target specific
20867       // instructions.
20868       continue;
20869
20870     case X86ISD::PSHUFD:
20871       // Found another dword shuffle.
20872       break;
20873
20874     case X86ISD::PSHUFLW:
20875       // Check that the low words (being shuffled) are the identity in the
20876       // dword shuffle, and the high words are self-contained.
20877       if (Mask[0] != 0 || Mask[1] != 1 ||
20878           !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
20879         return SDValue();
20880
20881       Chain.push_back(V);
20882       continue;
20883
20884     case X86ISD::PSHUFHW:
20885       // Check that the high words (being shuffled) are the identity in the
20886       // dword shuffle, and the low words are self-contained.
20887       if (Mask[2] != 2 || Mask[3] != 3 ||
20888           !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
20889         return SDValue();
20890
20891       Chain.push_back(V);
20892       continue;
20893
20894     case X86ISD::UNPCKL:
20895     case X86ISD::UNPCKH:
20896       // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
20897       // shuffle into a preceding word shuffle.
20898       if (V.getSimpleValueType().getScalarType() != MVT::i8 &&
20899           V.getSimpleValueType().getScalarType() != MVT::i16)
20900         return SDValue();
20901
20902       // Search for a half-shuffle which we can combine with.
20903       unsigned CombineOp =
20904           V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
20905       if (V.getOperand(0) != V.getOperand(1) ||
20906           !V->isOnlyUserOf(V.getOperand(0).getNode()))
20907         return SDValue();
20908       Chain.push_back(V);
20909       V = V.getOperand(0);
20910       do {
20911         switch (V.getOpcode()) {
20912         default:
20913           return SDValue(); // Nothing to combine.
20914
20915         case X86ISD::PSHUFLW:
20916         case X86ISD::PSHUFHW:
20917           if (V.getOpcode() == CombineOp)
20918             break;
20919
20920           Chain.push_back(V);
20921
20922           // Fallthrough!
20923         case ISD::BITCAST:
20924           V = V.getOperand(0);
20925           continue;
20926         }
20927         break;
20928       } while (V.hasOneUse());
20929       break;
20930     }
20931     // Break out of the loop if we break out of the switch.
20932     break;
20933   }
20934
20935   if (!V.hasOneUse())
20936     // We fell out of the loop without finding a viable combining instruction.
20937     return SDValue();
20938
20939   // Merge this node's mask and our incoming mask.
20940   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
20941   for (int &M : Mask)
20942     M = VMask[M];
20943   V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
20944                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
20945
20946   // Rebuild the chain around this new shuffle.
20947   while (!Chain.empty()) {
20948     SDValue W = Chain.pop_back_val();
20949
20950     if (V.getValueType() != W.getOperand(0).getValueType())
20951       V = DAG.getBitcast(W.getOperand(0).getValueType(), V);
20952
20953     switch (W.getOpcode()) {
20954     default:
20955       llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
20956
20957     case X86ISD::UNPCKL:
20958     case X86ISD::UNPCKH:
20959       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
20960       break;
20961
20962     case X86ISD::PSHUFD:
20963     case X86ISD::PSHUFLW:
20964     case X86ISD::PSHUFHW:
20965       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
20966       break;
20967     }
20968   }
20969   if (V.getValueType() != N.getValueType())
20970     V = DAG.getBitcast(N.getValueType(), V);
20971
20972   // Return the new chain to replace N.
20973   return V;
20974 }
20975
20976 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or pshufhw.
20977 ///
20978 /// We walk up the chain, skipping shuffles of the other half and looking
20979 /// through shuffles which switch halves trying to find a shuffle of the same
20980 /// pair of dwords.
20981 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
20982                                         SelectionDAG &DAG,
20983                                         TargetLowering::DAGCombinerInfo &DCI) {
20984   assert(
20985       (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
20986       "Called with something other than an x86 128-bit half shuffle!");
20987   SDLoc DL(N);
20988   unsigned CombineOpcode = N.getOpcode();
20989
20990   // Walk up a single-use chain looking for a combinable shuffle.
20991   SDValue V = N.getOperand(0);
20992   for (; V.hasOneUse(); V = V.getOperand(0)) {
20993     switch (V.getOpcode()) {
20994     default:
20995       return false; // Nothing combined!
20996
20997     case ISD::BITCAST:
20998       // Skip bitcasts as we always know the type for the target specific
20999       // instructions.
21000       continue;
21001
21002     case X86ISD::PSHUFLW:
21003     case X86ISD::PSHUFHW:
21004       if (V.getOpcode() == CombineOpcode)
21005         break;
21006
21007       // Other-half shuffles are no-ops.
21008       continue;
21009     }
21010     // Break out of the loop if we break out of the switch.
21011     break;
21012   }
21013
21014   if (!V.hasOneUse())
21015     // We fell out of the loop without finding a viable combining instruction.
21016     return false;
21017
21018   // Combine away the bottom node as its shuffle will be accumulated into
21019   // a preceding shuffle.
21020   DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
21021
21022   // Record the old value.
21023   SDValue Old = V;
21024
21025   // Merge this node's mask and our incoming mask (adjusted to account for all
21026   // the pshufd instructions encountered).
21027   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
21028   for (int &M : Mask)
21029     M = VMask[M];
21030   V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
21031                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
21032
21033   // Check that the shuffles didn't cancel each other out. If not, we need to
21034   // combine to the new one.
21035   if (Old != V)
21036     // Replace the combinable shuffle with the combined one, updating all users
21037     // so that we re-evaluate the chain here.
21038     DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
21039
21040   return true;
21041 }
21042
21043 /// \brief Try to combine x86 target specific shuffles.
21044 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
21045                                            TargetLowering::DAGCombinerInfo &DCI,
21046                                            const X86Subtarget *Subtarget) {
21047   SDLoc DL(N);
21048   MVT VT = N.getSimpleValueType();
21049   SmallVector<int, 4> Mask;
21050
21051   switch (N.getOpcode()) {
21052   case X86ISD::PSHUFD:
21053   case X86ISD::PSHUFLW:
21054   case X86ISD::PSHUFHW:
21055     Mask = getPSHUFShuffleMask(N);
21056     assert(Mask.size() == 4);
21057     break;
21058   default:
21059     return SDValue();
21060   }
21061
21062   // Nuke no-op shuffles that show up after combining.
21063   if (isNoopShuffleMask(Mask))
21064     return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
21065
21066   // Look for simplifications involving one or two shuffle instructions.
21067   SDValue V = N.getOperand(0);
21068   switch (N.getOpcode()) {
21069   default:
21070     break;
21071   case X86ISD::PSHUFLW:
21072   case X86ISD::PSHUFHW:
21073     assert(VT.getScalarType() == MVT::i16 && "Bad word shuffle type!");
21074
21075     if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
21076       return SDValue(); // We combined away this shuffle, so we're done.
21077
21078     // See if this reduces to a PSHUFD which is no more expensive and can
21079     // combine with more operations. Note that it has to at least flip the
21080     // dwords as otherwise it would have been removed as a no-op.
21081     if (makeArrayRef(Mask).equals({2, 3, 0, 1})) {
21082       int DMask[] = {0, 1, 2, 3};
21083       int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
21084       DMask[DOffset + 0] = DOffset + 1;
21085       DMask[DOffset + 1] = DOffset + 0;
21086       MVT DVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
21087       V = DAG.getBitcast(DVT, V);
21088       DCI.AddToWorklist(V.getNode());
21089       V = DAG.getNode(X86ISD::PSHUFD, DL, DVT, V,
21090                       getV4X86ShuffleImm8ForMask(DMask, DL, DAG));
21091       DCI.AddToWorklist(V.getNode());
21092       return DAG.getBitcast(VT, V);
21093     }
21094
21095     // Look for shuffle patterns which can be implemented as a single unpack.
21096     // FIXME: This doesn't handle the location of the PSHUFD generically, and
21097     // only works when we have a PSHUFD followed by two half-shuffles.
21098     if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
21099         (V.getOpcode() == X86ISD::PSHUFLW ||
21100          V.getOpcode() == X86ISD::PSHUFHW) &&
21101         V.getOpcode() != N.getOpcode() &&
21102         V.hasOneUse()) {
21103       SDValue D = V.getOperand(0);
21104       while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
21105         D = D.getOperand(0);
21106       if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
21107         SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
21108         SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
21109         int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
21110         int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
21111         int WordMask[8];
21112         for (int i = 0; i < 4; ++i) {
21113           WordMask[i + NOffset] = Mask[i] + NOffset;
21114           WordMask[i + VOffset] = VMask[i] + VOffset;
21115         }
21116         // Map the word mask through the DWord mask.
21117         int MappedMask[8];
21118         for (int i = 0; i < 8; ++i)
21119           MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
21120         if (makeArrayRef(MappedMask).equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
21121             makeArrayRef(MappedMask).equals({4, 4, 5, 5, 6, 6, 7, 7})) {
21122           // We can replace all three shuffles with an unpack.
21123           V = DAG.getBitcast(VT, D.getOperand(0));
21124           DCI.AddToWorklist(V.getNode());
21125           return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
21126                                                 : X86ISD::UNPCKH,
21127                              DL, VT, V, V);
21128         }
21129       }
21130     }
21131
21132     break;
21133
21134   case X86ISD::PSHUFD:
21135     if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG, DCI))
21136       return NewN;
21137
21138     break;
21139   }
21140
21141   return SDValue();
21142 }
21143
21144 /// \brief Try to combine a shuffle into a target-specific add-sub node.
21145 ///
21146 /// We combine this directly on the abstract vector shuffle nodes so it is
21147 /// easier to generically match. We also insert dummy vector shuffle nodes for
21148 /// the operands which explicitly discard the lanes which are unused by this
21149 /// operation to try to flow through the rest of the combiner the fact that
21150 /// they're unused.
21151 static SDValue combineShuffleToAddSub(SDNode *N, SelectionDAG &DAG) {
21152   SDLoc DL(N);
21153   EVT VT = N->getValueType(0);
21154
21155   // We only handle target-independent shuffles.
21156   // FIXME: It would be easy and harmless to use the target shuffle mask
21157   // extraction tool to support more.
21158   if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
21159     return SDValue();
21160
21161   auto *SVN = cast<ShuffleVectorSDNode>(N);
21162   ArrayRef<int> Mask = SVN->getMask();
21163   SDValue V1 = N->getOperand(0);
21164   SDValue V2 = N->getOperand(1);
21165
21166   // We require the first shuffle operand to be the SUB node, and the second to
21167   // be the ADD node.
21168   // FIXME: We should support the commuted patterns.
21169   if (V1->getOpcode() != ISD::FSUB || V2->getOpcode() != ISD::FADD)
21170     return SDValue();
21171
21172   // If there are other uses of these operations we can't fold them.
21173   if (!V1->hasOneUse() || !V2->hasOneUse())
21174     return SDValue();
21175
21176   // Ensure that both operations have the same operands. Note that we can
21177   // commute the FADD operands.
21178   SDValue LHS = V1->getOperand(0), RHS = V1->getOperand(1);
21179   if ((V2->getOperand(0) != LHS || V2->getOperand(1) != RHS) &&
21180       (V2->getOperand(0) != RHS || V2->getOperand(1) != LHS))
21181     return SDValue();
21182
21183   // We're looking for blends between FADD and FSUB nodes. We insist on these
21184   // nodes being lined up in a specific expected pattern.
21185   if (!(isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
21186         isShuffleEquivalent(V1, V2, Mask, {0, 5, 2, 7}) ||
21187         isShuffleEquivalent(V1, V2, Mask, {0, 9, 2, 11, 4, 13, 6, 15})))
21188     return SDValue();
21189
21190   // Only specific types are legal at this point, assert so we notice if and
21191   // when these change.
21192   assert((VT == MVT::v4f32 || VT == MVT::v2f64 || VT == MVT::v8f32 ||
21193           VT == MVT::v4f64) &&
21194          "Unknown vector type encountered!");
21195
21196   return DAG.getNode(X86ISD::ADDSUB, DL, VT, LHS, RHS);
21197 }
21198
21199 /// PerformShuffleCombine - Performs several different shuffle combines.
21200 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
21201                                      TargetLowering::DAGCombinerInfo &DCI,
21202                                      const X86Subtarget *Subtarget) {
21203   SDLoc dl(N);
21204   SDValue N0 = N->getOperand(0);
21205   SDValue N1 = N->getOperand(1);
21206   EVT VT = N->getValueType(0);
21207
21208   // Don't create instructions with illegal types after legalize types has run.
21209   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21210   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
21211     return SDValue();
21212
21213   // If we have legalized the vector types, look for blends of FADD and FSUB
21214   // nodes that we can fuse into an ADDSUB node.
21215   if (TLI.isTypeLegal(VT) && Subtarget->hasSSE3())
21216     if (SDValue AddSub = combineShuffleToAddSub(N, DAG))
21217       return AddSub;
21218
21219   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
21220   if (Subtarget->hasFp256() && VT.is256BitVector() &&
21221       N->getOpcode() == ISD::VECTOR_SHUFFLE)
21222     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
21223
21224   // During Type Legalization, when promoting illegal vector types,
21225   // the backend might introduce new shuffle dag nodes and bitcasts.
21226   //
21227   // This code performs the following transformation:
21228   // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
21229   //       (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
21230   //
21231   // We do this only if both the bitcast and the BINOP dag nodes have
21232   // one use. Also, perform this transformation only if the new binary
21233   // operation is legal. This is to avoid introducing dag nodes that
21234   // potentially need to be further expanded (or custom lowered) into a
21235   // less optimal sequence of dag nodes.
21236   if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
21237       N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
21238       N0.getOpcode() == ISD::BITCAST) {
21239     SDValue BC0 = N0.getOperand(0);
21240     EVT SVT = BC0.getValueType();
21241     unsigned Opcode = BC0.getOpcode();
21242     unsigned NumElts = VT.getVectorNumElements();
21243
21244     if (BC0.hasOneUse() && SVT.isVector() &&
21245         SVT.getVectorNumElements() * 2 == NumElts &&
21246         TLI.isOperationLegal(Opcode, VT)) {
21247       bool CanFold = false;
21248       switch (Opcode) {
21249       default : break;
21250       case ISD::ADD :
21251       case ISD::FADD :
21252       case ISD::SUB :
21253       case ISD::FSUB :
21254       case ISD::MUL :
21255       case ISD::FMUL :
21256         CanFold = true;
21257       }
21258
21259       unsigned SVTNumElts = SVT.getVectorNumElements();
21260       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
21261       for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
21262         CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
21263       for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
21264         CanFold = SVOp->getMaskElt(i) < 0;
21265
21266       if (CanFold) {
21267         SDValue BC00 = DAG.getBitcast(VT, BC0.getOperand(0));
21268         SDValue BC01 = DAG.getBitcast(VT, BC0.getOperand(1));
21269         SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
21270         return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
21271       }
21272     }
21273   }
21274
21275   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
21276   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
21277   // consecutive, non-overlapping, and in the right order.
21278   SmallVector<SDValue, 16> Elts;
21279   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
21280     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
21281
21282   if (SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true))
21283     return LD;
21284
21285   if (isTargetShuffle(N->getOpcode())) {
21286     SDValue Shuffle =
21287         PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
21288     if (Shuffle.getNode())
21289       return Shuffle;
21290
21291     // Try recursively combining arbitrary sequences of x86 shuffle
21292     // instructions into higher-order shuffles. We do this after combining
21293     // specific PSHUF instruction sequences into their minimal form so that we
21294     // can evaluate how many specialized shuffle instructions are involved in
21295     // a particular chain.
21296     SmallVector<int, 1> NonceMask; // Just a placeholder.
21297     NonceMask.push_back(0);
21298     if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
21299                                       /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
21300                                       DCI, Subtarget))
21301       return SDValue(); // This routine will use CombineTo to replace N.
21302   }
21303
21304   return SDValue();
21305 }
21306
21307 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
21308 /// specific shuffle of a load can be folded into a single element load.
21309 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
21310 /// shuffles have been custom lowered so we need to handle those here.
21311 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
21312                                          TargetLowering::DAGCombinerInfo &DCI) {
21313   if (DCI.isBeforeLegalizeOps())
21314     return SDValue();
21315
21316   SDValue InVec = N->getOperand(0);
21317   SDValue EltNo = N->getOperand(1);
21318
21319   if (!isa<ConstantSDNode>(EltNo))
21320     return SDValue();
21321
21322   EVT OriginalVT = InVec.getValueType();
21323
21324   if (InVec.getOpcode() == ISD::BITCAST) {
21325     // Don't duplicate a load with other uses.
21326     if (!InVec.hasOneUse())
21327       return SDValue();
21328     EVT BCVT = InVec.getOperand(0).getValueType();
21329     if (!BCVT.isVector() ||
21330         BCVT.getVectorNumElements() != OriginalVT.getVectorNumElements())
21331       return SDValue();
21332     InVec = InVec.getOperand(0);
21333   }
21334
21335   EVT CurrentVT = InVec.getValueType();
21336
21337   if (!isTargetShuffle(InVec.getOpcode()))
21338     return SDValue();
21339
21340   // Don't duplicate a load with other uses.
21341   if (!InVec.hasOneUse())
21342     return SDValue();
21343
21344   SmallVector<int, 16> ShuffleMask;
21345   bool UnaryShuffle;
21346   if (!getTargetShuffleMask(InVec.getNode(), CurrentVT.getSimpleVT(),
21347                             ShuffleMask, UnaryShuffle))
21348     return SDValue();
21349
21350   // Select the input vector, guarding against out of range extract vector.
21351   unsigned NumElems = CurrentVT.getVectorNumElements();
21352   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
21353   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
21354   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
21355                                          : InVec.getOperand(1);
21356
21357   // If inputs to shuffle are the same for both ops, then allow 2 uses
21358   unsigned AllowedUses = InVec.getNumOperands() > 1 &&
21359                          InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
21360
21361   if (LdNode.getOpcode() == ISD::BITCAST) {
21362     // Don't duplicate a load with other uses.
21363     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
21364       return SDValue();
21365
21366     AllowedUses = 1; // only allow 1 load use if we have a bitcast
21367     LdNode = LdNode.getOperand(0);
21368   }
21369
21370   if (!ISD::isNormalLoad(LdNode.getNode()))
21371     return SDValue();
21372
21373   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
21374
21375   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
21376     return SDValue();
21377
21378   EVT EltVT = N->getValueType(0);
21379   // If there's a bitcast before the shuffle, check if the load type and
21380   // alignment is valid.
21381   unsigned Align = LN0->getAlignment();
21382   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21383   unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
21384       EltVT.getTypeForEVT(*DAG.getContext()));
21385
21386   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, EltVT))
21387     return SDValue();
21388
21389   // All checks match so transform back to vector_shuffle so that DAG combiner
21390   // can finish the job
21391   SDLoc dl(N);
21392
21393   // Create shuffle node taking into account the case that its a unary shuffle
21394   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(CurrentVT)
21395                                    : InVec.getOperand(1);
21396   Shuffle = DAG.getVectorShuffle(CurrentVT, dl,
21397                                  InVec.getOperand(0), Shuffle,
21398                                  &ShuffleMask[0]);
21399   Shuffle = DAG.getBitcast(OriginalVT, Shuffle);
21400   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
21401                      EltNo);
21402 }
21403
21404 /// \brief Detect bitcasts between i32 to x86mmx low word. Since MMX types are
21405 /// special and don't usually play with other vector types, it's better to
21406 /// handle them early to be sure we emit efficient code by avoiding
21407 /// store-load conversions.
21408 static SDValue PerformBITCASTCombine(SDNode *N, SelectionDAG &DAG) {
21409   if (N->getValueType(0) != MVT::x86mmx ||
21410       N->getOperand(0)->getOpcode() != ISD::BUILD_VECTOR ||
21411       N->getOperand(0)->getValueType(0) != MVT::v2i32)
21412     return SDValue();
21413
21414   SDValue V = N->getOperand(0);
21415   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V.getOperand(1));
21416   if (C && C->getZExtValue() == 0 && V.getOperand(0).getValueType() == MVT::i32)
21417     return DAG.getNode(X86ISD::MMX_MOVW2D, SDLoc(V.getOperand(0)),
21418                        N->getValueType(0), V.getOperand(0));
21419
21420   return SDValue();
21421 }
21422
21423 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
21424 /// generation and convert it from being a bunch of shuffles and extracts
21425 /// into a somewhat faster sequence. For i686, the best sequence is apparently
21426 /// storing the value and loading scalars back, while for x64 we should
21427 /// use 64-bit extracts and shifts.
21428 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
21429                                          TargetLowering::DAGCombinerInfo &DCI) {
21430   if (SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI))
21431     return NewOp;
21432
21433   SDValue InputVector = N->getOperand(0);
21434   SDLoc dl(InputVector);
21435   // Detect mmx to i32 conversion through a v2i32 elt extract.
21436   if (InputVector.getOpcode() == ISD::BITCAST && InputVector.hasOneUse() &&
21437       N->getValueType(0) == MVT::i32 &&
21438       InputVector.getValueType() == MVT::v2i32) {
21439
21440     // The bitcast source is a direct mmx result.
21441     SDValue MMXSrc = InputVector.getNode()->getOperand(0);
21442     if (MMXSrc.getValueType() == MVT::x86mmx)
21443       return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
21444                          N->getValueType(0),
21445                          InputVector.getNode()->getOperand(0));
21446
21447     // The mmx is indirect: (i64 extract_elt (v1i64 bitcast (x86mmx ...))).
21448     SDValue MMXSrcOp = MMXSrc.getOperand(0);
21449     if (MMXSrc.getOpcode() == ISD::EXTRACT_VECTOR_ELT && MMXSrc.hasOneUse() &&
21450         MMXSrc.getValueType() == MVT::i64 && MMXSrcOp.hasOneUse() &&
21451         MMXSrcOp.getOpcode() == ISD::BITCAST &&
21452         MMXSrcOp.getValueType() == MVT::v1i64 &&
21453         MMXSrcOp.getOperand(0).getValueType() == MVT::x86mmx)
21454       return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
21455                          N->getValueType(0),
21456                          MMXSrcOp.getOperand(0));
21457   }
21458
21459   EVT VT = N->getValueType(0);
21460
21461   if (VT == MVT::i1 && dyn_cast<ConstantSDNode>(N->getOperand(1)) &&
21462       InputVector.getOpcode() == ISD::BITCAST &&
21463       dyn_cast<ConstantSDNode>(InputVector.getOperand(0))) {
21464     uint64_t ExtractedElt =
21465           cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
21466     uint64_t InputValue =
21467           cast<ConstantSDNode>(InputVector.getOperand(0))->getZExtValue();
21468     uint64_t Res = (InputValue >> ExtractedElt) & 1;
21469     return DAG.getConstant(Res, dl, MVT::i1);
21470   }
21471   // Only operate on vectors of 4 elements, where the alternative shuffling
21472   // gets to be more expensive.
21473   if (InputVector.getValueType() != MVT::v4i32)
21474     return SDValue();
21475
21476   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
21477   // single use which is a sign-extend or zero-extend, and all elements are
21478   // used.
21479   SmallVector<SDNode *, 4> Uses;
21480   unsigned ExtractedElements = 0;
21481   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
21482        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
21483     if (UI.getUse().getResNo() != InputVector.getResNo())
21484       return SDValue();
21485
21486     SDNode *Extract = *UI;
21487     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
21488       return SDValue();
21489
21490     if (Extract->getValueType(0) != MVT::i32)
21491       return SDValue();
21492     if (!Extract->hasOneUse())
21493       return SDValue();
21494     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
21495         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
21496       return SDValue();
21497     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
21498       return SDValue();
21499
21500     // Record which element was extracted.
21501     ExtractedElements |=
21502       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
21503
21504     Uses.push_back(Extract);
21505   }
21506
21507   // If not all the elements were used, this may not be worthwhile.
21508   if (ExtractedElements != 15)
21509     return SDValue();
21510
21511   // Ok, we've now decided to do the transformation.
21512   // If 64-bit shifts are legal, use the extract-shift sequence,
21513   // otherwise bounce the vector off the cache.
21514   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21515   SDValue Vals[4];
21516
21517   if (TLI.isOperationLegal(ISD::SRA, MVT::i64)) {
21518     SDValue Cst = DAG.getBitcast(MVT::v2i64, InputVector);
21519     EVT VecIdxTy = DAG.getTargetLoweringInfo().getVectorIdxTy();
21520     SDValue BottomHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
21521       DAG.getConstant(0, dl, VecIdxTy));
21522     SDValue TopHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
21523       DAG.getConstant(1, dl, VecIdxTy));
21524
21525     SDValue ShAmt = DAG.getConstant(32, dl,
21526       DAG.getTargetLoweringInfo().getShiftAmountTy(MVT::i64));
21527     Vals[0] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BottomHalf);
21528     Vals[1] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
21529       DAG.getNode(ISD::SRA, dl, MVT::i64, BottomHalf, ShAmt));
21530     Vals[2] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, TopHalf);
21531     Vals[3] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
21532       DAG.getNode(ISD::SRA, dl, MVT::i64, TopHalf, ShAmt));
21533   } else {
21534     // Store the value to a temporary stack slot.
21535     SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
21536     SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
21537       MachinePointerInfo(), false, false, 0);
21538
21539     EVT ElementType = InputVector.getValueType().getVectorElementType();
21540     unsigned EltSize = ElementType.getSizeInBits() / 8;
21541
21542     // Replace each use (extract) with a load of the appropriate element.
21543     for (unsigned i = 0; i < 4; ++i) {
21544       uint64_t Offset = EltSize * i;
21545       SDValue OffsetVal = DAG.getConstant(Offset, dl, TLI.getPointerTy());
21546
21547       SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
21548                                        StackPtr, OffsetVal);
21549
21550       // Load the scalar.
21551       Vals[i] = DAG.getLoad(ElementType, dl, Ch,
21552                             ScalarAddr, MachinePointerInfo(),
21553                             false, false, false, 0);
21554
21555     }
21556   }
21557
21558   // Replace the extracts
21559   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
21560     UE = Uses.end(); UI != UE; ++UI) {
21561     SDNode *Extract = *UI;
21562
21563     SDValue Idx = Extract->getOperand(1);
21564     uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
21565     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), Vals[IdxVal]);
21566   }
21567
21568   // The replacement was made in place; don't return anything.
21569   return SDValue();
21570 }
21571
21572 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
21573 static std::pair<unsigned, bool>
21574 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
21575                    SelectionDAG &DAG, const X86Subtarget *Subtarget) {
21576   if (!VT.isVector())
21577     return std::make_pair(0, false);
21578
21579   bool NeedSplit = false;
21580   switch (VT.getSimpleVT().SimpleTy) {
21581   default: return std::make_pair(0, false);
21582   case MVT::v4i64:
21583   case MVT::v2i64:
21584     if (!Subtarget->hasVLX())
21585       return std::make_pair(0, false);
21586     break;
21587   case MVT::v64i8:
21588   case MVT::v32i16:
21589     if (!Subtarget->hasBWI())
21590       return std::make_pair(0, false);
21591     break;
21592   case MVT::v16i32:
21593   case MVT::v8i64:
21594     if (!Subtarget->hasAVX512())
21595       return std::make_pair(0, false);
21596     break;
21597   case MVT::v32i8:
21598   case MVT::v16i16:
21599   case MVT::v8i32:
21600     if (!Subtarget->hasAVX2())
21601       NeedSplit = true;
21602     if (!Subtarget->hasAVX())
21603       return std::make_pair(0, false);
21604     break;
21605   case MVT::v16i8:
21606   case MVT::v8i16:
21607   case MVT::v4i32:
21608     if (!Subtarget->hasSSE2())
21609       return std::make_pair(0, false);
21610   }
21611
21612   // SSE2 has only a small subset of the operations.
21613   bool hasUnsigned = Subtarget->hasSSE41() ||
21614                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
21615   bool hasSigned = Subtarget->hasSSE41() ||
21616                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
21617
21618   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
21619
21620   unsigned Opc = 0;
21621   // Check for x CC y ? x : y.
21622   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
21623       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
21624     switch (CC) {
21625     default: break;
21626     case ISD::SETULT:
21627     case ISD::SETULE:
21628       Opc = hasUnsigned ? X86ISD::UMIN : 0u; break;
21629     case ISD::SETUGT:
21630     case ISD::SETUGE:
21631       Opc = hasUnsigned ? X86ISD::UMAX : 0u; break;
21632     case ISD::SETLT:
21633     case ISD::SETLE:
21634       Opc = hasSigned ? X86ISD::SMIN : 0u; break;
21635     case ISD::SETGT:
21636     case ISD::SETGE:
21637       Opc = hasSigned ? X86ISD::SMAX : 0u; break;
21638     }
21639   // Check for x CC y ? y : x -- a min/max with reversed arms.
21640   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
21641              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
21642     switch (CC) {
21643     default: break;
21644     case ISD::SETULT:
21645     case ISD::SETULE:
21646       Opc = hasUnsigned ? X86ISD::UMAX : 0u; break;
21647     case ISD::SETUGT:
21648     case ISD::SETUGE:
21649       Opc = hasUnsigned ? X86ISD::UMIN : 0u; break;
21650     case ISD::SETLT:
21651     case ISD::SETLE:
21652       Opc = hasSigned ? X86ISD::SMAX : 0u; break;
21653     case ISD::SETGT:
21654     case ISD::SETGE:
21655       Opc = hasSigned ? X86ISD::SMIN : 0u; break;
21656     }
21657   }
21658
21659   return std::make_pair(Opc, NeedSplit);
21660 }
21661
21662 static SDValue
21663 transformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
21664                                       const X86Subtarget *Subtarget) {
21665   SDLoc dl(N);
21666   SDValue Cond = N->getOperand(0);
21667   SDValue LHS = N->getOperand(1);
21668   SDValue RHS = N->getOperand(2);
21669
21670   if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
21671     SDValue CondSrc = Cond->getOperand(0);
21672     if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
21673       Cond = CondSrc->getOperand(0);
21674   }
21675
21676   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
21677     return SDValue();
21678
21679   // A vselect where all conditions and data are constants can be optimized into
21680   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
21681   if (ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
21682       ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
21683     return SDValue();
21684
21685   unsigned MaskValue = 0;
21686   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
21687     return SDValue();
21688
21689   MVT VT = N->getSimpleValueType(0);
21690   unsigned NumElems = VT.getVectorNumElements();
21691   SmallVector<int, 8> ShuffleMask(NumElems, -1);
21692   for (unsigned i = 0; i < NumElems; ++i) {
21693     // Be sure we emit undef where we can.
21694     if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
21695       ShuffleMask[i] = -1;
21696     else
21697       ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
21698   }
21699
21700   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21701   if (!TLI.isShuffleMaskLegal(ShuffleMask, VT))
21702     return SDValue();
21703   return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
21704 }
21705
21706 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
21707 /// nodes.
21708 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
21709                                     TargetLowering::DAGCombinerInfo &DCI,
21710                                     const X86Subtarget *Subtarget) {
21711   SDLoc DL(N);
21712   SDValue Cond = N->getOperand(0);
21713   // Get the LHS/RHS of the select.
21714   SDValue LHS = N->getOperand(1);
21715   SDValue RHS = N->getOperand(2);
21716   EVT VT = LHS.getValueType();
21717   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21718
21719   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
21720   // instructions match the semantics of the common C idiom x<y?x:y but not
21721   // x<=y?x:y, because of how they handle negative zero (which can be
21722   // ignored in unsafe-math mode).
21723   // We also try to create v2f32 min/max nodes, which we later widen to v4f32.
21724   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
21725       VT != MVT::f80 && (TLI.isTypeLegal(VT) || VT == MVT::v2f32) &&
21726       (Subtarget->hasSSE2() ||
21727        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
21728     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
21729
21730     unsigned Opcode = 0;
21731     // Check for x CC y ? x : y.
21732     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
21733         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
21734       switch (CC) {
21735       default: break;
21736       case ISD::SETULT:
21737         // Converting this to a min would handle NaNs incorrectly, and swapping
21738         // the operands would cause it to handle comparisons between positive
21739         // and negative zero incorrectly.
21740         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
21741           if (!DAG.getTarget().Options.UnsafeFPMath &&
21742               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
21743             break;
21744           std::swap(LHS, RHS);
21745         }
21746         Opcode = X86ISD::FMIN;
21747         break;
21748       case ISD::SETOLE:
21749         // Converting this to a min would handle comparisons between positive
21750         // and negative zero incorrectly.
21751         if (!DAG.getTarget().Options.UnsafeFPMath &&
21752             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
21753           break;
21754         Opcode = X86ISD::FMIN;
21755         break;
21756       case ISD::SETULE:
21757         // Converting this to a min would handle both negative zeros and NaNs
21758         // incorrectly, but we can swap the operands to fix both.
21759         std::swap(LHS, RHS);
21760       case ISD::SETOLT:
21761       case ISD::SETLT:
21762       case ISD::SETLE:
21763         Opcode = X86ISD::FMIN;
21764         break;
21765
21766       case ISD::SETOGE:
21767         // Converting this to a max would handle comparisons between positive
21768         // and negative zero incorrectly.
21769         if (!DAG.getTarget().Options.UnsafeFPMath &&
21770             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
21771           break;
21772         Opcode = X86ISD::FMAX;
21773         break;
21774       case ISD::SETUGT:
21775         // Converting this to a max would handle NaNs incorrectly, and swapping
21776         // the operands would cause it to handle comparisons between positive
21777         // and negative zero incorrectly.
21778         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
21779           if (!DAG.getTarget().Options.UnsafeFPMath &&
21780               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
21781             break;
21782           std::swap(LHS, RHS);
21783         }
21784         Opcode = X86ISD::FMAX;
21785         break;
21786       case ISD::SETUGE:
21787         // Converting this to a max would handle both negative zeros and NaNs
21788         // incorrectly, but we can swap the operands to fix both.
21789         std::swap(LHS, RHS);
21790       case ISD::SETOGT:
21791       case ISD::SETGT:
21792       case ISD::SETGE:
21793         Opcode = X86ISD::FMAX;
21794         break;
21795       }
21796     // Check for x CC y ? y : x -- a min/max with reversed arms.
21797     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
21798                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
21799       switch (CC) {
21800       default: break;
21801       case ISD::SETOGE:
21802         // Converting this to a min would handle comparisons between positive
21803         // and negative zero incorrectly, and swapping the operands would
21804         // cause it to handle NaNs incorrectly.
21805         if (!DAG.getTarget().Options.UnsafeFPMath &&
21806             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
21807           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
21808             break;
21809           std::swap(LHS, RHS);
21810         }
21811         Opcode = X86ISD::FMIN;
21812         break;
21813       case ISD::SETUGT:
21814         // Converting this to a min would handle NaNs incorrectly.
21815         if (!DAG.getTarget().Options.UnsafeFPMath &&
21816             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
21817           break;
21818         Opcode = X86ISD::FMIN;
21819         break;
21820       case ISD::SETUGE:
21821         // Converting this to a min would handle both negative zeros and NaNs
21822         // incorrectly, but we can swap the operands to fix both.
21823         std::swap(LHS, RHS);
21824       case ISD::SETOGT:
21825       case ISD::SETGT:
21826       case ISD::SETGE:
21827         Opcode = X86ISD::FMIN;
21828         break;
21829
21830       case ISD::SETULT:
21831         // Converting this to a max would handle NaNs incorrectly.
21832         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
21833           break;
21834         Opcode = X86ISD::FMAX;
21835         break;
21836       case ISD::SETOLE:
21837         // Converting this to a max would handle comparisons between positive
21838         // and negative zero incorrectly, and swapping the operands would
21839         // cause it to handle NaNs incorrectly.
21840         if (!DAG.getTarget().Options.UnsafeFPMath &&
21841             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
21842           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
21843             break;
21844           std::swap(LHS, RHS);
21845         }
21846         Opcode = X86ISD::FMAX;
21847         break;
21848       case ISD::SETULE:
21849         // Converting this to a max would handle both negative zeros and NaNs
21850         // incorrectly, but we can swap the operands to fix both.
21851         std::swap(LHS, RHS);
21852       case ISD::SETOLT:
21853       case ISD::SETLT:
21854       case ISD::SETLE:
21855         Opcode = X86ISD::FMAX;
21856         break;
21857       }
21858     }
21859
21860     if (Opcode)
21861       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
21862   }
21863
21864   EVT CondVT = Cond.getValueType();
21865   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
21866       CondVT.getVectorElementType() == MVT::i1) {
21867     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
21868     // lowering on KNL. In this case we convert it to
21869     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
21870     // The same situation for all 128 and 256-bit vectors of i8 and i16.
21871     // Since SKX these selects have a proper lowering.
21872     EVT OpVT = LHS.getValueType();
21873     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
21874         (OpVT.getVectorElementType() == MVT::i8 ||
21875          OpVT.getVectorElementType() == MVT::i16) &&
21876         !(Subtarget->hasBWI() && Subtarget->hasVLX())) {
21877       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
21878       DCI.AddToWorklist(Cond.getNode());
21879       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
21880     }
21881   }
21882   // If this is a select between two integer constants, try to do some
21883   // optimizations.
21884   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
21885     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
21886       // Don't do this for crazy integer types.
21887       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
21888         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
21889         // so that TrueC (the true value) is larger than FalseC.
21890         bool NeedsCondInvert = false;
21891
21892         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
21893             // Efficiently invertible.
21894             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
21895              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
21896               isa<ConstantSDNode>(Cond.getOperand(1))))) {
21897           NeedsCondInvert = true;
21898           std::swap(TrueC, FalseC);
21899         }
21900
21901         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
21902         if (FalseC->getAPIntValue() == 0 &&
21903             TrueC->getAPIntValue().isPowerOf2()) {
21904           if (NeedsCondInvert) // Invert the condition if needed.
21905             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
21906                                DAG.getConstant(1, DL, Cond.getValueType()));
21907
21908           // Zero extend the condition if needed.
21909           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
21910
21911           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
21912           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
21913                              DAG.getConstant(ShAmt, DL, MVT::i8));
21914         }
21915
21916         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
21917         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
21918           if (NeedsCondInvert) // Invert the condition if needed.
21919             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
21920                                DAG.getConstant(1, DL, Cond.getValueType()));
21921
21922           // Zero extend the condition if needed.
21923           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
21924                              FalseC->getValueType(0), Cond);
21925           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
21926                              SDValue(FalseC, 0));
21927         }
21928
21929         // Optimize cases that will turn into an LEA instruction.  This requires
21930         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
21931         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
21932           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
21933           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
21934
21935           bool isFastMultiplier = false;
21936           if (Diff < 10) {
21937             switch ((unsigned char)Diff) {
21938               default: break;
21939               case 1:  // result = add base, cond
21940               case 2:  // result = lea base(    , cond*2)
21941               case 3:  // result = lea base(cond, cond*2)
21942               case 4:  // result = lea base(    , cond*4)
21943               case 5:  // result = lea base(cond, cond*4)
21944               case 8:  // result = lea base(    , cond*8)
21945               case 9:  // result = lea base(cond, cond*8)
21946                 isFastMultiplier = true;
21947                 break;
21948             }
21949           }
21950
21951           if (isFastMultiplier) {
21952             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
21953             if (NeedsCondInvert) // Invert the condition if needed.
21954               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
21955                                  DAG.getConstant(1, DL, Cond.getValueType()));
21956
21957             // Zero extend the condition if needed.
21958             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
21959                                Cond);
21960             // Scale the condition by the difference.
21961             if (Diff != 1)
21962               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
21963                                  DAG.getConstant(Diff, DL,
21964                                                  Cond.getValueType()));
21965
21966             // Add the base if non-zero.
21967             if (FalseC->getAPIntValue() != 0)
21968               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
21969                                  SDValue(FalseC, 0));
21970             return Cond;
21971           }
21972         }
21973       }
21974   }
21975
21976   // Canonicalize max and min:
21977   // (x > y) ? x : y -> (x >= y) ? x : y
21978   // (x < y) ? x : y -> (x <= y) ? x : y
21979   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
21980   // the need for an extra compare
21981   // against zero. e.g.
21982   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
21983   // subl   %esi, %edi
21984   // testl  %edi, %edi
21985   // movl   $0, %eax
21986   // cmovgl %edi, %eax
21987   // =>
21988   // xorl   %eax, %eax
21989   // subl   %esi, $edi
21990   // cmovsl %eax, %edi
21991   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
21992       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
21993       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
21994     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
21995     switch (CC) {
21996     default: break;
21997     case ISD::SETLT:
21998     case ISD::SETGT: {
21999       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
22000       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
22001                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
22002       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
22003     }
22004     }
22005   }
22006
22007   // Early exit check
22008   if (!TLI.isTypeLegal(VT))
22009     return SDValue();
22010
22011   // Match VSELECTs into subs with unsigned saturation.
22012   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
22013       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
22014       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
22015        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
22016     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22017
22018     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
22019     // left side invert the predicate to simplify logic below.
22020     SDValue Other;
22021     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
22022       Other = RHS;
22023       CC = ISD::getSetCCInverse(CC, true);
22024     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
22025       Other = LHS;
22026     }
22027
22028     if (Other.getNode() && Other->getNumOperands() == 2 &&
22029         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
22030       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
22031       SDValue CondRHS = Cond->getOperand(1);
22032
22033       // Look for a general sub with unsigned saturation first.
22034       // x >= y ? x-y : 0 --> subus x, y
22035       // x >  y ? x-y : 0 --> subus x, y
22036       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
22037           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
22038         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
22039
22040       if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
22041         if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
22042           if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
22043             if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
22044               // If the RHS is a constant we have to reverse the const
22045               // canonicalization.
22046               // x > C-1 ? x+-C : 0 --> subus x, C
22047               if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
22048                   CondRHSConst->getAPIntValue() ==
22049                       (-OpRHSConst->getAPIntValue() - 1))
22050                 return DAG.getNode(
22051                     X86ISD::SUBUS, DL, VT, OpLHS,
22052                     DAG.getConstant(-OpRHSConst->getAPIntValue(), DL, VT));
22053
22054           // Another special case: If C was a sign bit, the sub has been
22055           // canonicalized into a xor.
22056           // FIXME: Would it be better to use computeKnownBits to determine
22057           //        whether it's safe to decanonicalize the xor?
22058           // x s< 0 ? x^C : 0 --> subus x, C
22059           if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
22060               ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
22061               OpRHSConst->getAPIntValue().isSignBit())
22062             // Note that we have to rebuild the RHS constant here to ensure we
22063             // don't rely on particular values of undef lanes.
22064             return DAG.getNode(
22065                 X86ISD::SUBUS, DL, VT, OpLHS,
22066                 DAG.getConstant(OpRHSConst->getAPIntValue(), DL, VT));
22067         }
22068     }
22069   }
22070
22071   // Try to match a min/max vector operation.
22072   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
22073     std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
22074     unsigned Opc = ret.first;
22075     bool NeedSplit = ret.second;
22076
22077     if (Opc && NeedSplit) {
22078       unsigned NumElems = VT.getVectorNumElements();
22079       // Extract the LHS vectors
22080       SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
22081       SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
22082
22083       // Extract the RHS vectors
22084       SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
22085       SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
22086
22087       // Create min/max for each subvector
22088       LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
22089       RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
22090
22091       // Merge the result
22092       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
22093     } else if (Opc)
22094       return DAG.getNode(Opc, DL, VT, LHS, RHS);
22095   }
22096
22097   // Simplify vector selection if condition value type matches vselect
22098   // operand type
22099   if (N->getOpcode() == ISD::VSELECT && CondVT == VT) {
22100     assert(Cond.getValueType().isVector() &&
22101            "vector select expects a vector selector!");
22102
22103     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
22104     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
22105
22106     // Try invert the condition if true value is not all 1s and false value
22107     // is not all 0s.
22108     if (!TValIsAllOnes && !FValIsAllZeros &&
22109         // Check if the selector will be produced by CMPP*/PCMP*
22110         Cond.getOpcode() == ISD::SETCC &&
22111         // Check if SETCC has already been promoted
22112         TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT) {
22113       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
22114       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
22115
22116       if (TValIsAllZeros || FValIsAllOnes) {
22117         SDValue CC = Cond.getOperand(2);
22118         ISD::CondCode NewCC =
22119           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
22120                                Cond.getOperand(0).getValueType().isInteger());
22121         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
22122         std::swap(LHS, RHS);
22123         TValIsAllOnes = FValIsAllOnes;
22124         FValIsAllZeros = TValIsAllZeros;
22125       }
22126     }
22127
22128     if (TValIsAllOnes || FValIsAllZeros) {
22129       SDValue Ret;
22130
22131       if (TValIsAllOnes && FValIsAllZeros)
22132         Ret = Cond;
22133       else if (TValIsAllOnes)
22134         Ret =
22135             DAG.getNode(ISD::OR, DL, CondVT, Cond, DAG.getBitcast(CondVT, RHS));
22136       else if (FValIsAllZeros)
22137         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
22138                           DAG.getBitcast(CondVT, LHS));
22139
22140       return DAG.getBitcast(VT, Ret);
22141     }
22142   }
22143
22144   // We should generate an X86ISD::BLENDI from a vselect if its argument
22145   // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
22146   // constants. This specific pattern gets generated when we split a
22147   // selector for a 512 bit vector in a machine without AVX512 (but with
22148   // 256-bit vectors), during legalization:
22149   //
22150   // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
22151   //
22152   // Iff we find this pattern and the build_vectors are built from
22153   // constants, we translate the vselect into a shuffle_vector that we
22154   // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
22155   if ((N->getOpcode() == ISD::VSELECT ||
22156        N->getOpcode() == X86ISD::SHRUNKBLEND) &&
22157       !DCI.isBeforeLegalize() && !VT.is512BitVector()) {
22158     SDValue Shuffle = transformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
22159     if (Shuffle.getNode())
22160       return Shuffle;
22161   }
22162
22163   // If this is a *dynamic* select (non-constant condition) and we can match
22164   // this node with one of the variable blend instructions, restructure the
22165   // condition so that the blends can use the high bit of each element and use
22166   // SimplifyDemandedBits to simplify the condition operand.
22167   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
22168       !DCI.isBeforeLegalize() &&
22169       !ISD::isBuildVectorOfConstantSDNodes(Cond.getNode())) {
22170     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
22171
22172     // Don't optimize vector selects that map to mask-registers.
22173     if (BitWidth == 1)
22174       return SDValue();
22175
22176     // We can only handle the cases where VSELECT is directly legal on the
22177     // subtarget. We custom lower VSELECT nodes with constant conditions and
22178     // this makes it hard to see whether a dynamic VSELECT will correctly
22179     // lower, so we both check the operation's status and explicitly handle the
22180     // cases where a *dynamic* blend will fail even though a constant-condition
22181     // blend could be custom lowered.
22182     // FIXME: We should find a better way to handle this class of problems.
22183     // Potentially, we should combine constant-condition vselect nodes
22184     // pre-legalization into shuffles and not mark as many types as custom
22185     // lowered.
22186     if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
22187       return SDValue();
22188     // FIXME: We don't support i16-element blends currently. We could and
22189     // should support them by making *all* the bits in the condition be set
22190     // rather than just the high bit and using an i8-element blend.
22191     if (VT.getScalarType() == MVT::i16)
22192       return SDValue();
22193     // Dynamic blending was only available from SSE4.1 onward.
22194     if (VT.getSizeInBits() == 128 && !Subtarget->hasSSE41())
22195       return SDValue();
22196     // Byte blends are only available in AVX2
22197     if (VT.getSizeInBits() == 256 && VT.getScalarType() == MVT::i8 &&
22198         !Subtarget->hasAVX2())
22199       return SDValue();
22200
22201     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
22202     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
22203
22204     APInt KnownZero, KnownOne;
22205     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
22206                                           DCI.isBeforeLegalizeOps());
22207     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
22208         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne,
22209                                  TLO)) {
22210       // If we changed the computation somewhere in the DAG, this change
22211       // will affect all users of Cond.
22212       // Make sure it is fine and update all the nodes so that we do not
22213       // use the generic VSELECT anymore. Otherwise, we may perform
22214       // wrong optimizations as we messed up with the actual expectation
22215       // for the vector boolean values.
22216       if (Cond != TLO.Old) {
22217         // Check all uses of that condition operand to check whether it will be
22218         // consumed by non-BLEND instructions, which may depend on all bits are
22219         // set properly.
22220         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
22221              I != E; ++I)
22222           if (I->getOpcode() != ISD::VSELECT)
22223             // TODO: Add other opcodes eventually lowered into BLEND.
22224             return SDValue();
22225
22226         // Update all the users of the condition, before committing the change,
22227         // so that the VSELECT optimizations that expect the correct vector
22228         // boolean value will not be triggered.
22229         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
22230              I != E; ++I)
22231           DAG.ReplaceAllUsesOfValueWith(
22232               SDValue(*I, 0),
22233               DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(*I), I->getValueType(0),
22234                           Cond, I->getOperand(1), I->getOperand(2)));
22235         DCI.CommitTargetLoweringOpt(TLO);
22236         return SDValue();
22237       }
22238       // At this point, only Cond is changed. Change the condition
22239       // just for N to keep the opportunity to optimize all other
22240       // users their own way.
22241       DAG.ReplaceAllUsesOfValueWith(
22242           SDValue(N, 0),
22243           DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(N), N->getValueType(0),
22244                       TLO.New, N->getOperand(1), N->getOperand(2)));
22245       return SDValue();
22246     }
22247   }
22248
22249   return SDValue();
22250 }
22251
22252 // Check whether a boolean test is testing a boolean value generated by
22253 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
22254 // code.
22255 //
22256 // Simplify the following patterns:
22257 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
22258 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
22259 // to (Op EFLAGS Cond)
22260 //
22261 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
22262 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
22263 // to (Op EFLAGS !Cond)
22264 //
22265 // where Op could be BRCOND or CMOV.
22266 //
22267 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
22268   // Quit if not CMP and SUB with its value result used.
22269   if (Cmp.getOpcode() != X86ISD::CMP &&
22270       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
22271       return SDValue();
22272
22273   // Quit if not used as a boolean value.
22274   if (CC != X86::COND_E && CC != X86::COND_NE)
22275     return SDValue();
22276
22277   // Check CMP operands. One of them should be 0 or 1 and the other should be
22278   // an SetCC or extended from it.
22279   SDValue Op1 = Cmp.getOperand(0);
22280   SDValue Op2 = Cmp.getOperand(1);
22281
22282   SDValue SetCC;
22283   const ConstantSDNode* C = nullptr;
22284   bool needOppositeCond = (CC == X86::COND_E);
22285   bool checkAgainstTrue = false; // Is it a comparison against 1?
22286
22287   if ((C = dyn_cast<ConstantSDNode>(Op1)))
22288     SetCC = Op2;
22289   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
22290     SetCC = Op1;
22291   else // Quit if all operands are not constants.
22292     return SDValue();
22293
22294   if (C->getZExtValue() == 1) {
22295     needOppositeCond = !needOppositeCond;
22296     checkAgainstTrue = true;
22297   } else if (C->getZExtValue() != 0)
22298     // Quit if the constant is neither 0 or 1.
22299     return SDValue();
22300
22301   bool truncatedToBoolWithAnd = false;
22302   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
22303   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
22304          SetCC.getOpcode() == ISD::TRUNCATE ||
22305          SetCC.getOpcode() == ISD::AND) {
22306     if (SetCC.getOpcode() == ISD::AND) {
22307       int OpIdx = -1;
22308       ConstantSDNode *CS;
22309       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
22310           CS->getZExtValue() == 1)
22311         OpIdx = 1;
22312       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
22313           CS->getZExtValue() == 1)
22314         OpIdx = 0;
22315       if (OpIdx == -1)
22316         break;
22317       SetCC = SetCC.getOperand(OpIdx);
22318       truncatedToBoolWithAnd = true;
22319     } else
22320       SetCC = SetCC.getOperand(0);
22321   }
22322
22323   switch (SetCC.getOpcode()) {
22324   case X86ISD::SETCC_CARRY:
22325     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
22326     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
22327     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
22328     // truncated to i1 using 'and'.
22329     if (checkAgainstTrue && !truncatedToBoolWithAnd)
22330       break;
22331     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
22332            "Invalid use of SETCC_CARRY!");
22333     // FALL THROUGH
22334   case X86ISD::SETCC:
22335     // Set the condition code or opposite one if necessary.
22336     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
22337     if (needOppositeCond)
22338       CC = X86::GetOppositeBranchCondition(CC);
22339     return SetCC.getOperand(1);
22340   case X86ISD::CMOV: {
22341     // Check whether false/true value has canonical one, i.e. 0 or 1.
22342     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
22343     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
22344     // Quit if true value is not a constant.
22345     if (!TVal)
22346       return SDValue();
22347     // Quit if false value is not a constant.
22348     if (!FVal) {
22349       SDValue Op = SetCC.getOperand(0);
22350       // Skip 'zext' or 'trunc' node.
22351       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
22352           Op.getOpcode() == ISD::TRUNCATE)
22353         Op = Op.getOperand(0);
22354       // A special case for rdrand/rdseed, where 0 is set if false cond is
22355       // found.
22356       if ((Op.getOpcode() != X86ISD::RDRAND &&
22357            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
22358         return SDValue();
22359     }
22360     // Quit if false value is not the constant 0 or 1.
22361     bool FValIsFalse = true;
22362     if (FVal && FVal->getZExtValue() != 0) {
22363       if (FVal->getZExtValue() != 1)
22364         return SDValue();
22365       // If FVal is 1, opposite cond is needed.
22366       needOppositeCond = !needOppositeCond;
22367       FValIsFalse = false;
22368     }
22369     // Quit if TVal is not the constant opposite of FVal.
22370     if (FValIsFalse && TVal->getZExtValue() != 1)
22371       return SDValue();
22372     if (!FValIsFalse && TVal->getZExtValue() != 0)
22373       return SDValue();
22374     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
22375     if (needOppositeCond)
22376       CC = X86::GetOppositeBranchCondition(CC);
22377     return SetCC.getOperand(3);
22378   }
22379   }
22380
22381   return SDValue();
22382 }
22383
22384 /// Check whether Cond is an AND/OR of SETCCs off of the same EFLAGS.
22385 /// Match:
22386 ///   (X86or (X86setcc) (X86setcc))
22387 ///   (X86cmp (and (X86setcc) (X86setcc)), 0)
22388 static bool checkBoolTestAndOrSetCCCombine(SDValue Cond, X86::CondCode &CC0,
22389                                            X86::CondCode &CC1, SDValue &Flags,
22390                                            bool &isAnd) {
22391   if (Cond->getOpcode() == X86ISD::CMP) {
22392     ConstantSDNode *CondOp1C = dyn_cast<ConstantSDNode>(Cond->getOperand(1));
22393     if (!CondOp1C || !CondOp1C->isNullValue())
22394       return false;
22395
22396     Cond = Cond->getOperand(0);
22397   }
22398
22399   isAnd = false;
22400
22401   SDValue SetCC0, SetCC1;
22402   switch (Cond->getOpcode()) {
22403   default: return false;
22404   case ISD::AND:
22405   case X86ISD::AND:
22406     isAnd = true;
22407     // fallthru
22408   case ISD::OR:
22409   case X86ISD::OR:
22410     SetCC0 = Cond->getOperand(0);
22411     SetCC1 = Cond->getOperand(1);
22412     break;
22413   };
22414
22415   // Make sure we have SETCC nodes, using the same flags value.
22416   if (SetCC0.getOpcode() != X86ISD::SETCC ||
22417       SetCC1.getOpcode() != X86ISD::SETCC ||
22418       SetCC0->getOperand(1) != SetCC1->getOperand(1))
22419     return false;
22420
22421   CC0 = (X86::CondCode)SetCC0->getConstantOperandVal(0);
22422   CC1 = (X86::CondCode)SetCC1->getConstantOperandVal(0);
22423   Flags = SetCC0->getOperand(1);
22424   return true;
22425 }
22426
22427 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
22428 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
22429                                   TargetLowering::DAGCombinerInfo &DCI,
22430                                   const X86Subtarget *Subtarget) {
22431   SDLoc DL(N);
22432
22433   // If the flag operand isn't dead, don't touch this CMOV.
22434   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
22435     return SDValue();
22436
22437   SDValue FalseOp = N->getOperand(0);
22438   SDValue TrueOp = N->getOperand(1);
22439   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
22440   SDValue Cond = N->getOperand(3);
22441
22442   if (CC == X86::COND_E || CC == X86::COND_NE) {
22443     switch (Cond.getOpcode()) {
22444     default: break;
22445     case X86ISD::BSR:
22446     case X86ISD::BSF:
22447       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
22448       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
22449         return (CC == X86::COND_E) ? FalseOp : TrueOp;
22450     }
22451   }
22452
22453   SDValue Flags;
22454
22455   Flags = checkBoolTestSetCCCombine(Cond, CC);
22456   if (Flags.getNode() &&
22457       // Extra check as FCMOV only supports a subset of X86 cond.
22458       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
22459     SDValue Ops[] = { FalseOp, TrueOp,
22460                       DAG.getConstant(CC, DL, MVT::i8), Flags };
22461     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
22462   }
22463
22464   // If this is a select between two integer constants, try to do some
22465   // optimizations.  Note that the operands are ordered the opposite of SELECT
22466   // operands.
22467   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
22468     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
22469       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
22470       // larger than FalseC (the false value).
22471       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
22472         CC = X86::GetOppositeBranchCondition(CC);
22473         std::swap(TrueC, FalseC);
22474         std::swap(TrueOp, FalseOp);
22475       }
22476
22477       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
22478       // This is efficient for any integer data type (including i8/i16) and
22479       // shift amount.
22480       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
22481         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
22482                            DAG.getConstant(CC, DL, MVT::i8), Cond);
22483
22484         // Zero extend the condition if needed.
22485         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
22486
22487         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
22488         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
22489                            DAG.getConstant(ShAmt, DL, MVT::i8));
22490         if (N->getNumValues() == 2)  // Dead flag value?
22491           return DCI.CombineTo(N, Cond, SDValue());
22492         return Cond;
22493       }
22494
22495       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
22496       // for any integer data type, including i8/i16.
22497       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
22498         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
22499                            DAG.getConstant(CC, DL, MVT::i8), Cond);
22500
22501         // Zero extend the condition if needed.
22502         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
22503                            FalseC->getValueType(0), Cond);
22504         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
22505                            SDValue(FalseC, 0));
22506
22507         if (N->getNumValues() == 2)  // Dead flag value?
22508           return DCI.CombineTo(N, Cond, SDValue());
22509         return Cond;
22510       }
22511
22512       // Optimize cases that will turn into an LEA instruction.  This requires
22513       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
22514       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
22515         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
22516         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
22517
22518         bool isFastMultiplier = false;
22519         if (Diff < 10) {
22520           switch ((unsigned char)Diff) {
22521           default: break;
22522           case 1:  // result = add base, cond
22523           case 2:  // result = lea base(    , cond*2)
22524           case 3:  // result = lea base(cond, cond*2)
22525           case 4:  // result = lea base(    , cond*4)
22526           case 5:  // result = lea base(cond, cond*4)
22527           case 8:  // result = lea base(    , cond*8)
22528           case 9:  // result = lea base(cond, cond*8)
22529             isFastMultiplier = true;
22530             break;
22531           }
22532         }
22533
22534         if (isFastMultiplier) {
22535           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
22536           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
22537                              DAG.getConstant(CC, DL, MVT::i8), Cond);
22538           // Zero extend the condition if needed.
22539           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
22540                              Cond);
22541           // Scale the condition by the difference.
22542           if (Diff != 1)
22543             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
22544                                DAG.getConstant(Diff, DL, Cond.getValueType()));
22545
22546           // Add the base if non-zero.
22547           if (FalseC->getAPIntValue() != 0)
22548             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
22549                                SDValue(FalseC, 0));
22550           if (N->getNumValues() == 2)  // Dead flag value?
22551             return DCI.CombineTo(N, Cond, SDValue());
22552           return Cond;
22553         }
22554       }
22555     }
22556   }
22557
22558   // Handle these cases:
22559   //   (select (x != c), e, c) -> select (x != c), e, x),
22560   //   (select (x == c), c, e) -> select (x == c), x, e)
22561   // where the c is an integer constant, and the "select" is the combination
22562   // of CMOV and CMP.
22563   //
22564   // The rationale for this change is that the conditional-move from a constant
22565   // needs two instructions, however, conditional-move from a register needs
22566   // only one instruction.
22567   //
22568   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
22569   //  some instruction-combining opportunities. This opt needs to be
22570   //  postponed as late as possible.
22571   //
22572   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
22573     // the DCI.xxxx conditions are provided to postpone the optimization as
22574     // late as possible.
22575
22576     ConstantSDNode *CmpAgainst = nullptr;
22577     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
22578         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
22579         !isa<ConstantSDNode>(Cond.getOperand(0))) {
22580
22581       if (CC == X86::COND_NE &&
22582           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
22583         CC = X86::GetOppositeBranchCondition(CC);
22584         std::swap(TrueOp, FalseOp);
22585       }
22586
22587       if (CC == X86::COND_E &&
22588           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
22589         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
22590                           DAG.getConstant(CC, DL, MVT::i8), Cond };
22591         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
22592       }
22593     }
22594   }
22595
22596   // Fold and/or of setcc's to double CMOV:
22597   //   (CMOV F, T, ((cc1 | cc2) != 0)) -> (CMOV (CMOV F, T, cc1), T, cc2)
22598   //   (CMOV F, T, ((cc1 & cc2) != 0)) -> (CMOV (CMOV T, F, !cc1), F, !cc2)
22599   //
22600   // This combine lets us generate:
22601   //   cmovcc1 (jcc1 if we don't have CMOV)
22602   //   cmovcc2 (same)
22603   // instead of:
22604   //   setcc1
22605   //   setcc2
22606   //   and/or
22607   //   cmovne (jne if we don't have CMOV)
22608   // When we can't use the CMOV instruction, it might increase branch
22609   // mispredicts.
22610   // When we can use CMOV, or when there is no mispredict, this improves
22611   // throughput and reduces register pressure.
22612   //
22613   if (CC == X86::COND_NE) {
22614     SDValue Flags;
22615     X86::CondCode CC0, CC1;
22616     bool isAndSetCC;
22617     if (checkBoolTestAndOrSetCCCombine(Cond, CC0, CC1, Flags, isAndSetCC)) {
22618       if (isAndSetCC) {
22619         std::swap(FalseOp, TrueOp);
22620         CC0 = X86::GetOppositeBranchCondition(CC0);
22621         CC1 = X86::GetOppositeBranchCondition(CC1);
22622       }
22623
22624       SDValue LOps[] = {FalseOp, TrueOp, DAG.getConstant(CC0, DL, MVT::i8),
22625         Flags};
22626       SDValue LCMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), LOps);
22627       SDValue Ops[] = {LCMOV, TrueOp, DAG.getConstant(CC1, DL, MVT::i8), Flags};
22628       SDValue CMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
22629       DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SDValue(CMOV.getNode(), 1));
22630       return CMOV;
22631     }
22632   }
22633
22634   return SDValue();
22635 }
22636
22637 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
22638                                                 const X86Subtarget *Subtarget) {
22639   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
22640   switch (IntNo) {
22641   default: return SDValue();
22642   // SSE/AVX/AVX2 blend intrinsics.
22643   case Intrinsic::x86_avx2_pblendvb:
22644     // Don't try to simplify this intrinsic if we don't have AVX2.
22645     if (!Subtarget->hasAVX2())
22646       return SDValue();
22647     // FALL-THROUGH
22648   case Intrinsic::x86_avx_blendv_pd_256:
22649   case Intrinsic::x86_avx_blendv_ps_256:
22650     // Don't try to simplify this intrinsic if we don't have AVX.
22651     if (!Subtarget->hasAVX())
22652       return SDValue();
22653     // FALL-THROUGH
22654   case Intrinsic::x86_sse41_blendvps:
22655   case Intrinsic::x86_sse41_blendvpd:
22656   case Intrinsic::x86_sse41_pblendvb: {
22657     SDValue Op0 = N->getOperand(1);
22658     SDValue Op1 = N->getOperand(2);
22659     SDValue Mask = N->getOperand(3);
22660
22661     // Don't try to simplify this intrinsic if we don't have SSE4.1.
22662     if (!Subtarget->hasSSE41())
22663       return SDValue();
22664
22665     // fold (blend A, A, Mask) -> A
22666     if (Op0 == Op1)
22667       return Op0;
22668     // fold (blend A, B, allZeros) -> A
22669     if (ISD::isBuildVectorAllZeros(Mask.getNode()))
22670       return Op0;
22671     // fold (blend A, B, allOnes) -> B
22672     if (ISD::isBuildVectorAllOnes(Mask.getNode()))
22673       return Op1;
22674
22675     // Simplify the case where the mask is a constant i32 value.
22676     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
22677       if (C->isNullValue())
22678         return Op0;
22679       if (C->isAllOnesValue())
22680         return Op1;
22681     }
22682
22683     return SDValue();
22684   }
22685
22686   // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
22687   case Intrinsic::x86_sse2_psrai_w:
22688   case Intrinsic::x86_sse2_psrai_d:
22689   case Intrinsic::x86_avx2_psrai_w:
22690   case Intrinsic::x86_avx2_psrai_d:
22691   case Intrinsic::x86_sse2_psra_w:
22692   case Intrinsic::x86_sse2_psra_d:
22693   case Intrinsic::x86_avx2_psra_w:
22694   case Intrinsic::x86_avx2_psra_d: {
22695     SDValue Op0 = N->getOperand(1);
22696     SDValue Op1 = N->getOperand(2);
22697     EVT VT = Op0.getValueType();
22698     assert(VT.isVector() && "Expected a vector type!");
22699
22700     if (isa<BuildVectorSDNode>(Op1))
22701       Op1 = Op1.getOperand(0);
22702
22703     if (!isa<ConstantSDNode>(Op1))
22704       return SDValue();
22705
22706     EVT SVT = VT.getVectorElementType();
22707     unsigned SVTBits = SVT.getSizeInBits();
22708
22709     ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
22710     const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
22711     uint64_t ShAmt = C.getZExtValue();
22712
22713     // Don't try to convert this shift into a ISD::SRA if the shift
22714     // count is bigger than or equal to the element size.
22715     if (ShAmt >= SVTBits)
22716       return SDValue();
22717
22718     // Trivial case: if the shift count is zero, then fold this
22719     // into the first operand.
22720     if (ShAmt == 0)
22721       return Op0;
22722
22723     // Replace this packed shift intrinsic with a target independent
22724     // shift dag node.
22725     SDLoc DL(N);
22726     SDValue Splat = DAG.getConstant(C, DL, VT);
22727     return DAG.getNode(ISD::SRA, DL, VT, Op0, Splat);
22728   }
22729   }
22730 }
22731
22732 /// PerformMulCombine - Optimize a single multiply with constant into two
22733 /// in order to implement it with two cheaper instructions, e.g.
22734 /// LEA + SHL, LEA + LEA.
22735 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
22736                                  TargetLowering::DAGCombinerInfo &DCI) {
22737   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
22738     return SDValue();
22739
22740   EVT VT = N->getValueType(0);
22741   if (VT != MVT::i64 && VT != MVT::i32)
22742     return SDValue();
22743
22744   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
22745   if (!C)
22746     return SDValue();
22747   uint64_t MulAmt = C->getZExtValue();
22748   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
22749     return SDValue();
22750
22751   uint64_t MulAmt1 = 0;
22752   uint64_t MulAmt2 = 0;
22753   if ((MulAmt % 9) == 0) {
22754     MulAmt1 = 9;
22755     MulAmt2 = MulAmt / 9;
22756   } else if ((MulAmt % 5) == 0) {
22757     MulAmt1 = 5;
22758     MulAmt2 = MulAmt / 5;
22759   } else if ((MulAmt % 3) == 0) {
22760     MulAmt1 = 3;
22761     MulAmt2 = MulAmt / 3;
22762   }
22763   if (MulAmt2 &&
22764       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
22765     SDLoc DL(N);
22766
22767     if (isPowerOf2_64(MulAmt2) &&
22768         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
22769       // If second multiplifer is pow2, issue it first. We want the multiply by
22770       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
22771       // is an add.
22772       std::swap(MulAmt1, MulAmt2);
22773
22774     SDValue NewMul;
22775     if (isPowerOf2_64(MulAmt1))
22776       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
22777                            DAG.getConstant(Log2_64(MulAmt1), DL, MVT::i8));
22778     else
22779       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
22780                            DAG.getConstant(MulAmt1, DL, VT));
22781
22782     if (isPowerOf2_64(MulAmt2))
22783       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
22784                            DAG.getConstant(Log2_64(MulAmt2), DL, MVT::i8));
22785     else
22786       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
22787                            DAG.getConstant(MulAmt2, DL, VT));
22788
22789     // Do not add new nodes to DAG combiner worklist.
22790     DCI.CombineTo(N, NewMul, false);
22791   }
22792   return SDValue();
22793 }
22794
22795 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
22796   SDValue N0 = N->getOperand(0);
22797   SDValue N1 = N->getOperand(1);
22798   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
22799   EVT VT = N0.getValueType();
22800
22801   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
22802   // since the result of setcc_c is all zero's or all ones.
22803   if (VT.isInteger() && !VT.isVector() &&
22804       N1C && N0.getOpcode() == ISD::AND &&
22805       N0.getOperand(1).getOpcode() == ISD::Constant) {
22806     SDValue N00 = N0.getOperand(0);
22807     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
22808         ((N00.getOpcode() == ISD::ANY_EXTEND ||
22809           N00.getOpcode() == ISD::ZERO_EXTEND) &&
22810          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
22811       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
22812       APInt ShAmt = N1C->getAPIntValue();
22813       Mask = Mask.shl(ShAmt);
22814       if (Mask != 0) {
22815         SDLoc DL(N);
22816         return DAG.getNode(ISD::AND, DL, VT,
22817                            N00, DAG.getConstant(Mask, DL, VT));
22818       }
22819     }
22820   }
22821
22822   // Hardware support for vector shifts is sparse which makes us scalarize the
22823   // vector operations in many cases. Also, on sandybridge ADD is faster than
22824   // shl.
22825   // (shl V, 1) -> add V,V
22826   if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
22827     if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
22828       assert(N0.getValueType().isVector() && "Invalid vector shift type");
22829       // We shift all of the values by one. In many cases we do not have
22830       // hardware support for this operation. This is better expressed as an ADD
22831       // of two values.
22832       if (N1SplatC->getZExtValue() == 1)
22833         return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
22834     }
22835
22836   return SDValue();
22837 }
22838
22839 /// \brief Returns a vector of 0s if the node in input is a vector logical
22840 /// shift by a constant amount which is known to be bigger than or equal
22841 /// to the vector element size in bits.
22842 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
22843                                       const X86Subtarget *Subtarget) {
22844   EVT VT = N->getValueType(0);
22845
22846   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
22847       (!Subtarget->hasInt256() ||
22848        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
22849     return SDValue();
22850
22851   SDValue Amt = N->getOperand(1);
22852   SDLoc DL(N);
22853   if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
22854     if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
22855       APInt ShiftAmt = AmtSplat->getAPIntValue();
22856       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
22857
22858       // SSE2/AVX2 logical shifts always return a vector of 0s
22859       // if the shift amount is bigger than or equal to
22860       // the element size. The constant shift amount will be
22861       // encoded as a 8-bit immediate.
22862       if (ShiftAmt.trunc(8).uge(MaxAmount))
22863         return getZeroVector(VT, Subtarget, DAG, DL);
22864     }
22865
22866   return SDValue();
22867 }
22868
22869 /// PerformShiftCombine - Combine shifts.
22870 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
22871                                    TargetLowering::DAGCombinerInfo &DCI,
22872                                    const X86Subtarget *Subtarget) {
22873   if (N->getOpcode() == ISD::SHL)
22874     if (SDValue V = PerformSHLCombine(N, DAG))
22875       return V;
22876
22877   // Try to fold this logical shift into a zero vector.
22878   if (N->getOpcode() != ISD::SRA)
22879     if (SDValue V = performShiftToAllZeros(N, DAG, Subtarget))
22880       return V;
22881
22882   return SDValue();
22883 }
22884
22885 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
22886 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
22887 // and friends.  Likewise for OR -> CMPNEQSS.
22888 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
22889                             TargetLowering::DAGCombinerInfo &DCI,
22890                             const X86Subtarget *Subtarget) {
22891   unsigned opcode;
22892
22893   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
22894   // we're requiring SSE2 for both.
22895   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
22896     SDValue N0 = N->getOperand(0);
22897     SDValue N1 = N->getOperand(1);
22898     SDValue CMP0 = N0->getOperand(1);
22899     SDValue CMP1 = N1->getOperand(1);
22900     SDLoc DL(N);
22901
22902     // The SETCCs should both refer to the same CMP.
22903     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
22904       return SDValue();
22905
22906     SDValue CMP00 = CMP0->getOperand(0);
22907     SDValue CMP01 = CMP0->getOperand(1);
22908     EVT     VT    = CMP00.getValueType();
22909
22910     if (VT == MVT::f32 || VT == MVT::f64) {
22911       bool ExpectingFlags = false;
22912       // Check for any users that want flags:
22913       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
22914            !ExpectingFlags && UI != UE; ++UI)
22915         switch (UI->getOpcode()) {
22916         default:
22917         case ISD::BR_CC:
22918         case ISD::BRCOND:
22919         case ISD::SELECT:
22920           ExpectingFlags = true;
22921           break;
22922         case ISD::CopyToReg:
22923         case ISD::SIGN_EXTEND:
22924         case ISD::ZERO_EXTEND:
22925         case ISD::ANY_EXTEND:
22926           break;
22927         }
22928
22929       if (!ExpectingFlags) {
22930         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
22931         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
22932
22933         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
22934           X86::CondCode tmp = cc0;
22935           cc0 = cc1;
22936           cc1 = tmp;
22937         }
22938
22939         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
22940             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
22941           // FIXME: need symbolic constants for these magic numbers.
22942           // See X86ATTInstPrinter.cpp:printSSECC().
22943           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
22944           if (Subtarget->hasAVX512()) {
22945             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
22946                                          CMP01,
22947                                          DAG.getConstant(x86cc, DL, MVT::i8));
22948             if (N->getValueType(0) != MVT::i1)
22949               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
22950                                  FSetCC);
22951             return FSetCC;
22952           }
22953           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
22954                                               CMP00.getValueType(), CMP00, CMP01,
22955                                               DAG.getConstant(x86cc, DL,
22956                                                               MVT::i8));
22957
22958           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
22959           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
22960
22961           if (is64BitFP && !Subtarget->is64Bit()) {
22962             // On a 32-bit target, we cannot bitcast the 64-bit float to a
22963             // 64-bit integer, since that's not a legal type. Since
22964             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
22965             // bits, but can do this little dance to extract the lowest 32 bits
22966             // and work with those going forward.
22967             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
22968                                            OnesOrZeroesF);
22969             SDValue Vector32 = DAG.getBitcast(MVT::v4f32, Vector64);
22970             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
22971                                         Vector32, DAG.getIntPtrConstant(0, DL));
22972             IntVT = MVT::i32;
22973           }
22974
22975           SDValue OnesOrZeroesI = DAG.getBitcast(IntVT, OnesOrZeroesF);
22976           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
22977                                       DAG.getConstant(1, DL, IntVT));
22978           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8,
22979                                               ANDed);
22980           return OneBitOfTruth;
22981         }
22982       }
22983     }
22984   }
22985   return SDValue();
22986 }
22987
22988 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
22989 /// so it can be folded inside ANDNP.
22990 static bool CanFoldXORWithAllOnes(const SDNode *N) {
22991   EVT VT = N->getValueType(0);
22992
22993   // Match direct AllOnes for 128 and 256-bit vectors
22994   if (ISD::isBuildVectorAllOnes(N))
22995     return true;
22996
22997   // Look through a bit convert.
22998   if (N->getOpcode() == ISD::BITCAST)
22999     N = N->getOperand(0).getNode();
23000
23001   // Sometimes the operand may come from a insert_subvector building a 256-bit
23002   // allones vector
23003   if (VT.is256BitVector() &&
23004       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
23005     SDValue V1 = N->getOperand(0);
23006     SDValue V2 = N->getOperand(1);
23007
23008     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
23009         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
23010         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
23011         ISD::isBuildVectorAllOnes(V2.getNode()))
23012       return true;
23013   }
23014
23015   return false;
23016 }
23017
23018 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
23019 // register. In most cases we actually compare or select YMM-sized registers
23020 // and mixing the two types creates horrible code. This method optimizes
23021 // some of the transition sequences.
23022 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
23023                                  TargetLowering::DAGCombinerInfo &DCI,
23024                                  const X86Subtarget *Subtarget) {
23025   EVT VT = N->getValueType(0);
23026   if (!VT.is256BitVector())
23027     return SDValue();
23028
23029   assert((N->getOpcode() == ISD::ANY_EXTEND ||
23030           N->getOpcode() == ISD::ZERO_EXTEND ||
23031           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
23032
23033   SDValue Narrow = N->getOperand(0);
23034   EVT NarrowVT = Narrow->getValueType(0);
23035   if (!NarrowVT.is128BitVector())
23036     return SDValue();
23037
23038   if (Narrow->getOpcode() != ISD::XOR &&
23039       Narrow->getOpcode() != ISD::AND &&
23040       Narrow->getOpcode() != ISD::OR)
23041     return SDValue();
23042
23043   SDValue N0  = Narrow->getOperand(0);
23044   SDValue N1  = Narrow->getOperand(1);
23045   SDLoc DL(Narrow);
23046
23047   // The Left side has to be a trunc.
23048   if (N0.getOpcode() != ISD::TRUNCATE)
23049     return SDValue();
23050
23051   // The type of the truncated inputs.
23052   EVT WideVT = N0->getOperand(0)->getValueType(0);
23053   if (WideVT != VT)
23054     return SDValue();
23055
23056   // The right side has to be a 'trunc' or a constant vector.
23057   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
23058   ConstantSDNode *RHSConstSplat = nullptr;
23059   if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
23060     RHSConstSplat = RHSBV->getConstantSplatNode();
23061   if (!RHSTrunc && !RHSConstSplat)
23062     return SDValue();
23063
23064   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23065
23066   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
23067     return SDValue();
23068
23069   // Set N0 and N1 to hold the inputs to the new wide operation.
23070   N0 = N0->getOperand(0);
23071   if (RHSConstSplat) {
23072     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
23073                      SDValue(RHSConstSplat, 0));
23074     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
23075     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
23076   } else if (RHSTrunc) {
23077     N1 = N1->getOperand(0);
23078   }
23079
23080   // Generate the wide operation.
23081   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
23082   unsigned Opcode = N->getOpcode();
23083   switch (Opcode) {
23084   case ISD::ANY_EXTEND:
23085     return Op;
23086   case ISD::ZERO_EXTEND: {
23087     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
23088     APInt Mask = APInt::getAllOnesValue(InBits);
23089     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
23090     return DAG.getNode(ISD::AND, DL, VT,
23091                        Op, DAG.getConstant(Mask, DL, VT));
23092   }
23093   case ISD::SIGN_EXTEND:
23094     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
23095                        Op, DAG.getValueType(NarrowVT));
23096   default:
23097     llvm_unreachable("Unexpected opcode");
23098   }
23099 }
23100
23101 static SDValue VectorZextCombine(SDNode *N, SelectionDAG &DAG,
23102                                  TargetLowering::DAGCombinerInfo &DCI,
23103                                  const X86Subtarget *Subtarget) {
23104   SDValue N0 = N->getOperand(0);
23105   SDValue N1 = N->getOperand(1);
23106   SDLoc DL(N);
23107
23108   // A vector zext_in_reg may be represented as a shuffle,
23109   // feeding into a bitcast (this represents anyext) feeding into
23110   // an and with a mask.
23111   // We'd like to try to combine that into a shuffle with zero
23112   // plus a bitcast, removing the and.
23113   if (N0.getOpcode() != ISD::BITCAST ||
23114       N0.getOperand(0).getOpcode() != ISD::VECTOR_SHUFFLE)
23115     return SDValue();
23116
23117   // The other side of the AND should be a splat of 2^C, where C
23118   // is the number of bits in the source type.
23119   if (N1.getOpcode() == ISD::BITCAST)
23120     N1 = N1.getOperand(0);
23121   if (N1.getOpcode() != ISD::BUILD_VECTOR)
23122     return SDValue();
23123   BuildVectorSDNode *Vector = cast<BuildVectorSDNode>(N1);
23124
23125   ShuffleVectorSDNode *Shuffle = cast<ShuffleVectorSDNode>(N0.getOperand(0));
23126   EVT SrcType = Shuffle->getValueType(0);
23127
23128   // We expect a single-source shuffle
23129   if (Shuffle->getOperand(1)->getOpcode() != ISD::UNDEF)
23130     return SDValue();
23131
23132   unsigned SrcSize = SrcType.getScalarSizeInBits();
23133
23134   APInt SplatValue, SplatUndef;
23135   unsigned SplatBitSize;
23136   bool HasAnyUndefs;
23137   if (!Vector->isConstantSplat(SplatValue, SplatUndef,
23138                                 SplatBitSize, HasAnyUndefs))
23139     return SDValue();
23140
23141   unsigned ResSize = N1.getValueType().getScalarSizeInBits();
23142   // Make sure the splat matches the mask we expect
23143   if (SplatBitSize > ResSize ||
23144       (SplatValue + 1).exactLogBase2() != (int)SrcSize)
23145     return SDValue();
23146
23147   // Make sure the input and output size make sense
23148   if (SrcSize >= ResSize || ResSize % SrcSize)
23149     return SDValue();
23150
23151   // We expect a shuffle of the form <0, u, u, u, 1, u, u, u...>
23152   // The number of u's between each two values depends on the ratio between
23153   // the source and dest type.
23154   unsigned ZextRatio = ResSize / SrcSize;
23155   bool IsZext = true;
23156   for (unsigned i = 0; i < SrcType.getVectorNumElements(); ++i) {
23157     if (i % ZextRatio) {
23158       if (Shuffle->getMaskElt(i) > 0) {
23159         // Expected undef
23160         IsZext = false;
23161         break;
23162       }
23163     } else {
23164       if (Shuffle->getMaskElt(i) != (int)(i / ZextRatio)) {
23165         // Expected element number
23166         IsZext = false;
23167         break;
23168       }
23169     }
23170   }
23171
23172   if (!IsZext)
23173     return SDValue();
23174
23175   // Ok, perform the transformation - replace the shuffle with
23176   // a shuffle of the form <0, k, k, k, 1, k, k, k> with zero
23177   // (instead of undef) where the k elements come from the zero vector.
23178   SmallVector<int, 8> Mask;
23179   unsigned NumElems = SrcType.getVectorNumElements();
23180   for (unsigned i = 0; i < NumElems; ++i)
23181     if (i % ZextRatio)
23182       Mask.push_back(NumElems);
23183     else
23184       Mask.push_back(i / ZextRatio);
23185
23186   SDValue NewShuffle = DAG.getVectorShuffle(Shuffle->getValueType(0), DL,
23187     Shuffle->getOperand(0), DAG.getConstant(0, DL, SrcType), Mask);
23188   return DAG.getBitcast(N0.getValueType(), NewShuffle);
23189 }
23190
23191 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
23192                                  TargetLowering::DAGCombinerInfo &DCI,
23193                                  const X86Subtarget *Subtarget) {
23194   if (DCI.isBeforeLegalizeOps())
23195     return SDValue();
23196
23197   if (SDValue Zext = VectorZextCombine(N, DAG, DCI, Subtarget))
23198     return Zext;
23199
23200   if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
23201     return R;
23202
23203   EVT VT = N->getValueType(0);
23204   SDValue N0 = N->getOperand(0);
23205   SDValue N1 = N->getOperand(1);
23206   SDLoc DL(N);
23207
23208   // Create BEXTR instructions
23209   // BEXTR is ((X >> imm) & (2**size-1))
23210   if (VT == MVT::i32 || VT == MVT::i64) {
23211     // Check for BEXTR.
23212     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
23213         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
23214       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
23215       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
23216       if (MaskNode && ShiftNode) {
23217         uint64_t Mask = MaskNode->getZExtValue();
23218         uint64_t Shift = ShiftNode->getZExtValue();
23219         if (isMask_64(Mask)) {
23220           uint64_t MaskSize = countPopulation(Mask);
23221           if (Shift + MaskSize <= VT.getSizeInBits())
23222             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
23223                                DAG.getConstant(Shift | (MaskSize << 8), DL,
23224                                                VT));
23225         }
23226       }
23227     } // BEXTR
23228
23229     return SDValue();
23230   }
23231
23232   // Want to form ANDNP nodes:
23233   // 1) In the hopes of then easily combining them with OR and AND nodes
23234   //    to form PBLEND/PSIGN.
23235   // 2) To match ANDN packed intrinsics
23236   if (VT != MVT::v2i64 && VT != MVT::v4i64)
23237     return SDValue();
23238
23239   // Check LHS for vnot
23240   if (N0.getOpcode() == ISD::XOR &&
23241       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
23242       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
23243     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
23244
23245   // Check RHS for vnot
23246   if (N1.getOpcode() == ISD::XOR &&
23247       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
23248       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
23249     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
23250
23251   return SDValue();
23252 }
23253
23254 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
23255                                 TargetLowering::DAGCombinerInfo &DCI,
23256                                 const X86Subtarget *Subtarget) {
23257   if (DCI.isBeforeLegalizeOps())
23258     return SDValue();
23259
23260   if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
23261     return R;
23262
23263   SDValue N0 = N->getOperand(0);
23264   SDValue N1 = N->getOperand(1);
23265   EVT VT = N->getValueType(0);
23266
23267   // look for psign/blend
23268   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
23269     if (!Subtarget->hasSSSE3() ||
23270         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
23271       return SDValue();
23272
23273     // Canonicalize pandn to RHS
23274     if (N0.getOpcode() == X86ISD::ANDNP)
23275       std::swap(N0, N1);
23276     // or (and (m, y), (pandn m, x))
23277     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
23278       SDValue Mask = N1.getOperand(0);
23279       SDValue X    = N1.getOperand(1);
23280       SDValue Y;
23281       if (N0.getOperand(0) == Mask)
23282         Y = N0.getOperand(1);
23283       if (N0.getOperand(1) == Mask)
23284         Y = N0.getOperand(0);
23285
23286       // Check to see if the mask appeared in both the AND and ANDNP and
23287       if (!Y.getNode())
23288         return SDValue();
23289
23290       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
23291       // Look through mask bitcast.
23292       if (Mask.getOpcode() == ISD::BITCAST)
23293         Mask = Mask.getOperand(0);
23294       if (X.getOpcode() == ISD::BITCAST)
23295         X = X.getOperand(0);
23296       if (Y.getOpcode() == ISD::BITCAST)
23297         Y = Y.getOperand(0);
23298
23299       EVT MaskVT = Mask.getValueType();
23300
23301       // Validate that the Mask operand is a vector sra node.
23302       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
23303       // there is no psrai.b
23304       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
23305       unsigned SraAmt = ~0;
23306       if (Mask.getOpcode() == ISD::SRA) {
23307         if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
23308           if (auto *AmtConst = AmtBV->getConstantSplatNode())
23309             SraAmt = AmtConst->getZExtValue();
23310       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
23311         SDValue SraC = Mask.getOperand(1);
23312         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
23313       }
23314       if ((SraAmt + 1) != EltBits)
23315         return SDValue();
23316
23317       SDLoc DL(N);
23318
23319       // Now we know we at least have a plendvb with the mask val.  See if
23320       // we can form a psignb/w/d.
23321       // psign = x.type == y.type == mask.type && y = sub(0, x);
23322       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
23323           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
23324           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
23325         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
23326                "Unsupported VT for PSIGN");
23327         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
23328         return DAG.getBitcast(VT, Mask);
23329       }
23330       // PBLENDVB only available on SSE 4.1
23331       if (!Subtarget->hasSSE41())
23332         return SDValue();
23333
23334       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
23335
23336       X = DAG.getBitcast(BlendVT, X);
23337       Y = DAG.getBitcast(BlendVT, Y);
23338       Mask = DAG.getBitcast(BlendVT, Mask);
23339       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
23340       return DAG.getBitcast(VT, Mask);
23341     }
23342   }
23343
23344   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
23345     return SDValue();
23346
23347   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
23348   MachineFunction &MF = DAG.getMachineFunction();
23349   bool OptForSize =
23350       MF.getFunction()->hasFnAttribute(Attribute::OptimizeForSize);
23351
23352   // SHLD/SHRD instructions have lower register pressure, but on some
23353   // platforms they have higher latency than the equivalent
23354   // series of shifts/or that would otherwise be generated.
23355   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
23356   // have higher latencies and we are not optimizing for size.
23357   if (!OptForSize && Subtarget->isSHLDSlow())
23358     return SDValue();
23359
23360   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
23361     std::swap(N0, N1);
23362   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
23363     return SDValue();
23364   if (!N0.hasOneUse() || !N1.hasOneUse())
23365     return SDValue();
23366
23367   SDValue ShAmt0 = N0.getOperand(1);
23368   if (ShAmt0.getValueType() != MVT::i8)
23369     return SDValue();
23370   SDValue ShAmt1 = N1.getOperand(1);
23371   if (ShAmt1.getValueType() != MVT::i8)
23372     return SDValue();
23373   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
23374     ShAmt0 = ShAmt0.getOperand(0);
23375   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
23376     ShAmt1 = ShAmt1.getOperand(0);
23377
23378   SDLoc DL(N);
23379   unsigned Opc = X86ISD::SHLD;
23380   SDValue Op0 = N0.getOperand(0);
23381   SDValue Op1 = N1.getOperand(0);
23382   if (ShAmt0.getOpcode() == ISD::SUB) {
23383     Opc = X86ISD::SHRD;
23384     std::swap(Op0, Op1);
23385     std::swap(ShAmt0, ShAmt1);
23386   }
23387
23388   unsigned Bits = VT.getSizeInBits();
23389   if (ShAmt1.getOpcode() == ISD::SUB) {
23390     SDValue Sum = ShAmt1.getOperand(0);
23391     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
23392       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
23393       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
23394         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
23395       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
23396         return DAG.getNode(Opc, DL, VT,
23397                            Op0, Op1,
23398                            DAG.getNode(ISD::TRUNCATE, DL,
23399                                        MVT::i8, ShAmt0));
23400     }
23401   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
23402     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
23403     if (ShAmt0C &&
23404         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
23405       return DAG.getNode(Opc, DL, VT,
23406                          N0.getOperand(0), N1.getOperand(0),
23407                          DAG.getNode(ISD::TRUNCATE, DL,
23408                                        MVT::i8, ShAmt0));
23409   }
23410
23411   return SDValue();
23412 }
23413
23414 // Generate NEG and CMOV for integer abs.
23415 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
23416   EVT VT = N->getValueType(0);
23417
23418   // Since X86 does not have CMOV for 8-bit integer, we don't convert
23419   // 8-bit integer abs to NEG and CMOV.
23420   if (VT.isInteger() && VT.getSizeInBits() == 8)
23421     return SDValue();
23422
23423   SDValue N0 = N->getOperand(0);
23424   SDValue N1 = N->getOperand(1);
23425   SDLoc DL(N);
23426
23427   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
23428   // and change it to SUB and CMOV.
23429   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
23430       N0.getOpcode() == ISD::ADD &&
23431       N0.getOperand(1) == N1 &&
23432       N1.getOpcode() == ISD::SRA &&
23433       N1.getOperand(0) == N0.getOperand(0))
23434     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
23435       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
23436         // Generate SUB & CMOV.
23437         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
23438                                   DAG.getConstant(0, DL, VT), N0.getOperand(0));
23439
23440         SDValue Ops[] = { N0.getOperand(0), Neg,
23441                           DAG.getConstant(X86::COND_GE, DL, MVT::i8),
23442                           SDValue(Neg.getNode(), 1) };
23443         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
23444       }
23445   return SDValue();
23446 }
23447
23448 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
23449 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
23450                                  TargetLowering::DAGCombinerInfo &DCI,
23451                                  const X86Subtarget *Subtarget) {
23452   if (DCI.isBeforeLegalizeOps())
23453     return SDValue();
23454
23455   if (Subtarget->hasCMov())
23456     if (SDValue RV = performIntegerAbsCombine(N, DAG))
23457       return RV;
23458
23459   return SDValue();
23460 }
23461
23462 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
23463 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
23464                                   TargetLowering::DAGCombinerInfo &DCI,
23465                                   const X86Subtarget *Subtarget) {
23466   LoadSDNode *Ld = cast<LoadSDNode>(N);
23467   EVT RegVT = Ld->getValueType(0);
23468   EVT MemVT = Ld->getMemoryVT();
23469   SDLoc dl(Ld);
23470   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23471
23472   // For chips with slow 32-byte unaligned loads, break the 32-byte operation
23473   // into two 16-byte operations.
23474   ISD::LoadExtType Ext = Ld->getExtensionType();
23475   unsigned Alignment = Ld->getAlignment();
23476   bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
23477   if (RegVT.is256BitVector() && Subtarget->isUnalignedMem32Slow() &&
23478       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
23479     unsigned NumElems = RegVT.getVectorNumElements();
23480     if (NumElems < 2)
23481       return SDValue();
23482
23483     SDValue Ptr = Ld->getBasePtr();
23484     SDValue Increment = DAG.getConstant(16, dl, TLI.getPointerTy());
23485
23486     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
23487                                   NumElems/2);
23488     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
23489                                 Ld->getPointerInfo(), Ld->isVolatile(),
23490                                 Ld->isNonTemporal(), Ld->isInvariant(),
23491                                 Alignment);
23492     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
23493     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
23494                                 Ld->getPointerInfo(), Ld->isVolatile(),
23495                                 Ld->isNonTemporal(), Ld->isInvariant(),
23496                                 std::min(16U, Alignment));
23497     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
23498                              Load1.getValue(1),
23499                              Load2.getValue(1));
23500
23501     SDValue NewVec = DAG.getUNDEF(RegVT);
23502     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
23503     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
23504     return DCI.CombineTo(N, NewVec, TF, true);
23505   }
23506
23507   return SDValue();
23508 }
23509
23510 /// PerformMLOADCombine - Resolve extending loads
23511 static SDValue PerformMLOADCombine(SDNode *N, SelectionDAG &DAG,
23512                                    TargetLowering::DAGCombinerInfo &DCI,
23513                                    const X86Subtarget *Subtarget) {
23514   MaskedLoadSDNode *Mld = cast<MaskedLoadSDNode>(N);
23515   if (Mld->getExtensionType() != ISD::SEXTLOAD)
23516     return SDValue();
23517
23518   EVT VT = Mld->getValueType(0);
23519   unsigned NumElems = VT.getVectorNumElements();
23520   EVT LdVT = Mld->getMemoryVT();
23521   SDLoc dl(Mld);
23522
23523   assert(LdVT != VT && "Cannot extend to the same type");
23524   unsigned ToSz = VT.getVectorElementType().getSizeInBits();
23525   unsigned FromSz = LdVT.getVectorElementType().getSizeInBits();
23526   // From, To sizes and ElemCount must be pow of two
23527   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
23528     "Unexpected size for extending masked load");
23529
23530   unsigned SizeRatio  = ToSz / FromSz;
23531   assert(SizeRatio * NumElems * FromSz == VT.getSizeInBits());
23532
23533   // Create a type on which we perform the shuffle
23534   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
23535           LdVT.getScalarType(), NumElems*SizeRatio);
23536   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
23537
23538   // Convert Src0 value
23539   SDValue WideSrc0 = DAG.getBitcast(WideVecVT, Mld->getSrc0());
23540   if (Mld->getSrc0().getOpcode() != ISD::UNDEF) {
23541     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
23542     for (unsigned i = 0; i != NumElems; ++i)
23543       ShuffleVec[i] = i * SizeRatio;
23544
23545     // Can't shuffle using an illegal type.
23546     assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
23547             && "WideVecVT should be legal");
23548     WideSrc0 = DAG.getVectorShuffle(WideVecVT, dl, WideSrc0,
23549                                     DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
23550   }
23551   // Prepare the new mask
23552   SDValue NewMask;
23553   SDValue Mask = Mld->getMask();
23554   if (Mask.getValueType() == VT) {
23555     // Mask and original value have the same type
23556     NewMask = DAG.getBitcast(WideVecVT, Mask);
23557     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
23558     for (unsigned i = 0; i != NumElems; ++i)
23559       ShuffleVec[i] = i * SizeRatio;
23560     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
23561       ShuffleVec[i] = NumElems*SizeRatio;
23562     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
23563                                    DAG.getConstant(0, dl, WideVecVT),
23564                                    &ShuffleVec[0]);
23565   }
23566   else {
23567     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
23568     unsigned WidenNumElts = NumElems*SizeRatio;
23569     unsigned MaskNumElts = VT.getVectorNumElements();
23570     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
23571                                      WidenNumElts);
23572
23573     unsigned NumConcat = WidenNumElts / MaskNumElts;
23574     SmallVector<SDValue, 16> Ops(NumConcat);
23575     SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
23576     Ops[0] = Mask;
23577     for (unsigned i = 1; i != NumConcat; ++i)
23578       Ops[i] = ZeroVal;
23579
23580     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
23581   }
23582
23583   SDValue WideLd = DAG.getMaskedLoad(WideVecVT, dl, Mld->getChain(),
23584                                      Mld->getBasePtr(), NewMask, WideSrc0,
23585                                      Mld->getMemoryVT(), Mld->getMemOperand(),
23586                                      ISD::NON_EXTLOAD);
23587   SDValue NewVec = DAG.getNode(X86ISD::VSEXT, dl, VT, WideLd);
23588   return DCI.CombineTo(N, NewVec, WideLd.getValue(1), true);
23589
23590 }
23591 /// PerformMSTORECombine - Resolve truncating stores
23592 static SDValue PerformMSTORECombine(SDNode *N, SelectionDAG &DAG,
23593                                     const X86Subtarget *Subtarget) {
23594   MaskedStoreSDNode *Mst = cast<MaskedStoreSDNode>(N);
23595   if (!Mst->isTruncatingStore())
23596     return SDValue();
23597
23598   EVT VT = Mst->getValue().getValueType();
23599   unsigned NumElems = VT.getVectorNumElements();
23600   EVT StVT = Mst->getMemoryVT();
23601   SDLoc dl(Mst);
23602
23603   assert(StVT != VT && "Cannot truncate to the same type");
23604   unsigned FromSz = VT.getVectorElementType().getSizeInBits();
23605   unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
23606
23607   // From, To sizes and ElemCount must be pow of two
23608   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
23609     "Unexpected size for truncating masked store");
23610   // We are going to use the original vector elt for storing.
23611   // Accumulated smaller vector elements must be a multiple of the store size.
23612   assert (((NumElems * FromSz) % ToSz) == 0 &&
23613           "Unexpected ratio for truncating masked store");
23614
23615   unsigned SizeRatio  = FromSz / ToSz;
23616   assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
23617
23618   // Create a type on which we perform the shuffle
23619   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
23620           StVT.getScalarType(), NumElems*SizeRatio);
23621
23622   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
23623
23624   SDValue WideVec = DAG.getBitcast(WideVecVT, Mst->getValue());
23625   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
23626   for (unsigned i = 0; i != NumElems; ++i)
23627     ShuffleVec[i] = i * SizeRatio;
23628
23629   // Can't shuffle using an illegal type.
23630   assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
23631           && "WideVecVT should be legal");
23632
23633   SDValue TruncatedVal = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
23634                                         DAG.getUNDEF(WideVecVT),
23635                                         &ShuffleVec[0]);
23636
23637   SDValue NewMask;
23638   SDValue Mask = Mst->getMask();
23639   if (Mask.getValueType() == VT) {
23640     // Mask and original value have the same type
23641     NewMask = DAG.getBitcast(WideVecVT, Mask);
23642     for (unsigned i = 0; i != NumElems; ++i)
23643       ShuffleVec[i] = i * SizeRatio;
23644     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
23645       ShuffleVec[i] = NumElems*SizeRatio;
23646     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
23647                                    DAG.getConstant(0, dl, WideVecVT),
23648                                    &ShuffleVec[0]);
23649   }
23650   else {
23651     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
23652     unsigned WidenNumElts = NumElems*SizeRatio;
23653     unsigned MaskNumElts = VT.getVectorNumElements();
23654     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
23655                                      WidenNumElts);
23656
23657     unsigned NumConcat = WidenNumElts / MaskNumElts;
23658     SmallVector<SDValue, 16> Ops(NumConcat);
23659     SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
23660     Ops[0] = Mask;
23661     for (unsigned i = 1; i != NumConcat; ++i)
23662       Ops[i] = ZeroVal;
23663
23664     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
23665   }
23666
23667   return DAG.getMaskedStore(Mst->getChain(), dl, TruncatedVal, Mst->getBasePtr(),
23668                             NewMask, StVT, Mst->getMemOperand(), false);
23669 }
23670 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
23671 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
23672                                    const X86Subtarget *Subtarget) {
23673   StoreSDNode *St = cast<StoreSDNode>(N);
23674   EVT VT = St->getValue().getValueType();
23675   EVT StVT = St->getMemoryVT();
23676   SDLoc dl(St);
23677   SDValue StoredVal = St->getOperand(1);
23678   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23679
23680   // If we are saving a concatenation of two XMM registers and 32-byte stores
23681   // are slow, such as on Sandy Bridge, perform two 16-byte stores.
23682   unsigned Alignment = St->getAlignment();
23683   bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
23684   if (VT.is256BitVector() && Subtarget->isUnalignedMem32Slow() &&
23685       StVT == VT && !IsAligned) {
23686     unsigned NumElems = VT.getVectorNumElements();
23687     if (NumElems < 2)
23688       return SDValue();
23689
23690     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
23691     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
23692
23693     SDValue Stride = DAG.getConstant(16, dl, TLI.getPointerTy());
23694     SDValue Ptr0 = St->getBasePtr();
23695     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
23696
23697     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
23698                                 St->getPointerInfo(), St->isVolatile(),
23699                                 St->isNonTemporal(), Alignment);
23700     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
23701                                 St->getPointerInfo(), St->isVolatile(),
23702                                 St->isNonTemporal(),
23703                                 std::min(16U, Alignment));
23704     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
23705   }
23706
23707   // Optimize trunc store (of multiple scalars) to shuffle and store.
23708   // First, pack all of the elements in one place. Next, store to memory
23709   // in fewer chunks.
23710   if (St->isTruncatingStore() && VT.isVector()) {
23711     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23712     unsigned NumElems = VT.getVectorNumElements();
23713     assert(StVT != VT && "Cannot truncate to the same type");
23714     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
23715     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
23716
23717     // From, To sizes and ElemCount must be pow of two
23718     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
23719     // We are going to use the original vector elt for storing.
23720     // Accumulated smaller vector elements must be a multiple of the store size.
23721     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
23722
23723     unsigned SizeRatio  = FromSz / ToSz;
23724
23725     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
23726
23727     // Create a type on which we perform the shuffle
23728     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
23729             StVT.getScalarType(), NumElems*SizeRatio);
23730
23731     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
23732
23733     SDValue WideVec = DAG.getBitcast(WideVecVT, St->getValue());
23734     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
23735     for (unsigned i = 0; i != NumElems; ++i)
23736       ShuffleVec[i] = i * SizeRatio;
23737
23738     // Can't shuffle using an illegal type.
23739     if (!TLI.isTypeLegal(WideVecVT))
23740       return SDValue();
23741
23742     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
23743                                          DAG.getUNDEF(WideVecVT),
23744                                          &ShuffleVec[0]);
23745     // At this point all of the data is stored at the bottom of the
23746     // register. We now need to save it to mem.
23747
23748     // Find the largest store unit
23749     MVT StoreType = MVT::i8;
23750     for (MVT Tp : MVT::integer_valuetypes()) {
23751       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
23752         StoreType = Tp;
23753     }
23754
23755     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
23756     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
23757         (64 <= NumElems * ToSz))
23758       StoreType = MVT::f64;
23759
23760     // Bitcast the original vector into a vector of store-size units
23761     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
23762             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
23763     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
23764     SDValue ShuffWide = DAG.getBitcast(StoreVecVT, Shuff);
23765     SmallVector<SDValue, 8> Chains;
23766     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8, dl,
23767                                         TLI.getPointerTy());
23768     SDValue Ptr = St->getBasePtr();
23769
23770     // Perform one or more big stores into memory.
23771     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
23772       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
23773                                    StoreType, ShuffWide,
23774                                    DAG.getIntPtrConstant(i, dl));
23775       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
23776                                 St->getPointerInfo(), St->isVolatile(),
23777                                 St->isNonTemporal(), St->getAlignment());
23778       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
23779       Chains.push_back(Ch);
23780     }
23781
23782     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
23783   }
23784
23785   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
23786   // the FP state in cases where an emms may be missing.
23787   // A preferable solution to the general problem is to figure out the right
23788   // places to insert EMMS.  This qualifies as a quick hack.
23789
23790   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
23791   if (VT.getSizeInBits() != 64)
23792     return SDValue();
23793
23794   const Function *F = DAG.getMachineFunction().getFunction();
23795   bool NoImplicitFloatOps = F->hasFnAttribute(Attribute::NoImplicitFloat);
23796   bool F64IsLegal =
23797       !Subtarget->useSoftFloat() && !NoImplicitFloatOps && Subtarget->hasSSE2();
23798   if ((VT.isVector() ||
23799        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
23800       isa<LoadSDNode>(St->getValue()) &&
23801       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
23802       St->getChain().hasOneUse() && !St->isVolatile()) {
23803     SDNode* LdVal = St->getValue().getNode();
23804     LoadSDNode *Ld = nullptr;
23805     int TokenFactorIndex = -1;
23806     SmallVector<SDValue, 8> Ops;
23807     SDNode* ChainVal = St->getChain().getNode();
23808     // Must be a store of a load.  We currently handle two cases:  the load
23809     // is a direct child, and it's under an intervening TokenFactor.  It is
23810     // possible to dig deeper under nested TokenFactors.
23811     if (ChainVal == LdVal)
23812       Ld = cast<LoadSDNode>(St->getChain());
23813     else if (St->getValue().hasOneUse() &&
23814              ChainVal->getOpcode() == ISD::TokenFactor) {
23815       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
23816         if (ChainVal->getOperand(i).getNode() == LdVal) {
23817           TokenFactorIndex = i;
23818           Ld = cast<LoadSDNode>(St->getValue());
23819         } else
23820           Ops.push_back(ChainVal->getOperand(i));
23821       }
23822     }
23823
23824     if (!Ld || !ISD::isNormalLoad(Ld))
23825       return SDValue();
23826
23827     // If this is not the MMX case, i.e. we are just turning i64 load/store
23828     // into f64 load/store, avoid the transformation if there are multiple
23829     // uses of the loaded value.
23830     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
23831       return SDValue();
23832
23833     SDLoc LdDL(Ld);
23834     SDLoc StDL(N);
23835     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
23836     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
23837     // pair instead.
23838     if (Subtarget->is64Bit() || F64IsLegal) {
23839       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
23840       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
23841                                   Ld->getPointerInfo(), Ld->isVolatile(),
23842                                   Ld->isNonTemporal(), Ld->isInvariant(),
23843                                   Ld->getAlignment());
23844       SDValue NewChain = NewLd.getValue(1);
23845       if (TokenFactorIndex != -1) {
23846         Ops.push_back(NewChain);
23847         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
23848       }
23849       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
23850                           St->getPointerInfo(),
23851                           St->isVolatile(), St->isNonTemporal(),
23852                           St->getAlignment());
23853     }
23854
23855     // Otherwise, lower to two pairs of 32-bit loads / stores.
23856     SDValue LoAddr = Ld->getBasePtr();
23857     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
23858                                  DAG.getConstant(4, LdDL, MVT::i32));
23859
23860     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
23861                                Ld->getPointerInfo(),
23862                                Ld->isVolatile(), Ld->isNonTemporal(),
23863                                Ld->isInvariant(), Ld->getAlignment());
23864     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
23865                                Ld->getPointerInfo().getWithOffset(4),
23866                                Ld->isVolatile(), Ld->isNonTemporal(),
23867                                Ld->isInvariant(),
23868                                MinAlign(Ld->getAlignment(), 4));
23869
23870     SDValue NewChain = LoLd.getValue(1);
23871     if (TokenFactorIndex != -1) {
23872       Ops.push_back(LoLd);
23873       Ops.push_back(HiLd);
23874       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
23875     }
23876
23877     LoAddr = St->getBasePtr();
23878     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
23879                          DAG.getConstant(4, StDL, MVT::i32));
23880
23881     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
23882                                 St->getPointerInfo(),
23883                                 St->isVolatile(), St->isNonTemporal(),
23884                                 St->getAlignment());
23885     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
23886                                 St->getPointerInfo().getWithOffset(4),
23887                                 St->isVolatile(),
23888                                 St->isNonTemporal(),
23889                                 MinAlign(St->getAlignment(), 4));
23890     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
23891   }
23892
23893   // This is similar to the above case, but here we handle a scalar 64-bit
23894   // integer store that is extracted from a vector on a 32-bit target.
23895   // If we have SSE2, then we can treat it like a floating-point double
23896   // to get past legalization. The execution dependencies fixup pass will
23897   // choose the optimal machine instruction for the store if this really is
23898   // an integer or v2f32 rather than an f64.
23899   if (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit() &&
23900       St->getOperand(1).getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
23901     SDValue OldExtract = St->getOperand(1);
23902     SDValue ExtOp0 = OldExtract.getOperand(0);
23903     unsigned VecSize = ExtOp0.getValueSizeInBits();
23904     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, VecSize / 64);
23905     SDValue BitCast = DAG.getBitcast(VecVT, ExtOp0);
23906     SDValue NewExtract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
23907                                      BitCast, OldExtract.getOperand(1));
23908     return DAG.getStore(St->getChain(), dl, NewExtract, St->getBasePtr(),
23909                         St->getPointerInfo(), St->isVolatile(),
23910                         St->isNonTemporal(), St->getAlignment());
23911   }
23912
23913   return SDValue();
23914 }
23915
23916 /// Return 'true' if this vector operation is "horizontal"
23917 /// and return the operands for the horizontal operation in LHS and RHS.  A
23918 /// horizontal operation performs the binary operation on successive elements
23919 /// of its first operand, then on successive elements of its second operand,
23920 /// returning the resulting values in a vector.  For example, if
23921 ///   A = < float a0, float a1, float a2, float a3 >
23922 /// and
23923 ///   B = < float b0, float b1, float b2, float b3 >
23924 /// then the result of doing a horizontal operation on A and B is
23925 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
23926 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
23927 /// A horizontal-op B, for some already available A and B, and if so then LHS is
23928 /// set to A, RHS to B, and the routine returns 'true'.
23929 /// Note that the binary operation should have the property that if one of the
23930 /// operands is UNDEF then the result is UNDEF.
23931 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
23932   // Look for the following pattern: if
23933   //   A = < float a0, float a1, float a2, float a3 >
23934   //   B = < float b0, float b1, float b2, float b3 >
23935   // and
23936   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
23937   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
23938   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
23939   // which is A horizontal-op B.
23940
23941   // At least one of the operands should be a vector shuffle.
23942   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
23943       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
23944     return false;
23945
23946   MVT VT = LHS.getSimpleValueType();
23947
23948   assert((VT.is128BitVector() || VT.is256BitVector()) &&
23949          "Unsupported vector type for horizontal add/sub");
23950
23951   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
23952   // operate independently on 128-bit lanes.
23953   unsigned NumElts = VT.getVectorNumElements();
23954   unsigned NumLanes = VT.getSizeInBits()/128;
23955   unsigned NumLaneElts = NumElts / NumLanes;
23956   assert((NumLaneElts % 2 == 0) &&
23957          "Vector type should have an even number of elements in each lane");
23958   unsigned HalfLaneElts = NumLaneElts/2;
23959
23960   // View LHS in the form
23961   //   LHS = VECTOR_SHUFFLE A, B, LMask
23962   // If LHS is not a shuffle then pretend it is the shuffle
23963   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
23964   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
23965   // type VT.
23966   SDValue A, B;
23967   SmallVector<int, 16> LMask(NumElts);
23968   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
23969     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
23970       A = LHS.getOperand(0);
23971     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
23972       B = LHS.getOperand(1);
23973     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
23974     std::copy(Mask.begin(), Mask.end(), LMask.begin());
23975   } else {
23976     if (LHS.getOpcode() != ISD::UNDEF)
23977       A = LHS;
23978     for (unsigned i = 0; i != NumElts; ++i)
23979       LMask[i] = i;
23980   }
23981
23982   // Likewise, view RHS in the form
23983   //   RHS = VECTOR_SHUFFLE C, D, RMask
23984   SDValue C, D;
23985   SmallVector<int, 16> RMask(NumElts);
23986   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
23987     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
23988       C = RHS.getOperand(0);
23989     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
23990       D = RHS.getOperand(1);
23991     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
23992     std::copy(Mask.begin(), Mask.end(), RMask.begin());
23993   } else {
23994     if (RHS.getOpcode() != ISD::UNDEF)
23995       C = RHS;
23996     for (unsigned i = 0; i != NumElts; ++i)
23997       RMask[i] = i;
23998   }
23999
24000   // Check that the shuffles are both shuffling the same vectors.
24001   if (!(A == C && B == D) && !(A == D && B == C))
24002     return false;
24003
24004   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
24005   if (!A.getNode() && !B.getNode())
24006     return false;
24007
24008   // If A and B occur in reverse order in RHS, then "swap" them (which means
24009   // rewriting the mask).
24010   if (A != C)
24011     ShuffleVectorSDNode::commuteMask(RMask);
24012
24013   // At this point LHS and RHS are equivalent to
24014   //   LHS = VECTOR_SHUFFLE A, B, LMask
24015   //   RHS = VECTOR_SHUFFLE A, B, RMask
24016   // Check that the masks correspond to performing a horizontal operation.
24017   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
24018     for (unsigned i = 0; i != NumLaneElts; ++i) {
24019       int LIdx = LMask[i+l], RIdx = RMask[i+l];
24020
24021       // Ignore any UNDEF components.
24022       if (LIdx < 0 || RIdx < 0 ||
24023           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
24024           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
24025         continue;
24026
24027       // Check that successive elements are being operated on.  If not, this is
24028       // not a horizontal operation.
24029       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
24030       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
24031       if (!(LIdx == Index && RIdx == Index + 1) &&
24032           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
24033         return false;
24034     }
24035   }
24036
24037   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
24038   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
24039   return true;
24040 }
24041
24042 /// Do target-specific dag combines on floating point adds.
24043 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
24044                                   const X86Subtarget *Subtarget) {
24045   EVT VT = N->getValueType(0);
24046   SDValue LHS = N->getOperand(0);
24047   SDValue RHS = N->getOperand(1);
24048
24049   // Try to synthesize horizontal adds from adds of shuffles.
24050   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
24051        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
24052       isHorizontalBinOp(LHS, RHS, true))
24053     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
24054   return SDValue();
24055 }
24056
24057 /// Do target-specific dag combines on floating point subs.
24058 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
24059                                   const X86Subtarget *Subtarget) {
24060   EVT VT = N->getValueType(0);
24061   SDValue LHS = N->getOperand(0);
24062   SDValue RHS = N->getOperand(1);
24063
24064   // Try to synthesize horizontal subs from subs of shuffles.
24065   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
24066        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
24067       isHorizontalBinOp(LHS, RHS, false))
24068     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
24069   return SDValue();
24070 }
24071
24072 /// Do target-specific dag combines on X86ISD::FOR and X86ISD::FXOR nodes.
24073 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
24074   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
24075
24076   // F[X]OR(0.0, x) -> x
24077   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
24078     if (C->getValueAPF().isPosZero())
24079       return N->getOperand(1);
24080
24081   // F[X]OR(x, 0.0) -> x
24082   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
24083     if (C->getValueAPF().isPosZero())
24084       return N->getOperand(0);
24085   return SDValue();
24086 }
24087
24088 /// Do target-specific dag combines on X86ISD::FMIN and X86ISD::FMAX nodes.
24089 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
24090   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
24091
24092   // Only perform optimizations if UnsafeMath is used.
24093   if (!DAG.getTarget().Options.UnsafeFPMath)
24094     return SDValue();
24095
24096   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
24097   // into FMINC and FMAXC, which are Commutative operations.
24098   unsigned NewOp = 0;
24099   switch (N->getOpcode()) {
24100     default: llvm_unreachable("unknown opcode");
24101     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
24102     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
24103   }
24104
24105   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
24106                      N->getOperand(0), N->getOperand(1));
24107 }
24108
24109 /// Do target-specific dag combines on X86ISD::FAND nodes.
24110 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
24111   // FAND(0.0, x) -> 0.0
24112   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
24113     if (C->getValueAPF().isPosZero())
24114       return N->getOperand(0);
24115
24116   // FAND(x, 0.0) -> 0.0
24117   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
24118     if (C->getValueAPF().isPosZero())
24119       return N->getOperand(1);
24120
24121   return SDValue();
24122 }
24123
24124 /// Do target-specific dag combines on X86ISD::FANDN nodes
24125 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
24126   // FANDN(0.0, x) -> x
24127   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
24128     if (C->getValueAPF().isPosZero())
24129       return N->getOperand(1);
24130
24131   // FANDN(x, 0.0) -> 0.0
24132   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
24133     if (C->getValueAPF().isPosZero())
24134       return N->getOperand(1);
24135
24136   return SDValue();
24137 }
24138
24139 static SDValue PerformBTCombine(SDNode *N,
24140                                 SelectionDAG &DAG,
24141                                 TargetLowering::DAGCombinerInfo &DCI) {
24142   // BT ignores high bits in the bit index operand.
24143   SDValue Op1 = N->getOperand(1);
24144   if (Op1.hasOneUse()) {
24145     unsigned BitWidth = Op1.getValueSizeInBits();
24146     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
24147     APInt KnownZero, KnownOne;
24148     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
24149                                           !DCI.isBeforeLegalizeOps());
24150     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24151     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
24152         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
24153       DCI.CommitTargetLoweringOpt(TLO);
24154   }
24155   return SDValue();
24156 }
24157
24158 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
24159   SDValue Op = N->getOperand(0);
24160   if (Op.getOpcode() == ISD::BITCAST)
24161     Op = Op.getOperand(0);
24162   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
24163   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
24164       VT.getVectorElementType().getSizeInBits() ==
24165       OpVT.getVectorElementType().getSizeInBits()) {
24166     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
24167   }
24168   return SDValue();
24169 }
24170
24171 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
24172                                                const X86Subtarget *Subtarget) {
24173   EVT VT = N->getValueType(0);
24174   if (!VT.isVector())
24175     return SDValue();
24176
24177   SDValue N0 = N->getOperand(0);
24178   SDValue N1 = N->getOperand(1);
24179   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
24180   SDLoc dl(N);
24181
24182   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
24183   // both SSE and AVX2 since there is no sign-extended shift right
24184   // operation on a vector with 64-bit elements.
24185   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
24186   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
24187   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
24188       N0.getOpcode() == ISD::SIGN_EXTEND)) {
24189     SDValue N00 = N0.getOperand(0);
24190
24191     // EXTLOAD has a better solution on AVX2,
24192     // it may be replaced with X86ISD::VSEXT node.
24193     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
24194       if (!ISD::isNormalLoad(N00.getNode()))
24195         return SDValue();
24196
24197     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
24198         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
24199                                   N00, N1);
24200       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
24201     }
24202   }
24203   return SDValue();
24204 }
24205
24206 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
24207                                   TargetLowering::DAGCombinerInfo &DCI,
24208                                   const X86Subtarget *Subtarget) {
24209   SDValue N0 = N->getOperand(0);
24210   EVT VT = N->getValueType(0);
24211   EVT SVT = VT.getScalarType();
24212   EVT InVT = N0.getValueType();
24213   EVT InSVT = InVT.getScalarType();
24214   SDLoc DL(N);
24215
24216   // (i8,i32 sext (sdivrem (i8 x, i8 y)) ->
24217   // (i8,i32 (sdivrem_sext_hreg (i8 x, i8 y)
24218   // This exposes the sext to the sdivrem lowering, so that it directly extends
24219   // from AH (which we otherwise need to do contortions to access).
24220   if (N0.getOpcode() == ISD::SDIVREM && N0.getResNo() == 1 &&
24221       InVT == MVT::i8 && VT == MVT::i32) {
24222     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
24223     SDValue R = DAG.getNode(X86ISD::SDIVREM8_SEXT_HREG, DL, NodeTys,
24224                             N0.getOperand(0), N0.getOperand(1));
24225     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
24226     return R.getValue(1);
24227   }
24228
24229   if (!DCI.isBeforeLegalizeOps()) {
24230     if (InVT == MVT::i1) {
24231       SDValue Zero = DAG.getConstant(0, DL, VT);
24232       SDValue AllOnes =
24233         DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL, VT);
24234       return DAG.getNode(ISD::SELECT, DL, VT, N0, AllOnes, Zero);
24235     }
24236     return SDValue();
24237   }
24238
24239   if (VT.isVector() && Subtarget->hasSSE2()) {
24240     auto ExtendVecSize = [&DAG](SDLoc DL, SDValue N, unsigned Size) {
24241       EVT InVT = N.getValueType();
24242       EVT OutVT = EVT::getVectorVT(*DAG.getContext(), InVT.getScalarType(),
24243                                    Size / InVT.getScalarSizeInBits());
24244       SmallVector<SDValue, 8> Opnds(Size / InVT.getSizeInBits(),
24245                                     DAG.getUNDEF(InVT));
24246       Opnds[0] = N;
24247       return DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Opnds);
24248     };
24249
24250     // If target-size is less than 128-bits, extend to a type that would extend
24251     // to 128 bits, extend that and extract the original target vector.
24252     if (VT.getSizeInBits() < 128 && !(128 % VT.getSizeInBits()) &&
24253         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
24254         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
24255       unsigned Scale = 128 / VT.getSizeInBits();
24256       EVT ExVT =
24257           EVT::getVectorVT(*DAG.getContext(), SVT, 128 / SVT.getSizeInBits());
24258       SDValue Ex = ExtendVecSize(DL, N0, Scale * InVT.getSizeInBits());
24259       SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, ExVT, Ex);
24260       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, SExt,
24261                          DAG.getIntPtrConstant(0, DL));
24262     }
24263
24264     // If target-size is 128-bits, then convert to ISD::SIGN_EXTEND_VECTOR_INREG
24265     // which ensures lowering to X86ISD::VSEXT (pmovsx*).
24266     if (VT.getSizeInBits() == 128 &&
24267         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
24268         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
24269       SDValue ExOp = ExtendVecSize(DL, N0, 128);
24270       return DAG.getSignExtendVectorInReg(ExOp, DL, VT);
24271     }
24272
24273     // On pre-AVX2 targets, split into 128-bit nodes of
24274     // ISD::SIGN_EXTEND_VECTOR_INREG.
24275     if (!Subtarget->hasInt256() && !(VT.getSizeInBits() % 128) &&
24276         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
24277         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
24278       unsigned NumVecs = VT.getSizeInBits() / 128;
24279       unsigned NumSubElts = 128 / SVT.getSizeInBits();
24280       EVT SubVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumSubElts);
24281       EVT InSubVT = EVT::getVectorVT(*DAG.getContext(), InSVT, NumSubElts);
24282
24283       SmallVector<SDValue, 8> Opnds;
24284       for (unsigned i = 0, Offset = 0; i != NumVecs;
24285            ++i, Offset += NumSubElts) {
24286         SDValue SrcVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InSubVT, N0,
24287                                      DAG.getIntPtrConstant(Offset, DL));
24288         SrcVec = ExtendVecSize(DL, SrcVec, 128);
24289         SrcVec = DAG.getSignExtendVectorInReg(SrcVec, DL, SubVT);
24290         Opnds.push_back(SrcVec);
24291       }
24292       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Opnds);
24293     }
24294   }
24295
24296   if (!Subtarget->hasFp256())
24297     return SDValue();
24298
24299   if (VT.isVector() && VT.getSizeInBits() == 256)
24300     if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
24301       return R;
24302
24303   return SDValue();
24304 }
24305
24306 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
24307                                  const X86Subtarget* Subtarget) {
24308   SDLoc dl(N);
24309   EVT VT = N->getValueType(0);
24310
24311   // Let legalize expand this if it isn't a legal type yet.
24312   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
24313     return SDValue();
24314
24315   EVT ScalarVT = VT.getScalarType();
24316   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
24317       (!Subtarget->hasFMA() && !Subtarget->hasFMA4() &&
24318        !Subtarget->hasAVX512()))
24319     return SDValue();
24320
24321   SDValue A = N->getOperand(0);
24322   SDValue B = N->getOperand(1);
24323   SDValue C = N->getOperand(2);
24324
24325   bool NegA = (A.getOpcode() == ISD::FNEG);
24326   bool NegB = (B.getOpcode() == ISD::FNEG);
24327   bool NegC = (C.getOpcode() == ISD::FNEG);
24328
24329   // Negative multiplication when NegA xor NegB
24330   bool NegMul = (NegA != NegB);
24331   if (NegA)
24332     A = A.getOperand(0);
24333   if (NegB)
24334     B = B.getOperand(0);
24335   if (NegC)
24336     C = C.getOperand(0);
24337
24338   unsigned Opcode;
24339   if (!NegMul)
24340     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
24341   else
24342     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
24343
24344   return DAG.getNode(Opcode, dl, VT, A, B, C);
24345 }
24346
24347 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
24348                                   TargetLowering::DAGCombinerInfo &DCI,
24349                                   const X86Subtarget *Subtarget) {
24350   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
24351   //           (and (i32 x86isd::setcc_carry), 1)
24352   // This eliminates the zext. This transformation is necessary because
24353   // ISD::SETCC is always legalized to i8.
24354   SDLoc dl(N);
24355   SDValue N0 = N->getOperand(0);
24356   EVT VT = N->getValueType(0);
24357
24358   if (N0.getOpcode() == ISD::AND &&
24359       N0.hasOneUse() &&
24360       N0.getOperand(0).hasOneUse()) {
24361     SDValue N00 = N0.getOperand(0);
24362     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
24363       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
24364       if (!C || C->getZExtValue() != 1)
24365         return SDValue();
24366       return DAG.getNode(ISD::AND, dl, VT,
24367                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
24368                                      N00.getOperand(0), N00.getOperand(1)),
24369                          DAG.getConstant(1, dl, VT));
24370     }
24371   }
24372
24373   if (N0.getOpcode() == ISD::TRUNCATE &&
24374       N0.hasOneUse() &&
24375       N0.getOperand(0).hasOneUse()) {
24376     SDValue N00 = N0.getOperand(0);
24377     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
24378       return DAG.getNode(ISD::AND, dl, VT,
24379                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
24380                                      N00.getOperand(0), N00.getOperand(1)),
24381                          DAG.getConstant(1, dl, VT));
24382     }
24383   }
24384
24385   if (VT.is256BitVector())
24386     if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
24387       return R;
24388
24389   // (i8,i32 zext (udivrem (i8 x, i8 y)) ->
24390   // (i8,i32 (udivrem_zext_hreg (i8 x, i8 y)
24391   // This exposes the zext to the udivrem lowering, so that it directly extends
24392   // from AH (which we otherwise need to do contortions to access).
24393   if (N0.getOpcode() == ISD::UDIVREM &&
24394       N0.getResNo() == 1 && N0.getValueType() == MVT::i8 &&
24395       (VT == MVT::i32 || VT == MVT::i64)) {
24396     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
24397     SDValue R = DAG.getNode(X86ISD::UDIVREM8_ZEXT_HREG, dl, NodeTys,
24398                             N0.getOperand(0), N0.getOperand(1));
24399     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
24400     return R.getValue(1);
24401   }
24402
24403   return SDValue();
24404 }
24405
24406 // Optimize x == -y --> x+y == 0
24407 //          x != -y --> x+y != 0
24408 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
24409                                       const X86Subtarget* Subtarget) {
24410   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
24411   SDValue LHS = N->getOperand(0);
24412   SDValue RHS = N->getOperand(1);
24413   EVT VT = N->getValueType(0);
24414   SDLoc DL(N);
24415
24416   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
24417     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
24418       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
24419         SDValue addV = DAG.getNode(ISD::ADD, DL, LHS.getValueType(), RHS,
24420                                    LHS.getOperand(1));
24421         return DAG.getSetCC(DL, N->getValueType(0), addV,
24422                             DAG.getConstant(0, DL, addV.getValueType()), CC);
24423       }
24424   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
24425     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
24426       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
24427         SDValue addV = DAG.getNode(ISD::ADD, DL, RHS.getValueType(), LHS,
24428                                    RHS.getOperand(1));
24429         return DAG.getSetCC(DL, N->getValueType(0), addV,
24430                             DAG.getConstant(0, DL, addV.getValueType()), CC);
24431       }
24432
24433   if (VT.getScalarType() == MVT::i1 &&
24434       (CC == ISD::SETNE || CC == ISD::SETEQ || ISD::isSignedIntSetCC(CC))) {
24435     bool IsSEXT0 =
24436         (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
24437         (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
24438     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
24439
24440     if (!IsSEXT0 || !IsVZero1) {
24441       // Swap the operands and update the condition code.
24442       std::swap(LHS, RHS);
24443       CC = ISD::getSetCCSwappedOperands(CC);
24444
24445       IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
24446                 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
24447       IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
24448     }
24449
24450     if (IsSEXT0 && IsVZero1) {
24451       assert(VT == LHS.getOperand(0).getValueType() &&
24452              "Uexpected operand type");
24453       if (CC == ISD::SETGT)
24454         return DAG.getConstant(0, DL, VT);
24455       if (CC == ISD::SETLE)
24456         return DAG.getConstant(1, DL, VT);
24457       if (CC == ISD::SETEQ || CC == ISD::SETGE)
24458         return DAG.getNOT(DL, LHS.getOperand(0), VT);
24459
24460       assert((CC == ISD::SETNE || CC == ISD::SETLT) &&
24461              "Unexpected condition code!");
24462       return LHS.getOperand(0);
24463     }
24464   }
24465
24466   return SDValue();
24467 }
24468
24469 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
24470                                          SelectionDAG &DAG) {
24471   SDLoc dl(Load);
24472   MVT VT = Load->getSimpleValueType(0);
24473   MVT EVT = VT.getVectorElementType();
24474   SDValue Addr = Load->getOperand(1);
24475   SDValue NewAddr = DAG.getNode(
24476       ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
24477       DAG.getConstant(Index * EVT.getStoreSize(), dl,
24478                       Addr.getSimpleValueType()));
24479
24480   SDValue NewLoad =
24481       DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
24482                   DAG.getMachineFunction().getMachineMemOperand(
24483                       Load->getMemOperand(), 0, EVT.getStoreSize()));
24484   return NewLoad;
24485 }
24486
24487 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
24488                                       const X86Subtarget *Subtarget) {
24489   SDLoc dl(N);
24490   MVT VT = N->getOperand(1)->getSimpleValueType(0);
24491   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
24492          "X86insertps is only defined for v4x32");
24493
24494   SDValue Ld = N->getOperand(1);
24495   if (MayFoldLoad(Ld)) {
24496     // Extract the countS bits from the immediate so we can get the proper
24497     // address when narrowing the vector load to a specific element.
24498     // When the second source op is a memory address, insertps doesn't use
24499     // countS and just gets an f32 from that address.
24500     unsigned DestIndex =
24501         cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
24502
24503     Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
24504
24505     // Create this as a scalar to vector to match the instruction pattern.
24506     SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
24507     // countS bits are ignored when loading from memory on insertps, which
24508     // means we don't need to explicitly set them to 0.
24509     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
24510                        LoadScalarToVector, N->getOperand(2));
24511   }
24512   return SDValue();
24513 }
24514
24515 static SDValue PerformBLENDICombine(SDNode *N, SelectionDAG &DAG) {
24516   SDValue V0 = N->getOperand(0);
24517   SDValue V1 = N->getOperand(1);
24518   SDLoc DL(N);
24519   EVT VT = N->getValueType(0);
24520
24521   // Canonicalize a v2f64 blend with a mask of 2 by swapping the vector
24522   // operands and changing the mask to 1. This saves us a bunch of
24523   // pattern-matching possibilities related to scalar math ops in SSE/AVX.
24524   // x86InstrInfo knows how to commute this back after instruction selection
24525   // if it would help register allocation.
24526
24527   // TODO: If optimizing for size or a processor that doesn't suffer from
24528   // partial register update stalls, this should be transformed into a MOVSD
24529   // instruction because a MOVSD is 1-2 bytes smaller than a BLENDPD.
24530
24531   if (VT == MVT::v2f64)
24532     if (auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(2)))
24533       if (Mask->getZExtValue() == 2 && !isShuffleFoldableLoad(V0)) {
24534         SDValue NewMask = DAG.getConstant(1, DL, MVT::i8);
24535         return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V0, NewMask);
24536       }
24537
24538   return SDValue();
24539 }
24540
24541 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
24542 // as "sbb reg,reg", since it can be extended without zext and produces
24543 // an all-ones bit which is more useful than 0/1 in some cases.
24544 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
24545                                MVT VT) {
24546   if (VT == MVT::i8)
24547     return DAG.getNode(ISD::AND, DL, VT,
24548                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
24549                                    DAG.getConstant(X86::COND_B, DL, MVT::i8),
24550                                    EFLAGS),
24551                        DAG.getConstant(1, DL, VT));
24552   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
24553   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
24554                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
24555                                  DAG.getConstant(X86::COND_B, DL, MVT::i8),
24556                                  EFLAGS));
24557 }
24558
24559 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
24560 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
24561                                    TargetLowering::DAGCombinerInfo &DCI,
24562                                    const X86Subtarget *Subtarget) {
24563   SDLoc DL(N);
24564   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
24565   SDValue EFLAGS = N->getOperand(1);
24566
24567   if (CC == X86::COND_A) {
24568     // Try to convert COND_A into COND_B in an attempt to facilitate
24569     // materializing "setb reg".
24570     //
24571     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
24572     // cannot take an immediate as its first operand.
24573     //
24574     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
24575         EFLAGS.getValueType().isInteger() &&
24576         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
24577       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
24578                                    EFLAGS.getNode()->getVTList(),
24579                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
24580       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
24581       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
24582     }
24583   }
24584
24585   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
24586   // a zext and produces an all-ones bit which is more useful than 0/1 in some
24587   // cases.
24588   if (CC == X86::COND_B)
24589     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
24590
24591   if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
24592     SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
24593     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
24594   }
24595
24596   return SDValue();
24597 }
24598
24599 // Optimize branch condition evaluation.
24600 //
24601 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
24602                                     TargetLowering::DAGCombinerInfo &DCI,
24603                                     const X86Subtarget *Subtarget) {
24604   SDLoc DL(N);
24605   SDValue Chain = N->getOperand(0);
24606   SDValue Dest = N->getOperand(1);
24607   SDValue EFLAGS = N->getOperand(3);
24608   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
24609
24610   if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
24611     SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
24612     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
24613                        Flags);
24614   }
24615
24616   return SDValue();
24617 }
24618
24619 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
24620                                                          SelectionDAG &DAG) {
24621   // Take advantage of vector comparisons producing 0 or -1 in each lane to
24622   // optimize away operation when it's from a constant.
24623   //
24624   // The general transformation is:
24625   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
24626   //       AND(VECTOR_CMP(x,y), constant2)
24627   //    constant2 = UNARYOP(constant)
24628
24629   // Early exit if this isn't a vector operation, the operand of the
24630   // unary operation isn't a bitwise AND, or if the sizes of the operations
24631   // aren't the same.
24632   EVT VT = N->getValueType(0);
24633   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
24634       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
24635       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
24636     return SDValue();
24637
24638   // Now check that the other operand of the AND is a constant. We could
24639   // make the transformation for non-constant splats as well, but it's unclear
24640   // that would be a benefit as it would not eliminate any operations, just
24641   // perform one more step in scalar code before moving to the vector unit.
24642   if (BuildVectorSDNode *BV =
24643           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
24644     // Bail out if the vector isn't a constant.
24645     if (!BV->isConstant())
24646       return SDValue();
24647
24648     // Everything checks out. Build up the new and improved node.
24649     SDLoc DL(N);
24650     EVT IntVT = BV->getValueType(0);
24651     // Create a new constant of the appropriate type for the transformed
24652     // DAG.
24653     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
24654     // The AND node needs bitcasts to/from an integer vector type around it.
24655     SDValue MaskConst = DAG.getBitcast(IntVT, SourceConst);
24656     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
24657                                  N->getOperand(0)->getOperand(0), MaskConst);
24658     SDValue Res = DAG.getBitcast(VT, NewAnd);
24659     return Res;
24660   }
24661
24662   return SDValue();
24663 }
24664
24665 static SDValue PerformUINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
24666                                         const X86Subtarget *Subtarget) {
24667   SDValue Op0 = N->getOperand(0);
24668   EVT VT = N->getValueType(0);
24669   EVT InVT = Op0.getValueType();
24670   EVT InSVT = InVT.getScalarType();
24671   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24672
24673   // UINT_TO_FP(vXi8) -> SINT_TO_FP(ZEXT(vXi8 to vXi32))
24674   // UINT_TO_FP(vXi16) -> SINT_TO_FP(ZEXT(vXi16 to vXi32))
24675   if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
24676     SDLoc dl(N);
24677     EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
24678                                  InVT.getVectorNumElements());
24679     SDValue P = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Op0);
24680
24681     if (TLI.isOperationLegal(ISD::UINT_TO_FP, DstVT))
24682       return DAG.getNode(ISD::UINT_TO_FP, dl, VT, P);
24683
24684     return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
24685   }
24686
24687   return SDValue();
24688 }
24689
24690 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
24691                                         const X86Subtarget *Subtarget) {
24692   // First try to optimize away the conversion entirely when it's
24693   // conditionally from a constant. Vectors only.
24694   if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
24695     return Res;
24696
24697   // Now move on to more general possibilities.
24698   SDValue Op0 = N->getOperand(0);
24699   EVT VT = N->getValueType(0);
24700   EVT InVT = Op0.getValueType();
24701   EVT InSVT = InVT.getScalarType();
24702
24703   // SINT_TO_FP(vXi8) -> SINT_TO_FP(SEXT(vXi8 to vXi32))
24704   // SINT_TO_FP(vXi16) -> SINT_TO_FP(SEXT(vXi16 to vXi32))
24705   if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
24706     SDLoc dl(N);
24707     EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
24708                                  InVT.getVectorNumElements());
24709     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
24710     return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
24711   }
24712
24713   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
24714   // a 32-bit target where SSE doesn't support i64->FP operations.
24715   if (Op0.getOpcode() == ISD::LOAD) {
24716     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
24717     EVT LdVT = Ld->getValueType(0);
24718
24719     // This transformation is not supported if the result type is f16
24720     if (VT == MVT::f16)
24721       return SDValue();
24722
24723     if (!Ld->isVolatile() && !VT.isVector() &&
24724         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
24725         !Subtarget->is64Bit() && LdVT == MVT::i64) {
24726       SDValue FILDChain = Subtarget->getTargetLowering()->BuildFILD(
24727           SDValue(N, 0), LdVT, Ld->getChain(), Op0, DAG);
24728       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
24729       return FILDChain;
24730     }
24731   }
24732   return SDValue();
24733 }
24734
24735 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
24736 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
24737                                  X86TargetLowering::DAGCombinerInfo &DCI) {
24738   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
24739   // the result is either zero or one (depending on the input carry bit).
24740   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
24741   if (X86::isZeroNode(N->getOperand(0)) &&
24742       X86::isZeroNode(N->getOperand(1)) &&
24743       // We don't have a good way to replace an EFLAGS use, so only do this when
24744       // dead right now.
24745       SDValue(N, 1).use_empty()) {
24746     SDLoc DL(N);
24747     EVT VT = N->getValueType(0);
24748     SDValue CarryOut = DAG.getConstant(0, DL, N->getValueType(1));
24749     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
24750                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
24751                                            DAG.getConstant(X86::COND_B, DL,
24752                                                            MVT::i8),
24753                                            N->getOperand(2)),
24754                                DAG.getConstant(1, DL, VT));
24755     return DCI.CombineTo(N, Res1, CarryOut);
24756   }
24757
24758   return SDValue();
24759 }
24760
24761 // fold (add Y, (sete  X, 0)) -> adc  0, Y
24762 //      (add Y, (setne X, 0)) -> sbb -1, Y
24763 //      (sub (sete  X, 0), Y) -> sbb  0, Y
24764 //      (sub (setne X, 0), Y) -> adc -1, Y
24765 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
24766   SDLoc DL(N);
24767
24768   // Look through ZExts.
24769   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
24770   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
24771     return SDValue();
24772
24773   SDValue SetCC = Ext.getOperand(0);
24774   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
24775     return SDValue();
24776
24777   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
24778   if (CC != X86::COND_E && CC != X86::COND_NE)
24779     return SDValue();
24780
24781   SDValue Cmp = SetCC.getOperand(1);
24782   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
24783       !X86::isZeroNode(Cmp.getOperand(1)) ||
24784       !Cmp.getOperand(0).getValueType().isInteger())
24785     return SDValue();
24786
24787   SDValue CmpOp0 = Cmp.getOperand(0);
24788   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
24789                                DAG.getConstant(1, DL, CmpOp0.getValueType()));
24790
24791   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
24792   if (CC == X86::COND_NE)
24793     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
24794                        DL, OtherVal.getValueType(), OtherVal,
24795                        DAG.getConstant(-1ULL, DL, OtherVal.getValueType()),
24796                        NewCmp);
24797   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
24798                      DL, OtherVal.getValueType(), OtherVal,
24799                      DAG.getConstant(0, DL, OtherVal.getValueType()), NewCmp);
24800 }
24801
24802 /// PerformADDCombine - Do target-specific dag combines on integer adds.
24803 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
24804                                  const X86Subtarget *Subtarget) {
24805   EVT VT = N->getValueType(0);
24806   SDValue Op0 = N->getOperand(0);
24807   SDValue Op1 = N->getOperand(1);
24808
24809   // Try to synthesize horizontal adds from adds of shuffles.
24810   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
24811        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
24812       isHorizontalBinOp(Op0, Op1, true))
24813     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
24814
24815   return OptimizeConditionalInDecrement(N, DAG);
24816 }
24817
24818 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
24819                                  const X86Subtarget *Subtarget) {
24820   SDValue Op0 = N->getOperand(0);
24821   SDValue Op1 = N->getOperand(1);
24822
24823   // X86 can't encode an immediate LHS of a sub. See if we can push the
24824   // negation into a preceding instruction.
24825   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
24826     // If the RHS of the sub is a XOR with one use and a constant, invert the
24827     // immediate. Then add one to the LHS of the sub so we can turn
24828     // X-Y -> X+~Y+1, saving one register.
24829     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
24830         isa<ConstantSDNode>(Op1.getOperand(1))) {
24831       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
24832       EVT VT = Op0.getValueType();
24833       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
24834                                    Op1.getOperand(0),
24835                                    DAG.getConstant(~XorC, SDLoc(Op1), VT));
24836       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
24837                          DAG.getConstant(C->getAPIntValue() + 1, SDLoc(N), VT));
24838     }
24839   }
24840
24841   // Try to synthesize horizontal adds from adds of shuffles.
24842   EVT VT = N->getValueType(0);
24843   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
24844        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
24845       isHorizontalBinOp(Op0, Op1, true))
24846     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
24847
24848   return OptimizeConditionalInDecrement(N, DAG);
24849 }
24850
24851 /// performVZEXTCombine - Performs build vector combines
24852 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
24853                                    TargetLowering::DAGCombinerInfo &DCI,
24854                                    const X86Subtarget *Subtarget) {
24855   SDLoc DL(N);
24856   MVT VT = N->getSimpleValueType(0);
24857   SDValue Op = N->getOperand(0);
24858   MVT OpVT = Op.getSimpleValueType();
24859   MVT OpEltVT = OpVT.getVectorElementType();
24860   unsigned InputBits = OpEltVT.getSizeInBits() * VT.getVectorNumElements();
24861
24862   // (vzext (bitcast (vzext (x)) -> (vzext x)
24863   SDValue V = Op;
24864   while (V.getOpcode() == ISD::BITCAST)
24865     V = V.getOperand(0);
24866
24867   if (V != Op && V.getOpcode() == X86ISD::VZEXT) {
24868     MVT InnerVT = V.getSimpleValueType();
24869     MVT InnerEltVT = InnerVT.getVectorElementType();
24870
24871     // If the element sizes match exactly, we can just do one larger vzext. This
24872     // is always an exact type match as vzext operates on integer types.
24873     if (OpEltVT == InnerEltVT) {
24874       assert(OpVT == InnerVT && "Types must match for vzext!");
24875       return DAG.getNode(X86ISD::VZEXT, DL, VT, V.getOperand(0));
24876     }
24877
24878     // The only other way we can combine them is if only a single element of the
24879     // inner vzext is used in the input to the outer vzext.
24880     if (InnerEltVT.getSizeInBits() < InputBits)
24881       return SDValue();
24882
24883     // In this case, the inner vzext is completely dead because we're going to
24884     // only look at bits inside of the low element. Just do the outer vzext on
24885     // a bitcast of the input to the inner.
24886     return DAG.getNode(X86ISD::VZEXT, DL, VT, DAG.getBitcast(OpVT, V));
24887   }
24888
24889   // Check if we can bypass extracting and re-inserting an element of an input
24890   // vector. Essentialy:
24891   // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
24892   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR &&
24893       V.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
24894       V.getOperand(0).getSimpleValueType().getSizeInBits() == InputBits) {
24895     SDValue ExtractedV = V.getOperand(0);
24896     SDValue OrigV = ExtractedV.getOperand(0);
24897     if (auto *ExtractIdx = dyn_cast<ConstantSDNode>(ExtractedV.getOperand(1)))
24898       if (ExtractIdx->getZExtValue() == 0) {
24899         MVT OrigVT = OrigV.getSimpleValueType();
24900         // Extract a subvector if necessary...
24901         if (OrigVT.getSizeInBits() > OpVT.getSizeInBits()) {
24902           int Ratio = OrigVT.getSizeInBits() / OpVT.getSizeInBits();
24903           OrigVT = MVT::getVectorVT(OrigVT.getVectorElementType(),
24904                                     OrigVT.getVectorNumElements() / Ratio);
24905           OrigV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigVT, OrigV,
24906                               DAG.getIntPtrConstant(0, DL));
24907         }
24908         Op = DAG.getBitcast(OpVT, OrigV);
24909         return DAG.getNode(X86ISD::VZEXT, DL, VT, Op);
24910       }
24911   }
24912
24913   return SDValue();
24914 }
24915
24916 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
24917                                              DAGCombinerInfo &DCI) const {
24918   SelectionDAG &DAG = DCI.DAG;
24919   switch (N->getOpcode()) {
24920   default: break;
24921   case ISD::EXTRACT_VECTOR_ELT:
24922     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
24923   case ISD::VSELECT:
24924   case ISD::SELECT:
24925   case X86ISD::SHRUNKBLEND:
24926     return PerformSELECTCombine(N, DAG, DCI, Subtarget);
24927   case ISD::BITCAST:        return PerformBITCASTCombine(N, DAG);
24928   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
24929   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
24930   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
24931   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
24932   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
24933   case ISD::SHL:
24934   case ISD::SRA:
24935   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
24936   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
24937   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
24938   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
24939   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
24940   case ISD::MLOAD:          return PerformMLOADCombine(N, DAG, DCI, Subtarget);
24941   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
24942   case ISD::MSTORE:         return PerformMSTORECombine(N, DAG, Subtarget);
24943   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, Subtarget);
24944   case ISD::UINT_TO_FP:     return PerformUINT_TO_FPCombine(N, DAG, Subtarget);
24945   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
24946   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
24947   case X86ISD::FXOR:
24948   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
24949   case X86ISD::FMIN:
24950   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
24951   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
24952   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
24953   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
24954   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
24955   case ISD::ANY_EXTEND:
24956   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
24957   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
24958   case ISD::SIGN_EXTEND_INREG:
24959     return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
24960   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
24961   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
24962   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
24963   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
24964   case X86ISD::SHUFP:       // Handle all target specific shuffles
24965   case X86ISD::PALIGNR:
24966   case X86ISD::UNPCKH:
24967   case X86ISD::UNPCKL:
24968   case X86ISD::MOVHLPS:
24969   case X86ISD::MOVLHPS:
24970   case X86ISD::PSHUFB:
24971   case X86ISD::PSHUFD:
24972   case X86ISD::PSHUFHW:
24973   case X86ISD::PSHUFLW:
24974   case X86ISD::MOVSS:
24975   case X86ISD::MOVSD:
24976   case X86ISD::VPERMILPI:
24977   case X86ISD::VPERM2X128:
24978   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
24979   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
24980   case ISD::INTRINSIC_WO_CHAIN:
24981     return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
24982   case X86ISD::INSERTPS: {
24983     if (getTargetMachine().getOptLevel() > CodeGenOpt::None)
24984       return PerformINSERTPSCombine(N, DAG, Subtarget);
24985     break;
24986   }
24987   case X86ISD::BLENDI:    return PerformBLENDICombine(N, DAG);
24988   }
24989
24990   return SDValue();
24991 }
24992
24993 /// isTypeDesirableForOp - Return true if the target has native support for
24994 /// the specified value type and it is 'desirable' to use the type for the
24995 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
24996 /// instruction encodings are longer and some i16 instructions are slow.
24997 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
24998   if (!isTypeLegal(VT))
24999     return false;
25000   if (VT != MVT::i16)
25001     return true;
25002
25003   switch (Opc) {
25004   default:
25005     return true;
25006   case ISD::LOAD:
25007   case ISD::SIGN_EXTEND:
25008   case ISD::ZERO_EXTEND:
25009   case ISD::ANY_EXTEND:
25010   case ISD::SHL:
25011   case ISD::SRL:
25012   case ISD::SUB:
25013   case ISD::ADD:
25014   case ISD::MUL:
25015   case ISD::AND:
25016   case ISD::OR:
25017   case ISD::XOR:
25018     return false;
25019   }
25020 }
25021
25022 /// IsDesirableToPromoteOp - This method query the target whether it is
25023 /// beneficial for dag combiner to promote the specified node. If true, it
25024 /// should return the desired promotion type by reference.
25025 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
25026   EVT VT = Op.getValueType();
25027   if (VT != MVT::i16)
25028     return false;
25029
25030   bool Promote = false;
25031   bool Commute = false;
25032   switch (Op.getOpcode()) {
25033   default: break;
25034   case ISD::LOAD: {
25035     LoadSDNode *LD = cast<LoadSDNode>(Op);
25036     // If the non-extending load has a single use and it's not live out, then it
25037     // might be folded.
25038     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
25039                                                      Op.hasOneUse()*/) {
25040       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
25041              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
25042         // The only case where we'd want to promote LOAD (rather then it being
25043         // promoted as an operand is when it's only use is liveout.
25044         if (UI->getOpcode() != ISD::CopyToReg)
25045           return false;
25046       }
25047     }
25048     Promote = true;
25049     break;
25050   }
25051   case ISD::SIGN_EXTEND:
25052   case ISD::ZERO_EXTEND:
25053   case ISD::ANY_EXTEND:
25054     Promote = true;
25055     break;
25056   case ISD::SHL:
25057   case ISD::SRL: {
25058     SDValue N0 = Op.getOperand(0);
25059     // Look out for (store (shl (load), x)).
25060     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
25061       return false;
25062     Promote = true;
25063     break;
25064   }
25065   case ISD::ADD:
25066   case ISD::MUL:
25067   case ISD::AND:
25068   case ISD::OR:
25069   case ISD::XOR:
25070     Commute = true;
25071     // fallthrough
25072   case ISD::SUB: {
25073     SDValue N0 = Op.getOperand(0);
25074     SDValue N1 = Op.getOperand(1);
25075     if (!Commute && MayFoldLoad(N1))
25076       return false;
25077     // Avoid disabling potential load folding opportunities.
25078     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
25079       return false;
25080     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
25081       return false;
25082     Promote = true;
25083   }
25084   }
25085
25086   PVT = MVT::i32;
25087   return Promote;
25088 }
25089
25090 //===----------------------------------------------------------------------===//
25091 //                           X86 Inline Assembly Support
25092 //===----------------------------------------------------------------------===//
25093
25094 // Helper to match a string separated by whitespace.
25095 static bool matchAsm(StringRef S, ArrayRef<const char *> Pieces) {
25096   S = S.substr(S.find_first_not_of(" \t")); // Skip leading whitespace.
25097
25098   for (StringRef Piece : Pieces) {
25099     if (!S.startswith(Piece)) // Check if the piece matches.
25100       return false;
25101
25102     S = S.substr(Piece.size());
25103     StringRef::size_type Pos = S.find_first_not_of(" \t");
25104     if (Pos == 0) // We matched a prefix.
25105       return false;
25106
25107     S = S.substr(Pos);
25108   }
25109
25110   return S.empty();
25111 }
25112
25113 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
25114
25115   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
25116     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
25117         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
25118         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
25119
25120       if (AsmPieces.size() == 3)
25121         return true;
25122       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
25123         return true;
25124     }
25125   }
25126   return false;
25127 }
25128
25129 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
25130   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
25131
25132   std::string AsmStr = IA->getAsmString();
25133
25134   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
25135   if (!Ty || Ty->getBitWidth() % 16 != 0)
25136     return false;
25137
25138   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
25139   SmallVector<StringRef, 4> AsmPieces;
25140   SplitString(AsmStr, AsmPieces, ";\n");
25141
25142   switch (AsmPieces.size()) {
25143   default: return false;
25144   case 1:
25145     // FIXME: this should verify that we are targeting a 486 or better.  If not,
25146     // we will turn this bswap into something that will be lowered to logical
25147     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
25148     // lower so don't worry about this.
25149     // bswap $0
25150     if (matchAsm(AsmPieces[0], {"bswap", "$0"}) ||
25151         matchAsm(AsmPieces[0], {"bswapl", "$0"}) ||
25152         matchAsm(AsmPieces[0], {"bswapq", "$0"}) ||
25153         matchAsm(AsmPieces[0], {"bswap", "${0:q}"}) ||
25154         matchAsm(AsmPieces[0], {"bswapl", "${0:q}"}) ||
25155         matchAsm(AsmPieces[0], {"bswapq", "${0:q}"})) {
25156       // No need to check constraints, nothing other than the equivalent of
25157       // "=r,0" would be valid here.
25158       return IntrinsicLowering::LowerToByteSwap(CI);
25159     }
25160
25161     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
25162     if (CI->getType()->isIntegerTy(16) &&
25163         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
25164         (matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) ||
25165          matchAsm(AsmPieces[0], {"rolw", "$$8,", "${0:w}"}))) {
25166       AsmPieces.clear();
25167       StringRef ConstraintsStr = IA->getConstraintString();
25168       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
25169       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
25170       if (clobbersFlagRegisters(AsmPieces))
25171         return IntrinsicLowering::LowerToByteSwap(CI);
25172     }
25173     break;
25174   case 3:
25175     if (CI->getType()->isIntegerTy(32) &&
25176         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
25177         matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) &&
25178         matchAsm(AsmPieces[1], {"rorl", "$$16,", "$0"}) &&
25179         matchAsm(AsmPieces[2], {"rorw", "$$8,", "${0:w}"})) {
25180       AsmPieces.clear();
25181       StringRef ConstraintsStr = IA->getConstraintString();
25182       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
25183       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
25184       if (clobbersFlagRegisters(AsmPieces))
25185         return IntrinsicLowering::LowerToByteSwap(CI);
25186     }
25187
25188     if (CI->getType()->isIntegerTy(64)) {
25189       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
25190       if (Constraints.size() >= 2 &&
25191           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
25192           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
25193         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
25194         if (matchAsm(AsmPieces[0], {"bswap", "%eax"}) &&
25195             matchAsm(AsmPieces[1], {"bswap", "%edx"}) &&
25196             matchAsm(AsmPieces[2], {"xchgl", "%eax,", "%edx"}))
25197           return IntrinsicLowering::LowerToByteSwap(CI);
25198       }
25199     }
25200     break;
25201   }
25202   return false;
25203 }
25204
25205 /// getConstraintType - Given a constraint letter, return the type of
25206 /// constraint it is for this target.
25207 X86TargetLowering::ConstraintType
25208 X86TargetLowering::getConstraintType(StringRef Constraint) const {
25209   if (Constraint.size() == 1) {
25210     switch (Constraint[0]) {
25211     case 'R':
25212     case 'q':
25213     case 'Q':
25214     case 'f':
25215     case 't':
25216     case 'u':
25217     case 'y':
25218     case 'x':
25219     case 'Y':
25220     case 'l':
25221       return C_RegisterClass;
25222     case 'a':
25223     case 'b':
25224     case 'c':
25225     case 'd':
25226     case 'S':
25227     case 'D':
25228     case 'A':
25229       return C_Register;
25230     case 'I':
25231     case 'J':
25232     case 'K':
25233     case 'L':
25234     case 'M':
25235     case 'N':
25236     case 'G':
25237     case 'C':
25238     case 'e':
25239     case 'Z':
25240       return C_Other;
25241     default:
25242       break;
25243     }
25244   }
25245   return TargetLowering::getConstraintType(Constraint);
25246 }
25247
25248 /// Examine constraint type and operand type and determine a weight value.
25249 /// This object must already have been set up with the operand type
25250 /// and the current alternative constraint selected.
25251 TargetLowering::ConstraintWeight
25252   X86TargetLowering::getSingleConstraintMatchWeight(
25253     AsmOperandInfo &info, const char *constraint) const {
25254   ConstraintWeight weight = CW_Invalid;
25255   Value *CallOperandVal = info.CallOperandVal;
25256     // If we don't have a value, we can't do a match,
25257     // but allow it at the lowest weight.
25258   if (!CallOperandVal)
25259     return CW_Default;
25260   Type *type = CallOperandVal->getType();
25261   // Look at the constraint type.
25262   switch (*constraint) {
25263   default:
25264     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
25265   case 'R':
25266   case 'q':
25267   case 'Q':
25268   case 'a':
25269   case 'b':
25270   case 'c':
25271   case 'd':
25272   case 'S':
25273   case 'D':
25274   case 'A':
25275     if (CallOperandVal->getType()->isIntegerTy())
25276       weight = CW_SpecificReg;
25277     break;
25278   case 'f':
25279   case 't':
25280   case 'u':
25281     if (type->isFloatingPointTy())
25282       weight = CW_SpecificReg;
25283     break;
25284   case 'y':
25285     if (type->isX86_MMXTy() && Subtarget->hasMMX())
25286       weight = CW_SpecificReg;
25287     break;
25288   case 'x':
25289   case 'Y':
25290     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
25291         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
25292       weight = CW_Register;
25293     break;
25294   case 'I':
25295     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
25296       if (C->getZExtValue() <= 31)
25297         weight = CW_Constant;
25298     }
25299     break;
25300   case 'J':
25301     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25302       if (C->getZExtValue() <= 63)
25303         weight = CW_Constant;
25304     }
25305     break;
25306   case 'K':
25307     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25308       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
25309         weight = CW_Constant;
25310     }
25311     break;
25312   case 'L':
25313     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25314       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
25315         weight = CW_Constant;
25316     }
25317     break;
25318   case 'M':
25319     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25320       if (C->getZExtValue() <= 3)
25321         weight = CW_Constant;
25322     }
25323     break;
25324   case 'N':
25325     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25326       if (C->getZExtValue() <= 0xff)
25327         weight = CW_Constant;
25328     }
25329     break;
25330   case 'G':
25331   case 'C':
25332     if (isa<ConstantFP>(CallOperandVal)) {
25333       weight = CW_Constant;
25334     }
25335     break;
25336   case 'e':
25337     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25338       if ((C->getSExtValue() >= -0x80000000LL) &&
25339           (C->getSExtValue() <= 0x7fffffffLL))
25340         weight = CW_Constant;
25341     }
25342     break;
25343   case 'Z':
25344     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25345       if (C->getZExtValue() <= 0xffffffff)
25346         weight = CW_Constant;
25347     }
25348     break;
25349   }
25350   return weight;
25351 }
25352
25353 /// LowerXConstraint - try to replace an X constraint, which matches anything,
25354 /// with another that has more specific requirements based on the type of the
25355 /// corresponding operand.
25356 const char *X86TargetLowering::
25357 LowerXConstraint(EVT ConstraintVT) const {
25358   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
25359   // 'f' like normal targets.
25360   if (ConstraintVT.isFloatingPoint()) {
25361     if (Subtarget->hasSSE2())
25362       return "Y";
25363     if (Subtarget->hasSSE1())
25364       return "x";
25365   }
25366
25367   return TargetLowering::LowerXConstraint(ConstraintVT);
25368 }
25369
25370 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
25371 /// vector.  If it is invalid, don't add anything to Ops.
25372 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
25373                                                      std::string &Constraint,
25374                                                      std::vector<SDValue>&Ops,
25375                                                      SelectionDAG &DAG) const {
25376   SDValue Result;
25377
25378   // Only support length 1 constraints for now.
25379   if (Constraint.length() > 1) return;
25380
25381   char ConstraintLetter = Constraint[0];
25382   switch (ConstraintLetter) {
25383   default: break;
25384   case 'I':
25385     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25386       if (C->getZExtValue() <= 31) {
25387         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
25388                                        Op.getValueType());
25389         break;
25390       }
25391     }
25392     return;
25393   case 'J':
25394     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25395       if (C->getZExtValue() <= 63) {
25396         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
25397                                        Op.getValueType());
25398         break;
25399       }
25400     }
25401     return;
25402   case 'K':
25403     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25404       if (isInt<8>(C->getSExtValue())) {
25405         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
25406                                        Op.getValueType());
25407         break;
25408       }
25409     }
25410     return;
25411   case 'L':
25412     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25413       if (C->getZExtValue() == 0xff || C->getZExtValue() == 0xffff ||
25414           (Subtarget->is64Bit() && C->getZExtValue() == 0xffffffff)) {
25415         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op),
25416                                        Op.getValueType());
25417         break;
25418       }
25419     }
25420     return;
25421   case 'M':
25422     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25423       if (C->getZExtValue() <= 3) {
25424         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
25425                                        Op.getValueType());
25426         break;
25427       }
25428     }
25429     return;
25430   case 'N':
25431     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25432       if (C->getZExtValue() <= 255) {
25433         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
25434                                        Op.getValueType());
25435         break;
25436       }
25437     }
25438     return;
25439   case 'O':
25440     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25441       if (C->getZExtValue() <= 127) {
25442         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
25443                                        Op.getValueType());
25444         break;
25445       }
25446     }
25447     return;
25448   case 'e': {
25449     // 32-bit signed value
25450     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25451       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
25452                                            C->getSExtValue())) {
25453         // Widen to 64 bits here to get it sign extended.
25454         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op), MVT::i64);
25455         break;
25456       }
25457     // FIXME gcc accepts some relocatable values here too, but only in certain
25458     // memory models; it's complicated.
25459     }
25460     return;
25461   }
25462   case 'Z': {
25463     // 32-bit unsigned value
25464     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25465       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
25466                                            C->getZExtValue())) {
25467         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
25468                                        Op.getValueType());
25469         break;
25470       }
25471     }
25472     // FIXME gcc accepts some relocatable values here too, but only in certain
25473     // memory models; it's complicated.
25474     return;
25475   }
25476   case 'i': {
25477     // Literal immediates are always ok.
25478     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
25479       // Widen to 64 bits here to get it sign extended.
25480       Result = DAG.getTargetConstant(CST->getSExtValue(), SDLoc(Op), MVT::i64);
25481       break;
25482     }
25483
25484     // In any sort of PIC mode addresses need to be computed at runtime by
25485     // adding in a register or some sort of table lookup.  These can't
25486     // be used as immediates.
25487     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
25488       return;
25489
25490     // If we are in non-pic codegen mode, we allow the address of a global (with
25491     // an optional displacement) to be used with 'i'.
25492     GlobalAddressSDNode *GA = nullptr;
25493     int64_t Offset = 0;
25494
25495     // Match either (GA), (GA+C), (GA+C1+C2), etc.
25496     while (1) {
25497       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
25498         Offset += GA->getOffset();
25499         break;
25500       } else if (Op.getOpcode() == ISD::ADD) {
25501         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
25502           Offset += C->getZExtValue();
25503           Op = Op.getOperand(0);
25504           continue;
25505         }
25506       } else if (Op.getOpcode() == ISD::SUB) {
25507         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
25508           Offset += -C->getZExtValue();
25509           Op = Op.getOperand(0);
25510           continue;
25511         }
25512       }
25513
25514       // Otherwise, this isn't something we can handle, reject it.
25515       return;
25516     }
25517
25518     const GlobalValue *GV = GA->getGlobal();
25519     // If we require an extra load to get this address, as in PIC mode, we
25520     // can't accept it.
25521     if (isGlobalStubReference(
25522             Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
25523       return;
25524
25525     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
25526                                         GA->getValueType(0), Offset);
25527     break;
25528   }
25529   }
25530
25531   if (Result.getNode()) {
25532     Ops.push_back(Result);
25533     return;
25534   }
25535   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
25536 }
25537
25538 std::pair<unsigned, const TargetRegisterClass *>
25539 X86TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
25540                                                 StringRef Constraint,
25541                                                 MVT VT) const {
25542   // First, see if this is a constraint that directly corresponds to an LLVM
25543   // register class.
25544   if (Constraint.size() == 1) {
25545     // GCC Constraint Letters
25546     switch (Constraint[0]) {
25547     default: break;
25548       // TODO: Slight differences here in allocation order and leaving
25549       // RIP in the class. Do they matter any more here than they do
25550       // in the normal allocation?
25551     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
25552       if (Subtarget->is64Bit()) {
25553         if (VT == MVT::i32 || VT == MVT::f32)
25554           return std::make_pair(0U, &X86::GR32RegClass);
25555         if (VT == MVT::i16)
25556           return std::make_pair(0U, &X86::GR16RegClass);
25557         if (VT == MVT::i8 || VT == MVT::i1)
25558           return std::make_pair(0U, &X86::GR8RegClass);
25559         if (VT == MVT::i64 || VT == MVT::f64)
25560           return std::make_pair(0U, &X86::GR64RegClass);
25561         break;
25562       }
25563       // 32-bit fallthrough
25564     case 'Q':   // Q_REGS
25565       if (VT == MVT::i32 || VT == MVT::f32)
25566         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
25567       if (VT == MVT::i16)
25568         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
25569       if (VT == MVT::i8 || VT == MVT::i1)
25570         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
25571       if (VT == MVT::i64)
25572         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
25573       break;
25574     case 'r':   // GENERAL_REGS
25575     case 'l':   // INDEX_REGS
25576       if (VT == MVT::i8 || VT == MVT::i1)
25577         return std::make_pair(0U, &X86::GR8RegClass);
25578       if (VT == MVT::i16)
25579         return std::make_pair(0U, &X86::GR16RegClass);
25580       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
25581         return std::make_pair(0U, &X86::GR32RegClass);
25582       return std::make_pair(0U, &X86::GR64RegClass);
25583     case 'R':   // LEGACY_REGS
25584       if (VT == MVT::i8 || VT == MVT::i1)
25585         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
25586       if (VT == MVT::i16)
25587         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
25588       if (VT == MVT::i32 || !Subtarget->is64Bit())
25589         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
25590       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
25591     case 'f':  // FP Stack registers.
25592       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
25593       // value to the correct fpstack register class.
25594       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
25595         return std::make_pair(0U, &X86::RFP32RegClass);
25596       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
25597         return std::make_pair(0U, &X86::RFP64RegClass);
25598       return std::make_pair(0U, &X86::RFP80RegClass);
25599     case 'y':   // MMX_REGS if MMX allowed.
25600       if (!Subtarget->hasMMX()) break;
25601       return std::make_pair(0U, &X86::VR64RegClass);
25602     case 'Y':   // SSE_REGS if SSE2 allowed
25603       if (!Subtarget->hasSSE2()) break;
25604       // FALL THROUGH.
25605     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
25606       if (!Subtarget->hasSSE1()) break;
25607
25608       switch (VT.SimpleTy) {
25609       default: break;
25610       // Scalar SSE types.
25611       case MVT::f32:
25612       case MVT::i32:
25613         return std::make_pair(0U, &X86::FR32RegClass);
25614       case MVT::f64:
25615       case MVT::i64:
25616         return std::make_pair(0U, &X86::FR64RegClass);
25617       // Vector types.
25618       case MVT::v16i8:
25619       case MVT::v8i16:
25620       case MVT::v4i32:
25621       case MVT::v2i64:
25622       case MVT::v4f32:
25623       case MVT::v2f64:
25624         return std::make_pair(0U, &X86::VR128RegClass);
25625       // AVX types.
25626       case MVT::v32i8:
25627       case MVT::v16i16:
25628       case MVT::v8i32:
25629       case MVT::v4i64:
25630       case MVT::v8f32:
25631       case MVT::v4f64:
25632         return std::make_pair(0U, &X86::VR256RegClass);
25633       case MVT::v8f64:
25634       case MVT::v16f32:
25635       case MVT::v16i32:
25636       case MVT::v8i64:
25637         return std::make_pair(0U, &X86::VR512RegClass);
25638       }
25639       break;
25640     }
25641   }
25642
25643   // Use the default implementation in TargetLowering to convert the register
25644   // constraint into a member of a register class.
25645   std::pair<unsigned, const TargetRegisterClass*> Res;
25646   Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
25647
25648   // Not found as a standard register?
25649   if (!Res.second) {
25650     // Map st(0) -> st(7) -> ST0
25651     if (Constraint.size() == 7 && Constraint[0] == '{' &&
25652         tolower(Constraint[1]) == 's' &&
25653         tolower(Constraint[2]) == 't' &&
25654         Constraint[3] == '(' &&
25655         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
25656         Constraint[5] == ')' &&
25657         Constraint[6] == '}') {
25658
25659       Res.first = X86::FP0+Constraint[4]-'0';
25660       Res.second = &X86::RFP80RegClass;
25661       return Res;
25662     }
25663
25664     // GCC allows "st(0)" to be called just plain "st".
25665     if (StringRef("{st}").equals_lower(Constraint)) {
25666       Res.first = X86::FP0;
25667       Res.second = &X86::RFP80RegClass;
25668       return Res;
25669     }
25670
25671     // flags -> EFLAGS
25672     if (StringRef("{flags}").equals_lower(Constraint)) {
25673       Res.first = X86::EFLAGS;
25674       Res.second = &X86::CCRRegClass;
25675       return Res;
25676     }
25677
25678     // 'A' means EAX + EDX.
25679     if (Constraint == "A") {
25680       Res.first = X86::EAX;
25681       Res.second = &X86::GR32_ADRegClass;
25682       return Res;
25683     }
25684     return Res;
25685   }
25686
25687   // Otherwise, check to see if this is a register class of the wrong value
25688   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
25689   // turn into {ax},{dx}.
25690   // MVT::Other is used to specify clobber names.
25691   if (Res.second->hasType(VT) || VT == MVT::Other)
25692     return Res;   // Correct type already, nothing to do.
25693
25694   // Get a matching integer of the correct size. i.e. "ax" with MVT::32 should
25695   // return "eax". This should even work for things like getting 64bit integer
25696   // registers when given an f64 type.
25697   const TargetRegisterClass *Class = Res.second;
25698   if (Class == &X86::GR8RegClass || Class == &X86::GR16RegClass ||
25699       Class == &X86::GR32RegClass || Class == &X86::GR64RegClass) {
25700     unsigned Size = VT.getSizeInBits();
25701     MVT::SimpleValueType SimpleTy = Size == 1 || Size == 8 ? MVT::i8
25702                                   : Size == 16 ? MVT::i16
25703                                   : Size == 32 ? MVT::i32
25704                                   : Size == 64 ? MVT::i64
25705                                   : MVT::Other;
25706     unsigned DestReg = getX86SubSuperRegisterOrZero(Res.first, SimpleTy);
25707     if (DestReg > 0) {
25708       Res.first = DestReg;
25709       Res.second = SimpleTy == MVT::i8 ? &X86::GR8RegClass
25710                  : SimpleTy == MVT::i16 ? &X86::GR16RegClass
25711                  : SimpleTy == MVT::i32 ? &X86::GR32RegClass
25712                  : &X86::GR64RegClass;
25713       assert(Res.second->contains(Res.first) && "Register in register class");
25714     } else {
25715       // No register found/type mismatch.
25716       Res.first = 0;
25717       Res.second = nullptr;
25718     }
25719   } else if (Class == &X86::FR32RegClass || Class == &X86::FR64RegClass ||
25720              Class == &X86::VR128RegClass || Class == &X86::VR256RegClass ||
25721              Class == &X86::FR32XRegClass || Class == &X86::FR64XRegClass ||
25722              Class == &X86::VR128XRegClass || Class == &X86::VR256XRegClass ||
25723              Class == &X86::VR512RegClass) {
25724     // Handle references to XMM physical registers that got mapped into the
25725     // wrong class.  This can happen with constraints like {xmm0} where the
25726     // target independent register mapper will just pick the first match it can
25727     // find, ignoring the required type.
25728
25729     if (VT == MVT::f32 || VT == MVT::i32)
25730       Res.second = &X86::FR32RegClass;
25731     else if (VT == MVT::f64 || VT == MVT::i64)
25732       Res.second = &X86::FR64RegClass;
25733     else if (X86::VR128RegClass.hasType(VT))
25734       Res.second = &X86::VR128RegClass;
25735     else if (X86::VR256RegClass.hasType(VT))
25736       Res.second = &X86::VR256RegClass;
25737     else if (X86::VR512RegClass.hasType(VT))
25738       Res.second = &X86::VR512RegClass;
25739     else {
25740       // Type mismatch and not a clobber: Return an error;
25741       Res.first = 0;
25742       Res.second = nullptr;
25743     }
25744   }
25745
25746   return Res;
25747 }
25748
25749 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
25750                                             Type *Ty,
25751                                             unsigned AS) const {
25752   // Scaling factors are not free at all.
25753   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
25754   // will take 2 allocations in the out of order engine instead of 1
25755   // for plain addressing mode, i.e. inst (reg1).
25756   // E.g.,
25757   // vaddps (%rsi,%drx), %ymm0, %ymm1
25758   // Requires two allocations (one for the load, one for the computation)
25759   // whereas:
25760   // vaddps (%rsi), %ymm0, %ymm1
25761   // Requires just 1 allocation, i.e., freeing allocations for other operations
25762   // and having less micro operations to execute.
25763   //
25764   // For some X86 architectures, this is even worse because for instance for
25765   // stores, the complex addressing mode forces the instruction to use the
25766   // "load" ports instead of the dedicated "store" port.
25767   // E.g., on Haswell:
25768   // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
25769   // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
25770   if (isLegalAddressingMode(AM, Ty, AS))
25771     // Scale represents reg2 * scale, thus account for 1
25772     // as soon as we use a second register.
25773     return AM.Scale != 0;
25774   return -1;
25775 }
25776
25777 bool X86TargetLowering::isTargetFTOL() const {
25778   return Subtarget->isTargetKnownWindowsMSVC() && !Subtarget->is64Bit();
25779 }