ScheduleDAGInstrs: In functions with tail calls PseudoSourceValues are not non-aliasi...
[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 static cl::opt<int> ReciprocalEstimateRefinementSteps(
71     "x86-recip-refinement-steps", cl::init(1),
72     cl::desc("Specify the number of Newton-Raphson iterations applied to the "
73              "result of the hardware reciprocal estimate instruction."),
74     cl::NotHidden);
75
76 // Forward declarations.
77 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
78                        SDValue V2);
79
80 X86TargetLowering::X86TargetLowering(const X86TargetMachine &TM,
81                                      const X86Subtarget &STI)
82     : TargetLowering(TM), Subtarget(&STI) {
83   X86ScalarSSEf64 = Subtarget->hasSSE2();
84   X86ScalarSSEf32 = Subtarget->hasSSE1();
85   TD = getDataLayout();
86
87   // Set up the TargetLowering object.
88   static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
89
90   // X86 is weird. It always uses i8 for shift amounts and setcc results.
91   setBooleanContents(ZeroOrOneBooleanContent);
92   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
93   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
94
95   // For 64-bit, since we have so many registers, use the ILP scheduler.
96   // For 32-bit, use the register pressure specific scheduling.
97   // For Atom, always use ILP scheduling.
98   if (Subtarget->isAtom())
99     setSchedulingPreference(Sched::ILP);
100   else if (Subtarget->is64Bit())
101     setSchedulingPreference(Sched::ILP);
102   else
103     setSchedulingPreference(Sched::RegPressure);
104   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
105   setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
106
107   // Bypass expensive divides on Atom when compiling with O2.
108   if (TM.getOptLevel() >= CodeGenOpt::Default) {
109     if (Subtarget->hasSlowDivide32())
110       addBypassSlowDiv(32, 8);
111     if (Subtarget->hasSlowDivide64() && Subtarget->is64Bit())
112       addBypassSlowDiv(64, 16);
113   }
114
115   if (Subtarget->isTargetKnownWindowsMSVC()) {
116     // Setup Windows compiler runtime calls.
117     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
118     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
119     setLibcallName(RTLIB::SREM_I64, "_allrem");
120     setLibcallName(RTLIB::UREM_I64, "_aullrem");
121     setLibcallName(RTLIB::MUL_I64, "_allmul");
122     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
123     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
124     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
125     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
126     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
127
128     // The _ftol2 runtime function has an unusual calling conv, which
129     // is modeled by a special pseudo-instruction.
130     setLibcallName(RTLIB::FPTOUINT_F64_I64, nullptr);
131     setLibcallName(RTLIB::FPTOUINT_F32_I64, nullptr);
132     setLibcallName(RTLIB::FPTOUINT_F64_I32, nullptr);
133     setLibcallName(RTLIB::FPTOUINT_F32_I32, nullptr);
134   }
135
136   if (Subtarget->isTargetDarwin()) {
137     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
138     setUseUnderscoreSetJmp(false);
139     setUseUnderscoreLongJmp(false);
140   } else if (Subtarget->isTargetWindowsGNU()) {
141     // MS runtime is weird: it exports _setjmp, but longjmp!
142     setUseUnderscoreSetJmp(true);
143     setUseUnderscoreLongJmp(false);
144   } else {
145     setUseUnderscoreSetJmp(true);
146     setUseUnderscoreLongJmp(true);
147   }
148
149   // Set up the register classes.
150   addRegisterClass(MVT::i8, &X86::GR8RegClass);
151   addRegisterClass(MVT::i16, &X86::GR16RegClass);
152   addRegisterClass(MVT::i32, &X86::GR32RegClass);
153   if (Subtarget->is64Bit())
154     addRegisterClass(MVT::i64, &X86::GR64RegClass);
155
156   for (MVT VT : MVT::integer_valuetypes())
157     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
158
159   // We don't accept any truncstore of integer registers.
160   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
161   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
162   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
163   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
164   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
165   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
166
167   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
168
169   // SETOEQ and SETUNE require checking two conditions.
170   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
171   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
172   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
173   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
174   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
175   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
176
177   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
178   // operation.
179   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
180   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
181   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
182
183   if (Subtarget->is64Bit()) {
184     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
185     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
186   } else if (!TM.Options.UseSoftFloat) {
187     // We have an algorithm for SSE2->double, and we turn this into a
188     // 64-bit FILD followed by conditional FADD for other targets.
189     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
190     // We have an algorithm for SSE2, and we turn this into a 64-bit
191     // FILD for other targets.
192     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
193   }
194
195   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
196   // this operation.
197   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
198   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
199
200   if (!TM.Options.UseSoftFloat) {
201     // SSE has no i16 to fp conversion, only i32
202     if (X86ScalarSSEf32) {
203       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
204       // f32 and f64 cases are Legal, f80 case is not
205       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
206     } else {
207       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
208       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
209     }
210   } else {
211     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
212     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
213   }
214
215   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
216   // are Legal, f80 is custom lowered.
217   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
218   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
219
220   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
221   // this operation.
222   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
223   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
224
225   if (X86ScalarSSEf32) {
226     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
227     // f32 and f64 cases are Legal, f80 case is not
228     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
229   } else {
230     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
231     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
232   }
233
234   // Handle FP_TO_UINT by promoting the destination to a larger signed
235   // conversion.
236   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
237   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
238   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
239
240   if (Subtarget->is64Bit()) {
241     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
242     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
243   } else if (!TM.Options.UseSoftFloat) {
244     // Since AVX is a superset of SSE3, only check for SSE here.
245     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
246       // Expand FP_TO_UINT into a select.
247       // FIXME: We would like to use a Custom expander here eventually to do
248       // the optimal thing for SSE vs. the default expansion in the legalizer.
249       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
250     else
251       // With SSE3 we can use fisttpll to convert to a signed i64; without
252       // SSE, we're stuck with a fistpll.
253       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
254   }
255
256   if (isTargetFTOL()) {
257     // Use the _ftol2 runtime function, which has a pseudo-instruction
258     // to handle its weird calling convention.
259     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
260   }
261
262   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
263   if (!X86ScalarSSEf64) {
264     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
265     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
266     if (Subtarget->is64Bit()) {
267       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
268       // Without SSE, i64->f64 goes through memory.
269       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
270     }
271   }
272
273   // Scalar integer divide and remainder are lowered to use operations that
274   // produce two results, to match the available instructions. This exposes
275   // the two-result form to trivial CSE, which is able to combine x/y and x%y
276   // into a single instruction.
277   //
278   // Scalar integer multiply-high is also lowered to use two-result
279   // operations, to match the available instructions. However, plain multiply
280   // (low) operations are left as Legal, as there are single-result
281   // instructions for this in x86. Using the two-result multiply instructions
282   // when both high and low results are needed must be arranged by dagcombine.
283   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
284     MVT VT = IntVTs[i];
285     setOperationAction(ISD::MULHS, VT, Expand);
286     setOperationAction(ISD::MULHU, VT, Expand);
287     setOperationAction(ISD::SDIV, VT, Expand);
288     setOperationAction(ISD::UDIV, VT, Expand);
289     setOperationAction(ISD::SREM, VT, Expand);
290     setOperationAction(ISD::UREM, VT, Expand);
291
292     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
293     setOperationAction(ISD::ADDC, VT, Custom);
294     setOperationAction(ISD::ADDE, VT, Custom);
295     setOperationAction(ISD::SUBC, VT, Custom);
296     setOperationAction(ISD::SUBE, VT, Custom);
297   }
298
299   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
300   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
301   setOperationAction(ISD::BR_CC            , MVT::f32,   Expand);
302   setOperationAction(ISD::BR_CC            , MVT::f64,   Expand);
303   setOperationAction(ISD::BR_CC            , MVT::f80,   Expand);
304   setOperationAction(ISD::BR_CC            , MVT::i8,    Expand);
305   setOperationAction(ISD::BR_CC            , MVT::i16,   Expand);
306   setOperationAction(ISD::BR_CC            , MVT::i32,   Expand);
307   setOperationAction(ISD::BR_CC            , MVT::i64,   Expand);
308   setOperationAction(ISD::SELECT_CC        , MVT::f32,   Expand);
309   setOperationAction(ISD::SELECT_CC        , MVT::f64,   Expand);
310   setOperationAction(ISD::SELECT_CC        , MVT::f80,   Expand);
311   setOperationAction(ISD::SELECT_CC        , MVT::i8,    Expand);
312   setOperationAction(ISD::SELECT_CC        , MVT::i16,   Expand);
313   setOperationAction(ISD::SELECT_CC        , MVT::i32,   Expand);
314   setOperationAction(ISD::SELECT_CC        , MVT::i64,   Expand);
315   if (Subtarget->is64Bit())
316     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
317   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
318   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
319   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
320   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
321   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
322   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
323   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
324   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
325
326   // Promote the i8 variants and force them on up to i32 which has a shorter
327   // encoding.
328   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
329   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
330   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
331   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
332   if (Subtarget->hasBMI()) {
333     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
334     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
335     if (Subtarget->is64Bit())
336       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
337   } else {
338     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
339     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
340     if (Subtarget->is64Bit())
341       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
342   }
343
344   if (Subtarget->hasLZCNT()) {
345     // When promoting the i8 variants, force them to i32 for a shorter
346     // encoding.
347     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
348     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
349     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
350     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
351     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
352     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
353     if (Subtarget->is64Bit())
354       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
355   } else {
356     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
357     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
358     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
359     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
360     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
361     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
362     if (Subtarget->is64Bit()) {
363       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
364       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
365     }
366   }
367
368   // Special handling for half-precision floating point conversions.
369   // If we don't have F16C support, then lower half float conversions
370   // into library calls.
371   if (TM.Options.UseSoftFloat || !Subtarget->hasF16C()) {
372     setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
373     setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
374   }
375
376   // There's never any support for operations beyond MVT::f32.
377   setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
378   setOperationAction(ISD::FP16_TO_FP, MVT::f80, Expand);
379   setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
380   setOperationAction(ISD::FP_TO_FP16, MVT::f80, Expand);
381
382   setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
383   setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
384   setLoadExtAction(ISD::EXTLOAD, MVT::f80, MVT::f16, Expand);
385   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
386   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
387   setTruncStoreAction(MVT::f80, MVT::f16, Expand);
388
389   if (Subtarget->hasPOPCNT()) {
390     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
391   } else {
392     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
393     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
394     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
395     if (Subtarget->is64Bit())
396       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
397   }
398
399   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
400
401   if (!Subtarget->hasMOVBE())
402     setOperationAction(ISD::BSWAP          , MVT::i16  , Expand);
403
404   // These should be promoted to a larger select which is supported.
405   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
406   // X86 wants to expand cmov itself.
407   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
408   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
409   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
410   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
411   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
412   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
413   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
414   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
415   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
416   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
417   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
418   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
419   if (Subtarget->is64Bit()) {
420     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
421     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
422   }
423   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
424   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
425   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
426   // support continuation, user-level threading, and etc.. As a result, no
427   // other SjLj exception interfaces are implemented and please don't build
428   // your own exception handling based on them.
429   // LLVM/Clang supports zero-cost DWARF exception handling.
430   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
431   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
432
433   // Darwin ABI issue.
434   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
435   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
436   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
437   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
438   if (Subtarget->is64Bit())
439     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
440   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
441   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
442   if (Subtarget->is64Bit()) {
443     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
444     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
445     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
446     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
447     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
448   }
449   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
450   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
451   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
452   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
453   if (Subtarget->is64Bit()) {
454     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
455     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
456     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
457   }
458
459   if (Subtarget->hasSSE1())
460     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
461
462   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
463
464   // Expand certain atomics
465   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
466     MVT VT = IntVTs[i];
467     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
468     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
469     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
470   }
471
472   if (Subtarget->hasCmpxchg16b()) {
473     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
474   }
475
476   // FIXME - use subtarget debug flags
477   if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetELF() &&
478       !Subtarget->isTargetCygMing() && !Subtarget->isTargetWin64()) {
479     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
480   }
481
482   if (Subtarget->is64Bit()) {
483     setExceptionPointerRegister(X86::RAX);
484     setExceptionSelectorRegister(X86::RDX);
485   } else {
486     setExceptionPointerRegister(X86::EAX);
487     setExceptionSelectorRegister(X86::EDX);
488   }
489   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
490   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
491
492   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
493   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
494
495   setOperationAction(ISD::TRAP, MVT::Other, Legal);
496   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
497
498   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
499   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
500   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
501   if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
502     // TargetInfo::X86_64ABIBuiltinVaList
503     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
504     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
505   } else {
506     // TargetInfo::CharPtrBuiltinVaList
507     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
508     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
509   }
510
511   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
512   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
513
514   setOperationAction(ISD::DYNAMIC_STACKALLOC, getPointerTy(), Custom);
515
516   // GC_TRANSITION_START and GC_TRANSITION_END need custom lowering.
517   setOperationAction(ISD::GC_TRANSITION_START, MVT::Other, Custom);
518   setOperationAction(ISD::GC_TRANSITION_END, MVT::Other, Custom);
519
520   if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
521     // f32 and f64 use SSE.
522     // Set up the FP register classes.
523     addRegisterClass(MVT::f32, &X86::FR32RegClass);
524     addRegisterClass(MVT::f64, &X86::FR64RegClass);
525
526     // Use ANDPD to simulate FABS.
527     setOperationAction(ISD::FABS , MVT::f64, Custom);
528     setOperationAction(ISD::FABS , MVT::f32, Custom);
529
530     // Use XORP to simulate FNEG.
531     setOperationAction(ISD::FNEG , MVT::f64, Custom);
532     setOperationAction(ISD::FNEG , MVT::f32, Custom);
533
534     // Use ANDPD and ORPD to simulate FCOPYSIGN.
535     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
536     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
537
538     // Lower this to FGETSIGNx86 plus an AND.
539     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
540     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
541
542     // We don't support sin/cos/fmod
543     setOperationAction(ISD::FSIN   , MVT::f64, Expand);
544     setOperationAction(ISD::FCOS   , MVT::f64, Expand);
545     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
546     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
547     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
548     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
549
550     // Expand FP immediates into loads from the stack, except for the special
551     // cases we handle.
552     addLegalFPImmediate(APFloat(+0.0)); // xorpd
553     addLegalFPImmediate(APFloat(+0.0f)); // xorps
554   } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
555     // Use SSE for f32, x87 for f64.
556     // Set up the FP register classes.
557     addRegisterClass(MVT::f32, &X86::FR32RegClass);
558     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
559
560     // Use ANDPS to simulate FABS.
561     setOperationAction(ISD::FABS , MVT::f32, Custom);
562
563     // Use XORP to simulate FNEG.
564     setOperationAction(ISD::FNEG , MVT::f32, Custom);
565
566     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
567
568     // Use ANDPS and ORPS to simulate FCOPYSIGN.
569     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
570     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
571
572     // We don't support sin/cos/fmod
573     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
574     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
575     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
576
577     // Special cases we handle for FP constants.
578     addLegalFPImmediate(APFloat(+0.0f)); // xorps
579     addLegalFPImmediate(APFloat(+0.0)); // FLD0
580     addLegalFPImmediate(APFloat(+1.0)); // FLD1
581     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
582     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
583
584     if (!TM.Options.UnsafeFPMath) {
585       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
586       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
587       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
588     }
589   } else if (!TM.Options.UseSoftFloat) {
590     // f32 and f64 in x87.
591     // Set up the FP register classes.
592     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
593     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
594
595     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
596     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
597     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
598     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
599
600     if (!TM.Options.UnsafeFPMath) {
601       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
602       setOperationAction(ISD::FSIN   , MVT::f32, Expand);
603       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
604       setOperationAction(ISD::FCOS   , MVT::f32, Expand);
605       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
606       setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
607     }
608     addLegalFPImmediate(APFloat(+0.0)); // FLD0
609     addLegalFPImmediate(APFloat(+1.0)); // FLD1
610     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
611     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
612     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
613     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
614     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
615     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
616   }
617
618   // We don't support FMA.
619   setOperationAction(ISD::FMA, MVT::f64, Expand);
620   setOperationAction(ISD::FMA, MVT::f32, Expand);
621
622   // Long double always uses X87.
623   if (!TM.Options.UseSoftFloat) {
624     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
625     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
626     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
627     {
628       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
629       addLegalFPImmediate(TmpFlt);  // FLD0
630       TmpFlt.changeSign();
631       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
632
633       bool ignored;
634       APFloat TmpFlt2(+1.0);
635       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
636                       &ignored);
637       addLegalFPImmediate(TmpFlt2);  // FLD1
638       TmpFlt2.changeSign();
639       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
640     }
641
642     if (!TM.Options.UnsafeFPMath) {
643       setOperationAction(ISD::FSIN   , MVT::f80, Expand);
644       setOperationAction(ISD::FCOS   , MVT::f80, Expand);
645       setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
646     }
647
648     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
649     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
650     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
651     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
652     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
653     setOperationAction(ISD::FMA, MVT::f80, Expand);
654   }
655
656   // Always use a library call for pow.
657   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
658   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
659   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
660
661   setOperationAction(ISD::FLOG, MVT::f80, Expand);
662   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
663   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
664   setOperationAction(ISD::FEXP, MVT::f80, Expand);
665   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
666   setOperationAction(ISD::FMINNUM, MVT::f80, Expand);
667   setOperationAction(ISD::FMAXNUM, MVT::f80, Expand);
668
669   // First set operation action for all vector types to either promote
670   // (for widening) or expand (for scalarization). Then we will selectively
671   // turn on ones that can be effectively codegen'd.
672   for (MVT VT : MVT::vector_valuetypes()) {
673     setOperationAction(ISD::ADD , VT, Expand);
674     setOperationAction(ISD::SUB , VT, Expand);
675     setOperationAction(ISD::FADD, VT, Expand);
676     setOperationAction(ISD::FNEG, VT, Expand);
677     setOperationAction(ISD::FSUB, VT, Expand);
678     setOperationAction(ISD::MUL , VT, Expand);
679     setOperationAction(ISD::FMUL, VT, Expand);
680     setOperationAction(ISD::SDIV, VT, Expand);
681     setOperationAction(ISD::UDIV, VT, Expand);
682     setOperationAction(ISD::FDIV, VT, Expand);
683     setOperationAction(ISD::SREM, VT, Expand);
684     setOperationAction(ISD::UREM, VT, Expand);
685     setOperationAction(ISD::LOAD, VT, Expand);
686     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
687     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
688     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
689     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
690     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
691     setOperationAction(ISD::FABS, VT, Expand);
692     setOperationAction(ISD::FSIN, VT, Expand);
693     setOperationAction(ISD::FSINCOS, VT, Expand);
694     setOperationAction(ISD::FCOS, VT, Expand);
695     setOperationAction(ISD::FSINCOS, VT, Expand);
696     setOperationAction(ISD::FREM, VT, Expand);
697     setOperationAction(ISD::FMA,  VT, Expand);
698     setOperationAction(ISD::FPOWI, VT, Expand);
699     setOperationAction(ISD::FSQRT, VT, Expand);
700     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
701     setOperationAction(ISD::FFLOOR, VT, Expand);
702     setOperationAction(ISD::FCEIL, VT, Expand);
703     setOperationAction(ISD::FTRUNC, VT, Expand);
704     setOperationAction(ISD::FRINT, VT, Expand);
705     setOperationAction(ISD::FNEARBYINT, VT, Expand);
706     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
707     setOperationAction(ISD::MULHS, VT, Expand);
708     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
709     setOperationAction(ISD::MULHU, VT, Expand);
710     setOperationAction(ISD::SDIVREM, VT, Expand);
711     setOperationAction(ISD::UDIVREM, VT, Expand);
712     setOperationAction(ISD::FPOW, VT, Expand);
713     setOperationAction(ISD::CTPOP, VT, Expand);
714     setOperationAction(ISD::CTTZ, VT, Expand);
715     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
716     setOperationAction(ISD::CTLZ, VT, Expand);
717     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
718     setOperationAction(ISD::SHL, VT, Expand);
719     setOperationAction(ISD::SRA, VT, Expand);
720     setOperationAction(ISD::SRL, VT, Expand);
721     setOperationAction(ISD::ROTL, VT, Expand);
722     setOperationAction(ISD::ROTR, VT, Expand);
723     setOperationAction(ISD::BSWAP, VT, Expand);
724     setOperationAction(ISD::SETCC, VT, Expand);
725     setOperationAction(ISD::FLOG, VT, Expand);
726     setOperationAction(ISD::FLOG2, VT, Expand);
727     setOperationAction(ISD::FLOG10, VT, Expand);
728     setOperationAction(ISD::FEXP, VT, Expand);
729     setOperationAction(ISD::FEXP2, VT, Expand);
730     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
731     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
732     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
733     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
734     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
735     setOperationAction(ISD::TRUNCATE, VT, Expand);
736     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
737     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
738     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
739     setOperationAction(ISD::VSELECT, VT, Expand);
740     setOperationAction(ISD::SELECT_CC, VT, Expand);
741     for (MVT InnerVT : MVT::vector_valuetypes()) {
742       setTruncStoreAction(InnerVT, VT, Expand);
743
744       setLoadExtAction(ISD::SEXTLOAD, InnerVT, VT, Expand);
745       setLoadExtAction(ISD::ZEXTLOAD, InnerVT, VT, Expand);
746
747       // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like
748       // types, we have to deal with them whether we ask for Expansion or not.
749       // Setting Expand causes its own optimisation problems though, so leave
750       // them legal.
751       if (VT.getVectorElementType() == MVT::i1)
752         setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
753     }
754   }
755
756   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
757   // with -msoft-float, disable use of MMX as well.
758   if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
759     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
760     // No operations on x86mmx supported, everything uses intrinsics.
761   }
762
763   // MMX-sized vectors (other than x86mmx) are expected to be expanded
764   // into smaller operations.
765   for (MVT MMXTy : {MVT::v8i8, MVT::v4i16, MVT::v2i32, MVT::v1i64}) {
766     setOperationAction(ISD::MULHS,              MMXTy,      Expand);
767     setOperationAction(ISD::AND,                MMXTy,      Expand);
768     setOperationAction(ISD::OR,                 MMXTy,      Expand);
769     setOperationAction(ISD::XOR,                MMXTy,      Expand);
770     setOperationAction(ISD::SCALAR_TO_VECTOR,   MMXTy,      Expand);
771     setOperationAction(ISD::SELECT,             MMXTy,      Expand);
772     setOperationAction(ISD::BITCAST,            MMXTy,      Expand);
773   }
774   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
775
776   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
777     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
778
779     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
780     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
781     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
782     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
783     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
784     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
785     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
786     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
787     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
788     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
789     setOperationAction(ISD::VSELECT,            MVT::v4f32, Custom);
790     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
791     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
792     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Custom);
793   }
794
795   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
796     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
797
798     // FIXME: Unfortunately, -soft-float and -no-implicit-float mean XMM
799     // registers cannot be used even for integer operations.
800     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
801     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
802     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
803     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
804
805     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
806     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
807     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
808     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
809     setOperationAction(ISD::MUL,                MVT::v16i8, Custom);
810     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
811     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
812     setOperationAction(ISD::UMUL_LOHI,          MVT::v4i32, Custom);
813     setOperationAction(ISD::SMUL_LOHI,          MVT::v4i32, Custom);
814     setOperationAction(ISD::MULHU,              MVT::v8i16, Legal);
815     setOperationAction(ISD::MULHS,              MVT::v8i16, Legal);
816     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
817     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
818     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
819     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
820     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
821     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
822     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
823     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
824     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
825     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
826     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
827     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
828
829     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
830     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
831     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
832     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
833
834     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
835     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
836     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
837     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
838     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
839
840     // Only provide customized ctpop vector bit twiddling for vector types we
841     // know to perform better than using the popcnt instructions on each vector
842     // element. If popcnt isn't supported, always provide the custom version.
843     if (!Subtarget->hasPOPCNT()) {
844       setOperationAction(ISD::CTPOP,            MVT::v4i32, Custom);
845       setOperationAction(ISD::CTPOP,            MVT::v2i64, Custom);
846     }
847
848     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
849     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
850       MVT VT = (MVT::SimpleValueType)i;
851       // Do not attempt to custom lower non-power-of-2 vectors
852       if (!isPowerOf2_32(VT.getVectorNumElements()))
853         continue;
854       // Do not attempt to custom lower non-128-bit vectors
855       if (!VT.is128BitVector())
856         continue;
857       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
858       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
859       setOperationAction(ISD::VSELECT,            VT, Custom);
860       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
861     }
862
863     // We support custom legalizing of sext and anyext loads for specific
864     // memory vector types which we can load as a scalar (or sequence of
865     // scalars) and extend in-register to a legal 128-bit vector type. For sext
866     // loads these must work with a single scalar load.
867     for (MVT VT : MVT::integer_vector_valuetypes()) {
868       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i8, Custom);
869       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i16, Custom);
870       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v8i8, Custom);
871       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i8, Custom);
872       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i16, Custom);
873       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i32, Custom);
874       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i8, Custom);
875       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i16, Custom);
876       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8i8, Custom);
877     }
878
879     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
880     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
881     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
882     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
883     setOperationAction(ISD::VSELECT,            MVT::v2f64, Custom);
884     setOperationAction(ISD::VSELECT,            MVT::v2i64, Custom);
885     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
886     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
887
888     if (Subtarget->is64Bit()) {
889       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
890       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
891     }
892
893     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
894     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
895       MVT VT = (MVT::SimpleValueType)i;
896
897       // Do not attempt to promote non-128-bit vectors
898       if (!VT.is128BitVector())
899         continue;
900
901       setOperationAction(ISD::AND,    VT, Promote);
902       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
903       setOperationAction(ISD::OR,     VT, Promote);
904       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
905       setOperationAction(ISD::XOR,    VT, Promote);
906       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
907       setOperationAction(ISD::LOAD,   VT, Promote);
908       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
909       setOperationAction(ISD::SELECT, VT, Promote);
910       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
911     }
912
913     // Custom lower v2i64 and v2f64 selects.
914     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
915     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
916     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
917     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
918
919     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
920     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
921
922     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
923     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
924     // As there is no 64-bit GPR available, we need build a special custom
925     // sequence to convert from v2i32 to v2f32.
926     if (!Subtarget->is64Bit())
927       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
928
929     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
930     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
931
932     for (MVT VT : MVT::fp_vector_valuetypes())
933       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2f32, Legal);
934
935     setOperationAction(ISD::BITCAST,            MVT::v2i32, Custom);
936     setOperationAction(ISD::BITCAST,            MVT::v4i16, Custom);
937     setOperationAction(ISD::BITCAST,            MVT::v8i8,  Custom);
938   }
939
940   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE41()) {
941     for (MVT RoundedTy : {MVT::f32, MVT::f64, MVT::v4f32, MVT::v2f64}) {
942       setOperationAction(ISD::FFLOOR,           RoundedTy,  Legal);
943       setOperationAction(ISD::FCEIL,            RoundedTy,  Legal);
944       setOperationAction(ISD::FTRUNC,           RoundedTy,  Legal);
945       setOperationAction(ISD::FRINT,            RoundedTy,  Legal);
946       setOperationAction(ISD::FNEARBYINT,       RoundedTy,  Legal);
947     }
948
949     // FIXME: Do we need to handle scalar-to-vector here?
950     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
951
952     // We directly match byte blends in the backend as they match the VSELECT
953     // condition form.
954     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
955
956     // SSE41 brings specific instructions for doing vector sign extend even in
957     // cases where we don't have SRA.
958     for (MVT VT : MVT::integer_vector_valuetypes()) {
959       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i8, Custom);
960       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i16, Custom);
961       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i32, Custom);
962     }
963
964     // SSE41 also has vector sign/zero extending loads, PMOV[SZ]X
965     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i16, MVT::v8i8,  Legal);
966     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i8,  Legal);
967     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i8,  Legal);
968     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
969     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
970     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
971
972     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i16, MVT::v8i8,  Legal);
973     setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i8,  Legal);
974     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i8,  Legal);
975     setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
976     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
977     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
978
979     // i8 and i16 vectors are custom because the source register and source
980     // source memory operand types are not the same width.  f32 vectors are
981     // custom since the immediate controlling the insert encodes additional
982     // information.
983     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
984     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
985     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
986     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
987
988     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
989     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
990     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
991     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
992
993     // FIXME: these should be Legal, but that's only for the case where
994     // the index is constant.  For now custom expand to deal with that.
995     if (Subtarget->is64Bit()) {
996       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
997       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
998     }
999   }
1000
1001   if (Subtarget->hasSSE2()) {
1002     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1003     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1004
1005     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1006     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1007
1008     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1009     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1010
1011     // In the customized shift lowering, the legal cases in AVX2 will be
1012     // recognized.
1013     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1014     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1015
1016     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1017     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1018
1019     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1020   }
1021
1022   if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1023     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1024     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1025     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1026     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1027     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1028     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1029
1030     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1031     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1032     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1033
1034     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1035     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1036     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1037     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1038     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1039     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1040     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1041     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1042     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1043     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1044     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1045     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1046
1047     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1048     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1049     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1050     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1051     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1052     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1053     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1054     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1055     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1056     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1057     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1058     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1059
1060     // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1061     // even though v8i16 is a legal type.
1062     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Promote);
1063     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i16, Promote);
1064     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1065
1066     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1067     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1068     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1069
1070     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1071     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1072
1073     for (MVT VT : MVT::fp_vector_valuetypes())
1074       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4f32, Legal);
1075
1076     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1077     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1078
1079     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1080     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1081
1082     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1083     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1084
1085     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1086     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1087     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1088     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1089
1090     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1091     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1092     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1093
1094     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1095     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1096     setOperationAction(ISD::SIGN_EXTEND,       MVT::v16i16, Custom);
1097     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1098     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1099     setOperationAction(ISD::ZERO_EXTEND,       MVT::v16i16, Custom);
1100     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1101     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1102     setOperationAction(ISD::ANY_EXTEND,        MVT::v16i16, Custom);
1103     setOperationAction(ISD::TRUNCATE,          MVT::v16i8, Custom);
1104     setOperationAction(ISD::TRUNCATE,          MVT::v8i16, Custom);
1105     setOperationAction(ISD::TRUNCATE,          MVT::v4i32, Custom);
1106
1107     if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1108       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1109       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1110       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1111       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1112       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1113       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1114     }
1115
1116     if (Subtarget->hasInt256()) {
1117       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1118       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1119       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1120       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1121
1122       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1123       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1124       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1125       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1126
1127       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1128       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1129       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1130       setOperationAction(ISD::MUL,             MVT::v32i8, Custom);
1131
1132       setOperationAction(ISD::UMUL_LOHI,       MVT::v8i32, Custom);
1133       setOperationAction(ISD::SMUL_LOHI,       MVT::v8i32, Custom);
1134       setOperationAction(ISD::MULHU,           MVT::v16i16, Legal);
1135       setOperationAction(ISD::MULHS,           MVT::v16i16, Legal);
1136
1137       // The custom lowering for UINT_TO_FP for v8i32 becomes interesting
1138       // when we have a 256bit-wide blend with immediate.
1139       setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Custom);
1140
1141       // Only provide customized ctpop vector bit twiddling for vector types we
1142       // know to perform better than using the popcnt instructions on each
1143       // vector element. If popcnt isn't supported, always provide the custom
1144       // version.
1145       if (!Subtarget->hasPOPCNT())
1146         setOperationAction(ISD::CTPOP,           MVT::v4i64, Custom);
1147
1148       // Custom CTPOP always performs better on natively supported v8i32
1149       setOperationAction(ISD::CTPOP,             MVT::v8i32, Custom);
1150
1151       // AVX2 also has wider vector sign/zero extending loads, VPMOV[SZ]X
1152       setLoadExtAction(ISD::SEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1153       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32,  MVT::v8i8,  Legal);
1154       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i8,  Legal);
1155       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32,  MVT::v8i16, Legal);
1156       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i16, Legal);
1157       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i32, Legal);
1158
1159       setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1160       setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32,  MVT::v8i8,  Legal);
1161       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i8,  Legal);
1162       setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32,  MVT::v8i16, Legal);
1163       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i16, Legal);
1164       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i32, Legal);
1165     } else {
1166       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1167       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1168       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1169       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1170
1171       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1172       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1173       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1174       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1175
1176       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1177       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1178       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1179       setOperationAction(ISD::MUL,             MVT::v32i8, Custom);
1180     }
1181
1182     // In the customized shift lowering, the legal cases in AVX2 will be
1183     // recognized.
1184     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1185     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1186
1187     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1188     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1189
1190     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1191
1192     // Custom lower several nodes for 256-bit types.
1193     for (MVT VT : MVT::vector_valuetypes()) {
1194       if (VT.getScalarSizeInBits() >= 32) {
1195         setOperationAction(ISD::MLOAD,  VT, Legal);
1196         setOperationAction(ISD::MSTORE, VT, Legal);
1197       }
1198       // Extract subvector is special because the value type
1199       // (result) is 128-bit but the source is 256-bit wide.
1200       if (VT.is128BitVector()) {
1201         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1202       }
1203       // Do not attempt to custom lower other non-256-bit vectors
1204       if (!VT.is256BitVector())
1205         continue;
1206
1207       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1208       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1209       setOperationAction(ISD::VSELECT,            VT, Custom);
1210       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1211       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1212       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1213       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1214       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1215     }
1216
1217     if (Subtarget->hasInt256())
1218       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1219
1220
1221     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1222     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1223       MVT VT = (MVT::SimpleValueType)i;
1224
1225       // Do not attempt to promote non-256-bit vectors
1226       if (!VT.is256BitVector())
1227         continue;
1228
1229       setOperationAction(ISD::AND,    VT, Promote);
1230       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1231       setOperationAction(ISD::OR,     VT, Promote);
1232       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1233       setOperationAction(ISD::XOR,    VT, Promote);
1234       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1235       setOperationAction(ISD::LOAD,   VT, Promote);
1236       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1237       setOperationAction(ISD::SELECT, VT, Promote);
1238       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1239     }
1240   }
1241
1242   if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512()) {
1243     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1244     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1245     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1246     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1247
1248     addRegisterClass(MVT::i1,     &X86::VK1RegClass);
1249     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1250     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1251
1252     for (MVT VT : MVT::fp_vector_valuetypes())
1253       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8f32, Legal);
1254
1255     setOperationAction(ISD::BR_CC,              MVT::i1,    Expand);
1256     setOperationAction(ISD::SETCC,              MVT::i1,    Custom);
1257     setOperationAction(ISD::XOR,                MVT::i1,    Legal);
1258     setOperationAction(ISD::OR,                 MVT::i1,    Legal);
1259     setOperationAction(ISD::AND,                MVT::i1,    Legal);
1260     setOperationAction(ISD::LOAD,               MVT::v16f32, Legal);
1261     setOperationAction(ISD::LOAD,               MVT::v8f64, Legal);
1262     setOperationAction(ISD::LOAD,               MVT::v8i64, Legal);
1263     setOperationAction(ISD::LOAD,               MVT::v16i32, Legal);
1264     setOperationAction(ISD::LOAD,               MVT::v16i1, Legal);
1265
1266     setOperationAction(ISD::FADD,               MVT::v16f32, Legal);
1267     setOperationAction(ISD::FSUB,               MVT::v16f32, Legal);
1268     setOperationAction(ISD::FMUL,               MVT::v16f32, Legal);
1269     setOperationAction(ISD::FDIV,               MVT::v16f32, Legal);
1270     setOperationAction(ISD::FSQRT,              MVT::v16f32, Legal);
1271     setOperationAction(ISD::FNEG,               MVT::v16f32, Custom);
1272
1273     setOperationAction(ISD::FADD,               MVT::v8f64, Legal);
1274     setOperationAction(ISD::FSUB,               MVT::v8f64, Legal);
1275     setOperationAction(ISD::FMUL,               MVT::v8f64, Legal);
1276     setOperationAction(ISD::FDIV,               MVT::v8f64, Legal);
1277     setOperationAction(ISD::FSQRT,              MVT::v8f64, Legal);
1278     setOperationAction(ISD::FNEG,               MVT::v8f64, Custom);
1279     setOperationAction(ISD::FMA,                MVT::v8f64, Legal);
1280     setOperationAction(ISD::FMA,                MVT::v16f32, Legal);
1281
1282     setOperationAction(ISD::FP_TO_SINT,         MVT::i32, Legal);
1283     setOperationAction(ISD::FP_TO_UINT,         MVT::i32, Legal);
1284     setOperationAction(ISD::SINT_TO_FP,         MVT::i32, Legal);
1285     setOperationAction(ISD::UINT_TO_FP,         MVT::i32, Legal);
1286     if (Subtarget->is64Bit()) {
1287       setOperationAction(ISD::FP_TO_UINT,       MVT::i64, Legal);
1288       setOperationAction(ISD::FP_TO_SINT,       MVT::i64, Legal);
1289       setOperationAction(ISD::SINT_TO_FP,       MVT::i64, Legal);
1290       setOperationAction(ISD::UINT_TO_FP,       MVT::i64, Legal);
1291     }
1292     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1293     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1294     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1295     setOperationAction(ISD::FP_TO_UINT,         MVT::v4i32, Legal);
1296     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1297     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i1,   Custom);
1298     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i1,  Custom);
1299     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i8,  Promote);
1300     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i16, Promote);
1301     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1302     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1303     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Legal);
1304     setOperationAction(ISD::FP_ROUND,           MVT::v8f32, Legal);
1305     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Legal);
1306
1307     setOperationAction(ISD::TRUNCATE,           MVT::i1, Custom);
1308     setOperationAction(ISD::TRUNCATE,           MVT::v16i8, Custom);
1309     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1310     if (Subtarget->hasDQI()) {
1311       setOperationAction(ISD::TRUNCATE,           MVT::v2i1, Custom);
1312       setOperationAction(ISD::TRUNCATE,           MVT::v4i1, Custom);
1313     }
1314     setOperationAction(ISD::TRUNCATE,           MVT::v8i1, Custom);
1315     setOperationAction(ISD::TRUNCATE,           MVT::v16i1, Custom);
1316     setOperationAction(ISD::TRUNCATE,           MVT::v16i16, Custom);
1317     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1318     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1319     setOperationAction(ISD::ANY_EXTEND,         MVT::v16i32, Custom);
1320     setOperationAction(ISD::ANY_EXTEND,         MVT::v8i64, Custom);
1321     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1322     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1323     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i8, Custom);
1324     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i16, Custom);
1325     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i16, Custom);
1326     if (Subtarget->hasDQI()) {
1327       setOperationAction(ISD::SIGN_EXTEND,        MVT::v4i32, Custom);
1328       setOperationAction(ISD::SIGN_EXTEND,        MVT::v2i64, Custom);
1329     }
1330     setOperationAction(ISD::FFLOOR,             MVT::v16f32, Legal);
1331     setOperationAction(ISD::FFLOOR,             MVT::v8f64, Legal);
1332     setOperationAction(ISD::FCEIL,              MVT::v16f32, Legal);
1333     setOperationAction(ISD::FCEIL,              MVT::v8f64, Legal);
1334     setOperationAction(ISD::FTRUNC,             MVT::v16f32, Legal);
1335     setOperationAction(ISD::FTRUNC,             MVT::v8f64, Legal);
1336     setOperationAction(ISD::FRINT,              MVT::v16f32, Legal);
1337     setOperationAction(ISD::FRINT,              MVT::v8f64, Legal);
1338     setOperationAction(ISD::FNEARBYINT,         MVT::v16f32, Legal);
1339     setOperationAction(ISD::FNEARBYINT,         MVT::v8f64, Legal);
1340
1341     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1342     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1343     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1344     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1345     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i1, Legal);
1346
1347     setOperationAction(ISD::SETCC,              MVT::v16i1, Custom);
1348     setOperationAction(ISD::SETCC,              MVT::v8i1, Custom);
1349
1350     setOperationAction(ISD::MUL,              MVT::v8i64, Custom);
1351
1352     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1,  Custom);
1353     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1354     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i1, Custom);
1355     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i1, Custom);
1356     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i1, Custom);
1357     setOperationAction(ISD::BUILD_VECTOR,       MVT::v16i1, Custom);
1358     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1359     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1360     setOperationAction(ISD::SELECT,             MVT::v16f32, Custom);
1361
1362     setOperationAction(ISD::ADD,                MVT::v8i64, Legal);
1363     setOperationAction(ISD::ADD,                MVT::v16i32, Legal);
1364
1365     setOperationAction(ISD::SUB,                MVT::v8i64, Legal);
1366     setOperationAction(ISD::SUB,                MVT::v16i32, Legal);
1367
1368     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1369
1370     setOperationAction(ISD::SRL,                MVT::v8i64, Custom);
1371     setOperationAction(ISD::SRL,                MVT::v16i32, Custom);
1372
1373     setOperationAction(ISD::SHL,                MVT::v8i64, Custom);
1374     setOperationAction(ISD::SHL,                MVT::v16i32, Custom);
1375
1376     setOperationAction(ISD::SRA,                MVT::v8i64, Custom);
1377     setOperationAction(ISD::SRA,                MVT::v16i32, Custom);
1378
1379     setOperationAction(ISD::AND,                MVT::v8i64, Legal);
1380     setOperationAction(ISD::OR,                 MVT::v8i64, Legal);
1381     setOperationAction(ISD::XOR,                MVT::v8i64, Legal);
1382     setOperationAction(ISD::AND,                MVT::v16i32, Legal);
1383     setOperationAction(ISD::OR,                 MVT::v16i32, Legal);
1384     setOperationAction(ISD::XOR,                MVT::v16i32, Legal);
1385
1386     if (Subtarget->hasCDI()) {
1387       setOperationAction(ISD::CTLZ,             MVT::v8i64, Legal);
1388       setOperationAction(ISD::CTLZ,             MVT::v16i32, Legal);
1389     }
1390     if (Subtarget->hasDQI()) {
1391       setOperationAction(ISD::MUL,             MVT::v2i64, Legal);
1392       setOperationAction(ISD::MUL,             MVT::v4i64, Legal);
1393       setOperationAction(ISD::MUL,             MVT::v8i64, Legal);
1394     }
1395     // Custom lower several nodes.
1396     for (MVT VT : MVT::vector_valuetypes()) {
1397       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1398       if (EltSize >= 32 && VT.getSizeInBits() <= 512) {
1399         setOperationAction(ISD::MGATHER,  VT, Custom);
1400         setOperationAction(ISD::MSCATTER, VT, Custom);
1401       }
1402       // Extract subvector is special because the value type
1403       // (result) is 256/128-bit but the source is 512-bit wide.
1404       if (VT.is128BitVector() || VT.is256BitVector()) {
1405         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1406       }
1407       if (VT.getVectorElementType() == MVT::i1)
1408         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1409
1410       // Do not attempt to custom lower other non-512-bit vectors
1411       if (!VT.is512BitVector())
1412         continue;
1413
1414       if (EltSize >= 32) {
1415         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1416         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1417         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1418         setOperationAction(ISD::VSELECT,             VT, Legal);
1419         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1420         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1421         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1422         setOperationAction(ISD::MLOAD,               VT, Legal);
1423         setOperationAction(ISD::MSTORE,              VT, Legal);
1424       }
1425     }
1426     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1427       MVT VT = (MVT::SimpleValueType)i;
1428
1429       // Do not attempt to promote non-512-bit vectors.
1430       if (!VT.is512BitVector())
1431         continue;
1432
1433       setOperationAction(ISD::SELECT, VT, Promote);
1434       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1435     }
1436   }// has  AVX-512
1437
1438   if (!TM.Options.UseSoftFloat && Subtarget->hasBWI()) {
1439     addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1440     addRegisterClass(MVT::v64i8,  &X86::VR512RegClass);
1441
1442     addRegisterClass(MVT::v32i1,  &X86::VK32RegClass);
1443     addRegisterClass(MVT::v64i1,  &X86::VK64RegClass);
1444
1445     setOperationAction(ISD::LOAD,               MVT::v32i16, Legal);
1446     setOperationAction(ISD::LOAD,               MVT::v64i8, Legal);
1447     setOperationAction(ISD::SETCC,              MVT::v32i1, Custom);
1448     setOperationAction(ISD::SETCC,              MVT::v64i1, Custom);
1449     setOperationAction(ISD::ADD,                MVT::v32i16, Legal);
1450     setOperationAction(ISD::ADD,                MVT::v64i8, Legal);
1451     setOperationAction(ISD::SUB,                MVT::v32i16, Legal);
1452     setOperationAction(ISD::SUB,                MVT::v64i8, Legal);
1453     setOperationAction(ISD::MUL,                MVT::v32i16, Legal);
1454     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v32i1, Custom);
1455     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v64i1, Custom);
1456     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v32i1, Custom);
1457     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v64i1, Custom);
1458
1459     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1460       const MVT VT = (MVT::SimpleValueType)i;
1461
1462       const unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1463
1464       // Do not attempt to promote non-512-bit vectors.
1465       if (!VT.is512BitVector())
1466         continue;
1467
1468       if (EltSize < 32) {
1469         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1470         setOperationAction(ISD::VSELECT,             VT, Legal);
1471       }
1472     }
1473   }
1474
1475   if (!TM.Options.UseSoftFloat && Subtarget->hasVLX()) {
1476     addRegisterClass(MVT::v4i1,   &X86::VK4RegClass);
1477     addRegisterClass(MVT::v2i1,   &X86::VK2RegClass);
1478
1479     setOperationAction(ISD::SETCC,              MVT::v4i1, Custom);
1480     setOperationAction(ISD::SETCC,              MVT::v2i1, Custom);
1481     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i1, Custom);
1482     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1, Custom);
1483     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v8i1, Custom);
1484     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v4i1, Custom);
1485
1486     setOperationAction(ISD::AND,                MVT::v8i32, Legal);
1487     setOperationAction(ISD::OR,                 MVT::v8i32, Legal);
1488     setOperationAction(ISD::XOR,                MVT::v8i32, Legal);
1489     setOperationAction(ISD::AND,                MVT::v4i32, Legal);
1490     setOperationAction(ISD::OR,                 MVT::v4i32, Legal);
1491     setOperationAction(ISD::XOR,                MVT::v4i32, Legal);
1492   }
1493
1494   // We want to custom lower some of our intrinsics.
1495   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1496   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1497   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1498   if (!Subtarget->is64Bit())
1499     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1500
1501   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1502   // handle type legalization for these operations here.
1503   //
1504   // FIXME: We really should do custom legalization for addition and
1505   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1506   // than generic legalization for 64-bit multiplication-with-overflow, though.
1507   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1508     // Add/Sub/Mul with overflow operations are custom lowered.
1509     MVT VT = IntVTs[i];
1510     setOperationAction(ISD::SADDO, VT, Custom);
1511     setOperationAction(ISD::UADDO, VT, Custom);
1512     setOperationAction(ISD::SSUBO, VT, Custom);
1513     setOperationAction(ISD::USUBO, VT, Custom);
1514     setOperationAction(ISD::SMULO, VT, Custom);
1515     setOperationAction(ISD::UMULO, VT, Custom);
1516   }
1517
1518
1519   if (!Subtarget->is64Bit()) {
1520     // These libcalls are not available in 32-bit.
1521     setLibcallName(RTLIB::SHL_I128, nullptr);
1522     setLibcallName(RTLIB::SRL_I128, nullptr);
1523     setLibcallName(RTLIB::SRA_I128, nullptr);
1524   }
1525
1526   // Combine sin / cos into one node or libcall if possible.
1527   if (Subtarget->hasSinCos()) {
1528     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1529     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1530     if (Subtarget->isTargetDarwin()) {
1531       // For MacOSX, we don't want the normal expansion of a libcall to sincos.
1532       // We want to issue a libcall to __sincos_stret to avoid memory traffic.
1533       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1534       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1535     }
1536   }
1537
1538   if (Subtarget->isTargetWin64()) {
1539     setOperationAction(ISD::SDIV, MVT::i128, Custom);
1540     setOperationAction(ISD::UDIV, MVT::i128, Custom);
1541     setOperationAction(ISD::SREM, MVT::i128, Custom);
1542     setOperationAction(ISD::UREM, MVT::i128, Custom);
1543     setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1544     setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1545   }
1546
1547   // We have target-specific dag combine patterns for the following nodes:
1548   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1549   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1550   setTargetDAGCombine(ISD::BITCAST);
1551   setTargetDAGCombine(ISD::VSELECT);
1552   setTargetDAGCombine(ISD::SELECT);
1553   setTargetDAGCombine(ISD::SHL);
1554   setTargetDAGCombine(ISD::SRA);
1555   setTargetDAGCombine(ISD::SRL);
1556   setTargetDAGCombine(ISD::OR);
1557   setTargetDAGCombine(ISD::AND);
1558   setTargetDAGCombine(ISD::ADD);
1559   setTargetDAGCombine(ISD::FADD);
1560   setTargetDAGCombine(ISD::FSUB);
1561   setTargetDAGCombine(ISD::FMA);
1562   setTargetDAGCombine(ISD::SUB);
1563   setTargetDAGCombine(ISD::LOAD);
1564   setTargetDAGCombine(ISD::MLOAD);
1565   setTargetDAGCombine(ISD::STORE);
1566   setTargetDAGCombine(ISD::MSTORE);
1567   setTargetDAGCombine(ISD::ZERO_EXTEND);
1568   setTargetDAGCombine(ISD::ANY_EXTEND);
1569   setTargetDAGCombine(ISD::SIGN_EXTEND);
1570   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1571   setTargetDAGCombine(ISD::TRUNCATE);
1572   setTargetDAGCombine(ISD::SINT_TO_FP);
1573   setTargetDAGCombine(ISD::SETCC);
1574   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1575   setTargetDAGCombine(ISD::BUILD_VECTOR);
1576   setTargetDAGCombine(ISD::MUL);
1577   setTargetDAGCombine(ISD::XOR);
1578
1579   computeRegisterProperties(Subtarget->getRegisterInfo());
1580
1581   // On Darwin, -Os means optimize for size without hurting performance,
1582   // do not reduce the limit.
1583   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1584   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1585   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1586   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1587   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1588   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1589   setPrefLoopAlignment(4); // 2^4 bytes.
1590
1591   // Predictable cmov don't hurt on atom because it's in-order.
1592   PredictableSelectIsExpensive = !Subtarget->isAtom();
1593   EnableExtLdPromotion = true;
1594   setPrefFunctionAlignment(4); // 2^4 bytes.
1595
1596   verifyIntrinsicTables();
1597 }
1598
1599 // This has so far only been implemented for 64-bit MachO.
1600 bool X86TargetLowering::useLoadStackGuardNode() const {
1601   return Subtarget->isTargetMachO() && Subtarget->is64Bit();
1602 }
1603
1604 TargetLoweringBase::LegalizeTypeAction
1605 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1606   if (ExperimentalVectorWideningLegalization &&
1607       VT.getVectorNumElements() != 1 &&
1608       VT.getVectorElementType().getSimpleVT() != MVT::i1)
1609     return TypeWidenVector;
1610
1611   return TargetLoweringBase::getPreferredVectorAction(VT);
1612 }
1613
1614 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1615   if (!VT.isVector())
1616     return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1617
1618   const unsigned NumElts = VT.getVectorNumElements();
1619   const EVT EltVT = VT.getVectorElementType();
1620   if (VT.is512BitVector()) {
1621     if (Subtarget->hasAVX512())
1622       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1623           EltVT == MVT::f32 || EltVT == MVT::f64)
1624         switch(NumElts) {
1625         case  8: return MVT::v8i1;
1626         case 16: return MVT::v16i1;
1627       }
1628     if (Subtarget->hasBWI())
1629       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1630         switch(NumElts) {
1631         case 32: return MVT::v32i1;
1632         case 64: return MVT::v64i1;
1633       }
1634   }
1635
1636   if (VT.is256BitVector() || VT.is128BitVector()) {
1637     if (Subtarget->hasVLX())
1638       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1639           EltVT == MVT::f32 || EltVT == MVT::f64)
1640         switch(NumElts) {
1641         case 2: return MVT::v2i1;
1642         case 4: return MVT::v4i1;
1643         case 8: return MVT::v8i1;
1644       }
1645     if (Subtarget->hasBWI() && Subtarget->hasVLX())
1646       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1647         switch(NumElts) {
1648         case  8: return MVT::v8i1;
1649         case 16: return MVT::v16i1;
1650         case 32: return MVT::v32i1;
1651       }
1652   }
1653
1654   return VT.changeVectorElementTypeToInteger();
1655 }
1656
1657 /// Helper for getByValTypeAlignment to determine
1658 /// the desired ByVal argument alignment.
1659 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1660   if (MaxAlign == 16)
1661     return;
1662   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1663     if (VTy->getBitWidth() == 128)
1664       MaxAlign = 16;
1665   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1666     unsigned EltAlign = 0;
1667     getMaxByValAlign(ATy->getElementType(), EltAlign);
1668     if (EltAlign > MaxAlign)
1669       MaxAlign = EltAlign;
1670   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1671     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1672       unsigned EltAlign = 0;
1673       getMaxByValAlign(STy->getElementType(i), EltAlign);
1674       if (EltAlign > MaxAlign)
1675         MaxAlign = EltAlign;
1676       if (MaxAlign == 16)
1677         break;
1678     }
1679   }
1680 }
1681
1682 /// Return the desired alignment for ByVal aggregate
1683 /// function arguments in the caller parameter area. For X86, aggregates
1684 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1685 /// are at 4-byte boundaries.
1686 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1687   if (Subtarget->is64Bit()) {
1688     // Max of 8 and alignment of type.
1689     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1690     if (TyAlign > 8)
1691       return TyAlign;
1692     return 8;
1693   }
1694
1695   unsigned Align = 4;
1696   if (Subtarget->hasSSE1())
1697     getMaxByValAlign(Ty, Align);
1698   return Align;
1699 }
1700
1701 /// Returns the target specific optimal type for load
1702 /// and store operations as a result of memset, memcpy, and memmove
1703 /// lowering. If DstAlign is zero that means it's safe to destination
1704 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1705 /// means there isn't a need to check it against alignment requirement,
1706 /// probably because the source does not need to be loaded. If 'IsMemset' is
1707 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1708 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1709 /// source is constant so it does not need to be loaded.
1710 /// It returns EVT::Other if the type should be determined using generic
1711 /// target-independent logic.
1712 EVT
1713 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1714                                        unsigned DstAlign, unsigned SrcAlign,
1715                                        bool IsMemset, bool ZeroMemset,
1716                                        bool MemcpyStrSrc,
1717                                        MachineFunction &MF) const {
1718   const Function *F = MF.getFunction();
1719   if ((!IsMemset || ZeroMemset) &&
1720       !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1721     if (Size >= 16 &&
1722         (Subtarget->isUnalignedMemAccessFast() ||
1723          ((DstAlign == 0 || DstAlign >= 16) &&
1724           (SrcAlign == 0 || SrcAlign >= 16)))) {
1725       if (Size >= 32) {
1726         if (Subtarget->hasInt256())
1727           return MVT::v8i32;
1728         if (Subtarget->hasFp256())
1729           return MVT::v8f32;
1730       }
1731       if (Subtarget->hasSSE2())
1732         return MVT::v4i32;
1733       if (Subtarget->hasSSE1())
1734         return MVT::v4f32;
1735     } else if (!MemcpyStrSrc && Size >= 8 &&
1736                !Subtarget->is64Bit() &&
1737                Subtarget->hasSSE2()) {
1738       // Do not use f64 to lower memcpy if source is string constant. It's
1739       // better to use i32 to avoid the loads.
1740       return MVT::f64;
1741     }
1742   }
1743   if (Subtarget->is64Bit() && Size >= 8)
1744     return MVT::i64;
1745   return MVT::i32;
1746 }
1747
1748 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1749   if (VT == MVT::f32)
1750     return X86ScalarSSEf32;
1751   else if (VT == MVT::f64)
1752     return X86ScalarSSEf64;
1753   return true;
1754 }
1755
1756 bool
1757 X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1758                                                   unsigned,
1759                                                   unsigned,
1760                                                   bool *Fast) const {
1761   if (Fast)
1762     *Fast = Subtarget->isUnalignedMemAccessFast();
1763   return true;
1764 }
1765
1766 /// Return the entry encoding for a jump table in the
1767 /// current function.  The returned value is a member of the
1768 /// MachineJumpTableInfo::JTEntryKind enum.
1769 unsigned X86TargetLowering::getJumpTableEncoding() const {
1770   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1771   // symbol.
1772   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1773       Subtarget->isPICStyleGOT())
1774     return MachineJumpTableInfo::EK_Custom32;
1775
1776   // Otherwise, use the normal jump table encoding heuristics.
1777   return TargetLowering::getJumpTableEncoding();
1778 }
1779
1780 const MCExpr *
1781 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1782                                              const MachineBasicBlock *MBB,
1783                                              unsigned uid,MCContext &Ctx) const{
1784   assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
1785          Subtarget->isPICStyleGOT());
1786   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1787   // entries.
1788   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1789                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1790 }
1791
1792 /// Returns relocation base for the given PIC jumptable.
1793 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1794                                                     SelectionDAG &DAG) const {
1795   if (!Subtarget->is64Bit())
1796     // This doesn't have SDLoc associated with it, but is not really the
1797     // same as a Register.
1798     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1799   return Table;
1800 }
1801
1802 /// This returns the relocation base for the given PIC jumptable,
1803 /// the same as getPICJumpTableRelocBase, but as an MCExpr.
1804 const MCExpr *X86TargetLowering::
1805 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1806                              MCContext &Ctx) const {
1807   // X86-64 uses RIP relative addressing based on the jump table label.
1808   if (Subtarget->isPICStyleRIPRel())
1809     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1810
1811   // Otherwise, the reference is relative to the PIC base.
1812   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1813 }
1814
1815 std::pair<const TargetRegisterClass *, uint8_t>
1816 X86TargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1817                                            MVT VT) const {
1818   const TargetRegisterClass *RRC = nullptr;
1819   uint8_t Cost = 1;
1820   switch (VT.SimpleTy) {
1821   default:
1822     return TargetLowering::findRepresentativeClass(TRI, VT);
1823   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1824     RRC = Subtarget->is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
1825     break;
1826   case MVT::x86mmx:
1827     RRC = &X86::VR64RegClass;
1828     break;
1829   case MVT::f32: case MVT::f64:
1830   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1831   case MVT::v4f32: case MVT::v2f64:
1832   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1833   case MVT::v4f64:
1834     RRC = &X86::VR128RegClass;
1835     break;
1836   }
1837   return std::make_pair(RRC, Cost);
1838 }
1839
1840 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1841                                                unsigned &Offset) const {
1842   if (!Subtarget->isTargetLinux())
1843     return false;
1844
1845   if (Subtarget->is64Bit()) {
1846     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1847     Offset = 0x28;
1848     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1849       AddressSpace = 256;
1850     else
1851       AddressSpace = 257;
1852   } else {
1853     // %gs:0x14 on i386
1854     Offset = 0x14;
1855     AddressSpace = 256;
1856   }
1857   return true;
1858 }
1859
1860 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1861                                             unsigned DestAS) const {
1862   assert(SrcAS != DestAS && "Expected different address spaces!");
1863
1864   return SrcAS < 256 && DestAS < 256;
1865 }
1866
1867 //===----------------------------------------------------------------------===//
1868 //               Return Value Calling Convention Implementation
1869 //===----------------------------------------------------------------------===//
1870
1871 #include "X86GenCallingConv.inc"
1872
1873 bool
1874 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1875                                   MachineFunction &MF, bool isVarArg,
1876                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1877                         LLVMContext &Context) const {
1878   SmallVector<CCValAssign, 16> RVLocs;
1879   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
1880   return CCInfo.CheckReturn(Outs, RetCC_X86);
1881 }
1882
1883 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1884   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1885   return ScratchRegs;
1886 }
1887
1888 SDValue
1889 X86TargetLowering::LowerReturn(SDValue Chain,
1890                                CallingConv::ID CallConv, bool isVarArg,
1891                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1892                                const SmallVectorImpl<SDValue> &OutVals,
1893                                SDLoc dl, SelectionDAG &DAG) const {
1894   MachineFunction &MF = DAG.getMachineFunction();
1895   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1896
1897   SmallVector<CCValAssign, 16> RVLocs;
1898   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
1899   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1900
1901   SDValue Flag;
1902   SmallVector<SDValue, 6> RetOps;
1903   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1904   // Operand #1 = Bytes To Pop
1905   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(), dl,
1906                    MVT::i16));
1907
1908   // Copy the result values into the output registers.
1909   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1910     CCValAssign &VA = RVLocs[i];
1911     assert(VA.isRegLoc() && "Can only return in registers!");
1912     SDValue ValToCopy = OutVals[i];
1913     EVT ValVT = ValToCopy.getValueType();
1914
1915     // Promote values to the appropriate types.
1916     if (VA.getLocInfo() == CCValAssign::SExt)
1917       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1918     else if (VA.getLocInfo() == CCValAssign::ZExt)
1919       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1920     else if (VA.getLocInfo() == CCValAssign::AExt) {
1921       if (ValVT.getScalarType() == MVT::i1)
1922         ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1923       else
1924         ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1925     }   
1926     else if (VA.getLocInfo() == CCValAssign::BCvt)
1927       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1928
1929     assert(VA.getLocInfo() != CCValAssign::FPExt &&
1930            "Unexpected FP-extend for return value.");
1931
1932     // If this is x86-64, and we disabled SSE, we can't return FP values,
1933     // or SSE or MMX vectors.
1934     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1935          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1936           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1937       report_fatal_error("SSE register return with SSE disabled");
1938     }
1939     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1940     // llvm-gcc has never done it right and no one has noticed, so this
1941     // should be OK for now.
1942     if (ValVT == MVT::f64 &&
1943         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1944       report_fatal_error("SSE2 register return with SSE2 disabled");
1945
1946     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1947     // the RET instruction and handled by the FP Stackifier.
1948     if (VA.getLocReg() == X86::FP0 ||
1949         VA.getLocReg() == X86::FP1) {
1950       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1951       // change the value to the FP stack register class.
1952       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1953         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1954       RetOps.push_back(ValToCopy);
1955       // Don't emit a copytoreg.
1956       continue;
1957     }
1958
1959     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1960     // which is returned in RAX / RDX.
1961     if (Subtarget->is64Bit()) {
1962       if (ValVT == MVT::x86mmx) {
1963         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1964           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1965           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1966                                   ValToCopy);
1967           // If we don't have SSE2 available, convert to v4f32 so the generated
1968           // register is legal.
1969           if (!Subtarget->hasSSE2())
1970             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1971         }
1972       }
1973     }
1974
1975     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1976     Flag = Chain.getValue(1);
1977     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1978   }
1979
1980   // The x86-64 ABIs require that for returning structs by value we copy
1981   // the sret argument into %rax/%eax (depending on ABI) for the return.
1982   // Win32 requires us to put the sret argument to %eax as well.
1983   // We saved the argument into a virtual register in the entry block,
1984   // so now we copy the value out and into %rax/%eax.
1985   //
1986   // Checking Function.hasStructRetAttr() here is insufficient because the IR
1987   // may not have an explicit sret argument. If FuncInfo.CanLowerReturn is
1988   // false, then an sret argument may be implicitly inserted in the SelDAG. In
1989   // either case FuncInfo->setSRetReturnReg() will have been called.
1990   if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
1991     assert((Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC()) &&
1992            "No need for an sret register");
1993     SDValue Val = DAG.getCopyFromReg(Chain, dl, SRetReg, getPointerTy());
1994
1995     unsigned RetValReg
1996         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
1997           X86::RAX : X86::EAX;
1998     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
1999     Flag = Chain.getValue(1);
2000
2001     // RAX/EAX now acts like a return value.
2002     RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
2003   }
2004
2005   RetOps[0] = Chain;  // Update chain.
2006
2007   // Add the flag if we have it.
2008   if (Flag.getNode())
2009     RetOps.push_back(Flag);
2010
2011   return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
2012 }
2013
2014 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2015   if (N->getNumValues() != 1)
2016     return false;
2017   if (!N->hasNUsesOfValue(1, 0))
2018     return false;
2019
2020   SDValue TCChain = Chain;
2021   SDNode *Copy = *N->use_begin();
2022   if (Copy->getOpcode() == ISD::CopyToReg) {
2023     // If the copy has a glue operand, we conservatively assume it isn't safe to
2024     // perform a tail call.
2025     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2026       return false;
2027     TCChain = Copy->getOperand(0);
2028   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2029     return false;
2030
2031   bool HasRet = false;
2032   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2033        UI != UE; ++UI) {
2034     if (UI->getOpcode() != X86ISD::RET_FLAG)
2035       return false;
2036     // If we are returning more than one value, we can definitely
2037     // not make a tail call see PR19530
2038     if (UI->getNumOperands() > 4)
2039       return false;
2040     if (UI->getNumOperands() == 4 &&
2041         UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2042       return false;
2043     HasRet = true;
2044   }
2045
2046   if (!HasRet)
2047     return false;
2048
2049   Chain = TCChain;
2050   return true;
2051 }
2052
2053 EVT
2054 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
2055                                             ISD::NodeType ExtendKind) const {
2056   MVT ReturnMVT;
2057   // TODO: Is this also valid on 32-bit?
2058   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2059     ReturnMVT = MVT::i8;
2060   else
2061     ReturnMVT = MVT::i32;
2062
2063   EVT MinVT = getRegisterType(Context, ReturnMVT);
2064   return VT.bitsLT(MinVT) ? MinVT : VT;
2065 }
2066
2067 /// Lower the result values of a call into the
2068 /// appropriate copies out of appropriate physical registers.
2069 ///
2070 SDValue
2071 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2072                                    CallingConv::ID CallConv, bool isVarArg,
2073                                    const SmallVectorImpl<ISD::InputArg> &Ins,
2074                                    SDLoc dl, SelectionDAG &DAG,
2075                                    SmallVectorImpl<SDValue> &InVals) const {
2076
2077   // Assign locations to each value returned by this call.
2078   SmallVector<CCValAssign, 16> RVLocs;
2079   bool Is64Bit = Subtarget->is64Bit();
2080   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2081                  *DAG.getContext());
2082   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2083
2084   // Copy all of the result registers out of their specified physreg.
2085   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2086     CCValAssign &VA = RVLocs[i];
2087     EVT CopyVT = VA.getLocVT();
2088
2089     // If this is x86-64, and we disabled SSE, we can't return FP values
2090     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2091         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2092       report_fatal_error("SSE register return with SSE disabled");
2093     }
2094
2095     // If we prefer to use the value in xmm registers, copy it out as f80 and
2096     // use a truncate to move it from fp stack reg to xmm reg.
2097     bool RoundAfterCopy = false;
2098     if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2099         isScalarFPTypeInSSEReg(VA.getValVT())) {
2100       CopyVT = MVT::f80;
2101       RoundAfterCopy = (CopyVT != VA.getLocVT());
2102     }
2103
2104     Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2105                                CopyVT, InFlag).getValue(1);
2106     SDValue Val = Chain.getValue(0);
2107
2108     if (RoundAfterCopy)
2109       Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2110                         // This truncation won't change the value.
2111                         DAG.getIntPtrConstant(1, dl));
2112
2113     InFlag = Chain.getValue(2);
2114     InVals.push_back(Val);
2115   }
2116
2117   return Chain;
2118 }
2119
2120 //===----------------------------------------------------------------------===//
2121 //                C & StdCall & Fast Calling Convention implementation
2122 //===----------------------------------------------------------------------===//
2123 //  StdCall calling convention seems to be standard for many Windows' API
2124 //  routines and around. It differs from C calling convention just a little:
2125 //  callee should clean up the stack, not caller. Symbols should be also
2126 //  decorated in some fancy way :) It doesn't support any vector arguments.
2127 //  For info on fast calling convention see Fast Calling Convention (tail call)
2128 //  implementation LowerX86_32FastCCCallTo.
2129
2130 /// CallIsStructReturn - Determines whether a call uses struct return
2131 /// semantics.
2132 enum StructReturnType {
2133   NotStructReturn,
2134   RegStructReturn,
2135   StackStructReturn
2136 };
2137 static StructReturnType
2138 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2139   if (Outs.empty())
2140     return NotStructReturn;
2141
2142   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2143   if (!Flags.isSRet())
2144     return NotStructReturn;
2145   if (Flags.isInReg())
2146     return RegStructReturn;
2147   return StackStructReturn;
2148 }
2149
2150 /// Determines whether a function uses struct return semantics.
2151 static StructReturnType
2152 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2153   if (Ins.empty())
2154     return NotStructReturn;
2155
2156   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2157   if (!Flags.isSRet())
2158     return NotStructReturn;
2159   if (Flags.isInReg())
2160     return RegStructReturn;
2161   return StackStructReturn;
2162 }
2163
2164 /// Make a copy of an aggregate at address specified by "Src" to address
2165 /// "Dst" with size and alignment information specified by the specific
2166 /// parameter attribute. The copy will be passed as a byval function parameter.
2167 static SDValue
2168 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2169                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2170                           SDLoc dl) {
2171   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
2172
2173   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2174                        /*isVolatile*/false, /*AlwaysInline=*/true,
2175                        /*isTailCall*/false,
2176                        MachinePointerInfo(), MachinePointerInfo());
2177 }
2178
2179 /// Return true if the calling convention is one that
2180 /// supports tail call optimization.
2181 static bool IsTailCallConvention(CallingConv::ID CC) {
2182   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2183           CC == CallingConv::HiPE);
2184 }
2185
2186 /// \brief Return true if the calling convention is a C calling convention.
2187 static bool IsCCallConvention(CallingConv::ID CC) {
2188   return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2189           CC == CallingConv::X86_64_SysV);
2190 }
2191
2192 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2193   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2194     return false;
2195
2196   CallSite CS(CI);
2197   CallingConv::ID CalleeCC = CS.getCallingConv();
2198   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2199     return false;
2200
2201   return true;
2202 }
2203
2204 /// Return true if the function is being made into
2205 /// a tailcall target by changing its ABI.
2206 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2207                                    bool GuaranteedTailCallOpt) {
2208   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2209 }
2210
2211 SDValue
2212 X86TargetLowering::LowerMemArgument(SDValue Chain,
2213                                     CallingConv::ID CallConv,
2214                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2215                                     SDLoc dl, SelectionDAG &DAG,
2216                                     const CCValAssign &VA,
2217                                     MachineFrameInfo *MFI,
2218                                     unsigned i) const {
2219   // Create the nodes corresponding to a load from this parameter slot.
2220   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2221   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2222       CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2223   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2224   EVT ValVT;
2225
2226   // If value is passed by pointer we have address passed instead of the value
2227   // itself.
2228   if (VA.getLocInfo() == CCValAssign::Indirect)
2229     ValVT = VA.getLocVT();
2230   else
2231     ValVT = VA.getValVT();
2232
2233   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2234   // changed with more analysis.
2235   // In case of tail call optimization mark all arguments mutable. Since they
2236   // could be overwritten by lowering of arguments in case of a tail call.
2237   if (Flags.isByVal()) {
2238     unsigned Bytes = Flags.getByValSize();
2239     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2240     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2241     return DAG.getFrameIndex(FI, getPointerTy());
2242   } else {
2243     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2244                                     VA.getLocMemOffset(), isImmutable);
2245     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2246     return DAG.getLoad(ValVT, dl, Chain, FIN,
2247                        MachinePointerInfo::getFixedStack(FI),
2248                        false, false, false, 0);
2249   }
2250 }
2251
2252 // FIXME: Get this from tablegen.
2253 static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
2254                                                 const X86Subtarget *Subtarget) {
2255   assert(Subtarget->is64Bit());
2256
2257   if (Subtarget->isCallingConvWin64(CallConv)) {
2258     static const MCPhysReg GPR64ArgRegsWin64[] = {
2259       X86::RCX, X86::RDX, X86::R8,  X86::R9
2260     };
2261     return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
2262   }
2263
2264   static const MCPhysReg GPR64ArgRegs64Bit[] = {
2265     X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2266   };
2267   return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
2268 }
2269
2270 // FIXME: Get this from tablegen.
2271 static ArrayRef<MCPhysReg> get64BitArgumentXMMs(MachineFunction &MF,
2272                                                 CallingConv::ID CallConv,
2273                                                 const X86Subtarget *Subtarget) {
2274   assert(Subtarget->is64Bit());
2275   if (Subtarget->isCallingConvWin64(CallConv)) {
2276     // The XMM registers which might contain var arg parameters are shadowed
2277     // in their paired GPR.  So we only need to save the GPR to their home
2278     // slots.
2279     // TODO: __vectorcall will change this.
2280     return None;
2281   }
2282
2283   const Function *Fn = MF.getFunction();
2284   bool NoImplicitFloatOps = Fn->hasFnAttribute(Attribute::NoImplicitFloat);
2285   bool isSoftFloat = MF.getTarget().Options.UseSoftFloat;
2286   assert(!(isSoftFloat && NoImplicitFloatOps) &&
2287          "SSE register cannot be used when SSE is disabled!");
2288   if (isSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
2289     // Kernel mode asks for SSE to be disabled, so there are no XMM argument
2290     // registers.
2291     return None;
2292
2293   static const MCPhysReg XMMArgRegs64Bit[] = {
2294     X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2295     X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2296   };
2297   return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
2298 }
2299
2300 SDValue
2301 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2302                                         CallingConv::ID CallConv,
2303                                         bool isVarArg,
2304                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2305                                         SDLoc dl,
2306                                         SelectionDAG &DAG,
2307                                         SmallVectorImpl<SDValue> &InVals)
2308                                           const {
2309   MachineFunction &MF = DAG.getMachineFunction();
2310   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2311   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
2312
2313   const Function* Fn = MF.getFunction();
2314   if (Fn->hasExternalLinkage() &&
2315       Subtarget->isTargetCygMing() &&
2316       Fn->getName() == "main")
2317     FuncInfo->setForceFramePointer(true);
2318
2319   MachineFrameInfo *MFI = MF.getFrameInfo();
2320   bool Is64Bit = Subtarget->is64Bit();
2321   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2322
2323   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2324          "Var args not supported with calling convention fastcc, ghc or hipe");
2325
2326   // Assign locations to all of the incoming arguments.
2327   SmallVector<CCValAssign, 16> ArgLocs;
2328   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2329
2330   // Allocate shadow area for Win64
2331   if (IsWin64)
2332     CCInfo.AllocateStack(32, 8);
2333
2334   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2335
2336   unsigned LastVal = ~0U;
2337   SDValue ArgValue;
2338   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2339     CCValAssign &VA = ArgLocs[i];
2340     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2341     // places.
2342     assert(VA.getValNo() != LastVal &&
2343            "Don't support value assigned to multiple locs yet");
2344     (void)LastVal;
2345     LastVal = VA.getValNo();
2346
2347     if (VA.isRegLoc()) {
2348       EVT RegVT = VA.getLocVT();
2349       const TargetRegisterClass *RC;
2350       if (RegVT == MVT::i32)
2351         RC = &X86::GR32RegClass;
2352       else if (Is64Bit && RegVT == MVT::i64)
2353         RC = &X86::GR64RegClass;
2354       else if (RegVT == MVT::f32)
2355         RC = &X86::FR32RegClass;
2356       else if (RegVT == MVT::f64)
2357         RC = &X86::FR64RegClass;
2358       else if (RegVT.is512BitVector())
2359         RC = &X86::VR512RegClass;
2360       else if (RegVT.is256BitVector())
2361         RC = &X86::VR256RegClass;
2362       else if (RegVT.is128BitVector())
2363         RC = &X86::VR128RegClass;
2364       else if (RegVT == MVT::x86mmx)
2365         RC = &X86::VR64RegClass;
2366       else if (RegVT == MVT::i1)
2367         RC = &X86::VK1RegClass;
2368       else if (RegVT == MVT::v8i1)
2369         RC = &X86::VK8RegClass;
2370       else if (RegVT == MVT::v16i1)
2371         RC = &X86::VK16RegClass;
2372       else if (RegVT == MVT::v32i1)
2373         RC = &X86::VK32RegClass;
2374       else if (RegVT == MVT::v64i1)
2375         RC = &X86::VK64RegClass;
2376       else
2377         llvm_unreachable("Unknown argument type!");
2378
2379       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2380       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2381
2382       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2383       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2384       // right size.
2385       if (VA.getLocInfo() == CCValAssign::SExt)
2386         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2387                                DAG.getValueType(VA.getValVT()));
2388       else if (VA.getLocInfo() == CCValAssign::ZExt)
2389         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2390                                DAG.getValueType(VA.getValVT()));
2391       else if (VA.getLocInfo() == CCValAssign::BCvt)
2392         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2393
2394       if (VA.isExtInLoc()) {
2395         // Handle MMX values passed in XMM regs.
2396         if (RegVT.isVector() && VA.getValVT().getScalarType() != MVT::i1)
2397           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2398         else
2399           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2400       }
2401     } else {
2402       assert(VA.isMemLoc());
2403       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2404     }
2405
2406     // If value is passed via pointer - do a load.
2407     if (VA.getLocInfo() == CCValAssign::Indirect)
2408       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2409                              MachinePointerInfo(), false, false, false, 0);
2410
2411     InVals.push_back(ArgValue);
2412   }
2413
2414   if (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC()) {
2415     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2416       // The x86-64 ABIs require that for returning structs by value we copy
2417       // the sret argument into %rax/%eax (depending on ABI) for the return.
2418       // Win32 requires us to put the sret argument to %eax as well.
2419       // Save the argument into a virtual register so that we can access it
2420       // from the return points.
2421       if (Ins[i].Flags.isSRet()) {
2422         unsigned Reg = FuncInfo->getSRetReturnReg();
2423         if (!Reg) {
2424           MVT PtrTy = getPointerTy();
2425           Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2426           FuncInfo->setSRetReturnReg(Reg);
2427         }
2428         SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2429         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2430         break;
2431       }
2432     }
2433   }
2434
2435   unsigned StackSize = CCInfo.getNextStackOffset();
2436   // Align stack specially for tail calls.
2437   if (FuncIsMadeTailCallSafe(CallConv,
2438                              MF.getTarget().Options.GuaranteedTailCallOpt))
2439     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2440
2441   // If the function takes variable number of arguments, make a frame index for
2442   // the start of the first vararg value... for expansion of llvm.va_start. We
2443   // can skip this if there are no va_start calls.
2444   if (MFI->hasVAStart() &&
2445       (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2446                    CallConv != CallingConv::X86_ThisCall))) {
2447     FuncInfo->setVarArgsFrameIndex(
2448         MFI->CreateFixedObject(1, StackSize, true));
2449   }
2450
2451   MachineModuleInfo &MMI = MF.getMMI();
2452   const Function *WinEHParent = nullptr;
2453   if (IsWin64 && MMI.hasWinEHFuncInfo(Fn))
2454     WinEHParent = MMI.getWinEHParent(Fn);
2455   bool IsWinEHOutlined = WinEHParent && WinEHParent != Fn;
2456   bool IsWinEHParent = WinEHParent && WinEHParent == Fn;
2457
2458   // Figure out if XMM registers are in use.
2459   assert(!(MF.getTarget().Options.UseSoftFloat &&
2460            Fn->hasFnAttribute(Attribute::NoImplicitFloat)) &&
2461          "SSE register cannot be used when SSE is disabled!");
2462
2463   // 64-bit calling conventions support varargs and register parameters, so we
2464   // have to do extra work to spill them in the prologue.
2465   if (Is64Bit && isVarArg && MFI->hasVAStart()) {
2466     // Find the first unallocated argument registers.
2467     ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
2468     ArrayRef<MCPhysReg> ArgXMMs = get64BitArgumentXMMs(MF, CallConv, Subtarget);
2469     unsigned NumIntRegs = CCInfo.getFirstUnallocated(ArgGPRs);
2470     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(ArgXMMs);
2471     assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2472            "SSE register cannot be used when SSE is disabled!");
2473
2474     // Gather all the live in physical registers.
2475     SmallVector<SDValue, 6> LiveGPRs;
2476     SmallVector<SDValue, 8> LiveXMMRegs;
2477     SDValue ALVal;
2478     for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
2479       unsigned GPR = MF.addLiveIn(Reg, &X86::GR64RegClass);
2480       LiveGPRs.push_back(
2481           DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64));
2482     }
2483     if (!ArgXMMs.empty()) {
2484       unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2485       ALVal = DAG.getCopyFromReg(Chain, dl, AL, MVT::i8);
2486       for (MCPhysReg Reg : ArgXMMs.slice(NumXMMRegs)) {
2487         unsigned XMMReg = MF.addLiveIn(Reg, &X86::VR128RegClass);
2488         LiveXMMRegs.push_back(
2489             DAG.getCopyFromReg(Chain, dl, XMMReg, MVT::v4f32));
2490       }
2491     }
2492
2493     if (IsWin64) {
2494       // Get to the caller-allocated home save location.  Add 8 to account
2495       // for the return address.
2496       int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2497       FuncInfo->setRegSaveFrameIndex(
2498           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2499       // Fixup to set vararg frame on shadow area (4 x i64).
2500       if (NumIntRegs < 4)
2501         FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2502     } else {
2503       // For X86-64, if there are vararg parameters that are passed via
2504       // registers, then we must store them to their spots on the stack so
2505       // they may be loaded by deferencing the result of va_next.
2506       FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2507       FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
2508       FuncInfo->setRegSaveFrameIndex(MFI->CreateStackObject(
2509           ArgGPRs.size() * 8 + ArgXMMs.size() * 16, 16, false));
2510     }
2511
2512     // Store the integer parameter registers.
2513     SmallVector<SDValue, 8> MemOps;
2514     SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2515                                       getPointerTy());
2516     unsigned Offset = FuncInfo->getVarArgsGPOffset();
2517     for (SDValue Val : LiveGPRs) {
2518       SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2519                                 DAG.getIntPtrConstant(Offset, dl));
2520       SDValue Store =
2521         DAG.getStore(Val.getValue(1), dl, Val, FIN,
2522                      MachinePointerInfo::getFixedStack(
2523                        FuncInfo->getRegSaveFrameIndex(), Offset),
2524                      false, false, 0);
2525       MemOps.push_back(Store);
2526       Offset += 8;
2527     }
2528
2529     if (!ArgXMMs.empty() && NumXMMRegs != ArgXMMs.size()) {
2530       // Now store the XMM (fp + vector) parameter registers.
2531       SmallVector<SDValue, 12> SaveXMMOps;
2532       SaveXMMOps.push_back(Chain);
2533       SaveXMMOps.push_back(ALVal);
2534       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2535                              FuncInfo->getRegSaveFrameIndex(), dl));
2536       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2537                              FuncInfo->getVarArgsFPOffset(), dl));
2538       SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
2539                         LiveXMMRegs.end());
2540       MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2541                                    MVT::Other, SaveXMMOps));
2542     }
2543
2544     if (!MemOps.empty())
2545       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2546   } else if (IsWinEHOutlined) {
2547     // Get to the caller-allocated home save location.  Add 8 to account
2548     // for the return address.
2549     int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2550     FuncInfo->setRegSaveFrameIndex(MFI->CreateFixedObject(
2551         /*Size=*/1, /*SPOffset=*/HomeOffset + 8, /*Immutable=*/false));
2552
2553     MMI.getWinEHFuncInfo(Fn)
2554         .CatchHandlerParentFrameObjIdx[const_cast<Function *>(Fn)] =
2555         FuncInfo->getRegSaveFrameIndex();
2556
2557     // Store the second integer parameter (rdx) into rsp+16 relative to the
2558     // stack pointer at the entry of the function.
2559     SDValue RSFIN =
2560         DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), getPointerTy());
2561     unsigned GPR = MF.addLiveIn(X86::RDX, &X86::GR64RegClass);
2562     SDValue Val = DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64);
2563     Chain = DAG.getStore(
2564         Val.getValue(1), dl, Val, RSFIN,
2565         MachinePointerInfo::getFixedStack(FuncInfo->getRegSaveFrameIndex()),
2566         /*isVolatile=*/true, /*isNonTemporal=*/false, /*Alignment=*/0);
2567   }
2568
2569   if (isVarArg && MFI->hasMustTailInVarArgFunc()) {
2570     // Find the largest legal vector type.
2571     MVT VecVT = MVT::Other;
2572     // FIXME: Only some x86_32 calling conventions support AVX512.
2573     if (Subtarget->hasAVX512() &&
2574         (Is64Bit || (CallConv == CallingConv::X86_VectorCall ||
2575                      CallConv == CallingConv::Intel_OCL_BI)))
2576       VecVT = MVT::v16f32;
2577     else if (Subtarget->hasAVX())
2578       VecVT = MVT::v8f32;
2579     else if (Subtarget->hasSSE2())
2580       VecVT = MVT::v4f32;
2581
2582     // We forward some GPRs and some vector types.
2583     SmallVector<MVT, 2> RegParmTypes;
2584     MVT IntVT = Is64Bit ? MVT::i64 : MVT::i32;
2585     RegParmTypes.push_back(IntVT);
2586     if (VecVT != MVT::Other)
2587       RegParmTypes.push_back(VecVT);
2588
2589     // Compute the set of forwarded registers. The rest are scratch.
2590     SmallVectorImpl<ForwardedRegister> &Forwards =
2591         FuncInfo->getForwardedMustTailRegParms();
2592     CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, CC_X86);
2593
2594     // Conservatively forward AL on x86_64, since it might be used for varargs.
2595     if (Is64Bit && !CCInfo.isAllocated(X86::AL)) {
2596       unsigned ALVReg = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2597       Forwards.push_back(ForwardedRegister(ALVReg, X86::AL, MVT::i8));
2598     }
2599
2600     // Copy all forwards from physical to virtual registers.
2601     for (ForwardedRegister &F : Forwards) {
2602       // FIXME: Can we use a less constrained schedule?
2603       SDValue RegVal = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2604       F.VReg = MF.getRegInfo().createVirtualRegister(getRegClassFor(F.VT));
2605       Chain = DAG.getCopyToReg(Chain, dl, F.VReg, RegVal);
2606     }
2607   }
2608
2609   // Some CCs need callee pop.
2610   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2611                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2612     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2613   } else {
2614     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2615     // If this is an sret function, the return should pop the hidden pointer.
2616     if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2617         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2618         argsAreStructReturn(Ins) == StackStructReturn)
2619       FuncInfo->setBytesToPopOnReturn(4);
2620   }
2621
2622   if (!Is64Bit) {
2623     // RegSaveFrameIndex is X86-64 only.
2624     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2625     if (CallConv == CallingConv::X86_FastCall ||
2626         CallConv == CallingConv::X86_ThisCall)
2627       // fastcc functions can't have varargs.
2628       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2629   }
2630
2631   FuncInfo->setArgumentStackSize(StackSize);
2632
2633   if (IsWinEHParent) {
2634     int UnwindHelpFI = MFI->CreateStackObject(8, 8, /*isSS=*/false);
2635     SDValue StackSlot = DAG.getFrameIndex(UnwindHelpFI, MVT::i64);
2636     MMI.getWinEHFuncInfo(MF.getFunction()).UnwindHelpFrameIdx = UnwindHelpFI;
2637     SDValue Neg2 = DAG.getConstant(-2, dl, MVT::i64);
2638     Chain = DAG.getStore(Chain, dl, Neg2, StackSlot,
2639                          MachinePointerInfo::getFixedStack(UnwindHelpFI),
2640                          /*isVolatile=*/true,
2641                          /*isNonTemporal=*/false, /*Alignment=*/0);
2642   }
2643
2644   return Chain;
2645 }
2646
2647 SDValue
2648 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2649                                     SDValue StackPtr, SDValue Arg,
2650                                     SDLoc dl, SelectionDAG &DAG,
2651                                     const CCValAssign &VA,
2652                                     ISD::ArgFlagsTy Flags) const {
2653   unsigned LocMemOffset = VA.getLocMemOffset();
2654   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
2655   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2656   if (Flags.isByVal())
2657     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2658
2659   return DAG.getStore(Chain, dl, Arg, PtrOff,
2660                       MachinePointerInfo::getStack(LocMemOffset),
2661                       false, false, 0);
2662 }
2663
2664 /// Emit a load of return address if tail call
2665 /// optimization is performed and it is required.
2666 SDValue
2667 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2668                                            SDValue &OutRetAddr, SDValue Chain,
2669                                            bool IsTailCall, bool Is64Bit,
2670                                            int FPDiff, SDLoc dl) const {
2671   // Adjust the Return address stack slot.
2672   EVT VT = getPointerTy();
2673   OutRetAddr = getReturnAddressFrameIndex(DAG);
2674
2675   // Load the "old" Return address.
2676   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2677                            false, false, false, 0);
2678   return SDValue(OutRetAddr.getNode(), 1);
2679 }
2680
2681 /// Emit a store of the return address if tail call
2682 /// optimization is performed and it is required (FPDiff!=0).
2683 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2684                                         SDValue Chain, SDValue RetAddrFrIdx,
2685                                         EVT PtrVT, unsigned SlotSize,
2686                                         int FPDiff, SDLoc dl) {
2687   // Store the return address to the appropriate stack slot.
2688   if (!FPDiff) return Chain;
2689   // Calculate the new stack slot for the return address.
2690   int NewReturnAddrFI =
2691     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2692                                          false);
2693   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2694   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2695                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2696                        false, false, 0);
2697   return Chain;
2698 }
2699
2700 SDValue
2701 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2702                              SmallVectorImpl<SDValue> &InVals) const {
2703   SelectionDAG &DAG                     = CLI.DAG;
2704   SDLoc &dl                             = CLI.DL;
2705   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2706   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2707   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2708   SDValue Chain                         = CLI.Chain;
2709   SDValue Callee                        = CLI.Callee;
2710   CallingConv::ID CallConv              = CLI.CallConv;
2711   bool &isTailCall                      = CLI.IsTailCall;
2712   bool isVarArg                         = CLI.IsVarArg;
2713
2714   MachineFunction &MF = DAG.getMachineFunction();
2715   bool Is64Bit        = Subtarget->is64Bit();
2716   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2717   StructReturnType SR = callIsStructReturn(Outs);
2718   bool IsSibcall      = false;
2719   X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2720
2721   if (MF.getTarget().Options.DisableTailCalls)
2722     isTailCall = false;
2723
2724   bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2725   if (IsMustTail) {
2726     // Force this to be a tail call.  The verifier rules are enough to ensure
2727     // that we can lower this successfully without moving the return address
2728     // around.
2729     isTailCall = true;
2730   } else if (isTailCall) {
2731     // Check if it's really possible to do a tail call.
2732     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2733                     isVarArg, SR != NotStructReturn,
2734                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2735                     Outs, OutVals, Ins, DAG);
2736
2737     // Sibcalls are automatically detected tailcalls which do not require
2738     // ABI changes.
2739     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2740       IsSibcall = true;
2741
2742     if (isTailCall)
2743       ++NumTailCalls;
2744   }
2745
2746   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2747          "Var args not supported with calling convention fastcc, ghc or hipe");
2748
2749   // Analyze operands of the call, assigning locations to each operand.
2750   SmallVector<CCValAssign, 16> ArgLocs;
2751   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2752
2753   // Allocate shadow area for Win64
2754   if (IsWin64)
2755     CCInfo.AllocateStack(32, 8);
2756
2757   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2758
2759   // Get a count of how many bytes are to be pushed on the stack.
2760   unsigned NumBytes = CCInfo.getNextStackOffset();
2761   if (IsSibcall)
2762     // This is a sibcall. The memory operands are available in caller's
2763     // own caller's stack.
2764     NumBytes = 0;
2765   else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
2766            IsTailCallConvention(CallConv))
2767     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2768
2769   int FPDiff = 0;
2770   if (isTailCall && !IsSibcall && !IsMustTail) {
2771     // Lower arguments at fp - stackoffset + fpdiff.
2772     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2773
2774     FPDiff = NumBytesCallerPushed - NumBytes;
2775
2776     // Set the delta of movement of the returnaddr stackslot.
2777     // But only set if delta is greater than previous delta.
2778     if (FPDiff < X86Info->getTCReturnAddrDelta())
2779       X86Info->setTCReturnAddrDelta(FPDiff);
2780   }
2781
2782   unsigned NumBytesToPush = NumBytes;
2783   unsigned NumBytesToPop = NumBytes;
2784
2785   // If we have an inalloca argument, all stack space has already been allocated
2786   // for us and be right at the top of the stack.  We don't support multiple
2787   // arguments passed in memory when using inalloca.
2788   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2789     NumBytesToPush = 0;
2790     if (!ArgLocs.back().isMemLoc())
2791       report_fatal_error("cannot use inalloca attribute on a register "
2792                          "parameter");
2793     if (ArgLocs.back().getLocMemOffset() != 0)
2794       report_fatal_error("any parameter with the inalloca attribute must be "
2795                          "the only memory argument");
2796   }
2797
2798   if (!IsSibcall)
2799     Chain = DAG.getCALLSEQ_START(
2800         Chain, DAG.getIntPtrConstant(NumBytesToPush, dl, true), dl);
2801
2802   SDValue RetAddrFrIdx;
2803   // Load return address for tail calls.
2804   if (isTailCall && FPDiff)
2805     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2806                                     Is64Bit, FPDiff, dl);
2807
2808   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2809   SmallVector<SDValue, 8> MemOpChains;
2810   SDValue StackPtr;
2811
2812   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2813   // of tail call optimization arguments are handle later.
2814   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
2815   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2816     // Skip inalloca arguments, they have already been written.
2817     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2818     if (Flags.isInAlloca())
2819       continue;
2820
2821     CCValAssign &VA = ArgLocs[i];
2822     EVT RegVT = VA.getLocVT();
2823     SDValue Arg = OutVals[i];
2824     bool isByVal = Flags.isByVal();
2825
2826     // Promote the value if needed.
2827     switch (VA.getLocInfo()) {
2828     default: llvm_unreachable("Unknown loc info!");
2829     case CCValAssign::Full: break;
2830     case CCValAssign::SExt:
2831       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2832       break;
2833     case CCValAssign::ZExt:
2834       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2835       break;
2836     case CCValAssign::AExt:
2837       if (Arg.getValueType().getScalarType() == MVT::i1)
2838         Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2839       else if (RegVT.is128BitVector()) {
2840         // Special case: passing MMX values in XMM registers.
2841         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2842         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2843         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2844       } else
2845         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2846       break;
2847     case CCValAssign::BCvt:
2848       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2849       break;
2850     case CCValAssign::Indirect: {
2851       // Store the argument.
2852       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2853       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2854       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2855                            MachinePointerInfo::getFixedStack(FI),
2856                            false, false, 0);
2857       Arg = SpillSlot;
2858       break;
2859     }
2860     }
2861
2862     if (VA.isRegLoc()) {
2863       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2864       if (isVarArg && IsWin64) {
2865         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2866         // shadow reg if callee is a varargs function.
2867         unsigned ShadowReg = 0;
2868         switch (VA.getLocReg()) {
2869         case X86::XMM0: ShadowReg = X86::RCX; break;
2870         case X86::XMM1: ShadowReg = X86::RDX; break;
2871         case X86::XMM2: ShadowReg = X86::R8; break;
2872         case X86::XMM3: ShadowReg = X86::R9; break;
2873         }
2874         if (ShadowReg)
2875           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2876       }
2877     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2878       assert(VA.isMemLoc());
2879       if (!StackPtr.getNode())
2880         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2881                                       getPointerTy());
2882       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2883                                              dl, DAG, VA, Flags));
2884     }
2885   }
2886
2887   if (!MemOpChains.empty())
2888     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2889
2890   if (Subtarget->isPICStyleGOT()) {
2891     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2892     // GOT pointer.
2893     if (!isTailCall) {
2894       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2895                DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2896     } else {
2897       // If we are tail calling and generating PIC/GOT style code load the
2898       // address of the callee into ECX. The value in ecx is used as target of
2899       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2900       // for tail calls on PIC/GOT architectures. Normally we would just put the
2901       // address of GOT into ebx and then call target@PLT. But for tail calls
2902       // ebx would be restored (since ebx is callee saved) before jumping to the
2903       // target@PLT.
2904
2905       // Note: The actual moving to ECX is done further down.
2906       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2907       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2908           !G->getGlobal()->hasProtectedVisibility())
2909         Callee = LowerGlobalAddress(Callee, DAG);
2910       else if (isa<ExternalSymbolSDNode>(Callee))
2911         Callee = LowerExternalSymbol(Callee, DAG);
2912     }
2913   }
2914
2915   if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail) {
2916     // From AMD64 ABI document:
2917     // For calls that may call functions that use varargs or stdargs
2918     // (prototype-less calls or calls to functions containing ellipsis (...) in
2919     // the declaration) %al is used as hidden argument to specify the number
2920     // of SSE registers used. The contents of %al do not need to match exactly
2921     // the number of registers, but must be an ubound on the number of SSE
2922     // registers used and is in the range 0 - 8 inclusive.
2923
2924     // Count the number of XMM registers allocated.
2925     static const MCPhysReg XMMArgRegs[] = {
2926       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2927       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2928     };
2929     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
2930     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2931            && "SSE registers cannot be used when SSE is disabled");
2932
2933     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2934                                         DAG.getConstant(NumXMMRegs, dl,
2935                                                         MVT::i8)));
2936   }
2937
2938   if (isVarArg && IsMustTail) {
2939     const auto &Forwards = X86Info->getForwardedMustTailRegParms();
2940     for (const auto &F : Forwards) {
2941       SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2942       RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
2943     }
2944   }
2945
2946   // For tail calls lower the arguments to the 'real' stack slots.  Sibcalls
2947   // don't need this because the eligibility check rejects calls that require
2948   // shuffling arguments passed in memory.
2949   if (!IsSibcall && isTailCall) {
2950     // Force all the incoming stack arguments to be loaded from the stack
2951     // before any new outgoing arguments are stored to the stack, because the
2952     // outgoing stack slots may alias the incoming argument stack slots, and
2953     // the alias isn't otherwise explicit. This is slightly more conservative
2954     // than necessary, because it means that each store effectively depends
2955     // on every argument instead of just those arguments it would clobber.
2956     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2957
2958     SmallVector<SDValue, 8> MemOpChains2;
2959     SDValue FIN;
2960     int FI = 0;
2961     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2962       CCValAssign &VA = ArgLocs[i];
2963       if (VA.isRegLoc())
2964         continue;
2965       assert(VA.isMemLoc());
2966       SDValue Arg = OutVals[i];
2967       ISD::ArgFlagsTy Flags = Outs[i].Flags;
2968       // Skip inalloca arguments.  They don't require any work.
2969       if (Flags.isInAlloca())
2970         continue;
2971       // Create frame index.
2972       int32_t Offset = VA.getLocMemOffset()+FPDiff;
2973       uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2974       FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2975       FIN = DAG.getFrameIndex(FI, getPointerTy());
2976
2977       if (Flags.isByVal()) {
2978         // Copy relative to framepointer.
2979         SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset(), dl);
2980         if (!StackPtr.getNode())
2981           StackPtr = DAG.getCopyFromReg(Chain, dl,
2982                                         RegInfo->getStackRegister(),
2983                                         getPointerTy());
2984         Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2985
2986         MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2987                                                          ArgChain,
2988                                                          Flags, DAG, dl));
2989       } else {
2990         // Store relative to framepointer.
2991         MemOpChains2.push_back(
2992           DAG.getStore(ArgChain, dl, Arg, FIN,
2993                        MachinePointerInfo::getFixedStack(FI),
2994                        false, false, 0));
2995       }
2996     }
2997
2998     if (!MemOpChains2.empty())
2999       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3000
3001     // Store the return address to the appropriate stack slot.
3002     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
3003                                      getPointerTy(), RegInfo->getSlotSize(),
3004                                      FPDiff, dl);
3005   }
3006
3007   // Build a sequence of copy-to-reg nodes chained together with token chain
3008   // and flag operands which copy the outgoing args into registers.
3009   SDValue InFlag;
3010   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3011     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3012                              RegsToPass[i].second, InFlag);
3013     InFlag = Chain.getValue(1);
3014   }
3015
3016   if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
3017     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
3018     // In the 64-bit large code model, we have to make all calls
3019     // through a register, since the call instruction's 32-bit
3020     // pc-relative offset may not be large enough to hold the whole
3021     // address.
3022   } else if (Callee->getOpcode() == ISD::GlobalAddress) {
3023     // If the callee is a GlobalAddress node (quite common, every direct call
3024     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
3025     // it.
3026     GlobalAddressSDNode* G = cast<GlobalAddressSDNode>(Callee);
3027
3028     // We should use extra load for direct calls to dllimported functions in
3029     // non-JIT mode.
3030     const GlobalValue *GV = G->getGlobal();
3031     if (!GV->hasDLLImportStorageClass()) {
3032       unsigned char OpFlags = 0;
3033       bool ExtraLoad = false;
3034       unsigned WrapperKind = ISD::DELETED_NODE;
3035
3036       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
3037       // external symbols most go through the PLT in PIC mode.  If the symbol
3038       // has hidden or protected visibility, or if it is static or local, then
3039       // we don't need to use the PLT - we can directly call it.
3040       if (Subtarget->isTargetELF() &&
3041           DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
3042           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
3043         OpFlags = X86II::MO_PLT;
3044       } else if (Subtarget->isPICStyleStubAny() &&
3045                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
3046                  (!Subtarget->getTargetTriple().isMacOSX() ||
3047                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3048         // PC-relative references to external symbols should go through $stub,
3049         // unless we're building with the leopard linker or later, which
3050         // automatically synthesizes these stubs.
3051         OpFlags = X86II::MO_DARWIN_STUB;
3052       } else if (Subtarget->isPICStyleRIPRel() && isa<Function>(GV) &&
3053                  cast<Function>(GV)->hasFnAttribute(Attribute::NonLazyBind)) {
3054         // If the function is marked as non-lazy, generate an indirect call
3055         // which loads from the GOT directly. This avoids runtime overhead
3056         // at the cost of eager binding (and one extra byte of encoding).
3057         OpFlags = X86II::MO_GOTPCREL;
3058         WrapperKind = X86ISD::WrapperRIP;
3059         ExtraLoad = true;
3060       }
3061
3062       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
3063                                           G->getOffset(), OpFlags);
3064
3065       // Add a wrapper if needed.
3066       if (WrapperKind != ISD::DELETED_NODE)
3067         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
3068       // Add extra indirection if needed.
3069       if (ExtraLoad)
3070         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
3071                              MachinePointerInfo::getGOT(),
3072                              false, false, false, 0);
3073     }
3074   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3075     unsigned char OpFlags = 0;
3076
3077     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
3078     // external symbols should go through the PLT.
3079     if (Subtarget->isTargetELF() &&
3080         DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
3081       OpFlags = X86II::MO_PLT;
3082     } else if (Subtarget->isPICStyleStubAny() &&
3083                (!Subtarget->getTargetTriple().isMacOSX() ||
3084                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3085       // PC-relative references to external symbols should go through $stub,
3086       // unless we're building with the leopard linker or later, which
3087       // automatically synthesizes these stubs.
3088       OpFlags = X86II::MO_DARWIN_STUB;
3089     }
3090
3091     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
3092                                          OpFlags);
3093   } else if (Subtarget->isTarget64BitILP32() &&
3094              Callee->getValueType(0) == MVT::i32) {
3095     // Zero-extend the 32-bit Callee address into a 64-bit according to x32 ABI
3096     Callee = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Callee);
3097   }
3098
3099   // Returns a chain & a flag for retval copy to use.
3100   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3101   SmallVector<SDValue, 8> Ops;
3102
3103   if (!IsSibcall && isTailCall) {
3104     Chain = DAG.getCALLSEQ_END(Chain,
3105                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3106                                DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
3107     InFlag = Chain.getValue(1);
3108   }
3109
3110   Ops.push_back(Chain);
3111   Ops.push_back(Callee);
3112
3113   if (isTailCall)
3114     Ops.push_back(DAG.getConstant(FPDiff, dl, MVT::i32));
3115
3116   // Add argument registers to the end of the list so that they are known live
3117   // into the call.
3118   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3119     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3120                                   RegsToPass[i].second.getValueType()));
3121
3122   // Add a register mask operand representing the call-preserved registers.
3123   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
3124   const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
3125   assert(Mask && "Missing call preserved mask for calling convention");
3126   Ops.push_back(DAG.getRegisterMask(Mask));
3127
3128   if (InFlag.getNode())
3129     Ops.push_back(InFlag);
3130
3131   if (isTailCall) {
3132     // We used to do:
3133     //// If this is the first return lowered for this function, add the regs
3134     //// to the liveout set for the function.
3135     // This isn't right, although it's probably harmless on x86; liveouts
3136     // should be computed from returns not tail calls.  Consider a void
3137     // function making a tail call to a function returning int.
3138     MF.getFrameInfo()->setHasTailCall();
3139     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3140   }
3141
3142   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3143   InFlag = Chain.getValue(1);
3144
3145   // Create the CALLSEQ_END node.
3146   unsigned NumBytesForCalleeToPop;
3147   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3148                        DAG.getTarget().Options.GuaranteedTailCallOpt))
3149     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
3150   else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
3151            !Subtarget->getTargetTriple().isOSMSVCRT() &&
3152            SR == StackStructReturn)
3153     // If this is a call to a struct-return function, the callee
3154     // pops the hidden struct pointer, so we have to push it back.
3155     // This is common for Darwin/X86, Linux & Mingw32 targets.
3156     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3157     NumBytesForCalleeToPop = 4;
3158   else
3159     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
3160
3161   // Returns a flag for retval copy to use.
3162   if (!IsSibcall) {
3163     Chain = DAG.getCALLSEQ_END(Chain,
3164                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3165                                DAG.getIntPtrConstant(NumBytesForCalleeToPop, dl,
3166                                                      true),
3167                                InFlag, dl);
3168     InFlag = Chain.getValue(1);
3169   }
3170
3171   // Handle result values, copying them out of physregs into vregs that we
3172   // return.
3173   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3174                          Ins, dl, DAG, InVals);
3175 }
3176
3177 //===----------------------------------------------------------------------===//
3178 //                Fast Calling Convention (tail call) implementation
3179 //===----------------------------------------------------------------------===//
3180
3181 //  Like std call, callee cleans arguments, convention except that ECX is
3182 //  reserved for storing the tail called function address. Only 2 registers are
3183 //  free for argument passing (inreg). Tail call optimization is performed
3184 //  provided:
3185 //                * tailcallopt is enabled
3186 //                * caller/callee are fastcc
3187 //  On X86_64 architecture with GOT-style position independent code only local
3188 //  (within module) calls are supported at the moment.
3189 //  To keep the stack aligned according to platform abi the function
3190 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
3191 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3192 //  If a tail called function callee has more arguments than the caller the
3193 //  caller needs to make sure that there is room to move the RETADDR to. This is
3194 //  achieved by reserving an area the size of the argument delta right after the
3195 //  original RETADDR, but before the saved framepointer or the spilled registers
3196 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3197 //  stack layout:
3198 //    arg1
3199 //    arg2
3200 //    RETADDR
3201 //    [ new RETADDR
3202 //      move area ]
3203 //    (possible EBP)
3204 //    ESI
3205 //    EDI
3206 //    local1 ..
3207
3208 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3209 /// for a 16 byte align requirement.
3210 unsigned
3211 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3212                                                SelectionDAG& DAG) const {
3213   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3214   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
3215   unsigned StackAlignment = TFI.getStackAlignment();
3216   uint64_t AlignMask = StackAlignment - 1;
3217   int64_t Offset = StackSize;
3218   unsigned SlotSize = RegInfo->getSlotSize();
3219   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3220     // Number smaller than 12 so just add the difference.
3221     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3222   } else {
3223     // Mask out lower bits, add stackalignment once plus the 12 bytes.
3224     Offset = ((~AlignMask) & Offset) + StackAlignment +
3225       (StackAlignment-SlotSize);
3226   }
3227   return Offset;
3228 }
3229
3230 /// MatchingStackOffset - Return true if the given stack call argument is
3231 /// already available in the same position (relatively) of the caller's
3232 /// incoming argument stack.
3233 static
3234 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3235                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3236                          const X86InstrInfo *TII) {
3237   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3238   int FI = INT_MAX;
3239   if (Arg.getOpcode() == ISD::CopyFromReg) {
3240     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3241     if (!TargetRegisterInfo::isVirtualRegister(VR))
3242       return false;
3243     MachineInstr *Def = MRI->getVRegDef(VR);
3244     if (!Def)
3245       return false;
3246     if (!Flags.isByVal()) {
3247       if (!TII->isLoadFromStackSlot(Def, FI))
3248         return false;
3249     } else {
3250       unsigned Opcode = Def->getOpcode();
3251       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r ||
3252            Opcode == X86::LEA64_32r) &&
3253           Def->getOperand(1).isFI()) {
3254         FI = Def->getOperand(1).getIndex();
3255         Bytes = Flags.getByValSize();
3256       } else
3257         return false;
3258     }
3259   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3260     if (Flags.isByVal())
3261       // ByVal argument is passed in as a pointer but it's now being
3262       // dereferenced. e.g.
3263       // define @foo(%struct.X* %A) {
3264       //   tail call @bar(%struct.X* byval %A)
3265       // }
3266       return false;
3267     SDValue Ptr = Ld->getBasePtr();
3268     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3269     if (!FINode)
3270       return false;
3271     FI = FINode->getIndex();
3272   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3273     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3274     FI = FINode->getIndex();
3275     Bytes = Flags.getByValSize();
3276   } else
3277     return false;
3278
3279   assert(FI != INT_MAX);
3280   if (!MFI->isFixedObjectIndex(FI))
3281     return false;
3282   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3283 }
3284
3285 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3286 /// for tail call optimization. Targets which want to do tail call
3287 /// optimization should implement this function.
3288 bool
3289 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3290                                                      CallingConv::ID CalleeCC,
3291                                                      bool isVarArg,
3292                                                      bool isCalleeStructRet,
3293                                                      bool isCallerStructRet,
3294                                                      Type *RetTy,
3295                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3296                                     const SmallVectorImpl<SDValue> &OutVals,
3297                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3298                                                      SelectionDAG &DAG) const {
3299   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3300     return false;
3301
3302   // If -tailcallopt is specified, make fastcc functions tail-callable.
3303   const MachineFunction &MF = DAG.getMachineFunction();
3304   const Function *CallerF = MF.getFunction();
3305
3306   // If the function return type is x86_fp80 and the callee return type is not,
3307   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3308   // perform a tailcall optimization here.
3309   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3310     return false;
3311
3312   CallingConv::ID CallerCC = CallerF->getCallingConv();
3313   bool CCMatch = CallerCC == CalleeCC;
3314   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3315   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3316
3317   // Win64 functions have extra shadow space for argument homing. Don't do the
3318   // sibcall if the caller and callee have mismatched expectations for this
3319   // space.
3320   if (IsCalleeWin64 != IsCallerWin64)
3321     return false;
3322
3323   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3324     if (IsTailCallConvention(CalleeCC) && CCMatch)
3325       return true;
3326     return false;
3327   }
3328
3329   // Look for obvious safe cases to perform tail call optimization that do not
3330   // require ABI changes. This is what gcc calls sibcall.
3331
3332   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3333   // emit a special epilogue.
3334   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3335   if (RegInfo->needsStackRealignment(MF))
3336     return false;
3337
3338   // Also avoid sibcall optimization if either caller or callee uses struct
3339   // return semantics.
3340   if (isCalleeStructRet || isCallerStructRet)
3341     return false;
3342
3343   // An stdcall/thiscall caller is expected to clean up its arguments; the
3344   // callee isn't going to do that.
3345   // FIXME: this is more restrictive than needed. We could produce a tailcall
3346   // when the stack adjustment matches. For example, with a thiscall that takes
3347   // only one argument.
3348   if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3349                    CallerCC == CallingConv::X86_ThisCall))
3350     return false;
3351
3352   // Do not sibcall optimize vararg calls unless all arguments are passed via
3353   // registers.
3354   if (isVarArg && !Outs.empty()) {
3355
3356     // Optimizing for varargs on Win64 is unlikely to be safe without
3357     // additional testing.
3358     if (IsCalleeWin64 || IsCallerWin64)
3359       return false;
3360
3361     SmallVector<CCValAssign, 16> ArgLocs;
3362     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3363                    *DAG.getContext());
3364
3365     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3366     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3367       if (!ArgLocs[i].isRegLoc())
3368         return false;
3369   }
3370
3371   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3372   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3373   // this into a sibcall.
3374   bool Unused = false;
3375   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3376     if (!Ins[i].Used) {
3377       Unused = true;
3378       break;
3379     }
3380   }
3381   if (Unused) {
3382     SmallVector<CCValAssign, 16> RVLocs;
3383     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), RVLocs,
3384                    *DAG.getContext());
3385     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3386     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3387       CCValAssign &VA = RVLocs[i];
3388       if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3389         return false;
3390     }
3391   }
3392
3393   // If the calling conventions do not match, then we'd better make sure the
3394   // results are returned in the same way as what the caller expects.
3395   if (!CCMatch) {
3396     SmallVector<CCValAssign, 16> RVLocs1;
3397     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
3398                     *DAG.getContext());
3399     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3400
3401     SmallVector<CCValAssign, 16> RVLocs2;
3402     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
3403                     *DAG.getContext());
3404     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3405
3406     if (RVLocs1.size() != RVLocs2.size())
3407       return false;
3408     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3409       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3410         return false;
3411       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3412         return false;
3413       if (RVLocs1[i].isRegLoc()) {
3414         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3415           return false;
3416       } else {
3417         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3418           return false;
3419       }
3420     }
3421   }
3422
3423   // If the callee takes no arguments then go on to check the results of the
3424   // call.
3425   if (!Outs.empty()) {
3426     // Check if stack adjustment is needed. For now, do not do this if any
3427     // argument is passed on the stack.
3428     SmallVector<CCValAssign, 16> ArgLocs;
3429     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3430                    *DAG.getContext());
3431
3432     // Allocate shadow area for Win64
3433     if (IsCalleeWin64)
3434       CCInfo.AllocateStack(32, 8);
3435
3436     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3437     if (CCInfo.getNextStackOffset()) {
3438       MachineFunction &MF = DAG.getMachineFunction();
3439       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3440         return false;
3441
3442       // Check if the arguments are already laid out in the right way as
3443       // the caller's fixed stack objects.
3444       MachineFrameInfo *MFI = MF.getFrameInfo();
3445       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3446       const X86InstrInfo *TII = Subtarget->getInstrInfo();
3447       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3448         CCValAssign &VA = ArgLocs[i];
3449         SDValue Arg = OutVals[i];
3450         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3451         if (VA.getLocInfo() == CCValAssign::Indirect)
3452           return false;
3453         if (!VA.isRegLoc()) {
3454           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3455                                    MFI, MRI, TII))
3456             return false;
3457         }
3458       }
3459     }
3460
3461     // If the tailcall address may be in a register, then make sure it's
3462     // possible to register allocate for it. In 32-bit, the call address can
3463     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3464     // callee-saved registers are restored. These happen to be the same
3465     // registers used to pass 'inreg' arguments so watch out for those.
3466     if (!Subtarget->is64Bit() &&
3467         ((!isa<GlobalAddressSDNode>(Callee) &&
3468           !isa<ExternalSymbolSDNode>(Callee)) ||
3469          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3470       unsigned NumInRegs = 0;
3471       // In PIC we need an extra register to formulate the address computation
3472       // for the callee.
3473       unsigned MaxInRegs =
3474         (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3475
3476       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3477         CCValAssign &VA = ArgLocs[i];
3478         if (!VA.isRegLoc())
3479           continue;
3480         unsigned Reg = VA.getLocReg();
3481         switch (Reg) {
3482         default: break;
3483         case X86::EAX: case X86::EDX: case X86::ECX:
3484           if (++NumInRegs == MaxInRegs)
3485             return false;
3486           break;
3487         }
3488       }
3489     }
3490   }
3491
3492   return true;
3493 }
3494
3495 FastISel *
3496 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3497                                   const TargetLibraryInfo *libInfo) const {
3498   return X86::createFastISel(funcInfo, libInfo);
3499 }
3500
3501 //===----------------------------------------------------------------------===//
3502 //                           Other Lowering Hooks
3503 //===----------------------------------------------------------------------===//
3504
3505 static bool MayFoldLoad(SDValue Op) {
3506   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3507 }
3508
3509 static bool MayFoldIntoStore(SDValue Op) {
3510   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3511 }
3512
3513 static bool isTargetShuffle(unsigned Opcode) {
3514   switch(Opcode) {
3515   default: return false;
3516   case X86ISD::BLENDI:
3517   case X86ISD::PSHUFB:
3518   case X86ISD::PSHUFD:
3519   case X86ISD::PSHUFHW:
3520   case X86ISD::PSHUFLW:
3521   case X86ISD::SHUFP:
3522   case X86ISD::PALIGNR:
3523   case X86ISD::MOVLHPS:
3524   case X86ISD::MOVLHPD:
3525   case X86ISD::MOVHLPS:
3526   case X86ISD::MOVLPS:
3527   case X86ISD::MOVLPD:
3528   case X86ISD::MOVSHDUP:
3529   case X86ISD::MOVSLDUP:
3530   case X86ISD::MOVDDUP:
3531   case X86ISD::MOVSS:
3532   case X86ISD::MOVSD:
3533   case X86ISD::UNPCKL:
3534   case X86ISD::UNPCKH:
3535   case X86ISD::VPERMILPI:
3536   case X86ISD::VPERM2X128:
3537   case X86ISD::VPERMI:
3538     return true;
3539   }
3540 }
3541
3542 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3543                                     SDValue V1, unsigned TargetMask,
3544                                     SelectionDAG &DAG) {
3545   switch(Opc) {
3546   default: llvm_unreachable("Unknown x86 shuffle node");
3547   case X86ISD::PSHUFD:
3548   case X86ISD::PSHUFHW:
3549   case X86ISD::PSHUFLW:
3550   case X86ISD::VPERMILPI:
3551   case X86ISD::VPERMI:
3552     return DAG.getNode(Opc, dl, VT, V1,
3553                        DAG.getConstant(TargetMask, dl, MVT::i8));
3554   }
3555 }
3556
3557 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3558                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3559   switch(Opc) {
3560   default: llvm_unreachable("Unknown x86 shuffle node");
3561   case X86ISD::MOVLHPS:
3562   case X86ISD::MOVLHPD:
3563   case X86ISD::MOVHLPS:
3564   case X86ISD::MOVLPS:
3565   case X86ISD::MOVLPD:
3566   case X86ISD::MOVSS:
3567   case X86ISD::MOVSD:
3568   case X86ISD::UNPCKL:
3569   case X86ISD::UNPCKH:
3570     return DAG.getNode(Opc, dl, VT, V1, V2);
3571   }
3572 }
3573
3574 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3575   MachineFunction &MF = DAG.getMachineFunction();
3576   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3577   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3578   int ReturnAddrIndex = FuncInfo->getRAIndex();
3579
3580   if (ReturnAddrIndex == 0) {
3581     // Set up a frame object for the return address.
3582     unsigned SlotSize = RegInfo->getSlotSize();
3583     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3584                                                            -(int64_t)SlotSize,
3585                                                            false);
3586     FuncInfo->setRAIndex(ReturnAddrIndex);
3587   }
3588
3589   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3590 }
3591
3592 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3593                                        bool hasSymbolicDisplacement) {
3594   // Offset should fit into 32 bit immediate field.
3595   if (!isInt<32>(Offset))
3596     return false;
3597
3598   // If we don't have a symbolic displacement - we don't have any extra
3599   // restrictions.
3600   if (!hasSymbolicDisplacement)
3601     return true;
3602
3603   // FIXME: Some tweaks might be needed for medium code model.
3604   if (M != CodeModel::Small && M != CodeModel::Kernel)
3605     return false;
3606
3607   // For small code model we assume that latest object is 16MB before end of 31
3608   // bits boundary. We may also accept pretty large negative constants knowing
3609   // that all objects are in the positive half of address space.
3610   if (M == CodeModel::Small && Offset < 16*1024*1024)
3611     return true;
3612
3613   // For kernel code model we know that all object resist in the negative half
3614   // of 32bits address space. We may not accept negative offsets, since they may
3615   // be just off and we may accept pretty large positive ones.
3616   if (M == CodeModel::Kernel && Offset >= 0)
3617     return true;
3618
3619   return false;
3620 }
3621
3622 /// isCalleePop - Determines whether the callee is required to pop its
3623 /// own arguments. Callee pop is necessary to support tail calls.
3624 bool X86::isCalleePop(CallingConv::ID CallingConv,
3625                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3626   switch (CallingConv) {
3627   default:
3628     return false;
3629   case CallingConv::X86_StdCall:
3630   case CallingConv::X86_FastCall:
3631   case CallingConv::X86_ThisCall:
3632     return !is64Bit;
3633   case CallingConv::Fast:
3634   case CallingConv::GHC:
3635   case CallingConv::HiPE:
3636     if (IsVarArg)
3637       return false;
3638     return TailCallOpt;
3639   }
3640 }
3641
3642 /// \brief Return true if the condition is an unsigned comparison operation.
3643 static bool isX86CCUnsigned(unsigned X86CC) {
3644   switch (X86CC) {
3645   default: llvm_unreachable("Invalid integer condition!");
3646   case X86::COND_E:     return true;
3647   case X86::COND_G:     return false;
3648   case X86::COND_GE:    return false;
3649   case X86::COND_L:     return false;
3650   case X86::COND_LE:    return false;
3651   case X86::COND_NE:    return true;
3652   case X86::COND_B:     return true;
3653   case X86::COND_A:     return true;
3654   case X86::COND_BE:    return true;
3655   case X86::COND_AE:    return true;
3656   }
3657   llvm_unreachable("covered switch fell through?!");
3658 }
3659
3660 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3661 /// specific condition code, returning the condition code and the LHS/RHS of the
3662 /// comparison to make.
3663 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, SDLoc DL, bool isFP,
3664                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3665   if (!isFP) {
3666     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3667       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3668         // X > -1   -> X == 0, jump !sign.
3669         RHS = DAG.getConstant(0, DL, RHS.getValueType());
3670         return X86::COND_NS;
3671       }
3672       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3673         // X < 0   -> X == 0, jump on sign.
3674         return X86::COND_S;
3675       }
3676       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3677         // X < 1   -> X <= 0
3678         RHS = DAG.getConstant(0, DL, RHS.getValueType());
3679         return X86::COND_LE;
3680       }
3681     }
3682
3683     switch (SetCCOpcode) {
3684     default: llvm_unreachable("Invalid integer condition!");
3685     case ISD::SETEQ:  return X86::COND_E;
3686     case ISD::SETGT:  return X86::COND_G;
3687     case ISD::SETGE:  return X86::COND_GE;
3688     case ISD::SETLT:  return X86::COND_L;
3689     case ISD::SETLE:  return X86::COND_LE;
3690     case ISD::SETNE:  return X86::COND_NE;
3691     case ISD::SETULT: return X86::COND_B;
3692     case ISD::SETUGT: return X86::COND_A;
3693     case ISD::SETULE: return X86::COND_BE;
3694     case ISD::SETUGE: return X86::COND_AE;
3695     }
3696   }
3697
3698   // First determine if it is required or is profitable to flip the operands.
3699
3700   // If LHS is a foldable load, but RHS is not, flip the condition.
3701   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3702       !ISD::isNON_EXTLoad(RHS.getNode())) {
3703     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3704     std::swap(LHS, RHS);
3705   }
3706
3707   switch (SetCCOpcode) {
3708   default: break;
3709   case ISD::SETOLT:
3710   case ISD::SETOLE:
3711   case ISD::SETUGT:
3712   case ISD::SETUGE:
3713     std::swap(LHS, RHS);
3714     break;
3715   }
3716
3717   // On a floating point condition, the flags are set as follows:
3718   // ZF  PF  CF   op
3719   //  0 | 0 | 0 | X > Y
3720   //  0 | 0 | 1 | X < Y
3721   //  1 | 0 | 0 | X == Y
3722   //  1 | 1 | 1 | unordered
3723   switch (SetCCOpcode) {
3724   default: llvm_unreachable("Condcode should be pre-legalized away");
3725   case ISD::SETUEQ:
3726   case ISD::SETEQ:   return X86::COND_E;
3727   case ISD::SETOLT:              // flipped
3728   case ISD::SETOGT:
3729   case ISD::SETGT:   return X86::COND_A;
3730   case ISD::SETOLE:              // flipped
3731   case ISD::SETOGE:
3732   case ISD::SETGE:   return X86::COND_AE;
3733   case ISD::SETUGT:              // flipped
3734   case ISD::SETULT:
3735   case ISD::SETLT:   return X86::COND_B;
3736   case ISD::SETUGE:              // flipped
3737   case ISD::SETULE:
3738   case ISD::SETLE:   return X86::COND_BE;
3739   case ISD::SETONE:
3740   case ISD::SETNE:   return X86::COND_NE;
3741   case ISD::SETUO:   return X86::COND_P;
3742   case ISD::SETO:    return X86::COND_NP;
3743   case ISD::SETOEQ:
3744   case ISD::SETUNE:  return X86::COND_INVALID;
3745   }
3746 }
3747
3748 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3749 /// code. Current x86 isa includes the following FP cmov instructions:
3750 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3751 static bool hasFPCMov(unsigned X86CC) {
3752   switch (X86CC) {
3753   default:
3754     return false;
3755   case X86::COND_B:
3756   case X86::COND_BE:
3757   case X86::COND_E:
3758   case X86::COND_P:
3759   case X86::COND_A:
3760   case X86::COND_AE:
3761   case X86::COND_NE:
3762   case X86::COND_NP:
3763     return true;
3764   }
3765 }
3766
3767 /// isFPImmLegal - Returns true if the target can instruction select the
3768 /// specified FP immediate natively. If false, the legalizer will
3769 /// materialize the FP immediate as a load from a constant pool.
3770 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3771   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3772     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3773       return true;
3774   }
3775   return false;
3776 }
3777
3778 bool X86TargetLowering::shouldReduceLoadWidth(SDNode *Load,
3779                                               ISD::LoadExtType ExtTy,
3780                                               EVT NewVT) const {
3781   // "ELF Handling for Thread-Local Storage" specifies that R_X86_64_GOTTPOFF
3782   // relocation target a movq or addq instruction: don't let the load shrink.
3783   SDValue BasePtr = cast<LoadSDNode>(Load)->getBasePtr();
3784   if (BasePtr.getOpcode() == X86ISD::WrapperRIP)
3785     if (const auto *GA = dyn_cast<GlobalAddressSDNode>(BasePtr.getOperand(0)))
3786       return GA->getTargetFlags() != X86II::MO_GOTTPOFF;
3787   return true;
3788 }
3789
3790 /// \brief Returns true if it is beneficial to convert a load of a constant
3791 /// to just the constant itself.
3792 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3793                                                           Type *Ty) const {
3794   assert(Ty->isIntegerTy());
3795
3796   unsigned BitSize = Ty->getPrimitiveSizeInBits();
3797   if (BitSize == 0 || BitSize > 64)
3798     return false;
3799   return true;
3800 }
3801
3802 bool X86TargetLowering::isExtractSubvectorCheap(EVT ResVT,
3803                                                 unsigned Index) const {
3804   if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
3805     return false;
3806
3807   return (Index == 0 || Index == ResVT.getVectorNumElements());
3808 }
3809
3810 bool X86TargetLowering::isCheapToSpeculateCttz() const {
3811   // Speculate cttz only if we can directly use TZCNT.
3812   return Subtarget->hasBMI();
3813 }
3814
3815 bool X86TargetLowering::isCheapToSpeculateCtlz() const {
3816   // Speculate ctlz only if we can directly use LZCNT.
3817   return Subtarget->hasLZCNT();
3818 }
3819
3820 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3821 /// the specified range (L, H].
3822 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3823   return (Val < 0) || (Val >= Low && Val < Hi);
3824 }
3825
3826 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3827 /// specified value.
3828 static bool isUndefOrEqual(int Val, int CmpVal) {
3829   return (Val < 0 || Val == CmpVal);
3830 }
3831
3832 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3833 /// from position Pos and ending in Pos+Size, falls within the specified
3834 /// sequential range (Low, Low+Size]. or is undef.
3835 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3836                                        unsigned Pos, unsigned Size, int Low) {
3837   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3838     if (!isUndefOrEqual(Mask[i], Low))
3839       return false;
3840   return true;
3841 }
3842
3843 /// isVEXTRACTIndex - Return true if the specified
3844 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3845 /// suitable for instruction that extract 128 or 256 bit vectors
3846 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
3847   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
3848   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3849     return false;
3850
3851   // The index should be aligned on a vecWidth-bit boundary.
3852   uint64_t Index =
3853     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3854
3855   MVT VT = N->getSimpleValueType(0);
3856   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
3857   bool Result = (Index * ElSize) % vecWidth == 0;
3858
3859   return Result;
3860 }
3861
3862 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
3863 /// operand specifies a subvector insert that is suitable for input to
3864 /// insertion of 128 or 256-bit subvectors
3865 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
3866   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
3867   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3868     return false;
3869   // The index should be aligned on a vecWidth-bit boundary.
3870   uint64_t Index =
3871     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3872
3873   MVT VT = N->getSimpleValueType(0);
3874   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
3875   bool Result = (Index * ElSize) % vecWidth == 0;
3876
3877   return Result;
3878 }
3879
3880 bool X86::isVINSERT128Index(SDNode *N) {
3881   return isVINSERTIndex(N, 128);
3882 }
3883
3884 bool X86::isVINSERT256Index(SDNode *N) {
3885   return isVINSERTIndex(N, 256);
3886 }
3887
3888 bool X86::isVEXTRACT128Index(SDNode *N) {
3889   return isVEXTRACTIndex(N, 128);
3890 }
3891
3892 bool X86::isVEXTRACT256Index(SDNode *N) {
3893   return isVEXTRACTIndex(N, 256);
3894 }
3895
3896 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
3897   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
3898   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3899     llvm_unreachable("Illegal extract subvector for VEXTRACT");
3900
3901   uint64_t Index =
3902     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3903
3904   MVT VecVT = N->getOperand(0).getSimpleValueType();
3905   MVT ElVT = VecVT.getVectorElementType();
3906
3907   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
3908   return Index / NumElemsPerChunk;
3909 }
3910
3911 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
3912   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
3913   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3914     llvm_unreachable("Illegal insert subvector for VINSERT");
3915
3916   uint64_t Index =
3917     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3918
3919   MVT VecVT = N->getSimpleValueType(0);
3920   MVT ElVT = VecVT.getVectorElementType();
3921
3922   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
3923   return Index / NumElemsPerChunk;
3924 }
3925
3926 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
3927 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
3928 /// and VINSERTI128 instructions.
3929 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
3930   return getExtractVEXTRACTImmediate(N, 128);
3931 }
3932
3933 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
3934 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
3935 /// and VINSERTI64x4 instructions.
3936 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
3937   return getExtractVEXTRACTImmediate(N, 256);
3938 }
3939
3940 /// getInsertVINSERT128Immediate - Return the appropriate immediate
3941 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
3942 /// and VINSERTI128 instructions.
3943 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
3944   return getInsertVINSERTImmediate(N, 128);
3945 }
3946
3947 /// getInsertVINSERT256Immediate - Return the appropriate immediate
3948 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
3949 /// and VINSERTI64x4 instructions.
3950 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
3951   return getInsertVINSERTImmediate(N, 256);
3952 }
3953
3954 /// isZero - Returns true if Elt is a constant integer zero
3955 static bool isZero(SDValue V) {
3956   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
3957   return C && C->isNullValue();
3958 }
3959
3960 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
3961 /// constant +0.0.
3962 bool X86::isZeroNode(SDValue Elt) {
3963   if (isZero(Elt))
3964     return true;
3965   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
3966     return CFP->getValueAPF().isPosZero();
3967   return false;
3968 }
3969
3970 /// getZeroVector - Returns a vector of specified type with all zero elements.
3971 ///
3972 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
3973                              SelectionDAG &DAG, SDLoc dl) {
3974   assert(VT.isVector() && "Expected a vector type");
3975
3976   // Always build SSE zero vectors as <4 x i32> bitcasted
3977   // to their dest type. This ensures they get CSE'd.
3978   SDValue Vec;
3979   if (VT.is128BitVector()) {  // SSE
3980     if (Subtarget->hasSSE2()) {  // SSE2
3981       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
3982       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3983     } else { // SSE1
3984       SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
3985       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
3986     }
3987   } else if (VT.is256BitVector()) { // AVX
3988     if (Subtarget->hasInt256()) { // AVX2
3989       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
3990       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
3991       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
3992     } else {
3993       // 256-bit logic and arithmetic instructions in AVX are all
3994       // floating-point, no support for integer ops. Emit fp zeroed vectors.
3995       SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
3996       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
3997       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
3998     }
3999   } else if (VT.is512BitVector()) { // AVX-512
4000       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4001       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4002                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4003       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4004   } else if (VT.getScalarType() == MVT::i1) {
4005
4006     assert((Subtarget->hasBWI() || VT.getVectorNumElements() <= 16)
4007             && "Unexpected vector type");
4008     assert((Subtarget->hasVLX() || VT.getVectorNumElements() >= 8)
4009             && "Unexpected vector type");
4010     SDValue Cst = DAG.getConstant(0, dl, MVT::i1);
4011     SmallVector<SDValue, 64> Ops(VT.getVectorNumElements(), Cst);
4012     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4013   } else
4014     llvm_unreachable("Unexpected vector type");
4015
4016   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4017 }
4018
4019 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
4020                                 SelectionDAG &DAG, SDLoc dl,
4021                                 unsigned vectorWidth) {
4022   assert((vectorWidth == 128 || vectorWidth == 256) &&
4023          "Unsupported vector width");
4024   EVT VT = Vec.getValueType();
4025   EVT ElVT = VT.getVectorElementType();
4026   unsigned Factor = VT.getSizeInBits()/vectorWidth;
4027   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
4028                                   VT.getVectorNumElements()/Factor);
4029
4030   // Extract from UNDEF is UNDEF.
4031   if (Vec.getOpcode() == ISD::UNDEF)
4032     return DAG.getUNDEF(ResultVT);
4033
4034   // Extract the relevant vectorWidth bits.  Generate an EXTRACT_SUBVECTOR
4035   unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
4036
4037   // This is the index of the first element of the vectorWidth-bit chunk
4038   // we want.
4039   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
4040                                * ElemsPerChunk);
4041
4042   // If the input is a buildvector just emit a smaller one.
4043   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
4044     return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
4045                        makeArrayRef(Vec->op_begin() + NormalizedIdxVal,
4046                                     ElemsPerChunk));
4047
4048   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4049   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec, VecIdx);
4050 }
4051
4052 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
4053 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
4054 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
4055 /// instructions or a simple subregister reference. Idx is an index in the
4056 /// 128 bits we want.  It need not be aligned to a 128-bit boundary.  That makes
4057 /// lowering EXTRACT_VECTOR_ELT operations easier.
4058 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
4059                                    SelectionDAG &DAG, SDLoc dl) {
4060   assert((Vec.getValueType().is256BitVector() ||
4061           Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
4062   return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
4063 }
4064
4065 /// Generate a DAG to grab 256-bits from a 512-bit vector.
4066 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
4067                                    SelectionDAG &DAG, SDLoc dl) {
4068   assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
4069   return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
4070 }
4071
4072 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
4073                                unsigned IdxVal, SelectionDAG &DAG,
4074                                SDLoc dl, unsigned vectorWidth) {
4075   assert((vectorWidth == 128 || vectorWidth == 256) &&
4076          "Unsupported vector width");
4077   // Inserting UNDEF is Result
4078   if (Vec.getOpcode() == ISD::UNDEF)
4079     return Result;
4080   EVT VT = Vec.getValueType();
4081   EVT ElVT = VT.getVectorElementType();
4082   EVT ResultVT = Result.getValueType();
4083
4084   // Insert the relevant vectorWidth bits.
4085   unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
4086
4087   // This is the index of the first element of the vectorWidth-bit chunk
4088   // we want.
4089   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
4090                                * ElemsPerChunk);
4091
4092   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4093   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec, VecIdx);
4094 }
4095
4096 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
4097 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
4098 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
4099 /// simple superregister reference.  Idx is an index in the 128 bits
4100 /// we want.  It need not be aligned to a 128-bit boundary.  That makes
4101 /// lowering INSERT_VECTOR_ELT operations easier.
4102 static SDValue Insert128BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4103                                   SelectionDAG &DAG, SDLoc dl) {
4104   assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
4105
4106   // For insertion into the zero index (low half) of a 256-bit vector, it is
4107   // more efficient to generate a blend with immediate instead of an insert*128.
4108   // We are still creating an INSERT_SUBVECTOR below with an undef node to
4109   // extend the subvector to the size of the result vector. Make sure that
4110   // we are not recursing on that node by checking for undef here.
4111   if (IdxVal == 0 && Result.getValueType().is256BitVector() &&
4112       Result.getOpcode() != ISD::UNDEF) {
4113     EVT ResultVT = Result.getValueType();
4114     SDValue ZeroIndex = DAG.getIntPtrConstant(0, dl);
4115     SDValue Undef = DAG.getUNDEF(ResultVT);
4116     SDValue Vec256 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Undef,
4117                                  Vec, ZeroIndex);
4118
4119     // The blend instruction, and therefore its mask, depend on the data type.
4120     MVT ScalarType = ResultVT.getScalarType().getSimpleVT();
4121     if (ScalarType.isFloatingPoint()) {
4122       // Choose either vblendps (float) or vblendpd (double).
4123       unsigned ScalarSize = ScalarType.getSizeInBits();
4124       assert((ScalarSize == 64 || ScalarSize == 32) && "Unknown float type");
4125       unsigned MaskVal = (ScalarSize == 64) ? 0x03 : 0x0f;
4126       SDValue Mask = DAG.getConstant(MaskVal, dl, MVT::i8);
4127       return DAG.getNode(X86ISD::BLENDI, dl, ResultVT, Result, Vec256, Mask);
4128     }
4129
4130     const X86Subtarget &Subtarget =
4131     static_cast<const X86Subtarget &>(DAG.getSubtarget());
4132
4133     // AVX2 is needed for 256-bit integer blend support.
4134     // Integers must be cast to 32-bit because there is only vpblendd;
4135     // vpblendw can't be used for this because it has a handicapped mask.
4136
4137     // If we don't have AVX2, then cast to float. Using a wrong domain blend
4138     // is still more efficient than using the wrong domain vinsertf128 that
4139     // will be created by InsertSubVector().
4140     MVT CastVT = Subtarget.hasAVX2() ? MVT::v8i32 : MVT::v8f32;
4141
4142     SDValue Mask = DAG.getConstant(0x0f, dl, MVT::i8);
4143     Vec256 = DAG.getNode(ISD::BITCAST, dl, CastVT, Vec256);
4144     Vec256 = DAG.getNode(X86ISD::BLENDI, dl, CastVT, Result, Vec256, Mask);
4145     return DAG.getNode(ISD::BITCAST, dl, ResultVT, Vec256);
4146   }
4147
4148   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
4149 }
4150
4151 static SDValue Insert256BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4152                                   SelectionDAG &DAG, SDLoc dl) {
4153   assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
4154   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
4155 }
4156
4157 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
4158 /// instructions. This is used because creating CONCAT_VECTOR nodes of
4159 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
4160 /// large BUILD_VECTORS.
4161 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
4162                                    unsigned NumElems, SelectionDAG &DAG,
4163                                    SDLoc dl) {
4164   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4165   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
4166 }
4167
4168 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
4169                                    unsigned NumElems, SelectionDAG &DAG,
4170                                    SDLoc dl) {
4171   SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4172   return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
4173 }
4174
4175 /// getOnesVector - Returns a vector of specified type with all bits set.
4176 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4177 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4178 /// Then bitcast to their original type, ensuring they get CSE'd.
4179 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4180                              SDLoc dl) {
4181   assert(VT.isVector() && "Expected a vector type");
4182
4183   SDValue Cst = DAG.getConstant(~0U, dl, MVT::i32);
4184   SDValue Vec;
4185   if (VT.is256BitVector()) {
4186     if (HasInt256) { // AVX2
4187       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4188       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4189     } else { // AVX
4190       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4191       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4192     }
4193   } else if (VT.is128BitVector()) {
4194     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4195   } else
4196     llvm_unreachable("Unexpected vector type");
4197
4198   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4199 }
4200
4201 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4202 /// operation of specified width.
4203 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4204                        SDValue V2) {
4205   unsigned NumElems = VT.getVectorNumElements();
4206   SmallVector<int, 8> Mask;
4207   Mask.push_back(NumElems);
4208   for (unsigned i = 1; i != NumElems; ++i)
4209     Mask.push_back(i);
4210   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4211 }
4212
4213 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4214 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4215                           SDValue V2) {
4216   unsigned NumElems = VT.getVectorNumElements();
4217   SmallVector<int, 8> Mask;
4218   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4219     Mask.push_back(i);
4220     Mask.push_back(i + NumElems);
4221   }
4222   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4223 }
4224
4225 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4226 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4227                           SDValue V2) {
4228   unsigned NumElems = VT.getVectorNumElements();
4229   SmallVector<int, 8> Mask;
4230   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4231     Mask.push_back(i + Half);
4232     Mask.push_back(i + NumElems + Half);
4233   }
4234   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4235 }
4236
4237 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4238 /// vector of zero or undef vector.  This produces a shuffle where the low
4239 /// element of V2 is swizzled into the zero/undef vector, landing at element
4240 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4241 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4242                                            bool IsZero,
4243                                            const X86Subtarget *Subtarget,
4244                                            SelectionDAG &DAG) {
4245   MVT VT = V2.getSimpleValueType();
4246   SDValue V1 = IsZero
4247     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
4248   unsigned NumElems = VT.getVectorNumElements();
4249   SmallVector<int, 16> MaskVec;
4250   for (unsigned i = 0; i != NumElems; ++i)
4251     // If this is the insertion idx, put the low elt of V2 here.
4252     MaskVec.push_back(i == Idx ? NumElems : i);
4253   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
4254 }
4255
4256 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4257 /// target specific opcode. Returns true if the Mask could be calculated. Sets
4258 /// IsUnary to true if only uses one source. Note that this will set IsUnary for
4259 /// shuffles which use a single input multiple times, and in those cases it will
4260 /// adjust the mask to only have indices within that single input.
4261 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4262                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
4263   unsigned NumElems = VT.getVectorNumElements();
4264   SDValue ImmN;
4265
4266   IsUnary = false;
4267   bool IsFakeUnary = false;
4268   switch(N->getOpcode()) {
4269   case X86ISD::BLENDI:
4270     ImmN = N->getOperand(N->getNumOperands()-1);
4271     DecodeBLENDMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4272     break;
4273   case X86ISD::SHUFP:
4274     ImmN = N->getOperand(N->getNumOperands()-1);
4275     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4276     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4277     break;
4278   case X86ISD::UNPCKH:
4279     DecodeUNPCKHMask(VT, Mask);
4280     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4281     break;
4282   case X86ISD::UNPCKL:
4283     DecodeUNPCKLMask(VT, Mask);
4284     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4285     break;
4286   case X86ISD::MOVHLPS:
4287     DecodeMOVHLPSMask(NumElems, Mask);
4288     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4289     break;
4290   case X86ISD::MOVLHPS:
4291     DecodeMOVLHPSMask(NumElems, Mask);
4292     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4293     break;
4294   case X86ISD::PALIGNR:
4295     ImmN = N->getOperand(N->getNumOperands()-1);
4296     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4297     break;
4298   case X86ISD::PSHUFD:
4299   case X86ISD::VPERMILPI:
4300     ImmN = N->getOperand(N->getNumOperands()-1);
4301     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4302     IsUnary = true;
4303     break;
4304   case X86ISD::PSHUFHW:
4305     ImmN = N->getOperand(N->getNumOperands()-1);
4306     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4307     IsUnary = true;
4308     break;
4309   case X86ISD::PSHUFLW:
4310     ImmN = N->getOperand(N->getNumOperands()-1);
4311     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4312     IsUnary = true;
4313     break;
4314   case X86ISD::PSHUFB: {
4315     IsUnary = true;
4316     SDValue MaskNode = N->getOperand(1);
4317     while (MaskNode->getOpcode() == ISD::BITCAST)
4318       MaskNode = MaskNode->getOperand(0);
4319
4320     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4321       // If we have a build-vector, then things are easy.
4322       EVT VT = MaskNode.getValueType();
4323       assert(VT.isVector() &&
4324              "Can't produce a non-vector with a build_vector!");
4325       if (!VT.isInteger())
4326         return false;
4327
4328       int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
4329
4330       SmallVector<uint64_t, 32> RawMask;
4331       for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
4332         SDValue Op = MaskNode->getOperand(i);
4333         if (Op->getOpcode() == ISD::UNDEF) {
4334           RawMask.push_back((uint64_t)SM_SentinelUndef);
4335           continue;
4336         }
4337         auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4338         if (!CN)
4339           return false;
4340         APInt MaskElement = CN->getAPIntValue();
4341
4342         // We now have to decode the element which could be any integer size and
4343         // extract each byte of it.
4344         for (int j = 0; j < NumBytesPerElement; ++j) {
4345           // Note that this is x86 and so always little endian: the low byte is
4346           // the first byte of the mask.
4347           RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
4348           MaskElement = MaskElement.lshr(8);
4349         }
4350       }
4351       DecodePSHUFBMask(RawMask, Mask);
4352       break;
4353     }
4354
4355     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4356     if (!MaskLoad)
4357       return false;
4358
4359     SDValue Ptr = MaskLoad->getBasePtr();
4360     if (Ptr->getOpcode() == X86ISD::Wrapper ||
4361         Ptr->getOpcode() == X86ISD::WrapperRIP)
4362       Ptr = Ptr->getOperand(0);
4363
4364     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4365     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4366       return false;
4367
4368     if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
4369       DecodePSHUFBMask(C, Mask);
4370       if (Mask.empty())
4371         return false;
4372       break;
4373     }
4374
4375     return false;
4376   }
4377   case X86ISD::VPERMI:
4378     ImmN = N->getOperand(N->getNumOperands()-1);
4379     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4380     IsUnary = true;
4381     break;
4382   case X86ISD::MOVSS:
4383   case X86ISD::MOVSD:
4384     DecodeScalarMoveMask(VT, /* IsLoad */ false, Mask);
4385     break;
4386   case X86ISD::VPERM2X128:
4387     ImmN = N->getOperand(N->getNumOperands()-1);
4388     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4389     if (Mask.empty()) return false;
4390     break;
4391   case X86ISD::MOVSLDUP:
4392     DecodeMOVSLDUPMask(VT, Mask);
4393     IsUnary = true;
4394     break;
4395   case X86ISD::MOVSHDUP:
4396     DecodeMOVSHDUPMask(VT, Mask);
4397     IsUnary = true;
4398     break;
4399   case X86ISD::MOVDDUP:
4400     DecodeMOVDDUPMask(VT, Mask);
4401     IsUnary = true;
4402     break;
4403   case X86ISD::MOVLHPD:
4404   case X86ISD::MOVLPD:
4405   case X86ISD::MOVLPS:
4406     // Not yet implemented
4407     return false;
4408   default: llvm_unreachable("unknown target shuffle node");
4409   }
4410
4411   // If we have a fake unary shuffle, the shuffle mask is spread across two
4412   // inputs that are actually the same node. Re-map the mask to always point
4413   // into the first input.
4414   if (IsFakeUnary)
4415     for (int &M : Mask)
4416       if (M >= (int)Mask.size())
4417         M -= Mask.size();
4418
4419   return true;
4420 }
4421
4422 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4423 /// element of the result of the vector shuffle.
4424 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4425                                    unsigned Depth) {
4426   if (Depth == 6)
4427     return SDValue();  // Limit search depth.
4428
4429   SDValue V = SDValue(N, 0);
4430   EVT VT = V.getValueType();
4431   unsigned Opcode = V.getOpcode();
4432
4433   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4434   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4435     int Elt = SV->getMaskElt(Index);
4436
4437     if (Elt < 0)
4438       return DAG.getUNDEF(VT.getVectorElementType());
4439
4440     unsigned NumElems = VT.getVectorNumElements();
4441     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4442                                          : SV->getOperand(1);
4443     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4444   }
4445
4446   // Recurse into target specific vector shuffles to find scalars.
4447   if (isTargetShuffle(Opcode)) {
4448     MVT ShufVT = V.getSimpleValueType();
4449     unsigned NumElems = ShufVT.getVectorNumElements();
4450     SmallVector<int, 16> ShuffleMask;
4451     bool IsUnary;
4452
4453     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4454       return SDValue();
4455
4456     int Elt = ShuffleMask[Index];
4457     if (Elt < 0)
4458       return DAG.getUNDEF(ShufVT.getVectorElementType());
4459
4460     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4461                                          : N->getOperand(1);
4462     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4463                                Depth+1);
4464   }
4465
4466   // Actual nodes that may contain scalar elements
4467   if (Opcode == ISD::BITCAST) {
4468     V = V.getOperand(0);
4469     EVT SrcVT = V.getValueType();
4470     unsigned NumElems = VT.getVectorNumElements();
4471
4472     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4473       return SDValue();
4474   }
4475
4476   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4477     return (Index == 0) ? V.getOperand(0)
4478                         : DAG.getUNDEF(VT.getVectorElementType());
4479
4480   if (V.getOpcode() == ISD::BUILD_VECTOR)
4481     return V.getOperand(Index);
4482
4483   return SDValue();
4484 }
4485
4486 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4487 ///
4488 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4489                                        unsigned NumNonZero, unsigned NumZero,
4490                                        SelectionDAG &DAG,
4491                                        const X86Subtarget* Subtarget,
4492                                        const TargetLowering &TLI) {
4493   if (NumNonZero > 8)
4494     return SDValue();
4495
4496   SDLoc dl(Op);
4497   SDValue V;
4498   bool First = true;
4499
4500   // SSE4.1 - use PINSRB to insert each byte directly.
4501   if (Subtarget->hasSSE41()) {
4502     for (unsigned i = 0; i < 16; ++i) {
4503       bool isNonZero = (NonZeros & (1 << i)) != 0;
4504       if (isNonZero) {
4505         if (First) {
4506           if (NumZero)
4507             V = getZeroVector(MVT::v16i8, Subtarget, DAG, dl);
4508           else
4509             V = DAG.getUNDEF(MVT::v16i8);
4510           First = false;
4511         }
4512         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4513                         MVT::v16i8, V, Op.getOperand(i),
4514                         DAG.getIntPtrConstant(i, dl));
4515       }
4516     }
4517
4518     return V;
4519   }
4520
4521   // Pre-SSE4.1 - merge byte pairs and insert with PINSRW.
4522   for (unsigned i = 0; i < 16; ++i) {
4523     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4524     if (ThisIsNonZero && First) {
4525       if (NumZero)
4526         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4527       else
4528         V = DAG.getUNDEF(MVT::v8i16);
4529       First = false;
4530     }
4531
4532     if ((i & 1) != 0) {
4533       SDValue ThisElt, LastElt;
4534       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4535       if (LastIsNonZero) {
4536         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4537                               MVT::i16, Op.getOperand(i-1));
4538       }
4539       if (ThisIsNonZero) {
4540         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4541         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4542                               ThisElt, DAG.getConstant(8, dl, MVT::i8));
4543         if (LastIsNonZero)
4544           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4545       } else
4546         ThisElt = LastElt;
4547
4548       if (ThisElt.getNode())
4549         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4550                         DAG.getIntPtrConstant(i/2, dl));
4551     }
4552   }
4553
4554   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4555 }
4556
4557 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4558 ///
4559 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4560                                      unsigned NumNonZero, unsigned NumZero,
4561                                      SelectionDAG &DAG,
4562                                      const X86Subtarget* Subtarget,
4563                                      const TargetLowering &TLI) {
4564   if (NumNonZero > 4)
4565     return SDValue();
4566
4567   SDLoc dl(Op);
4568   SDValue V;
4569   bool First = true;
4570   for (unsigned i = 0; i < 8; ++i) {
4571     bool isNonZero = (NonZeros & (1 << i)) != 0;
4572     if (isNonZero) {
4573       if (First) {
4574         if (NumZero)
4575           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4576         else
4577           V = DAG.getUNDEF(MVT::v8i16);
4578         First = false;
4579       }
4580       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4581                       MVT::v8i16, V, Op.getOperand(i),
4582                       DAG.getIntPtrConstant(i, dl));
4583     }
4584   }
4585
4586   return V;
4587 }
4588
4589 /// LowerBuildVectorv4x32 - Custom lower build_vector of v4i32 or v4f32.
4590 static SDValue LowerBuildVectorv4x32(SDValue Op, SelectionDAG &DAG,
4591                                      const X86Subtarget *Subtarget,
4592                                      const TargetLowering &TLI) {
4593   // Find all zeroable elements.
4594   std::bitset<4> Zeroable;
4595   for (int i=0; i < 4; ++i) {
4596     SDValue Elt = Op->getOperand(i);
4597     Zeroable[i] = (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt));
4598   }
4599   assert(Zeroable.size() - Zeroable.count() > 1 &&
4600          "We expect at least two non-zero elements!");
4601
4602   // We only know how to deal with build_vector nodes where elements are either
4603   // zeroable or extract_vector_elt with constant index.
4604   SDValue FirstNonZero;
4605   unsigned FirstNonZeroIdx;
4606   for (unsigned i=0; i < 4; ++i) {
4607     if (Zeroable[i])
4608       continue;
4609     SDValue Elt = Op->getOperand(i);
4610     if (Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4611         !isa<ConstantSDNode>(Elt.getOperand(1)))
4612       return SDValue();
4613     // Make sure that this node is extracting from a 128-bit vector.
4614     MVT VT = Elt.getOperand(0).getSimpleValueType();
4615     if (!VT.is128BitVector())
4616       return SDValue();
4617     if (!FirstNonZero.getNode()) {
4618       FirstNonZero = Elt;
4619       FirstNonZeroIdx = i;
4620     }
4621   }
4622
4623   assert(FirstNonZero.getNode() && "Unexpected build vector of all zeros!");
4624   SDValue V1 = FirstNonZero.getOperand(0);
4625   MVT VT = V1.getSimpleValueType();
4626
4627   // See if this build_vector can be lowered as a blend with zero.
4628   SDValue Elt;
4629   unsigned EltMaskIdx, EltIdx;
4630   int Mask[4];
4631   for (EltIdx = 0; EltIdx < 4; ++EltIdx) {
4632     if (Zeroable[EltIdx]) {
4633       // The zero vector will be on the right hand side.
4634       Mask[EltIdx] = EltIdx+4;
4635       continue;
4636     }
4637
4638     Elt = Op->getOperand(EltIdx);
4639     // By construction, Elt is a EXTRACT_VECTOR_ELT with constant index.
4640     EltMaskIdx = cast<ConstantSDNode>(Elt.getOperand(1))->getZExtValue();
4641     if (Elt.getOperand(0) != V1 || EltMaskIdx != EltIdx)
4642       break;
4643     Mask[EltIdx] = EltIdx;
4644   }
4645
4646   if (EltIdx == 4) {
4647     // Let the shuffle legalizer deal with blend operations.
4648     SDValue VZero = getZeroVector(VT, Subtarget, DAG, SDLoc(Op));
4649     if (V1.getSimpleValueType() != VT)
4650       V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), VT, V1);
4651     return DAG.getVectorShuffle(VT, SDLoc(V1), V1, VZero, &Mask[0]);
4652   }
4653
4654   // See if we can lower this build_vector to a INSERTPS.
4655   if (!Subtarget->hasSSE41())
4656     return SDValue();
4657
4658   SDValue V2 = Elt.getOperand(0);
4659   if (Elt == FirstNonZero && EltIdx == FirstNonZeroIdx)
4660     V1 = SDValue();
4661
4662   bool CanFold = true;
4663   for (unsigned i = EltIdx + 1; i < 4 && CanFold; ++i) {
4664     if (Zeroable[i])
4665       continue;
4666
4667     SDValue Current = Op->getOperand(i);
4668     SDValue SrcVector = Current->getOperand(0);
4669     if (!V1.getNode())
4670       V1 = SrcVector;
4671     CanFold = SrcVector == V1 &&
4672       cast<ConstantSDNode>(Current.getOperand(1))->getZExtValue() == i;
4673   }
4674
4675   if (!CanFold)
4676     return SDValue();
4677
4678   assert(V1.getNode() && "Expected at least two non-zero elements!");
4679   if (V1.getSimpleValueType() != MVT::v4f32)
4680     V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), MVT::v4f32, V1);
4681   if (V2.getSimpleValueType() != MVT::v4f32)
4682     V2 = DAG.getNode(ISD::BITCAST, SDLoc(V2), MVT::v4f32, V2);
4683
4684   // Ok, we can emit an INSERTPS instruction.
4685   unsigned ZMask = Zeroable.to_ulong();
4686
4687   unsigned InsertPSMask = EltMaskIdx << 6 | EltIdx << 4 | ZMask;
4688   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
4689   SDLoc DL(Op);
4690   SDValue Result = DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
4691                                DAG.getIntPtrConstant(InsertPSMask, DL));
4692   return DAG.getNode(ISD::BITCAST, DL, VT, Result);
4693 }
4694
4695 /// Return a vector logical shift node.
4696 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4697                          unsigned NumBits, SelectionDAG &DAG,
4698                          const TargetLowering &TLI, SDLoc dl) {
4699   assert(VT.is128BitVector() && "Unknown type for VShift");
4700   MVT ShVT = MVT::v2i64;
4701   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4702   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4703   MVT ScalarShiftTy = TLI.getScalarShiftAmountTy(SrcOp.getValueType());
4704   assert(NumBits % 8 == 0 && "Only support byte sized shifts");
4705   SDValue ShiftVal = DAG.getConstant(NumBits/8, dl, ScalarShiftTy);
4706   return DAG.getNode(ISD::BITCAST, dl, VT,
4707                      DAG.getNode(Opc, dl, ShVT, SrcOp, ShiftVal));
4708 }
4709
4710 static SDValue
4711 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
4712
4713   // Check if the scalar load can be widened into a vector load. And if
4714   // the address is "base + cst" see if the cst can be "absorbed" into
4715   // the shuffle mask.
4716   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4717     SDValue Ptr = LD->getBasePtr();
4718     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4719       return SDValue();
4720     EVT PVT = LD->getValueType(0);
4721     if (PVT != MVT::i32 && PVT != MVT::f32)
4722       return SDValue();
4723
4724     int FI = -1;
4725     int64_t Offset = 0;
4726     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4727       FI = FINode->getIndex();
4728       Offset = 0;
4729     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4730                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4731       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4732       Offset = Ptr.getConstantOperandVal(1);
4733       Ptr = Ptr.getOperand(0);
4734     } else {
4735       return SDValue();
4736     }
4737
4738     // FIXME: 256-bit vector instructions don't require a strict alignment,
4739     // improve this code to support it better.
4740     unsigned RequiredAlign = VT.getSizeInBits()/8;
4741     SDValue Chain = LD->getChain();
4742     // Make sure the stack object alignment is at least 16 or 32.
4743     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4744     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4745       if (MFI->isFixedObjectIndex(FI)) {
4746         // Can't change the alignment. FIXME: It's possible to compute
4747         // the exact stack offset and reference FI + adjust offset instead.
4748         // If someone *really* cares about this. That's the way to implement it.
4749         return SDValue();
4750       } else {
4751         MFI->setObjectAlignment(FI, RequiredAlign);
4752       }
4753     }
4754
4755     // (Offset % 16 or 32) must be multiple of 4. Then address is then
4756     // Ptr + (Offset & ~15).
4757     if (Offset < 0)
4758       return SDValue();
4759     if ((Offset % RequiredAlign) & 3)
4760       return SDValue();
4761     int64_t StartOffset = Offset & ~(RequiredAlign-1);
4762     if (StartOffset) {
4763       SDLoc DL(Ptr);
4764       Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
4765                         DAG.getConstant(StartOffset, DL, Ptr.getValueType()));
4766     }
4767
4768     int EltNo = (Offset - StartOffset) >> 2;
4769     unsigned NumElems = VT.getVectorNumElements();
4770
4771     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4772     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4773                              LD->getPointerInfo().getWithOffset(StartOffset),
4774                              false, false, false, 0);
4775
4776     SmallVector<int, 8> Mask(NumElems, EltNo);
4777
4778     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
4779   }
4780
4781   return SDValue();
4782 }
4783
4784 /// Given the initializing elements 'Elts' of a vector of type 'VT', see if the
4785 /// elements can be replaced by a single large load which has the same value as
4786 /// a build_vector or insert_subvector whose loaded operands are 'Elts'.
4787 ///
4788 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4789 ///
4790 /// FIXME: we'd also like to handle the case where the last elements are zero
4791 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4792 /// There's even a handy isZeroNode for that purpose.
4793 static SDValue EltsFromConsecutiveLoads(EVT VT, ArrayRef<SDValue> Elts,
4794                                         SDLoc &DL, SelectionDAG &DAG,
4795                                         bool isAfterLegalize) {
4796   unsigned NumElems = Elts.size();
4797
4798   LoadSDNode *LDBase = nullptr;
4799   unsigned LastLoadedElt = -1U;
4800
4801   // For each element in the initializer, see if we've found a load or an undef.
4802   // If we don't find an initial load element, or later load elements are
4803   // non-consecutive, bail out.
4804   for (unsigned i = 0; i < NumElems; ++i) {
4805     SDValue Elt = Elts[i];
4806     // Look through a bitcast.
4807     if (Elt.getNode() && Elt.getOpcode() == ISD::BITCAST)
4808       Elt = Elt.getOperand(0);
4809     if (!Elt.getNode() ||
4810         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4811       return SDValue();
4812     if (!LDBase) {
4813       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4814         return SDValue();
4815       LDBase = cast<LoadSDNode>(Elt.getNode());
4816       LastLoadedElt = i;
4817       continue;
4818     }
4819     if (Elt.getOpcode() == ISD::UNDEF)
4820       continue;
4821
4822     LoadSDNode *LD = cast<LoadSDNode>(Elt);
4823     EVT LdVT = Elt.getValueType();
4824     // Each loaded element must be the correct fractional portion of the
4825     // requested vector load.
4826     if (LdVT.getSizeInBits() != VT.getSizeInBits() / NumElems)
4827       return SDValue();
4828     if (!DAG.isConsecutiveLoad(LD, LDBase, LdVT.getSizeInBits() / 8, i))
4829       return SDValue();
4830     LastLoadedElt = i;
4831   }
4832
4833   // If we have found an entire vector of loads and undefs, then return a large
4834   // load of the entire vector width starting at the base pointer.  If we found
4835   // consecutive loads for the low half, generate a vzext_load node.
4836   if (LastLoadedElt == NumElems - 1) {
4837     assert(LDBase && "Did not find base load for merging consecutive loads");
4838     EVT EltVT = LDBase->getValueType(0);
4839     // Ensure that the input vector size for the merged loads matches the
4840     // cumulative size of the input elements.
4841     if (VT.getSizeInBits() != EltVT.getSizeInBits() * NumElems)
4842       return SDValue();
4843
4844     if (isAfterLegalize &&
4845         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
4846       return SDValue();
4847
4848     SDValue NewLd = SDValue();
4849
4850     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4851                         LDBase->getPointerInfo(), LDBase->isVolatile(),
4852                         LDBase->isNonTemporal(), LDBase->isInvariant(),
4853                         LDBase->getAlignment());
4854
4855     if (LDBase->hasAnyUseOfValue(1)) {
4856       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
4857                                      SDValue(LDBase, 1),
4858                                      SDValue(NewLd.getNode(), 1));
4859       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
4860       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
4861                              SDValue(NewLd.getNode(), 1));
4862     }
4863
4864     return NewLd;
4865   }
4866
4867   //TODO: The code below fires only for for loading the low v2i32 / v2f32
4868   //of a v4i32 / v4f32. It's probably worth generalizing.
4869   EVT EltVT = VT.getVectorElementType();
4870   if (NumElems == 4 && LastLoadedElt == 1 && (EltVT.getSizeInBits() == 32) &&
4871       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
4872     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4873     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4874     SDValue ResNode =
4875         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
4876                                 LDBase->getPointerInfo(),
4877                                 LDBase->getAlignment(),
4878                                 false/*isVolatile*/, true/*ReadMem*/,
4879                                 false/*WriteMem*/);
4880
4881     // Make sure the newly-created LOAD is in the same position as LDBase in
4882     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
4883     // update uses of LDBase's output chain to use the TokenFactor.
4884     if (LDBase->hasAnyUseOfValue(1)) {
4885       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
4886                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
4887       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
4888       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
4889                              SDValue(ResNode.getNode(), 1));
4890     }
4891
4892     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
4893   }
4894   return SDValue();
4895 }
4896
4897 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
4898 /// to generate a splat value for the following cases:
4899 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
4900 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
4901 /// a scalar load, or a constant.
4902 /// The VBROADCAST node is returned when a pattern is found,
4903 /// or SDValue() otherwise.
4904 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
4905                                     SelectionDAG &DAG) {
4906   // VBROADCAST requires AVX.
4907   // TODO: Splats could be generated for non-AVX CPUs using SSE
4908   // instructions, but there's less potential gain for only 128-bit vectors.
4909   if (!Subtarget->hasAVX())
4910     return SDValue();
4911
4912   MVT VT = Op.getSimpleValueType();
4913   SDLoc dl(Op);
4914
4915   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
4916          "Unsupported vector type for broadcast.");
4917
4918   SDValue Ld;
4919   bool ConstSplatVal;
4920
4921   switch (Op.getOpcode()) {
4922     default:
4923       // Unknown pattern found.
4924       return SDValue();
4925
4926     case ISD::BUILD_VECTOR: {
4927       auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
4928       BitVector UndefElements;
4929       SDValue Splat = BVOp->getSplatValue(&UndefElements);
4930
4931       // We need a splat of a single value to use broadcast, and it doesn't
4932       // make any sense if the value is only in one element of the vector.
4933       if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
4934         return SDValue();
4935
4936       Ld = Splat;
4937       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
4938                        Ld.getOpcode() == ISD::ConstantFP);
4939
4940       // Make sure that all of the users of a non-constant load are from the
4941       // BUILD_VECTOR node.
4942       if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
4943         return SDValue();
4944       break;
4945     }
4946
4947     case ISD::VECTOR_SHUFFLE: {
4948       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4949
4950       // Shuffles must have a splat mask where the first element is
4951       // broadcasted.
4952       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
4953         return SDValue();
4954
4955       SDValue Sc = Op.getOperand(0);
4956       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
4957           Sc.getOpcode() != ISD::BUILD_VECTOR) {
4958
4959         if (!Subtarget->hasInt256())
4960           return SDValue();
4961
4962         // Use the register form of the broadcast instruction available on AVX2.
4963         if (VT.getSizeInBits() >= 256)
4964           Sc = Extract128BitVector(Sc, 0, DAG, dl);
4965         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
4966       }
4967
4968       Ld = Sc.getOperand(0);
4969       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
4970                        Ld.getOpcode() == ISD::ConstantFP);
4971
4972       // The scalar_to_vector node and the suspected
4973       // load node must have exactly one user.
4974       // Constants may have multiple users.
4975
4976       // AVX-512 has register version of the broadcast
4977       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
4978         Ld.getValueType().getSizeInBits() >= 32;
4979       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
4980           !hasRegVer))
4981         return SDValue();
4982       break;
4983     }
4984   }
4985
4986   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
4987   bool IsGE256 = (VT.getSizeInBits() >= 256);
4988
4989   // When optimizing for size, generate up to 5 extra bytes for a broadcast
4990   // instruction to save 8 or more bytes of constant pool data.
4991   // TODO: If multiple splats are generated to load the same constant,
4992   // it may be detrimental to overall size. There needs to be a way to detect
4993   // that condition to know if this is truly a size win.
4994   const Function *F = DAG.getMachineFunction().getFunction();
4995   bool OptForSize = F->hasFnAttribute(Attribute::OptimizeForSize);
4996
4997   // Handle broadcasting a single constant scalar from the constant pool
4998   // into a vector.
4999   // On Sandybridge (no AVX2), it is still better to load a constant vector
5000   // from the constant pool and not to broadcast it from a scalar.
5001   // But override that restriction when optimizing for size.
5002   // TODO: Check if splatting is recommended for other AVX-capable CPUs.
5003   if (ConstSplatVal && (Subtarget->hasAVX2() || OptForSize)) {
5004     EVT CVT = Ld.getValueType();
5005     assert(!CVT.isVector() && "Must not broadcast a vector type");
5006
5007     // Splat f32, i32, v4f64, v4i64 in all cases with AVX2.
5008     // For size optimization, also splat v2f64 and v2i64, and for size opt
5009     // with AVX2, also splat i8 and i16.
5010     // With pattern matching, the VBROADCAST node may become a VMOVDDUP.
5011     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5012         (OptForSize && (ScalarSize == 64 || Subtarget->hasAVX2()))) {
5013       const Constant *C = nullptr;
5014       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5015         C = CI->getConstantIntValue();
5016       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5017         C = CF->getConstantFPValue();
5018
5019       assert(C && "Invalid constant type");
5020
5021       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5022       SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
5023       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5024       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5025                        MachinePointerInfo::getConstantPool(),
5026                        false, false, false, Alignment);
5027
5028       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5029     }
5030   }
5031
5032   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5033
5034   // Handle AVX2 in-register broadcasts.
5035   if (!IsLoad && Subtarget->hasInt256() &&
5036       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5037     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5038
5039   // The scalar source must be a normal load.
5040   if (!IsLoad)
5041     return SDValue();
5042
5043   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5044       (Subtarget->hasVLX() && ScalarSize == 64))
5045     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5046
5047   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5048   // double since there is no vbroadcastsd xmm
5049   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5050     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5051       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5052   }
5053
5054   // Unsupported broadcast.
5055   return SDValue();
5056 }
5057
5058 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5059 /// underlying vector and index.
5060 ///
5061 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5062 /// index.
5063 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5064                                          SDValue ExtIdx) {
5065   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5066   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5067     return Idx;
5068
5069   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5070   // lowered this:
5071   //   (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5072   // to:
5073   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
5074   //                           (extract_subvector (v8f32 %vreg0), Constant<4>),
5075   //                           undef)
5076   //                       Constant<0>)
5077   // In this case the vector is the extract_subvector expression and the index
5078   // is 2, as specified by the shuffle.
5079   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5080   SDValue ShuffleVec = SVOp->getOperand(0);
5081   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5082   assert(ShuffleVecVT.getVectorElementType() ==
5083          ExtractedFromVec.getSimpleValueType().getVectorElementType());
5084
5085   int ShuffleIdx = SVOp->getMaskElt(Idx);
5086   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5087     ExtractedFromVec = ShuffleVec;
5088     return ShuffleIdx;
5089   }
5090   return Idx;
5091 }
5092
5093 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5094   MVT VT = Op.getSimpleValueType();
5095
5096   // Skip if insert_vec_elt is not supported.
5097   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5098   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5099     return SDValue();
5100
5101   SDLoc DL(Op);
5102   unsigned NumElems = Op.getNumOperands();
5103
5104   SDValue VecIn1;
5105   SDValue VecIn2;
5106   SmallVector<unsigned, 4> InsertIndices;
5107   SmallVector<int, 8> Mask(NumElems, -1);
5108
5109   for (unsigned i = 0; i != NumElems; ++i) {
5110     unsigned Opc = Op.getOperand(i).getOpcode();
5111
5112     if (Opc == ISD::UNDEF)
5113       continue;
5114
5115     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5116       // Quit if more than 1 elements need inserting.
5117       if (InsertIndices.size() > 1)
5118         return SDValue();
5119
5120       InsertIndices.push_back(i);
5121       continue;
5122     }
5123
5124     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5125     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5126     // Quit if non-constant index.
5127     if (!isa<ConstantSDNode>(ExtIdx))
5128       return SDValue();
5129     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5130
5131     // Quit if extracted from vector of different type.
5132     if (ExtractedFromVec.getValueType() != VT)
5133       return SDValue();
5134
5135     if (!VecIn1.getNode())
5136       VecIn1 = ExtractedFromVec;
5137     else if (VecIn1 != ExtractedFromVec) {
5138       if (!VecIn2.getNode())
5139         VecIn2 = ExtractedFromVec;
5140       else if (VecIn2 != ExtractedFromVec)
5141         // Quit if more than 2 vectors to shuffle
5142         return SDValue();
5143     }
5144
5145     if (ExtractedFromVec == VecIn1)
5146       Mask[i] = Idx;
5147     else if (ExtractedFromVec == VecIn2)
5148       Mask[i] = Idx + NumElems;
5149   }
5150
5151   if (!VecIn1.getNode())
5152     return SDValue();
5153
5154   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5155   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5156   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5157     unsigned Idx = InsertIndices[i];
5158     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5159                      DAG.getIntPtrConstant(Idx, DL));
5160   }
5161
5162   return NV;
5163 }
5164
5165 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5166 SDValue
5167 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5168
5169   MVT VT = Op.getSimpleValueType();
5170   assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
5171          "Unexpected type in LowerBUILD_VECTORvXi1!");
5172
5173   SDLoc dl(Op);
5174   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5175     SDValue Cst = DAG.getTargetConstant(0, dl, MVT::i1);
5176     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5177     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5178   }
5179
5180   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5181     SDValue Cst = DAG.getTargetConstant(1, dl, MVT::i1);
5182     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5183     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5184   }
5185
5186   bool AllContants = true;
5187   uint64_t Immediate = 0;
5188   int NonConstIdx = -1;
5189   bool IsSplat = true;
5190   unsigned NumNonConsts = 0;
5191   unsigned NumConsts = 0;
5192   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5193     SDValue In = Op.getOperand(idx);
5194     if (In.getOpcode() == ISD::UNDEF)
5195       continue;
5196     if (!isa<ConstantSDNode>(In)) {
5197       AllContants = false;
5198       NonConstIdx = idx;
5199       NumNonConsts++;
5200     } else {
5201       NumConsts++;
5202       if (cast<ConstantSDNode>(In)->getZExtValue())
5203       Immediate |= (1ULL << idx);
5204     }
5205     if (In != Op.getOperand(0))
5206       IsSplat = false;
5207   }
5208
5209   if (AllContants) {
5210     SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
5211       DAG.getConstant(Immediate, dl, MVT::i16));
5212     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
5213                        DAG.getIntPtrConstant(0, dl));
5214   }
5215
5216   if (NumNonConsts == 1 && NonConstIdx != 0) {
5217     SDValue DstVec;
5218     if (NumConsts) {
5219       SDValue VecAsImm = DAG.getConstant(Immediate, dl,
5220                                          MVT::getIntegerVT(VT.getSizeInBits()));
5221       DstVec = DAG.getNode(ISD::BITCAST, dl, VT, VecAsImm);
5222     }
5223     else
5224       DstVec = DAG.getUNDEF(VT);
5225     return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5226                        Op.getOperand(NonConstIdx),
5227                        DAG.getIntPtrConstant(NonConstIdx, dl));
5228   }
5229   if (!IsSplat && (NonConstIdx != 0))
5230     llvm_unreachable("Unsupported BUILD_VECTOR operation");
5231   MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
5232   SDValue Select;
5233   if (IsSplat)
5234     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
5235                           DAG.getConstant(-1, dl, SelectVT),
5236                           DAG.getConstant(0, dl, SelectVT));
5237   else
5238     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
5239                          DAG.getConstant((Immediate | 1), dl, SelectVT),
5240                          DAG.getConstant(Immediate, dl, SelectVT));
5241   return DAG.getNode(ISD::BITCAST, dl, VT, Select);
5242 }
5243
5244 /// \brief Return true if \p N implements a horizontal binop and return the
5245 /// operands for the horizontal binop into V0 and V1.
5246 ///
5247 /// This is a helper function of LowerToHorizontalOp().
5248 /// This function checks that the build_vector \p N in input implements a
5249 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
5250 /// operation to match.
5251 /// For example, if \p Opcode is equal to ISD::ADD, then this function
5252 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
5253 /// is equal to ISD::SUB, then this function checks if this is a horizontal
5254 /// arithmetic sub.
5255 ///
5256 /// This function only analyzes elements of \p N whose indices are
5257 /// in range [BaseIdx, LastIdx).
5258 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
5259                               SelectionDAG &DAG,
5260                               unsigned BaseIdx, unsigned LastIdx,
5261                               SDValue &V0, SDValue &V1) {
5262   EVT VT = N->getValueType(0);
5263
5264   assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
5265   assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
5266          "Invalid Vector in input!");
5267
5268   bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
5269   bool CanFold = true;
5270   unsigned ExpectedVExtractIdx = BaseIdx;
5271   unsigned NumElts = LastIdx - BaseIdx;
5272   V0 = DAG.getUNDEF(VT);
5273   V1 = DAG.getUNDEF(VT);
5274
5275   // Check if N implements a horizontal binop.
5276   for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
5277     SDValue Op = N->getOperand(i + BaseIdx);
5278
5279     // Skip UNDEFs.
5280     if (Op->getOpcode() == ISD::UNDEF) {
5281       // Update the expected vector extract index.
5282       if (i * 2 == NumElts)
5283         ExpectedVExtractIdx = BaseIdx;
5284       ExpectedVExtractIdx += 2;
5285       continue;
5286     }
5287
5288     CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
5289
5290     if (!CanFold)
5291       break;
5292
5293     SDValue Op0 = Op.getOperand(0);
5294     SDValue Op1 = Op.getOperand(1);
5295
5296     // Try to match the following pattern:
5297     // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
5298     CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5299         Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5300         Op0.getOperand(0) == Op1.getOperand(0) &&
5301         isa<ConstantSDNode>(Op0.getOperand(1)) &&
5302         isa<ConstantSDNode>(Op1.getOperand(1)));
5303     if (!CanFold)
5304       break;
5305
5306     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5307     unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
5308
5309     if (i * 2 < NumElts) {
5310       if (V0.getOpcode() == ISD::UNDEF) {
5311         V0 = Op0.getOperand(0);
5312         if (V0.getValueType() != VT)
5313           return false;
5314       }
5315     } else {
5316       if (V1.getOpcode() == ISD::UNDEF) {
5317         V1 = Op0.getOperand(0);
5318         if (V1.getValueType() != VT)
5319           return false;
5320       }
5321       if (i * 2 == NumElts)
5322         ExpectedVExtractIdx = BaseIdx;
5323     }
5324
5325     SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
5326     if (I0 == ExpectedVExtractIdx)
5327       CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
5328     else if (IsCommutable && I1 == ExpectedVExtractIdx) {
5329       // Try to match the following dag sequence:
5330       // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
5331       CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
5332     } else
5333       CanFold = false;
5334
5335     ExpectedVExtractIdx += 2;
5336   }
5337
5338   return CanFold;
5339 }
5340
5341 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
5342 /// a concat_vector.
5343 ///
5344 /// This is a helper function of LowerToHorizontalOp().
5345 /// This function expects two 256-bit vectors called V0 and V1.
5346 /// At first, each vector is split into two separate 128-bit vectors.
5347 /// Then, the resulting 128-bit vectors are used to implement two
5348 /// horizontal binary operations.
5349 ///
5350 /// The kind of horizontal binary operation is defined by \p X86Opcode.
5351 ///
5352 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
5353 /// the two new horizontal binop.
5354 /// When Mode is set, the first horizontal binop dag node would take as input
5355 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
5356 /// horizontal binop dag node would take as input the lower 128-bit of V1
5357 /// and the upper 128-bit of V1.
5358 ///   Example:
5359 ///     HADD V0_LO, V0_HI
5360 ///     HADD V1_LO, V1_HI
5361 ///
5362 /// Otherwise, the first horizontal binop dag node takes as input the lower
5363 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
5364 /// dag node takes the the upper 128-bit of V0 and the upper 128-bit of V1.
5365 ///   Example:
5366 ///     HADD V0_LO, V1_LO
5367 ///     HADD V0_HI, V1_HI
5368 ///
5369 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
5370 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
5371 /// the upper 128-bits of the result.
5372 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
5373                                      SDLoc DL, SelectionDAG &DAG,
5374                                      unsigned X86Opcode, bool Mode,
5375                                      bool isUndefLO, bool isUndefHI) {
5376   EVT VT = V0.getValueType();
5377   assert(VT.is256BitVector() && VT == V1.getValueType() &&
5378          "Invalid nodes in input!");
5379
5380   unsigned NumElts = VT.getVectorNumElements();
5381   SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
5382   SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
5383   SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
5384   SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
5385   EVT NewVT = V0_LO.getValueType();
5386
5387   SDValue LO = DAG.getUNDEF(NewVT);
5388   SDValue HI = DAG.getUNDEF(NewVT);
5389
5390   if (Mode) {
5391     // Don't emit a horizontal binop if the result is expected to be UNDEF.
5392     if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
5393       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
5394     if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
5395       HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
5396   } else {
5397     // Don't emit a horizontal binop if the result is expected to be UNDEF.
5398     if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
5399                        V1_LO->getOpcode() != ISD::UNDEF))
5400       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
5401
5402     if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
5403                        V1_HI->getOpcode() != ISD::UNDEF))
5404       HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
5405   }
5406
5407   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
5408 }
5409
5410 /// Try to fold a build_vector that performs an 'addsub' to an X86ISD::ADDSUB
5411 /// node.
5412 static SDValue LowerToAddSub(const BuildVectorSDNode *BV,
5413                              const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5414   EVT VT = BV->getValueType(0);
5415   if ((!Subtarget->hasSSE3() || (VT != MVT::v4f32 && VT != MVT::v2f64)) &&
5416       (!Subtarget->hasAVX() || (VT != MVT::v8f32 && VT != MVT::v4f64)))
5417     return SDValue();
5418
5419   SDLoc DL(BV);
5420   unsigned NumElts = VT.getVectorNumElements();
5421   SDValue InVec0 = DAG.getUNDEF(VT);
5422   SDValue InVec1 = DAG.getUNDEF(VT);
5423
5424   assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
5425           VT == MVT::v2f64) && "build_vector with an invalid type found!");
5426
5427   // Odd-numbered elements in the input build vector are obtained from
5428   // adding two integer/float elements.
5429   // Even-numbered elements in the input build vector are obtained from
5430   // subtracting two integer/float elements.
5431   unsigned ExpectedOpcode = ISD::FSUB;
5432   unsigned NextExpectedOpcode = ISD::FADD;
5433   bool AddFound = false;
5434   bool SubFound = false;
5435
5436   for (unsigned i = 0, e = NumElts; i != e; ++i) {
5437     SDValue Op = BV->getOperand(i);
5438
5439     // Skip 'undef' values.
5440     unsigned Opcode = Op.getOpcode();
5441     if (Opcode == ISD::UNDEF) {
5442       std::swap(ExpectedOpcode, NextExpectedOpcode);
5443       continue;
5444     }
5445
5446     // Early exit if we found an unexpected opcode.
5447     if (Opcode != ExpectedOpcode)
5448       return SDValue();
5449
5450     SDValue Op0 = Op.getOperand(0);
5451     SDValue Op1 = Op.getOperand(1);
5452
5453     // Try to match the following pattern:
5454     // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
5455     // Early exit if we cannot match that sequence.
5456     if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5457         Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5458         !isa<ConstantSDNode>(Op0.getOperand(1)) ||
5459         !isa<ConstantSDNode>(Op1.getOperand(1)) ||
5460         Op0.getOperand(1) != Op1.getOperand(1))
5461       return SDValue();
5462
5463     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5464     if (I0 != i)
5465       return SDValue();
5466
5467     // We found a valid add/sub node. Update the information accordingly.
5468     if (i & 1)
5469       AddFound = true;
5470     else
5471       SubFound = true;
5472
5473     // Update InVec0 and InVec1.
5474     if (InVec0.getOpcode() == ISD::UNDEF) {
5475       InVec0 = Op0.getOperand(0);
5476       if (InVec0.getValueType() != VT)
5477         return SDValue();
5478     }
5479     if (InVec1.getOpcode() == ISD::UNDEF) {
5480       InVec1 = Op1.getOperand(0);
5481       if (InVec1.getValueType() != VT)
5482         return SDValue();
5483     }
5484
5485     // Make sure that operands in input to each add/sub node always
5486     // come from a same pair of vectors.
5487     if (InVec0 != Op0.getOperand(0)) {
5488       if (ExpectedOpcode == ISD::FSUB)
5489         return SDValue();
5490
5491       // FADD is commutable. Try to commute the operands
5492       // and then test again.
5493       std::swap(Op0, Op1);
5494       if (InVec0 != Op0.getOperand(0))
5495         return SDValue();
5496     }
5497
5498     if (InVec1 != Op1.getOperand(0))
5499       return SDValue();
5500
5501     // Update the pair of expected opcodes.
5502     std::swap(ExpectedOpcode, NextExpectedOpcode);
5503   }
5504
5505   // Don't try to fold this build_vector into an ADDSUB if the inputs are undef.
5506   if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
5507       InVec1.getOpcode() != ISD::UNDEF)
5508     return DAG.getNode(X86ISD::ADDSUB, DL, VT, InVec0, InVec1);
5509
5510   return SDValue();
5511 }
5512
5513 /// Lower BUILD_VECTOR to a horizontal add/sub operation if possible.
5514 static SDValue LowerToHorizontalOp(const BuildVectorSDNode *BV,
5515                                    const X86Subtarget *Subtarget,
5516                                    SelectionDAG &DAG) {
5517   EVT VT = BV->getValueType(0);
5518   unsigned NumElts = VT.getVectorNumElements();
5519   unsigned NumUndefsLO = 0;
5520   unsigned NumUndefsHI = 0;
5521   unsigned Half = NumElts/2;
5522
5523   // Count the number of UNDEF operands in the build_vector in input.
5524   for (unsigned i = 0, e = Half; i != e; ++i)
5525     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5526       NumUndefsLO++;
5527
5528   for (unsigned i = Half, e = NumElts; i != e; ++i)
5529     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5530       NumUndefsHI++;
5531
5532   // Early exit if this is either a build_vector of all UNDEFs or all the
5533   // operands but one are UNDEF.
5534   if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
5535     return SDValue();
5536
5537   SDLoc DL(BV);
5538   SDValue InVec0, InVec1;
5539   if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
5540     // Try to match an SSE3 float HADD/HSUB.
5541     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5542       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5543
5544     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5545       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5546   } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
5547     // Try to match an SSSE3 integer HADD/HSUB.
5548     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5549       return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
5550
5551     if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5552       return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
5553   }
5554
5555   if (!Subtarget->hasAVX())
5556     return SDValue();
5557
5558   if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
5559     // Try to match an AVX horizontal add/sub of packed single/double
5560     // precision floating point values from 256-bit vectors.
5561     SDValue InVec2, InVec3;
5562     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
5563         isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
5564         ((InVec0.getOpcode() == ISD::UNDEF ||
5565           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5566         ((InVec1.getOpcode() == ISD::UNDEF ||
5567           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5568       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5569
5570     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
5571         isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
5572         ((InVec0.getOpcode() == ISD::UNDEF ||
5573           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5574         ((InVec1.getOpcode() == ISD::UNDEF ||
5575           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5576       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5577   } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
5578     // Try to match an AVX2 horizontal add/sub of signed integers.
5579     SDValue InVec2, InVec3;
5580     unsigned X86Opcode;
5581     bool CanFold = true;
5582
5583     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
5584         isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
5585         ((InVec0.getOpcode() == ISD::UNDEF ||
5586           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5587         ((InVec1.getOpcode() == ISD::UNDEF ||
5588           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5589       X86Opcode = X86ISD::HADD;
5590     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
5591         isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
5592         ((InVec0.getOpcode() == ISD::UNDEF ||
5593           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5594         ((InVec1.getOpcode() == ISD::UNDEF ||
5595           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5596       X86Opcode = X86ISD::HSUB;
5597     else
5598       CanFold = false;
5599
5600     if (CanFold) {
5601       // Fold this build_vector into a single horizontal add/sub.
5602       // Do this only if the target has AVX2.
5603       if (Subtarget->hasAVX2())
5604         return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
5605
5606       // Do not try to expand this build_vector into a pair of horizontal
5607       // add/sub if we can emit a pair of scalar add/sub.
5608       if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5609         return SDValue();
5610
5611       // Convert this build_vector into a pair of horizontal binop followed by
5612       // a concat vector.
5613       bool isUndefLO = NumUndefsLO == Half;
5614       bool isUndefHI = NumUndefsHI == Half;
5615       return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
5616                                    isUndefLO, isUndefHI);
5617     }
5618   }
5619
5620   if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
5621        VT == MVT::v16i16) && Subtarget->hasAVX()) {
5622     unsigned X86Opcode;
5623     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5624       X86Opcode = X86ISD::HADD;
5625     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5626       X86Opcode = X86ISD::HSUB;
5627     else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5628       X86Opcode = X86ISD::FHADD;
5629     else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5630       X86Opcode = X86ISD::FHSUB;
5631     else
5632       return SDValue();
5633
5634     // Don't try to expand this build_vector into a pair of horizontal add/sub
5635     // if we can simply emit a pair of scalar add/sub.
5636     if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5637       return SDValue();
5638
5639     // Convert this build_vector into two horizontal add/sub followed by
5640     // a concat vector.
5641     bool isUndefLO = NumUndefsLO == Half;
5642     bool isUndefHI = NumUndefsHI == Half;
5643     return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
5644                                  isUndefLO, isUndefHI);
5645   }
5646
5647   return SDValue();
5648 }
5649
5650 SDValue
5651 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5652   SDLoc dl(Op);
5653
5654   MVT VT = Op.getSimpleValueType();
5655   MVT ExtVT = VT.getVectorElementType();
5656   unsigned NumElems = Op.getNumOperands();
5657
5658   // Generate vectors for predicate vectors.
5659   if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
5660     return LowerBUILD_VECTORvXi1(Op, DAG);
5661
5662   // Vectors containing all zeros can be matched by pxor and xorps later
5663   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5664     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5665     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5666     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
5667       return Op;
5668
5669     return getZeroVector(VT, Subtarget, DAG, dl);
5670   }
5671
5672   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5673   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5674   // vpcmpeqd on 256-bit vectors.
5675   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5676     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5677       return Op;
5678
5679     if (!VT.is512BitVector())
5680       return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5681   }
5682
5683   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(Op.getNode());
5684   if (SDValue AddSub = LowerToAddSub(BV, Subtarget, DAG))
5685     return AddSub;
5686   if (SDValue HorizontalOp = LowerToHorizontalOp(BV, Subtarget, DAG))
5687     return HorizontalOp;
5688   if (SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG))
5689     return Broadcast;
5690
5691   unsigned EVTBits = ExtVT.getSizeInBits();
5692
5693   unsigned NumZero  = 0;
5694   unsigned NumNonZero = 0;
5695   unsigned NonZeros = 0;
5696   bool IsAllConstants = true;
5697   SmallSet<SDValue, 8> Values;
5698   for (unsigned i = 0; i < NumElems; ++i) {
5699     SDValue Elt = Op.getOperand(i);
5700     if (Elt.getOpcode() == ISD::UNDEF)
5701       continue;
5702     Values.insert(Elt);
5703     if (Elt.getOpcode() != ISD::Constant &&
5704         Elt.getOpcode() != ISD::ConstantFP)
5705       IsAllConstants = false;
5706     if (X86::isZeroNode(Elt))
5707       NumZero++;
5708     else {
5709       NonZeros |= (1 << i);
5710       NumNonZero++;
5711     }
5712   }
5713
5714   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5715   if (NumNonZero == 0)
5716     return DAG.getUNDEF(VT);
5717
5718   // Special case for single non-zero, non-undef, element.
5719   if (NumNonZero == 1) {
5720     unsigned Idx = countTrailingZeros(NonZeros);
5721     SDValue Item = Op.getOperand(Idx);
5722
5723     // If this is an insertion of an i64 value on x86-32, and if the top bits of
5724     // the value are obviously zero, truncate the value to i32 and do the
5725     // insertion that way.  Only do this if the value is non-constant or if the
5726     // value is a constant being inserted into element 0.  It is cheaper to do
5727     // a constant pool load than it is to do a movd + shuffle.
5728     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5729         (!IsAllConstants || Idx == 0)) {
5730       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5731         // Handle SSE only.
5732         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5733         EVT VecVT = MVT::v4i32;
5734
5735         // Truncate the value (which may itself be a constant) to i32, and
5736         // convert it to a vector with movd (S2V+shuffle to zero extend).
5737         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5738         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5739         return DAG.getNode(
5740             ISD::BITCAST, dl, VT,
5741             getShuffleVectorZeroOrUndef(Item, Idx * 2, true, Subtarget, DAG));
5742       }
5743     }
5744
5745     // If we have a constant or non-constant insertion into the low element of
5746     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5747     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5748     // depending on what the source datatype is.
5749     if (Idx == 0) {
5750       if (NumZero == 0)
5751         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5752
5753       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5754           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5755         if (VT.is512BitVector()) {
5756           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5757           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5758                              Item, DAG.getIntPtrConstant(0, dl));
5759         }
5760         assert((VT.is128BitVector() || VT.is256BitVector()) &&
5761                "Expected an SSE value type!");
5762         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5763         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5764         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5765       }
5766
5767       // We can't directly insert an i8 or i16 into a vector, so zero extend
5768       // it to i32 first.
5769       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5770         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5771         if (VT.is256BitVector()) {
5772           if (Subtarget->hasAVX()) {
5773             Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v8i32, Item);
5774             Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5775           } else {
5776             // Without AVX, we need to extend to a 128-bit vector and then
5777             // insert into the 256-bit vector.
5778             Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5779             SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5780             Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5781           }
5782         } else {
5783           assert(VT.is128BitVector() && "Expected an SSE value type!");
5784           Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5785           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5786         }
5787         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5788       }
5789     }
5790
5791     // Is it a vector logical left shift?
5792     if (NumElems == 2 && Idx == 1 &&
5793         X86::isZeroNode(Op.getOperand(0)) &&
5794         !X86::isZeroNode(Op.getOperand(1))) {
5795       unsigned NumBits = VT.getSizeInBits();
5796       return getVShift(true, VT,
5797                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5798                                    VT, Op.getOperand(1)),
5799                        NumBits/2, DAG, *this, dl);
5800     }
5801
5802     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5803       return SDValue();
5804
5805     // Otherwise, if this is a vector with i32 or f32 elements, and the element
5806     // is a non-constant being inserted into an element other than the low one,
5807     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
5808     // movd/movss) to move this into the low element, then shuffle it into
5809     // place.
5810     if (EVTBits == 32) {
5811       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5812       return getShuffleVectorZeroOrUndef(Item, Idx, NumZero > 0, Subtarget, DAG);
5813     }
5814   }
5815
5816   // Splat is obviously ok. Let legalizer expand it to a shuffle.
5817   if (Values.size() == 1) {
5818     if (EVTBits == 32) {
5819       // Instead of a shuffle like this:
5820       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5821       // Check if it's possible to issue this instead.
5822       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5823       unsigned Idx = countTrailingZeros(NonZeros);
5824       SDValue Item = Op.getOperand(Idx);
5825       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5826         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5827     }
5828     return SDValue();
5829   }
5830
5831   // A vector full of immediates; various special cases are already
5832   // handled, so this is best done with a single constant-pool load.
5833   if (IsAllConstants)
5834     return SDValue();
5835
5836   // For AVX-length vectors, see if we can use a vector load to get all of the
5837   // elements, otherwise build the individual 128-bit pieces and use
5838   // shuffles to put them in place.
5839   if (VT.is256BitVector() || VT.is512BitVector()) {
5840     SmallVector<SDValue, 64> V(Op->op_begin(), Op->op_begin() + NumElems);
5841
5842     // Check for a build vector of consecutive loads.
5843     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
5844       return LD;
5845
5846     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5847
5848     // Build both the lower and upper subvector.
5849     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
5850                                 makeArrayRef(&V[0], NumElems/2));
5851     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
5852                                 makeArrayRef(&V[NumElems / 2], NumElems/2));
5853
5854     // Recreate the wider vector with the lower and upper part.
5855     if (VT.is256BitVector())
5856       return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5857     return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5858   }
5859
5860   // Let legalizer expand 2-wide build_vectors.
5861   if (EVTBits == 64) {
5862     if (NumNonZero == 1) {
5863       // One half is zero or undef.
5864       unsigned Idx = countTrailingZeros(NonZeros);
5865       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5866                                  Op.getOperand(Idx));
5867       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
5868     }
5869     return SDValue();
5870   }
5871
5872   // If element VT is < 32 bits, convert it to inserts into a zero vector.
5873   if (EVTBits == 8 && NumElems == 16)
5874     if (SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5875                                         Subtarget, *this))
5876       return V;
5877
5878   if (EVTBits == 16 && NumElems == 8)
5879     if (SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5880                                       Subtarget, *this))
5881       return V;
5882
5883   // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
5884   if (EVTBits == 32 && NumElems == 4)
5885     if (SDValue V = LowerBuildVectorv4x32(Op, DAG, Subtarget, *this))
5886       return V;
5887
5888   // If element VT is == 32 bits, turn it into a number of shuffles.
5889   SmallVector<SDValue, 8> V(NumElems);
5890   if (NumElems == 4 && NumZero > 0) {
5891     for (unsigned i = 0; i < 4; ++i) {
5892       bool isZero = !(NonZeros & (1 << i));
5893       if (isZero)
5894         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
5895       else
5896         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5897     }
5898
5899     for (unsigned i = 0; i < 2; ++i) {
5900       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5901         default: break;
5902         case 0:
5903           V[i] = V[i*2];  // Must be a zero vector.
5904           break;
5905         case 1:
5906           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5907           break;
5908         case 2:
5909           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5910           break;
5911         case 3:
5912           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5913           break;
5914       }
5915     }
5916
5917     bool Reverse1 = (NonZeros & 0x3) == 2;
5918     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5919     int MaskVec[] = {
5920       Reverse1 ? 1 : 0,
5921       Reverse1 ? 0 : 1,
5922       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
5923       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
5924     };
5925     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5926   }
5927
5928   if (Values.size() > 1 && VT.is128BitVector()) {
5929     // Check for a build vector of consecutive loads.
5930     for (unsigned i = 0; i < NumElems; ++i)
5931       V[i] = Op.getOperand(i);
5932
5933     // Check for elements which are consecutive loads.
5934     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
5935       return LD;
5936
5937     // Check for a build vector from mostly shuffle plus few inserting.
5938     if (SDValue Sh = buildFromShuffleMostly(Op, DAG))
5939       return Sh;
5940
5941     // For SSE 4.1, use insertps to put the high elements into the low element.
5942     if (Subtarget->hasSSE41()) {
5943       SDValue Result;
5944       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5945         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5946       else
5947         Result = DAG.getUNDEF(VT);
5948
5949       for (unsigned i = 1; i < NumElems; ++i) {
5950         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5951         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5952                              Op.getOperand(i), DAG.getIntPtrConstant(i, dl));
5953       }
5954       return Result;
5955     }
5956
5957     // Otherwise, expand into a number of unpckl*, start by extending each of
5958     // our (non-undef) elements to the full vector width with the element in the
5959     // bottom slot of the vector (which generates no code for SSE).
5960     for (unsigned i = 0; i < NumElems; ++i) {
5961       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5962         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5963       else
5964         V[i] = DAG.getUNDEF(VT);
5965     }
5966
5967     // Next, we iteratively mix elements, e.g. for v4f32:
5968     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5969     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5970     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
5971     unsigned EltStride = NumElems >> 1;
5972     while (EltStride != 0) {
5973       for (unsigned i = 0; i < EltStride; ++i) {
5974         // If V[i+EltStride] is undef and this is the first round of mixing,
5975         // then it is safe to just drop this shuffle: V[i] is already in the
5976         // right place, the one element (since it's the first round) being
5977         // inserted as undef can be dropped.  This isn't safe for successive
5978         // rounds because they will permute elements within both vectors.
5979         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5980             EltStride == NumElems/2)
5981           continue;
5982
5983         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5984       }
5985       EltStride >>= 1;
5986     }
5987     return V[0];
5988   }
5989   return SDValue();
5990 }
5991
5992 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5993 // to create 256-bit vectors from two other 128-bit ones.
5994 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5995   SDLoc dl(Op);
5996   MVT ResVT = Op.getSimpleValueType();
5997
5998   assert((ResVT.is256BitVector() ||
5999           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6000
6001   SDValue V1 = Op.getOperand(0);
6002   SDValue V2 = Op.getOperand(1);
6003   unsigned NumElems = ResVT.getVectorNumElements();
6004   if (ResVT.is256BitVector())
6005     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6006
6007   if (Op.getNumOperands() == 4) {
6008     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6009                                 ResVT.getVectorNumElements()/2);
6010     SDValue V3 = Op.getOperand(2);
6011     SDValue V4 = Op.getOperand(3);
6012     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6013       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6014   }
6015   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6016 }
6017
6018 static SDValue LowerCONCAT_VECTORSvXi1(SDValue Op,
6019                                        const X86Subtarget *Subtarget,
6020                                        SelectionDAG & DAG) {
6021   SDLoc dl(Op);
6022   MVT ResVT = Op.getSimpleValueType();
6023   unsigned NumOfOperands = Op.getNumOperands();
6024
6025   assert(isPowerOf2_32(NumOfOperands) &&
6026          "Unexpected number of operands in CONCAT_VECTORS");
6027
6028   if (NumOfOperands > 2) {
6029     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6030                                   ResVT.getVectorNumElements()/2);
6031     SmallVector<SDValue, 2> Ops;
6032     for (unsigned i = 0; i < NumOfOperands/2; i++)
6033       Ops.push_back(Op.getOperand(i));
6034     SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6035     Ops.clear();
6036     for (unsigned i = NumOfOperands/2; i < NumOfOperands; i++)
6037       Ops.push_back(Op.getOperand(i));
6038     SDValue Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6039     return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Lo, Hi);
6040   }
6041
6042   SDValue V1 = Op.getOperand(0);
6043   SDValue V2 = Op.getOperand(1);
6044   bool IsZeroV1 = ISD::isBuildVectorAllZeros(V1.getNode());
6045   bool IsZeroV2 = ISD::isBuildVectorAllZeros(V2.getNode());
6046
6047   if (IsZeroV1 && IsZeroV2)
6048     return getZeroVector(ResVT, Subtarget, DAG, dl);
6049
6050   SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
6051   SDValue Undef = DAG.getUNDEF(ResVT);
6052   unsigned NumElems = ResVT.getVectorNumElements();
6053   SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
6054
6055   V2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V2, ZeroIdx);
6056   V2 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V2, ShiftBits);
6057   if (IsZeroV1)
6058     return V2;
6059
6060   V1 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V1, ZeroIdx);
6061   // Zero the upper bits of V1
6062   V1 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V1, ShiftBits);
6063   V1 = DAG.getNode(X86ISD::VSRLI, dl, ResVT, V1, ShiftBits);
6064   if (IsZeroV2)
6065     return V1;
6066   return DAG.getNode(ISD::OR, dl, ResVT, V1, V2);
6067 }
6068
6069 static SDValue LowerCONCAT_VECTORS(SDValue Op,
6070                                    const X86Subtarget *Subtarget,
6071                                    SelectionDAG &DAG) {
6072   MVT VT = Op.getSimpleValueType();
6073   if (VT.getVectorElementType() == MVT::i1)
6074     return LowerCONCAT_VECTORSvXi1(Op, Subtarget, DAG);
6075
6076   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6077          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6078           Op.getNumOperands() == 4)));
6079
6080   // AVX can use the vinsertf128 instruction to create 256-bit vectors
6081   // from two other 128-bit ones.
6082
6083   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6084   return LowerAVXCONCAT_VECTORS(Op, DAG);
6085 }
6086
6087
6088 //===----------------------------------------------------------------------===//
6089 // Vector shuffle lowering
6090 //
6091 // This is an experimental code path for lowering vector shuffles on x86. It is
6092 // designed to handle arbitrary vector shuffles and blends, gracefully
6093 // degrading performance as necessary. It works hard to recognize idiomatic
6094 // shuffles and lower them to optimal instruction patterns without leaving
6095 // a framework that allows reasonably efficient handling of all vector shuffle
6096 // patterns.
6097 //===----------------------------------------------------------------------===//
6098
6099 /// \brief Tiny helper function to identify a no-op mask.
6100 ///
6101 /// This is a somewhat boring predicate function. It checks whether the mask
6102 /// array input, which is assumed to be a single-input shuffle mask of the kind
6103 /// used by the X86 shuffle instructions (not a fully general
6104 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
6105 /// in-place shuffle are 'no-op's.
6106 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
6107   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6108     if (Mask[i] != -1 && Mask[i] != i)
6109       return false;
6110   return true;
6111 }
6112
6113 /// \brief Helper function to classify a mask as a single-input mask.
6114 ///
6115 /// This isn't a generic single-input test because in the vector shuffle
6116 /// lowering we canonicalize single inputs to be the first input operand. This
6117 /// means we can more quickly test for a single input by only checking whether
6118 /// an input from the second operand exists. We also assume that the size of
6119 /// mask corresponds to the size of the input vectors which isn't true in the
6120 /// fully general case.
6121 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
6122   for (int M : Mask)
6123     if (M >= (int)Mask.size())
6124       return false;
6125   return true;
6126 }
6127
6128 /// \brief Test whether there are elements crossing 128-bit lanes in this
6129 /// shuffle mask.
6130 ///
6131 /// X86 divides up its shuffles into in-lane and cross-lane shuffle operations
6132 /// and we routinely test for these.
6133 static bool is128BitLaneCrossingShuffleMask(MVT VT, ArrayRef<int> Mask) {
6134   int LaneSize = 128 / VT.getScalarSizeInBits();
6135   int Size = Mask.size();
6136   for (int i = 0; i < Size; ++i)
6137     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
6138       return true;
6139   return false;
6140 }
6141
6142 /// \brief Test whether a shuffle mask is equivalent within each 128-bit lane.
6143 ///
6144 /// This checks a shuffle mask to see if it is performing the same
6145 /// 128-bit lane-relative shuffle in each 128-bit lane. This trivially implies
6146 /// that it is also not lane-crossing. It may however involve a blend from the
6147 /// same lane of a second vector.
6148 ///
6149 /// The specific repeated shuffle mask is populated in \p RepeatedMask, as it is
6150 /// non-trivial to compute in the face of undef lanes. The representation is
6151 /// *not* suitable for use with existing 128-bit shuffles as it will contain
6152 /// entries from both V1 and V2 inputs to the wider mask.
6153 static bool
6154 is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
6155                                 SmallVectorImpl<int> &RepeatedMask) {
6156   int LaneSize = 128 / VT.getScalarSizeInBits();
6157   RepeatedMask.resize(LaneSize, -1);
6158   int Size = Mask.size();
6159   for (int i = 0; i < Size; ++i) {
6160     if (Mask[i] < 0)
6161       continue;
6162     if ((Mask[i] % Size) / LaneSize != i / LaneSize)
6163       // This entry crosses lanes, so there is no way to model this shuffle.
6164       return false;
6165
6166     // Ok, handle the in-lane shuffles by detecting if and when they repeat.
6167     if (RepeatedMask[i % LaneSize] == -1)
6168       // This is the first non-undef entry in this slot of a 128-bit lane.
6169       RepeatedMask[i % LaneSize] =
6170           Mask[i] < Size ? Mask[i] % LaneSize : Mask[i] % LaneSize + Size;
6171     else if (RepeatedMask[i % LaneSize] + (i / LaneSize) * LaneSize != Mask[i])
6172       // Found a mismatch with the repeated mask.
6173       return false;
6174   }
6175   return true;
6176 }
6177
6178 /// \brief Checks whether a shuffle mask is equivalent to an explicit list of
6179 /// arguments.
6180 ///
6181 /// This is a fast way to test a shuffle mask against a fixed pattern:
6182 ///
6183 ///   if (isShuffleEquivalent(Mask, 3, 2, {1, 0})) { ... }
6184 ///
6185 /// It returns true if the mask is exactly as wide as the argument list, and
6186 /// each element of the mask is either -1 (signifying undef) or the value given
6187 /// in the argument.
6188 static bool isShuffleEquivalent(SDValue V1, SDValue V2, ArrayRef<int> Mask,
6189                                 ArrayRef<int> ExpectedMask) {
6190   if (Mask.size() != ExpectedMask.size())
6191     return false;
6192
6193   int Size = Mask.size();
6194
6195   // If the values are build vectors, we can look through them to find
6196   // equivalent inputs that make the shuffles equivalent.
6197   auto *BV1 = dyn_cast<BuildVectorSDNode>(V1);
6198   auto *BV2 = dyn_cast<BuildVectorSDNode>(V2);
6199
6200   for (int i = 0; i < Size; ++i)
6201     if (Mask[i] != -1 && Mask[i] != ExpectedMask[i]) {
6202       auto *MaskBV = Mask[i] < Size ? BV1 : BV2;
6203       auto *ExpectedBV = ExpectedMask[i] < Size ? BV1 : BV2;
6204       if (!MaskBV || !ExpectedBV ||
6205           MaskBV->getOperand(Mask[i] % Size) !=
6206               ExpectedBV->getOperand(ExpectedMask[i] % Size))
6207         return false;
6208     }
6209
6210   return true;
6211 }
6212
6213 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
6214 ///
6215 /// This helper function produces an 8-bit shuffle immediate corresponding to
6216 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
6217 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
6218 /// example.
6219 ///
6220 /// NB: We rely heavily on "undef" masks preserving the input lane.
6221 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask, SDLoc DL,
6222                                           SelectionDAG &DAG) {
6223   assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
6224   assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
6225   assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
6226   assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
6227   assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
6228
6229   unsigned Imm = 0;
6230   Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
6231   Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
6232   Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
6233   Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
6234   return DAG.getConstant(Imm, DL, MVT::i8);
6235 }
6236
6237 /// \brief Try to emit a blend instruction for a shuffle using bit math.
6238 ///
6239 /// This is used as a fallback approach when first class blend instructions are
6240 /// unavailable. Currently it is only suitable for integer vectors, but could
6241 /// be generalized for floating point vectors if desirable.
6242 static SDValue lowerVectorShuffleAsBitBlend(SDLoc DL, MVT VT, SDValue V1,
6243                                             SDValue V2, ArrayRef<int> Mask,
6244                                             SelectionDAG &DAG) {
6245   assert(VT.isInteger() && "Only supports integer vector types!");
6246   MVT EltVT = VT.getScalarType();
6247   int NumEltBits = EltVT.getSizeInBits();
6248   SDValue Zero = DAG.getConstant(0, DL, EltVT);
6249   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6250                                     EltVT);
6251   SmallVector<SDValue, 16> MaskOps;
6252   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6253     if (Mask[i] != -1 && Mask[i] != i && Mask[i] != i + Size)
6254       return SDValue(); // Shuffled input!
6255     MaskOps.push_back(Mask[i] < Size ? AllOnes : Zero);
6256   }
6257
6258   SDValue V1Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, MaskOps);
6259   V1 = DAG.getNode(ISD::AND, DL, VT, V1, V1Mask);
6260   // We have to cast V2 around.
6261   MVT MaskVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
6262   V2 = DAG.getNode(ISD::BITCAST, DL, VT,
6263                    DAG.getNode(X86ISD::ANDNP, DL, MaskVT,
6264                                DAG.getNode(ISD::BITCAST, DL, MaskVT, V1Mask),
6265                                DAG.getNode(ISD::BITCAST, DL, MaskVT, V2)));
6266   return DAG.getNode(ISD::OR, DL, VT, V1, V2);
6267 }
6268
6269 /// \brief Try to emit a blend instruction for a shuffle.
6270 ///
6271 /// This doesn't do any checks for the availability of instructions for blending
6272 /// these values. It relies on the availability of the X86ISD::BLENDI pattern to
6273 /// be matched in the backend with the type given. What it does check for is
6274 /// that the shuffle mask is in fact a blend.
6275 static SDValue lowerVectorShuffleAsBlend(SDLoc DL, MVT VT, SDValue V1,
6276                                          SDValue V2, ArrayRef<int> Mask,
6277                                          const X86Subtarget *Subtarget,
6278                                          SelectionDAG &DAG) {
6279   unsigned BlendMask = 0;
6280   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6281     if (Mask[i] >= Size) {
6282       if (Mask[i] != i + Size)
6283         return SDValue(); // Shuffled V2 input!
6284       BlendMask |= 1u << i;
6285       continue;
6286     }
6287     if (Mask[i] >= 0 && Mask[i] != i)
6288       return SDValue(); // Shuffled V1 input!
6289   }
6290   switch (VT.SimpleTy) {
6291   case MVT::v2f64:
6292   case MVT::v4f32:
6293   case MVT::v4f64:
6294   case MVT::v8f32:
6295     return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V2,
6296                        DAG.getConstant(BlendMask, DL, MVT::i8));
6297
6298   case MVT::v4i64:
6299   case MVT::v8i32:
6300     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6301     // FALLTHROUGH
6302   case MVT::v2i64:
6303   case MVT::v4i32:
6304     // If we have AVX2 it is faster to use VPBLENDD when the shuffle fits into
6305     // that instruction.
6306     if (Subtarget->hasAVX2()) {
6307       // Scale the blend by the number of 32-bit dwords per element.
6308       int Scale =  VT.getScalarSizeInBits() / 32;
6309       BlendMask = 0;
6310       for (int i = 0, Size = Mask.size(); i < Size; ++i)
6311         if (Mask[i] >= Size)
6312           for (int j = 0; j < Scale; ++j)
6313             BlendMask |= 1u << (i * Scale + j);
6314
6315       MVT BlendVT = VT.getSizeInBits() > 128 ? MVT::v8i32 : MVT::v4i32;
6316       V1 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V1);
6317       V2 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V2);
6318       return DAG.getNode(ISD::BITCAST, DL, VT,
6319                          DAG.getNode(X86ISD::BLENDI, DL, BlendVT, V1, V2,
6320                                      DAG.getConstant(BlendMask, DL, MVT::i8)));
6321     }
6322     // FALLTHROUGH
6323   case MVT::v8i16: {
6324     // For integer shuffles we need to expand the mask and cast the inputs to
6325     // v8i16s prior to blending.
6326     int Scale = 8 / VT.getVectorNumElements();
6327     BlendMask = 0;
6328     for (int i = 0, Size = Mask.size(); i < Size; ++i)
6329       if (Mask[i] >= Size)
6330         for (int j = 0; j < Scale; ++j)
6331           BlendMask |= 1u << (i * Scale + j);
6332
6333     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1);
6334     V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V2);
6335     return DAG.getNode(ISD::BITCAST, DL, VT,
6336                        DAG.getNode(X86ISD::BLENDI, DL, MVT::v8i16, V1, V2,
6337                                    DAG.getConstant(BlendMask, DL, MVT::i8)));
6338   }
6339
6340   case MVT::v16i16: {
6341     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6342     SmallVector<int, 8> RepeatedMask;
6343     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
6344       // We can lower these with PBLENDW which is mirrored across 128-bit lanes.
6345       assert(RepeatedMask.size() == 8 && "Repeated mask size doesn't match!");
6346       BlendMask = 0;
6347       for (int i = 0; i < 8; ++i)
6348         if (RepeatedMask[i] >= 16)
6349           BlendMask |= 1u << i;
6350       return DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
6351                          DAG.getConstant(BlendMask, DL, MVT::i8));
6352     }
6353   }
6354     // FALLTHROUGH
6355   case MVT::v16i8:
6356   case MVT::v32i8: {
6357     assert((VT.getSizeInBits() == 128 || Subtarget->hasAVX2()) &&
6358            "256-bit byte-blends require AVX2 support!");
6359
6360     // Scale the blend by the number of bytes per element.
6361     int Scale = VT.getScalarSizeInBits() / 8;
6362
6363     // This form of blend is always done on bytes. Compute the byte vector
6364     // type.
6365     MVT BlendVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
6366
6367     // Compute the VSELECT mask. Note that VSELECT is really confusing in the
6368     // mix of LLVM's code generator and the x86 backend. We tell the code
6369     // generator that boolean values in the elements of an x86 vector register
6370     // are -1 for true and 0 for false. We then use the LLVM semantics of 'true'
6371     // mapping a select to operand #1, and 'false' mapping to operand #2. The
6372     // reality in x86 is that vector masks (pre-AVX-512) use only the high bit
6373     // of the element (the remaining are ignored) and 0 in that high bit would
6374     // mean operand #1 while 1 in the high bit would mean operand #2. So while
6375     // the LLVM model for boolean values in vector elements gets the relevant
6376     // bit set, it is set backwards and over constrained relative to x86's
6377     // actual model.
6378     SmallVector<SDValue, 32> VSELECTMask;
6379     for (int i = 0, Size = Mask.size(); i < Size; ++i)
6380       for (int j = 0; j < Scale; ++j)
6381         VSELECTMask.push_back(
6382             Mask[i] < 0 ? DAG.getUNDEF(MVT::i8)
6383                         : DAG.getConstant(Mask[i] < Size ? -1 : 0, DL,
6384                                           MVT::i8));
6385
6386     V1 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V1);
6387     V2 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V2);
6388     return DAG.getNode(
6389         ISD::BITCAST, DL, VT,
6390         DAG.getNode(ISD::VSELECT, DL, BlendVT,
6391                     DAG.getNode(ISD::BUILD_VECTOR, DL, BlendVT, VSELECTMask),
6392                     V1, V2));
6393   }
6394
6395   default:
6396     llvm_unreachable("Not a supported integer vector type!");
6397   }
6398 }
6399
6400 /// \brief Try to lower as a blend of elements from two inputs followed by
6401 /// a single-input permutation.
6402 ///
6403 /// This matches the pattern where we can blend elements from two inputs and
6404 /// then reduce the shuffle to a single-input permutation.
6405 static SDValue lowerVectorShuffleAsBlendAndPermute(SDLoc DL, MVT VT, SDValue V1,
6406                                                    SDValue V2,
6407                                                    ArrayRef<int> Mask,
6408                                                    SelectionDAG &DAG) {
6409   // We build up the blend mask while checking whether a blend is a viable way
6410   // to reduce the shuffle.
6411   SmallVector<int, 32> BlendMask(Mask.size(), -1);
6412   SmallVector<int, 32> PermuteMask(Mask.size(), -1);
6413
6414   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6415     if (Mask[i] < 0)
6416       continue;
6417
6418     assert(Mask[i] < Size * 2 && "Shuffle input is out of bounds.");
6419
6420     if (BlendMask[Mask[i] % Size] == -1)
6421       BlendMask[Mask[i] % Size] = Mask[i];
6422     else if (BlendMask[Mask[i] % Size] != Mask[i])
6423       return SDValue(); // Can't blend in the needed input!
6424
6425     PermuteMask[i] = Mask[i] % Size;
6426   }
6427
6428   SDValue V = DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6429   return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), PermuteMask);
6430 }
6431
6432 /// \brief Generic routine to decompose a shuffle and blend into indepndent
6433 /// blends and permutes.
6434 ///
6435 /// This matches the extremely common pattern for handling combined
6436 /// shuffle+blend operations on newer X86 ISAs where we have very fast blend
6437 /// operations. It will try to pick the best arrangement of shuffles and
6438 /// blends.
6439 static SDValue lowerVectorShuffleAsDecomposedShuffleBlend(SDLoc DL, MVT VT,
6440                                                           SDValue V1,
6441                                                           SDValue V2,
6442                                                           ArrayRef<int> Mask,
6443                                                           SelectionDAG &DAG) {
6444   // Shuffle the input elements into the desired positions in V1 and V2 and
6445   // blend them together.
6446   SmallVector<int, 32> V1Mask(Mask.size(), -1);
6447   SmallVector<int, 32> V2Mask(Mask.size(), -1);
6448   SmallVector<int, 32> BlendMask(Mask.size(), -1);
6449   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6450     if (Mask[i] >= 0 && Mask[i] < Size) {
6451       V1Mask[i] = Mask[i];
6452       BlendMask[i] = i;
6453     } else if (Mask[i] >= Size) {
6454       V2Mask[i] = Mask[i] - Size;
6455       BlendMask[i] = i + Size;
6456     }
6457
6458   // Try to lower with the simpler initial blend strategy unless one of the
6459   // input shuffles would be a no-op. We prefer to shuffle inputs as the
6460   // shuffle may be able to fold with a load or other benefit. However, when
6461   // we'll have to do 2x as many shuffles in order to achieve this, blending
6462   // first is a better strategy.
6463   if (!isNoopShuffleMask(V1Mask) && !isNoopShuffleMask(V2Mask))
6464     if (SDValue BlendPerm =
6465             lowerVectorShuffleAsBlendAndPermute(DL, VT, V1, V2, Mask, DAG))
6466       return BlendPerm;
6467
6468   V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
6469   V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
6470   return DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6471 }
6472
6473 /// \brief Try to lower a vector shuffle as a byte rotation.
6474 ///
6475 /// SSSE3 has a generic PALIGNR instruction in x86 that will do an arbitrary
6476 /// byte-rotation of the concatenation of two vectors; pre-SSSE3 can use
6477 /// a PSRLDQ/PSLLDQ/POR pattern to get a similar effect. This routine will
6478 /// try to generically lower a vector shuffle through such an pattern. It
6479 /// does not check for the profitability of lowering either as PALIGNR or
6480 /// PSRLDQ/PSLLDQ/POR, only whether the mask is valid to lower in that form.
6481 /// This matches shuffle vectors that look like:
6482 ///
6483 ///   v8i16 [11, 12, 13, 14, 15, 0, 1, 2]
6484 ///
6485 /// Essentially it concatenates V1 and V2, shifts right by some number of
6486 /// elements, and takes the low elements as the result. Note that while this is
6487 /// specified as a *right shift* because x86 is little-endian, it is a *left
6488 /// rotate* of the vector lanes.
6489 static SDValue lowerVectorShuffleAsByteRotate(SDLoc DL, MVT VT, SDValue V1,
6490                                               SDValue V2,
6491                                               ArrayRef<int> Mask,
6492                                               const X86Subtarget *Subtarget,
6493                                               SelectionDAG &DAG) {
6494   assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
6495
6496   int NumElts = Mask.size();
6497   int NumLanes = VT.getSizeInBits() / 128;
6498   int NumLaneElts = NumElts / NumLanes;
6499
6500   // We need to detect various ways of spelling a rotation:
6501   //   [11, 12, 13, 14, 15,  0,  1,  2]
6502   //   [-1, 12, 13, 14, -1, -1,  1, -1]
6503   //   [-1, -1, -1, -1, -1, -1,  1,  2]
6504   //   [ 3,  4,  5,  6,  7,  8,  9, 10]
6505   //   [-1,  4,  5,  6, -1, -1,  9, -1]
6506   //   [-1,  4,  5,  6, -1, -1, -1, -1]
6507   int Rotation = 0;
6508   SDValue Lo, Hi;
6509   for (int l = 0; l < NumElts; l += NumLaneElts) {
6510     for (int i = 0; i < NumLaneElts; ++i) {
6511       if (Mask[l + i] == -1)
6512         continue;
6513       assert(Mask[l + i] >= 0 && "Only -1 is a valid negative mask element!");
6514
6515       // Get the mod-Size index and lane correct it.
6516       int LaneIdx = (Mask[l + i] % NumElts) - l;
6517       // Make sure it was in this lane.
6518       if (LaneIdx < 0 || LaneIdx >= NumLaneElts)
6519         return SDValue();
6520
6521       // Determine where a rotated vector would have started.
6522       int StartIdx = i - LaneIdx;
6523       if (StartIdx == 0)
6524         // The identity rotation isn't interesting, stop.
6525         return SDValue();
6526
6527       // If we found the tail of a vector the rotation must be the missing
6528       // front. If we found the head of a vector, it must be how much of the
6529       // head.
6530       int CandidateRotation = StartIdx < 0 ? -StartIdx : NumLaneElts - StartIdx;
6531
6532       if (Rotation == 0)
6533         Rotation = CandidateRotation;
6534       else if (Rotation != CandidateRotation)
6535         // The rotations don't match, so we can't match this mask.
6536         return SDValue();
6537
6538       // Compute which value this mask is pointing at.
6539       SDValue MaskV = Mask[l + i] < NumElts ? V1 : V2;
6540
6541       // Compute which of the two target values this index should be assigned
6542       // to. This reflects whether the high elements are remaining or the low
6543       // elements are remaining.
6544       SDValue &TargetV = StartIdx < 0 ? Hi : Lo;
6545
6546       // Either set up this value if we've not encountered it before, or check
6547       // that it remains consistent.
6548       if (!TargetV)
6549         TargetV = MaskV;
6550       else if (TargetV != MaskV)
6551         // This may be a rotation, but it pulls from the inputs in some
6552         // unsupported interleaving.
6553         return SDValue();
6554     }
6555   }
6556
6557   // Check that we successfully analyzed the mask, and normalize the results.
6558   assert(Rotation != 0 && "Failed to locate a viable rotation!");
6559   assert((Lo || Hi) && "Failed to find a rotated input vector!");
6560   if (!Lo)
6561     Lo = Hi;
6562   else if (!Hi)
6563     Hi = Lo;
6564
6565   // The actual rotate instruction rotates bytes, so we need to scale the
6566   // rotation based on how many bytes are in the vector lane.
6567   int Scale = 16 / NumLaneElts;
6568
6569   // SSSE3 targets can use the palignr instruction.
6570   if (Subtarget->hasSSSE3()) {
6571     // Cast the inputs to i8 vector of correct length to match PALIGNR.
6572     MVT AlignVT = MVT::getVectorVT(MVT::i8, 16 * NumLanes);
6573     Lo = DAG.getNode(ISD::BITCAST, DL, AlignVT, Lo);
6574     Hi = DAG.getNode(ISD::BITCAST, DL, AlignVT, Hi);
6575
6576     return DAG.getNode(ISD::BITCAST, DL, VT,
6577                        DAG.getNode(X86ISD::PALIGNR, DL, AlignVT, Hi, Lo,
6578                                    DAG.getConstant(Rotation * Scale, DL,
6579                                                    MVT::i8)));
6580   }
6581
6582   assert(VT.getSizeInBits() == 128 &&
6583          "Rotate-based lowering only supports 128-bit lowering!");
6584   assert(Mask.size() <= 16 &&
6585          "Can shuffle at most 16 bytes in a 128-bit vector!");
6586
6587   // Default SSE2 implementation
6588   int LoByteShift = 16 - Rotation * Scale;
6589   int HiByteShift = Rotation * Scale;
6590
6591   // Cast the inputs to v2i64 to match PSLLDQ/PSRLDQ.
6592   Lo = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Lo);
6593   Hi = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Hi);
6594
6595   SDValue LoShift = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v2i64, Lo,
6596                                 DAG.getConstant(LoByteShift, DL, MVT::i8));
6597   SDValue HiShift = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v2i64, Hi,
6598                                 DAG.getConstant(HiByteShift, DL, MVT::i8));
6599   return DAG.getNode(ISD::BITCAST, DL, VT,
6600                      DAG.getNode(ISD::OR, DL, MVT::v2i64, LoShift, HiShift));
6601 }
6602
6603 /// \brief Compute whether each element of a shuffle is zeroable.
6604 ///
6605 /// A "zeroable" vector shuffle element is one which can be lowered to zero.
6606 /// Either it is an undef element in the shuffle mask, the element of the input
6607 /// referenced is undef, or the element of the input referenced is known to be
6608 /// zero. Many x86 shuffles can zero lanes cheaply and we often want to handle
6609 /// as many lanes with this technique as possible to simplify the remaining
6610 /// shuffle.
6611 static SmallBitVector computeZeroableShuffleElements(ArrayRef<int> Mask,
6612                                                      SDValue V1, SDValue V2) {
6613   SmallBitVector Zeroable(Mask.size(), false);
6614
6615   while (V1.getOpcode() == ISD::BITCAST)
6616     V1 = V1->getOperand(0);
6617   while (V2.getOpcode() == ISD::BITCAST)
6618     V2 = V2->getOperand(0);
6619
6620   bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
6621   bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
6622
6623   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6624     int M = Mask[i];
6625     // Handle the easy cases.
6626     if (M < 0 || (M >= 0 && M < Size && V1IsZero) || (M >= Size && V2IsZero)) {
6627       Zeroable[i] = true;
6628       continue;
6629     }
6630
6631     // If this is an index into a build_vector node (which has the same number
6632     // of elements), dig out the input value and use it.
6633     SDValue V = M < Size ? V1 : V2;
6634     if (V.getOpcode() != ISD::BUILD_VECTOR || Size != (int)V.getNumOperands())
6635       continue;
6636
6637     SDValue Input = V.getOperand(M % Size);
6638     // The UNDEF opcode check really should be dead code here, but not quite
6639     // worth asserting on (it isn't invalid, just unexpected).
6640     if (Input.getOpcode() == ISD::UNDEF || X86::isZeroNode(Input))
6641       Zeroable[i] = true;
6642   }
6643
6644   return Zeroable;
6645 }
6646
6647 /// \brief Try to emit a bitmask instruction for a shuffle.
6648 ///
6649 /// This handles cases where we can model a blend exactly as a bitmask due to
6650 /// one of the inputs being zeroable.
6651 static SDValue lowerVectorShuffleAsBitMask(SDLoc DL, MVT VT, SDValue V1,
6652                                            SDValue V2, ArrayRef<int> Mask,
6653                                            SelectionDAG &DAG) {
6654   MVT EltVT = VT.getScalarType();
6655   int NumEltBits = EltVT.getSizeInBits();
6656   MVT IntEltVT = MVT::getIntegerVT(NumEltBits);
6657   SDValue Zero = DAG.getConstant(0, DL, IntEltVT);
6658   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6659                                     IntEltVT);
6660   if (EltVT.isFloatingPoint()) {
6661     Zero = DAG.getNode(ISD::BITCAST, DL, EltVT, Zero);
6662     AllOnes = DAG.getNode(ISD::BITCAST, DL, EltVT, AllOnes);
6663   }
6664   SmallVector<SDValue, 16> VMaskOps(Mask.size(), Zero);
6665   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6666   SDValue V;
6667   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6668     if (Zeroable[i])
6669       continue;
6670     if (Mask[i] % Size != i)
6671       return SDValue(); // Not a blend.
6672     if (!V)
6673       V = Mask[i] < Size ? V1 : V2;
6674     else if (V != (Mask[i] < Size ? V1 : V2))
6675       return SDValue(); // Can only let one input through the mask.
6676
6677     VMaskOps[i] = AllOnes;
6678   }
6679   if (!V)
6680     return SDValue(); // No non-zeroable elements!
6681
6682   SDValue VMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, VMaskOps);
6683   V = DAG.getNode(VT.isFloatingPoint()
6684                   ? (unsigned) X86ISD::FAND : (unsigned) ISD::AND,
6685                   DL, VT, V, VMask);
6686   return V;
6687 }
6688
6689 /// \brief Try to lower a vector shuffle as a bit shift (shifts in zeros).
6690 ///
6691 /// Attempts to match a shuffle mask against the PSLL(W/D/Q/DQ) and
6692 /// PSRL(W/D/Q/DQ) SSE2 and AVX2 logical bit-shift instructions. The function
6693 /// matches elements from one of the input vectors shuffled to the left or
6694 /// right with zeroable elements 'shifted in'. It handles both the strictly
6695 /// bit-wise element shifts and the byte shift across an entire 128-bit double
6696 /// quad word lane.
6697 ///
6698 /// PSHL : (little-endian) left bit shift.
6699 /// [ zz, 0, zz,  2 ]
6700 /// [ -1, 4, zz, -1 ]
6701 /// PSRL : (little-endian) right bit shift.
6702 /// [  1, zz,  3, zz]
6703 /// [ -1, -1,  7, zz]
6704 /// PSLLDQ : (little-endian) left byte shift
6705 /// [ zz,  0,  1,  2,  3,  4,  5,  6]
6706 /// [ zz, zz, -1, -1,  2,  3,  4, -1]
6707 /// [ zz, zz, zz, zz, zz, zz, -1,  1]
6708 /// PSRLDQ : (little-endian) right byte shift
6709 /// [  5, 6,  7, zz, zz, zz, zz, zz]
6710 /// [ -1, 5,  6,  7, zz, zz, zz, zz]
6711 /// [  1, 2, -1, -1, -1, -1, zz, zz]
6712 static SDValue lowerVectorShuffleAsShift(SDLoc DL, MVT VT, SDValue V1,
6713                                          SDValue V2, ArrayRef<int> Mask,
6714                                          SelectionDAG &DAG) {
6715   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6716
6717   int Size = Mask.size();
6718   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
6719
6720   auto CheckZeros = [&](int Shift, int Scale, bool Left) {
6721     for (int i = 0; i < Size; i += Scale)
6722       for (int j = 0; j < Shift; ++j)
6723         if (!Zeroable[i + j + (Left ? 0 : (Scale - Shift))])
6724           return false;
6725
6726     return true;
6727   };
6728
6729   auto MatchShift = [&](int Shift, int Scale, bool Left, SDValue V) {
6730     for (int i = 0; i != Size; i += Scale) {
6731       unsigned Pos = Left ? i + Shift : i;
6732       unsigned Low = Left ? i : i + Shift;
6733       unsigned Len = Scale - Shift;
6734       if (!isSequentialOrUndefInRange(Mask, Pos, Len,
6735                                       Low + (V == V1 ? 0 : Size)))
6736         return SDValue();
6737     }
6738
6739     int ShiftEltBits = VT.getScalarSizeInBits() * Scale;
6740     bool ByteShift = ShiftEltBits > 64;
6741     unsigned OpCode = Left ? (ByteShift ? X86ISD::VSHLDQ : X86ISD::VSHLI)
6742                            : (ByteShift ? X86ISD::VSRLDQ : X86ISD::VSRLI);
6743     int ShiftAmt = Shift * VT.getScalarSizeInBits() / (ByteShift ? 8 : 1);
6744
6745     // Normalize the scale for byte shifts to still produce an i64 element
6746     // type.
6747     Scale = ByteShift ? Scale / 2 : Scale;
6748
6749     // We need to round trip through the appropriate type for the shift.
6750     MVT ShiftSVT = MVT::getIntegerVT(VT.getScalarSizeInBits() * Scale);
6751     MVT ShiftVT = MVT::getVectorVT(ShiftSVT, Size / Scale);
6752     assert(DAG.getTargetLoweringInfo().isTypeLegal(ShiftVT) &&
6753            "Illegal integer vector type");
6754     V = DAG.getNode(ISD::BITCAST, DL, ShiftVT, V);
6755
6756     V = DAG.getNode(OpCode, DL, ShiftVT, V,
6757                     DAG.getConstant(ShiftAmt, DL, MVT::i8));
6758     return DAG.getNode(ISD::BITCAST, DL, VT, V);
6759   };
6760
6761   // SSE/AVX supports logical shifts up to 64-bit integers - so we can just
6762   // keep doubling the size of the integer elements up to that. We can
6763   // then shift the elements of the integer vector by whole multiples of
6764   // their width within the elements of the larger integer vector. Test each
6765   // multiple to see if we can find a match with the moved element indices
6766   // and that the shifted in elements are all zeroable.
6767   for (int Scale = 2; Scale * VT.getScalarSizeInBits() <= 128; Scale *= 2)
6768     for (int Shift = 1; Shift != Scale; ++Shift)
6769       for (bool Left : {true, false})
6770         if (CheckZeros(Shift, Scale, Left))
6771           for (SDValue V : {V1, V2})
6772             if (SDValue Match = MatchShift(Shift, Scale, Left, V))
6773               return Match;
6774
6775   // no match
6776   return SDValue();
6777 }
6778
6779 /// \brief Lower a vector shuffle as a zero or any extension.
6780 ///
6781 /// Given a specific number of elements, element bit width, and extension
6782 /// stride, produce either a zero or any extension based on the available
6783 /// features of the subtarget.
6784 static SDValue lowerVectorShuffleAsSpecificZeroOrAnyExtend(
6785     SDLoc DL, MVT VT, int Scale, bool AnyExt, SDValue InputV,
6786     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6787   assert(Scale > 1 && "Need a scale to extend.");
6788   int NumElements = VT.getVectorNumElements();
6789   int EltBits = VT.getScalarSizeInBits();
6790   assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
6791          "Only 8, 16, and 32 bit elements can be extended.");
6792   assert(Scale * EltBits <= 64 && "Cannot zero extend past 64 bits.");
6793
6794   // Found a valid zext mask! Try various lowering strategies based on the
6795   // input type and available ISA extensions.
6796   if (Subtarget->hasSSE41()) {
6797     MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits * Scale),
6798                                  NumElements / Scale);
6799     return DAG.getNode(ISD::BITCAST, DL, VT,
6800                        DAG.getNode(X86ISD::VZEXT, DL, ExtVT, InputV));
6801   }
6802
6803   // For any extends we can cheat for larger element sizes and use shuffle
6804   // instructions that can fold with a load and/or copy.
6805   if (AnyExt && EltBits == 32) {
6806     int PSHUFDMask[4] = {0, -1, 1, -1};
6807     return DAG.getNode(
6808         ISD::BITCAST, DL, VT,
6809         DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
6810                     DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, InputV),
6811                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
6812   }
6813   if (AnyExt && EltBits == 16 && Scale > 2) {
6814     int PSHUFDMask[4] = {0, -1, 0, -1};
6815     InputV = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
6816                          DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, InputV),
6817                          getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG));
6818     int PSHUFHWMask[4] = {1, -1, -1, -1};
6819     return DAG.getNode(
6820         ISD::BITCAST, DL, VT,
6821         DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16,
6822                     DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, InputV),
6823                     getV4X86ShuffleImm8ForMask(PSHUFHWMask, DL, DAG)));
6824   }
6825
6826   // If this would require more than 2 unpack instructions to expand, use
6827   // pshufb when available. We can only use more than 2 unpack instructions
6828   // when zero extending i8 elements which also makes it easier to use pshufb.
6829   if (Scale > 4 && EltBits == 8 && Subtarget->hasSSSE3()) {
6830     assert(NumElements == 16 && "Unexpected byte vector width!");
6831     SDValue PSHUFBMask[16];
6832     for (int i = 0; i < 16; ++i)
6833       PSHUFBMask[i] =
6834           DAG.getConstant((i % Scale == 0) ? i / Scale : 0x80, DL, MVT::i8);
6835     InputV = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, InputV);
6836     return DAG.getNode(ISD::BITCAST, DL, VT,
6837                        DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, InputV,
6838                                    DAG.getNode(ISD::BUILD_VECTOR, DL,
6839                                                MVT::v16i8, PSHUFBMask)));
6840   }
6841
6842   // Otherwise emit a sequence of unpacks.
6843   do {
6844     MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
6845     SDValue Ext = AnyExt ? DAG.getUNDEF(InputVT)
6846                          : getZeroVector(InputVT, Subtarget, DAG, DL);
6847     InputV = DAG.getNode(ISD::BITCAST, DL, InputVT, InputV);
6848     InputV = DAG.getNode(X86ISD::UNPCKL, DL, InputVT, InputV, Ext);
6849     Scale /= 2;
6850     EltBits *= 2;
6851     NumElements /= 2;
6852   } while (Scale > 1);
6853   return DAG.getNode(ISD::BITCAST, DL, VT, InputV);
6854 }
6855
6856 /// \brief Try to lower a vector shuffle as a zero extension on any microarch.
6857 ///
6858 /// This routine will try to do everything in its power to cleverly lower
6859 /// a shuffle which happens to match the pattern of a zero extend. It doesn't
6860 /// check for the profitability of this lowering,  it tries to aggressively
6861 /// match this pattern. It will use all of the micro-architectural details it
6862 /// can to emit an efficient lowering. It handles both blends with all-zero
6863 /// inputs to explicitly zero-extend and undef-lanes (sometimes undef due to
6864 /// masking out later).
6865 ///
6866 /// The reason we have dedicated lowering for zext-style shuffles is that they
6867 /// are both incredibly common and often quite performance sensitive.
6868 static SDValue lowerVectorShuffleAsZeroOrAnyExtend(
6869     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
6870     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6871   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6872
6873   int Bits = VT.getSizeInBits();
6874   int NumElements = VT.getVectorNumElements();
6875   assert(VT.getScalarSizeInBits() <= 32 &&
6876          "Exceeds 32-bit integer zero extension limit");
6877   assert((int)Mask.size() == NumElements && "Unexpected shuffle mask size");
6878
6879   // Define a helper function to check a particular ext-scale and lower to it if
6880   // valid.
6881   auto Lower = [&](int Scale) -> SDValue {
6882     SDValue InputV;
6883     bool AnyExt = true;
6884     for (int i = 0; i < NumElements; ++i) {
6885       if (Mask[i] == -1)
6886         continue; // Valid anywhere but doesn't tell us anything.
6887       if (i % Scale != 0) {
6888         // Each of the extended elements need to be zeroable.
6889         if (!Zeroable[i])
6890           return SDValue();
6891
6892         // We no longer are in the anyext case.
6893         AnyExt = false;
6894         continue;
6895       }
6896
6897       // Each of the base elements needs to be consecutive indices into the
6898       // same input vector.
6899       SDValue V = Mask[i] < NumElements ? V1 : V2;
6900       if (!InputV)
6901         InputV = V;
6902       else if (InputV != V)
6903         return SDValue(); // Flip-flopping inputs.
6904
6905       if (Mask[i] % NumElements != i / Scale)
6906         return SDValue(); // Non-consecutive strided elements.
6907     }
6908
6909     // If we fail to find an input, we have a zero-shuffle which should always
6910     // have already been handled.
6911     // FIXME: Maybe handle this here in case during blending we end up with one?
6912     if (!InputV)
6913       return SDValue();
6914
6915     return lowerVectorShuffleAsSpecificZeroOrAnyExtend(
6916         DL, VT, Scale, AnyExt, InputV, Subtarget, DAG);
6917   };
6918
6919   // The widest scale possible for extending is to a 64-bit integer.
6920   assert(Bits % 64 == 0 &&
6921          "The number of bits in a vector must be divisible by 64 on x86!");
6922   int NumExtElements = Bits / 64;
6923
6924   // Each iteration, try extending the elements half as much, but into twice as
6925   // many elements.
6926   for (; NumExtElements < NumElements; NumExtElements *= 2) {
6927     assert(NumElements % NumExtElements == 0 &&
6928            "The input vector size must be divisible by the extended size.");
6929     if (SDValue V = Lower(NumElements / NumExtElements))
6930       return V;
6931   }
6932
6933   // General extends failed, but 128-bit vectors may be able to use MOVQ.
6934   if (Bits != 128)
6935     return SDValue();
6936
6937   // Returns one of the source operands if the shuffle can be reduced to a
6938   // MOVQ, copying the lower 64-bits and zero-extending to the upper 64-bits.
6939   auto CanZExtLowHalf = [&]() {
6940     for (int i = NumElements / 2; i != NumElements; ++i)
6941       if (!Zeroable[i])
6942         return SDValue();
6943     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, 0))
6944       return V1;
6945     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, NumElements))
6946       return V2;
6947     return SDValue();
6948   };
6949
6950   if (SDValue V = CanZExtLowHalf()) {
6951     V = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, V);
6952     V = DAG.getNode(X86ISD::VZEXT_MOVL, DL, MVT::v2i64, V);
6953     return DAG.getNode(ISD::BITCAST, DL, VT, V);
6954   }
6955
6956   // No viable ext lowering found.
6957   return SDValue();
6958 }
6959
6960 /// \brief Try to get a scalar value for a specific element of a vector.
6961 ///
6962 /// Looks through BUILD_VECTOR and SCALAR_TO_VECTOR nodes to find a scalar.
6963 static SDValue getScalarValueForVectorElement(SDValue V, int Idx,
6964                                               SelectionDAG &DAG) {
6965   MVT VT = V.getSimpleValueType();
6966   MVT EltVT = VT.getVectorElementType();
6967   while (V.getOpcode() == ISD::BITCAST)
6968     V = V.getOperand(0);
6969   // If the bitcasts shift the element size, we can't extract an equivalent
6970   // element from it.
6971   MVT NewVT = V.getSimpleValueType();
6972   if (!NewVT.isVector() || NewVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
6973     return SDValue();
6974
6975   if (V.getOpcode() == ISD::BUILD_VECTOR ||
6976       (Idx == 0 && V.getOpcode() == ISD::SCALAR_TO_VECTOR)) {
6977     // Ensure the scalar operand is the same size as the destination.
6978     // FIXME: Add support for scalar truncation where possible.
6979     SDValue S = V.getOperand(Idx);
6980     if (EltVT.getSizeInBits() == S.getSimpleValueType().getSizeInBits())
6981       return DAG.getNode(ISD::BITCAST, SDLoc(V), EltVT, S);
6982   }
6983
6984   return SDValue();
6985 }
6986
6987 /// \brief Helper to test for a load that can be folded with x86 shuffles.
6988 ///
6989 /// This is particularly important because the set of instructions varies
6990 /// significantly based on whether the operand is a load or not.
6991 static bool isShuffleFoldableLoad(SDValue V) {
6992   while (V.getOpcode() == ISD::BITCAST)
6993     V = V.getOperand(0);
6994
6995   return ISD::isNON_EXTLoad(V.getNode());
6996 }
6997
6998 /// \brief Try to lower insertion of a single element into a zero vector.
6999 ///
7000 /// This is a common pattern that we have especially efficient patterns to lower
7001 /// across all subtarget feature sets.
7002 static SDValue lowerVectorShuffleAsElementInsertion(
7003     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7004     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7005   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7006   MVT ExtVT = VT;
7007   MVT EltVT = VT.getVectorElementType();
7008
7009   int V2Index = std::find_if(Mask.begin(), Mask.end(),
7010                              [&Mask](int M) { return M >= (int)Mask.size(); }) -
7011                 Mask.begin();
7012   bool IsV1Zeroable = true;
7013   for (int i = 0, Size = Mask.size(); i < Size; ++i)
7014     if (i != V2Index && !Zeroable[i]) {
7015       IsV1Zeroable = false;
7016       break;
7017     }
7018
7019   // Check for a single input from a SCALAR_TO_VECTOR node.
7020   // FIXME: All of this should be canonicalized into INSERT_VECTOR_ELT and
7021   // all the smarts here sunk into that routine. However, the current
7022   // lowering of BUILD_VECTOR makes that nearly impossible until the old
7023   // vector shuffle lowering is dead.
7024   if (SDValue V2S = getScalarValueForVectorElement(
7025           V2, Mask[V2Index] - Mask.size(), DAG)) {
7026     // We need to zext the scalar if it is smaller than an i32.
7027     V2S = DAG.getNode(ISD::BITCAST, DL, EltVT, V2S);
7028     if (EltVT == MVT::i8 || EltVT == MVT::i16) {
7029       // Using zext to expand a narrow element won't work for non-zero
7030       // insertions.
7031       if (!IsV1Zeroable)
7032         return SDValue();
7033
7034       // Zero-extend directly to i32.
7035       ExtVT = MVT::v4i32;
7036       V2S = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, V2S);
7037     }
7038     V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
7039   } else if (Mask[V2Index] != (int)Mask.size() || EltVT == MVT::i8 ||
7040              EltVT == MVT::i16) {
7041     // Either not inserting from the low element of the input or the input
7042     // element size is too small to use VZEXT_MOVL to clear the high bits.
7043     return SDValue();
7044   }
7045
7046   if (!IsV1Zeroable) {
7047     // If V1 can't be treated as a zero vector we have fewer options to lower
7048     // this. We can't support integer vectors or non-zero targets cheaply, and
7049     // the V1 elements can't be permuted in any way.
7050     assert(VT == ExtVT && "Cannot change extended type when non-zeroable!");
7051     if (!VT.isFloatingPoint() || V2Index != 0)
7052       return SDValue();
7053     SmallVector<int, 8> V1Mask(Mask.begin(), Mask.end());
7054     V1Mask[V2Index] = -1;
7055     if (!isNoopShuffleMask(V1Mask))
7056       return SDValue();
7057     // This is essentially a special case blend operation, but if we have
7058     // general purpose blend operations, they are always faster. Bail and let
7059     // the rest of the lowering handle these as blends.
7060     if (Subtarget->hasSSE41())
7061       return SDValue();
7062
7063     // Otherwise, use MOVSD or MOVSS.
7064     assert((EltVT == MVT::f32 || EltVT == MVT::f64) &&
7065            "Only two types of floating point element types to handle!");
7066     return DAG.getNode(EltVT == MVT::f32 ? X86ISD::MOVSS : X86ISD::MOVSD, DL,
7067                        ExtVT, V1, V2);
7068   }
7069
7070   // This lowering only works for the low element with floating point vectors.
7071   if (VT.isFloatingPoint() && V2Index != 0)
7072     return SDValue();
7073
7074   V2 = DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2);
7075   if (ExtVT != VT)
7076     V2 = DAG.getNode(ISD::BITCAST, DL, VT, V2);
7077
7078   if (V2Index != 0) {
7079     // If we have 4 or fewer lanes we can cheaply shuffle the element into
7080     // the desired position. Otherwise it is more efficient to do a vector
7081     // shift left. We know that we can do a vector shift left because all
7082     // the inputs are zero.
7083     if (VT.isFloatingPoint() || VT.getVectorNumElements() <= 4) {
7084       SmallVector<int, 4> V2Shuffle(Mask.size(), 1);
7085       V2Shuffle[V2Index] = 0;
7086       V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Shuffle);
7087     } else {
7088       V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, V2);
7089       V2 = DAG.getNode(
7090           X86ISD::VSHLDQ, DL, MVT::v2i64, V2,
7091           DAG.getConstant(
7092               V2Index * EltVT.getSizeInBits()/8, DL,
7093               DAG.getTargetLoweringInfo().getScalarShiftAmountTy(MVT::v2i64)));
7094       V2 = DAG.getNode(ISD::BITCAST, DL, VT, V2);
7095     }
7096   }
7097   return V2;
7098 }
7099
7100 /// \brief Try to lower broadcast of a single element.
7101 ///
7102 /// For convenience, this code also bundles all of the subtarget feature set
7103 /// filtering. While a little annoying to re-dispatch on type here, there isn't
7104 /// a convenient way to factor it out.
7105 static SDValue lowerVectorShuffleAsBroadcast(SDLoc DL, MVT VT, SDValue V,
7106                                              ArrayRef<int> Mask,
7107                                              const X86Subtarget *Subtarget,
7108                                              SelectionDAG &DAG) {
7109   if (!Subtarget->hasAVX())
7110     return SDValue();
7111   if (VT.isInteger() && !Subtarget->hasAVX2())
7112     return SDValue();
7113
7114   // Check that the mask is a broadcast.
7115   int BroadcastIdx = -1;
7116   for (int M : Mask)
7117     if (M >= 0 && BroadcastIdx == -1)
7118       BroadcastIdx = M;
7119     else if (M >= 0 && M != BroadcastIdx)
7120       return SDValue();
7121
7122   assert(BroadcastIdx < (int)Mask.size() && "We only expect to be called with "
7123                                             "a sorted mask where the broadcast "
7124                                             "comes from V1.");
7125
7126   // Go up the chain of (vector) values to find a scalar load that we can
7127   // combine with the broadcast.
7128   for (;;) {
7129     switch (V.getOpcode()) {
7130     case ISD::CONCAT_VECTORS: {
7131       int OperandSize = Mask.size() / V.getNumOperands();
7132       V = V.getOperand(BroadcastIdx / OperandSize);
7133       BroadcastIdx %= OperandSize;
7134       continue;
7135     }
7136
7137     case ISD::INSERT_SUBVECTOR: {
7138       SDValue VOuter = V.getOperand(0), VInner = V.getOperand(1);
7139       auto ConstantIdx = dyn_cast<ConstantSDNode>(V.getOperand(2));
7140       if (!ConstantIdx)
7141         break;
7142
7143       int BeginIdx = (int)ConstantIdx->getZExtValue();
7144       int EndIdx =
7145           BeginIdx + (int)VInner.getValueType().getVectorNumElements();
7146       if (BroadcastIdx >= BeginIdx && BroadcastIdx < EndIdx) {
7147         BroadcastIdx -= BeginIdx;
7148         V = VInner;
7149       } else {
7150         V = VOuter;
7151       }
7152       continue;
7153     }
7154     }
7155     break;
7156   }
7157
7158   // Check if this is a broadcast of a scalar. We special case lowering
7159   // for scalars so that we can more effectively fold with loads.
7160   if (V.getOpcode() == ISD::BUILD_VECTOR ||
7161       (V.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)) {
7162     V = V.getOperand(BroadcastIdx);
7163
7164     // If the scalar isn't a load, we can't broadcast from it in AVX1.
7165     // Only AVX2 has register broadcasts.
7166     if (!Subtarget->hasAVX2() && !isShuffleFoldableLoad(V))
7167       return SDValue();
7168   } else if (BroadcastIdx != 0 || !Subtarget->hasAVX2()) {
7169     // We can't broadcast from a vector register without AVX2, and we can only
7170     // broadcast from the zero-element of a vector register.
7171     return SDValue();
7172   }
7173
7174   return DAG.getNode(X86ISD::VBROADCAST, DL, VT, V);
7175 }
7176
7177 // Check for whether we can use INSERTPS to perform the shuffle. We only use
7178 // INSERTPS when the V1 elements are already in the correct locations
7179 // because otherwise we can just always use two SHUFPS instructions which
7180 // are much smaller to encode than a SHUFPS and an INSERTPS. We can also
7181 // perform INSERTPS if a single V1 element is out of place and all V2
7182 // elements are zeroable.
7183 static SDValue lowerVectorShuffleAsInsertPS(SDValue Op, SDValue V1, SDValue V2,
7184                                             ArrayRef<int> Mask,
7185                                             SelectionDAG &DAG) {
7186   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7187   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7188   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7189   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7190
7191   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7192
7193   unsigned ZMask = 0;
7194   int V1DstIndex = -1;
7195   int V2DstIndex = -1;
7196   bool V1UsedInPlace = false;
7197
7198   for (int i = 0; i < 4; ++i) {
7199     // Synthesize a zero mask from the zeroable elements (includes undefs).
7200     if (Zeroable[i]) {
7201       ZMask |= 1 << i;
7202       continue;
7203     }
7204
7205     // Flag if we use any V1 inputs in place.
7206     if (i == Mask[i]) {
7207       V1UsedInPlace = true;
7208       continue;
7209     }
7210
7211     // We can only insert a single non-zeroable element.
7212     if (V1DstIndex != -1 || V2DstIndex != -1)
7213       return SDValue();
7214
7215     if (Mask[i] < 4) {
7216       // V1 input out of place for insertion.
7217       V1DstIndex = i;
7218     } else {
7219       // V2 input for insertion.
7220       V2DstIndex = i;
7221     }
7222   }
7223
7224   // Don't bother if we have no (non-zeroable) element for insertion.
7225   if (V1DstIndex == -1 && V2DstIndex == -1)
7226     return SDValue();
7227
7228   // Determine element insertion src/dst indices. The src index is from the
7229   // start of the inserted vector, not the start of the concatenated vector.
7230   unsigned V2SrcIndex = 0;
7231   if (V1DstIndex != -1) {
7232     // If we have a V1 input out of place, we use V1 as the V2 element insertion
7233     // and don't use the original V2 at all.
7234     V2SrcIndex = Mask[V1DstIndex];
7235     V2DstIndex = V1DstIndex;
7236     V2 = V1;
7237   } else {
7238     V2SrcIndex = Mask[V2DstIndex] - 4;
7239   }
7240
7241   // If no V1 inputs are used in place, then the result is created only from
7242   // the zero mask and the V2 insertion - so remove V1 dependency.
7243   if (!V1UsedInPlace)
7244     V1 = DAG.getUNDEF(MVT::v4f32);
7245
7246   unsigned InsertPSMask = V2SrcIndex << 6 | V2DstIndex << 4 | ZMask;
7247   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
7248
7249   // Insert the V2 element into the desired position.
7250   SDLoc DL(Op);
7251   return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
7252                      DAG.getConstant(InsertPSMask, DL, MVT::i8));
7253 }
7254
7255 /// \brief Try to lower a shuffle as a permute of the inputs followed by an
7256 /// UNPCK instruction.
7257 ///
7258 /// This specifically targets cases where we end up with alternating between
7259 /// the two inputs, and so can permute them into something that feeds a single
7260 /// UNPCK instruction. Note that this routine only targets integer vectors
7261 /// because for floating point vectors we have a generalized SHUFPS lowering
7262 /// strategy that handles everything that doesn't *exactly* match an unpack,
7263 /// making this clever lowering unnecessary.
7264 static SDValue lowerVectorShuffleAsUnpack(SDLoc DL, MVT VT, SDValue V1,
7265                                           SDValue V2, ArrayRef<int> Mask,
7266                                           SelectionDAG &DAG) {
7267   assert(!VT.isFloatingPoint() &&
7268          "This routine only supports integer vectors.");
7269   assert(!isSingleInputShuffleMask(Mask) &&
7270          "This routine should only be used when blending two inputs.");
7271   assert(Mask.size() >= 2 && "Single element masks are invalid.");
7272
7273   int Size = Mask.size();
7274
7275   int NumLoInputs = std::count_if(Mask.begin(), Mask.end(), [Size](int M) {
7276     return M >= 0 && M % Size < Size / 2;
7277   });
7278   int NumHiInputs = std::count_if(
7279       Mask.begin(), Mask.end(), [Size](int M) { return M % Size >= Size / 2; });
7280
7281   bool UnpackLo = NumLoInputs >= NumHiInputs;
7282
7283   auto TryUnpack = [&](MVT UnpackVT, int Scale) {
7284     SmallVector<int, 32> V1Mask(Mask.size(), -1);
7285     SmallVector<int, 32> V2Mask(Mask.size(), -1);
7286
7287     for (int i = 0; i < Size; ++i) {
7288       if (Mask[i] < 0)
7289         continue;
7290
7291       // Each element of the unpack contains Scale elements from this mask.
7292       int UnpackIdx = i / Scale;
7293
7294       // We only handle the case where V1 feeds the first slots of the unpack.
7295       // We rely on canonicalization to ensure this is the case.
7296       if ((UnpackIdx % 2 == 0) != (Mask[i] < Size))
7297         return SDValue();
7298
7299       // Setup the mask for this input. The indexing is tricky as we have to
7300       // handle the unpack stride.
7301       SmallVectorImpl<int> &VMask = (UnpackIdx % 2 == 0) ? V1Mask : V2Mask;
7302       VMask[(UnpackIdx / 2) * Scale + i % Scale + (UnpackLo ? 0 : Size / 2)] =
7303           Mask[i] % Size;
7304     }
7305
7306     // If we will have to shuffle both inputs to use the unpack, check whether
7307     // we can just unpack first and shuffle the result. If so, skip this unpack.
7308     if ((NumLoInputs == 0 || NumHiInputs == 0) && !isNoopShuffleMask(V1Mask) &&
7309         !isNoopShuffleMask(V2Mask))
7310       return SDValue();
7311
7312     // Shuffle the inputs into place.
7313     V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
7314     V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
7315
7316     // Cast the inputs to the type we will use to unpack them.
7317     V1 = DAG.getNode(ISD::BITCAST, DL, UnpackVT, V1);
7318     V2 = DAG.getNode(ISD::BITCAST, DL, UnpackVT, V2);
7319
7320     // Unpack the inputs and cast the result back to the desired type.
7321     return DAG.getNode(ISD::BITCAST, DL, VT,
7322                        DAG.getNode(UnpackLo ? X86ISD::UNPCKL : X86ISD::UNPCKH,
7323                                    DL, UnpackVT, V1, V2));
7324   };
7325
7326   // We try each unpack from the largest to the smallest to try and find one
7327   // that fits this mask.
7328   int OrigNumElements = VT.getVectorNumElements();
7329   int OrigScalarSize = VT.getScalarSizeInBits();
7330   for (int ScalarSize = 64; ScalarSize >= OrigScalarSize; ScalarSize /= 2) {
7331     int Scale = ScalarSize / OrigScalarSize;
7332     int NumElements = OrigNumElements / Scale;
7333     MVT UnpackVT = MVT::getVectorVT(MVT::getIntegerVT(ScalarSize), NumElements);
7334     if (SDValue Unpack = TryUnpack(UnpackVT, Scale))
7335       return Unpack;
7336   }
7337
7338   // If none of the unpack-rooted lowerings worked (or were profitable) try an
7339   // initial unpack.
7340   if (NumLoInputs == 0 || NumHiInputs == 0) {
7341     assert((NumLoInputs > 0 || NumHiInputs > 0) &&
7342            "We have to have *some* inputs!");
7343     int HalfOffset = NumLoInputs == 0 ? Size / 2 : 0;
7344
7345     // FIXME: We could consider the total complexity of the permute of each
7346     // possible unpacking. Or at the least we should consider how many
7347     // half-crossings are created.
7348     // FIXME: We could consider commuting the unpacks.
7349
7350     SmallVector<int, 32> PermMask;
7351     PermMask.assign(Size, -1);
7352     for (int i = 0; i < Size; ++i) {
7353       if (Mask[i] < 0)
7354         continue;
7355
7356       assert(Mask[i] % Size >= HalfOffset && "Found input from wrong half!");
7357
7358       PermMask[i] =
7359           2 * ((Mask[i] % Size) - HalfOffset) + (Mask[i] < Size ? 0 : 1);
7360     }
7361     return DAG.getVectorShuffle(
7362         VT, DL, DAG.getNode(NumLoInputs == 0 ? X86ISD::UNPCKH : X86ISD::UNPCKL,
7363                             DL, VT, V1, V2),
7364         DAG.getUNDEF(VT), PermMask);
7365   }
7366
7367   return SDValue();
7368 }
7369
7370 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
7371 ///
7372 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
7373 /// support for floating point shuffles but not integer shuffles. These
7374 /// instructions will incur a domain crossing penalty on some chips though so
7375 /// it is better to avoid lowering through this for integer vectors where
7376 /// possible.
7377 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7378                                        const X86Subtarget *Subtarget,
7379                                        SelectionDAG &DAG) {
7380   SDLoc DL(Op);
7381   assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
7382   assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7383   assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7384   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7385   ArrayRef<int> Mask = SVOp->getMask();
7386   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7387
7388   if (isSingleInputShuffleMask(Mask)) {
7389     // Use low duplicate instructions for masks that match their pattern.
7390     if (Subtarget->hasSSE3())
7391       if (isShuffleEquivalent(V1, V2, Mask, {0, 0}))
7392         return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v2f64, V1);
7393
7394     // Straight shuffle of a single input vector. Simulate this by using the
7395     // single input as both of the "inputs" to this instruction..
7396     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
7397
7398     if (Subtarget->hasAVX()) {
7399       // If we have AVX, we can use VPERMILPS which will allow folding a load
7400       // into the shuffle.
7401       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v2f64, V1,
7402                          DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7403     }
7404
7405     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V1,
7406                        DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7407   }
7408   assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
7409   assert(Mask[1] >= 2 && "Non-canonicalized blend!");
7410
7411   // If we have a single input, insert that into V1 if we can do so cheaply.
7412   if ((Mask[0] >= 2) + (Mask[1] >= 2) == 1) {
7413     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7414             DL, MVT::v2f64, V1, V2, Mask, Subtarget, DAG))
7415       return Insertion;
7416     // Try inverting the insertion since for v2 masks it is easy to do and we
7417     // can't reliably sort the mask one way or the other.
7418     int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
7419                           Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
7420     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7421             DL, MVT::v2f64, V2, V1, InverseMask, Subtarget, DAG))
7422       return Insertion;
7423   }
7424
7425   // Try to use one of the special instruction patterns to handle two common
7426   // blend patterns if a zero-blend above didn't work.
7427   if (isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
7428       isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7429     if (SDValue V1S = getScalarValueForVectorElement(V1, Mask[0], DAG))
7430       // We can either use a special instruction to load over the low double or
7431       // to move just the low double.
7432       return DAG.getNode(
7433           isShuffleFoldableLoad(V1S) ? X86ISD::MOVLPD : X86ISD::MOVSD,
7434           DL, MVT::v2f64, V2,
7435           DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V1S));
7436
7437   if (Subtarget->hasSSE41())
7438     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2f64, V1, V2, Mask,
7439                                                   Subtarget, DAG))
7440       return Blend;
7441
7442   // Use dedicated unpack instructions for masks that match their pattern.
7443   if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7444     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2f64, V1, V2);
7445   if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7446     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2f64, V1, V2);
7447
7448   unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
7449   return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V2,
7450                      DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7451 }
7452
7453 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
7454 ///
7455 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
7456 /// the integer unit to minimize domain crossing penalties. However, for blends
7457 /// it falls back to the floating point shuffle operation with appropriate bit
7458 /// casting.
7459 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7460                                        const X86Subtarget *Subtarget,
7461                                        SelectionDAG &DAG) {
7462   SDLoc DL(Op);
7463   assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
7464   assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7465   assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7466   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7467   ArrayRef<int> Mask = SVOp->getMask();
7468   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7469
7470   if (isSingleInputShuffleMask(Mask)) {
7471     // Check for being able to broadcast a single element.
7472     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v2i64, V1,
7473                                                           Mask, Subtarget, DAG))
7474       return Broadcast;
7475
7476     // Straight shuffle of a single input vector. For everything from SSE2
7477     // onward this has a single fast instruction with no scary immediates.
7478     // We have to map the mask as it is actually a v4i32 shuffle instruction.
7479     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V1);
7480     int WidenedMask[4] = {
7481         std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
7482         std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
7483     return DAG.getNode(
7484         ISD::BITCAST, DL, MVT::v2i64,
7485         DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
7486                     getV4X86ShuffleImm8ForMask(WidenedMask, DL, DAG)));
7487   }
7488   assert(Mask[0] != -1 && "No undef lanes in multi-input v2 shuffles!");
7489   assert(Mask[1] != -1 && "No undef lanes in multi-input v2 shuffles!");
7490   assert(Mask[0] < 2 && "We sort V1 to be the first input.");
7491   assert(Mask[1] >= 2 && "We sort V2 to be the second input.");
7492
7493   // If we have a blend of two PACKUS operations an the blend aligns with the
7494   // low and half halves, we can just merge the PACKUS operations. This is
7495   // particularly important as it lets us merge shuffles that this routine itself
7496   // creates.
7497   auto GetPackNode = [](SDValue V) {
7498     while (V.getOpcode() == ISD::BITCAST)
7499       V = V.getOperand(0);
7500
7501     return V.getOpcode() == X86ISD::PACKUS ? V : SDValue();
7502   };
7503   if (SDValue V1Pack = GetPackNode(V1))
7504     if (SDValue V2Pack = GetPackNode(V2))
7505       return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7506                          DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8,
7507                                      Mask[0] == 0 ? V1Pack.getOperand(0)
7508                                                   : V1Pack.getOperand(1),
7509                                      Mask[1] == 2 ? V2Pack.getOperand(0)
7510                                                   : V2Pack.getOperand(1)));
7511
7512   // Try to use shift instructions.
7513   if (SDValue Shift =
7514           lowerVectorShuffleAsShift(DL, MVT::v2i64, V1, V2, Mask, DAG))
7515     return Shift;
7516
7517   // When loading a scalar and then shuffling it into a vector we can often do
7518   // the insertion cheaply.
7519   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7520           DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
7521     return Insertion;
7522   // Try inverting the insertion since for v2 masks it is easy to do and we
7523   // can't reliably sort the mask one way or the other.
7524   int InverseMask[2] = {Mask[0] ^ 2, Mask[1] ^ 2};
7525   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7526           DL, MVT::v2i64, V2, V1, InverseMask, Subtarget, DAG))
7527     return Insertion;
7528
7529   // We have different paths for blend lowering, but they all must use the
7530   // *exact* same predicate.
7531   bool IsBlendSupported = Subtarget->hasSSE41();
7532   if (IsBlendSupported)
7533     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2i64, V1, V2, Mask,
7534                                                   Subtarget, DAG))
7535       return Blend;
7536
7537   // Use dedicated unpack instructions for masks that match their pattern.
7538   if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7539     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, V1, V2);
7540   if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7541     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2i64, V1, V2);
7542
7543   // Try to use byte rotation instructions.
7544   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
7545   if (Subtarget->hasSSSE3())
7546     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
7547             DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
7548       return Rotate;
7549
7550   // If we have direct support for blends, we should lower by decomposing into
7551   // a permute. That will be faster than the domain cross.
7552   if (IsBlendSupported)
7553     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v2i64, V1, V2,
7554                                                       Mask, DAG);
7555
7556   // We implement this with SHUFPD which is pretty lame because it will likely
7557   // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
7558   // However, all the alternatives are still more cycles and newer chips don't
7559   // have this problem. It would be really nice if x86 had better shuffles here.
7560   V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V1);
7561   V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V2);
7562   return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7563                      DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
7564 }
7565
7566 /// \brief Test whether this can be lowered with a single SHUFPS instruction.
7567 ///
7568 /// This is used to disable more specialized lowerings when the shufps lowering
7569 /// will happen to be efficient.
7570 static bool isSingleSHUFPSMask(ArrayRef<int> Mask) {
7571   // This routine only handles 128-bit shufps.
7572   assert(Mask.size() == 4 && "Unsupported mask size!");
7573
7574   // To lower with a single SHUFPS we need to have the low half and high half
7575   // each requiring a single input.
7576   if (Mask[0] != -1 && Mask[1] != -1 && (Mask[0] < 4) != (Mask[1] < 4))
7577     return false;
7578   if (Mask[2] != -1 && Mask[3] != -1 && (Mask[2] < 4) != (Mask[3] < 4))
7579     return false;
7580
7581   return true;
7582 }
7583
7584 /// \brief Lower a vector shuffle using the SHUFPS instruction.
7585 ///
7586 /// This is a helper routine dedicated to lowering vector shuffles using SHUFPS.
7587 /// It makes no assumptions about whether this is the *best* lowering, it simply
7588 /// uses it.
7589 static SDValue lowerVectorShuffleWithSHUFPS(SDLoc DL, MVT VT,
7590                                             ArrayRef<int> Mask, SDValue V1,
7591                                             SDValue V2, SelectionDAG &DAG) {
7592   SDValue LowV = V1, HighV = V2;
7593   int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
7594
7595   int NumV2Elements =
7596       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7597
7598   if (NumV2Elements == 1) {
7599     int V2Index =
7600         std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
7601         Mask.begin();
7602
7603     // Compute the index adjacent to V2Index and in the same half by toggling
7604     // the low bit.
7605     int V2AdjIndex = V2Index ^ 1;
7606
7607     if (Mask[V2AdjIndex] == -1) {
7608       // Handles all the cases where we have a single V2 element and an undef.
7609       // This will only ever happen in the high lanes because we commute the
7610       // vector otherwise.
7611       if (V2Index < 2)
7612         std::swap(LowV, HighV);
7613       NewMask[V2Index] -= 4;
7614     } else {
7615       // Handle the case where the V2 element ends up adjacent to a V1 element.
7616       // To make this work, blend them together as the first step.
7617       int V1Index = V2AdjIndex;
7618       int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
7619       V2 = DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
7620                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
7621
7622       // Now proceed to reconstruct the final blend as we have the necessary
7623       // high or low half formed.
7624       if (V2Index < 2) {
7625         LowV = V2;
7626         HighV = V1;
7627       } else {
7628         HighV = V2;
7629       }
7630       NewMask[V1Index] = 2; // We put the V1 element in V2[2].
7631       NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
7632     }
7633   } else if (NumV2Elements == 2) {
7634     if (Mask[0] < 4 && Mask[1] < 4) {
7635       // Handle the easy case where we have V1 in the low lanes and V2 in the
7636       // high lanes.
7637       NewMask[2] -= 4;
7638       NewMask[3] -= 4;
7639     } else if (Mask[2] < 4 && Mask[3] < 4) {
7640       // We also handle the reversed case because this utility may get called
7641       // when we detect a SHUFPS pattern but can't easily commute the shuffle to
7642       // arrange things in the right direction.
7643       NewMask[0] -= 4;
7644       NewMask[1] -= 4;
7645       HighV = V1;
7646       LowV = V2;
7647     } else {
7648       // We have a mixture of V1 and V2 in both low and high lanes. Rather than
7649       // trying to place elements directly, just blend them and set up the final
7650       // shuffle to place them.
7651
7652       // The first two blend mask elements are for V1, the second two are for
7653       // V2.
7654       int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
7655                           Mask[2] < 4 ? Mask[2] : Mask[3],
7656                           (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
7657                           (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
7658       V1 = DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
7659                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
7660
7661       // Now we do a normal shuffle of V1 by giving V1 as both operands to
7662       // a blend.
7663       LowV = HighV = V1;
7664       NewMask[0] = Mask[0] < 4 ? 0 : 2;
7665       NewMask[1] = Mask[0] < 4 ? 2 : 0;
7666       NewMask[2] = Mask[2] < 4 ? 1 : 3;
7667       NewMask[3] = Mask[2] < 4 ? 3 : 1;
7668     }
7669   }
7670   return DAG.getNode(X86ISD::SHUFP, DL, VT, LowV, HighV,
7671                      getV4X86ShuffleImm8ForMask(NewMask, DL, DAG));
7672 }
7673
7674 /// \brief Lower 4-lane 32-bit floating point shuffles.
7675 ///
7676 /// Uses instructions exclusively from the floating point unit to minimize
7677 /// domain crossing penalties, as these are sufficient to implement all v4f32
7678 /// shuffles.
7679 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7680                                        const X86Subtarget *Subtarget,
7681                                        SelectionDAG &DAG) {
7682   SDLoc DL(Op);
7683   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7684   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7685   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7686   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7687   ArrayRef<int> Mask = SVOp->getMask();
7688   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7689
7690   int NumV2Elements =
7691       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7692
7693   if (NumV2Elements == 0) {
7694     // Check for being able to broadcast a single element.
7695     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f32, V1,
7696                                                           Mask, Subtarget, DAG))
7697       return Broadcast;
7698
7699     // Use even/odd duplicate instructions for masks that match their pattern.
7700     if (Subtarget->hasSSE3()) {
7701       if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
7702         return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v4f32, V1);
7703       if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3}))
7704         return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v4f32, V1);
7705     }
7706
7707     if (Subtarget->hasAVX()) {
7708       // If we have AVX, we can use VPERMILPS which will allow folding a load
7709       // into the shuffle.
7710       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f32, V1,
7711                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
7712     }
7713
7714     // Otherwise, use a straight shuffle of a single input vector. We pass the
7715     // input vector to both operands to simulate this with a SHUFPS.
7716     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
7717                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
7718   }
7719
7720   // There are special ways we can lower some single-element blends. However, we
7721   // have custom ways we can lower more complex single-element blends below that
7722   // we defer to if both this and BLENDPS fail to match, so restrict this to
7723   // when the V2 input is targeting element 0 of the mask -- that is the fast
7724   // case here.
7725   if (NumV2Elements == 1 && Mask[0] >= 4)
7726     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4f32, V1, V2,
7727                                                          Mask, Subtarget, DAG))
7728       return V;
7729
7730   if (Subtarget->hasSSE41()) {
7731     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f32, V1, V2, Mask,
7732                                                   Subtarget, DAG))
7733       return Blend;
7734
7735     // Use INSERTPS if we can complete the shuffle efficiently.
7736     if (SDValue V = lowerVectorShuffleAsInsertPS(Op, V1, V2, Mask, DAG))
7737       return V;
7738
7739     if (!isSingleSHUFPSMask(Mask))
7740       if (SDValue BlendPerm = lowerVectorShuffleAsBlendAndPermute(
7741               DL, MVT::v4f32, V1, V2, Mask, DAG))
7742         return BlendPerm;
7743   }
7744
7745   // Use dedicated unpack instructions for masks that match their pattern.
7746   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
7747     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V1, V2);
7748   if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
7749     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V1, V2);
7750   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
7751     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V2, V1);
7752   if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
7753     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V2, V1);
7754
7755   // Otherwise fall back to a SHUFPS lowering strategy.
7756   return lowerVectorShuffleWithSHUFPS(DL, MVT::v4f32, Mask, V1, V2, DAG);
7757 }
7758
7759 /// \brief Lower 4-lane i32 vector shuffles.
7760 ///
7761 /// We try to handle these with integer-domain shuffles where we can, but for
7762 /// blends we use the floating point domain blend instructions.
7763 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7764                                        const X86Subtarget *Subtarget,
7765                                        SelectionDAG &DAG) {
7766   SDLoc DL(Op);
7767   assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
7768   assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7769   assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7770   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7771   ArrayRef<int> Mask = SVOp->getMask();
7772   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7773
7774   // Whenever we can lower this as a zext, that instruction is strictly faster
7775   // than any alternative. It also allows us to fold memory operands into the
7776   // shuffle in many cases.
7777   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v4i32, V1, V2,
7778                                                          Mask, Subtarget, DAG))
7779     return ZExt;
7780
7781   int NumV2Elements =
7782       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7783
7784   if (NumV2Elements == 0) {
7785     // Check for being able to broadcast a single element.
7786     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i32, V1,
7787                                                           Mask, Subtarget, DAG))
7788       return Broadcast;
7789
7790     // Straight shuffle of a single input vector. For everything from SSE2
7791     // onward this has a single fast instruction with no scary immediates.
7792     // We coerce the shuffle pattern to be compatible with UNPCK instructions
7793     // but we aren't actually going to use the UNPCK instruction because doing
7794     // so prevents folding a load into this instruction or making a copy.
7795     const int UnpackLoMask[] = {0, 0, 1, 1};
7796     const int UnpackHiMask[] = {2, 2, 3, 3};
7797     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 1, 1}))
7798       Mask = UnpackLoMask;
7799     else if (isShuffleEquivalent(V1, V2, Mask, {2, 2, 3, 3}))
7800       Mask = UnpackHiMask;
7801
7802     return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
7803                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
7804   }
7805
7806   // Try to use shift instructions.
7807   if (SDValue Shift =
7808           lowerVectorShuffleAsShift(DL, MVT::v4i32, V1, V2, Mask, DAG))
7809     return Shift;
7810
7811   // There are special ways we can lower some single-element blends.
7812   if (NumV2Elements == 1)
7813     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4i32, V1, V2,
7814                                                          Mask, Subtarget, DAG))
7815       return V;
7816
7817   // We have different paths for blend lowering, but they all must use the
7818   // *exact* same predicate.
7819   bool IsBlendSupported = Subtarget->hasSSE41();
7820   if (IsBlendSupported)
7821     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i32, V1, V2, Mask,
7822                                                   Subtarget, DAG))
7823       return Blend;
7824
7825   if (SDValue Masked =
7826           lowerVectorShuffleAsBitMask(DL, MVT::v4i32, V1, V2, Mask, DAG))
7827     return Masked;
7828
7829   // Use dedicated unpack instructions for masks that match their pattern.
7830   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
7831     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V1, V2);
7832   if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
7833     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V1, V2);
7834   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
7835     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V2, V1);
7836   if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
7837     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V2, V1);
7838
7839   // Try to use byte rotation instructions.
7840   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
7841   if (Subtarget->hasSSSE3())
7842     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
7843             DL, MVT::v4i32, V1, V2, Mask, Subtarget, DAG))
7844       return Rotate;
7845
7846   // If we have direct support for blends, we should lower by decomposing into
7847   // a permute. That will be faster than the domain cross.
7848   if (IsBlendSupported)
7849     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i32, V1, V2,
7850                                                       Mask, DAG);
7851
7852   // Try to lower by permuting the inputs into an unpack instruction.
7853   if (SDValue Unpack =
7854           lowerVectorShuffleAsUnpack(DL, MVT::v4i32, V1, V2, Mask, DAG))
7855     return Unpack;
7856
7857   // We implement this with SHUFPS because it can blend from two vectors.
7858   // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
7859   // up the inputs, bypassing domain shift penalties that we would encur if we
7860   // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
7861   // relevant.
7862   return DAG.getNode(ISD::BITCAST, DL, MVT::v4i32,
7863                      DAG.getVectorShuffle(
7864                          MVT::v4f32, DL,
7865                          DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V1),
7866                          DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V2), Mask));
7867 }
7868
7869 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
7870 /// shuffle lowering, and the most complex part.
7871 ///
7872 /// The lowering strategy is to try to form pairs of input lanes which are
7873 /// targeted at the same half of the final vector, and then use a dword shuffle
7874 /// to place them onto the right half, and finally unpack the paired lanes into
7875 /// their final position.
7876 ///
7877 /// The exact breakdown of how to form these dword pairs and align them on the
7878 /// correct sides is really tricky. See the comments within the function for
7879 /// more of the details.
7880 ///
7881 /// This code also handles repeated 128-bit lanes of v8i16 shuffles, but each
7882 /// lane must shuffle the *exact* same way. In fact, you must pass a v8 Mask to
7883 /// this routine for it to work correctly. To shuffle a 256-bit or 512-bit i16
7884 /// vector, form the analogous 128-bit 8-element Mask.
7885 static SDValue lowerV8I16GeneralSingleInputVectorShuffle(
7886     SDLoc DL, MVT VT, SDValue V, MutableArrayRef<int> Mask,
7887     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7888   assert(VT.getScalarType() == MVT::i16 && "Bad input type!");
7889   MVT PSHUFDVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
7890
7891   assert(Mask.size() == 8 && "Shuffle mask length doen't match!");
7892   MutableArrayRef<int> LoMask = Mask.slice(0, 4);
7893   MutableArrayRef<int> HiMask = Mask.slice(4, 4);
7894
7895   SmallVector<int, 4> LoInputs;
7896   std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
7897                [](int M) { return M >= 0; });
7898   std::sort(LoInputs.begin(), LoInputs.end());
7899   LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
7900   SmallVector<int, 4> HiInputs;
7901   std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
7902                [](int M) { return M >= 0; });
7903   std::sort(HiInputs.begin(), HiInputs.end());
7904   HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
7905   int NumLToL =
7906       std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
7907   int NumHToL = LoInputs.size() - NumLToL;
7908   int NumLToH =
7909       std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
7910   int NumHToH = HiInputs.size() - NumLToH;
7911   MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
7912   MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
7913   MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
7914   MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
7915
7916   // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
7917   // such inputs we can swap two of the dwords across the half mark and end up
7918   // with <=2 inputs to each half in each half. Once there, we can fall through
7919   // to the generic code below. For example:
7920   //
7921   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
7922   // Mask:  [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
7923   //
7924   // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
7925   // and an existing 2-into-2 on the other half. In this case we may have to
7926   // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
7927   // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
7928   // Fortunately, we don't have to handle anything but a 2-into-2 pattern
7929   // because any other situation (including a 3-into-1 or 1-into-3 in the other
7930   // half than the one we target for fixing) will be fixed when we re-enter this
7931   // path. We will also combine away any sequence of PSHUFD instructions that
7932   // result into a single instruction. Here is an example of the tricky case:
7933   //
7934   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
7935   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
7936   //
7937   // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
7938   //
7939   // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
7940   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
7941   //
7942   // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
7943   // Mask:  [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
7944   //
7945   // The result is fine to be handled by the generic logic.
7946   auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
7947                           ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
7948                           int AOffset, int BOffset) {
7949     assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
7950            "Must call this with A having 3 or 1 inputs from the A half.");
7951     assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
7952            "Must call this with B having 1 or 3 inputs from the B half.");
7953     assert(AToAInputs.size() + BToAInputs.size() == 4 &&
7954            "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
7955
7956     // Compute the index of dword with only one word among the three inputs in
7957     // a half by taking the sum of the half with three inputs and subtracting
7958     // the sum of the actual three inputs. The difference is the remaining
7959     // slot.
7960     int ADWord, BDWord;
7961     int &TripleDWord = AToAInputs.size() == 3 ? ADWord : BDWord;
7962     int &OneInputDWord = AToAInputs.size() == 3 ? BDWord : ADWord;
7963     int TripleInputOffset = AToAInputs.size() == 3 ? AOffset : BOffset;
7964     ArrayRef<int> TripleInputs = AToAInputs.size() == 3 ? AToAInputs : BToAInputs;
7965     int OneInput = AToAInputs.size() == 3 ? BToAInputs[0] : AToAInputs[0];
7966     int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
7967     int TripleNonInputIdx =
7968         TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
7969     TripleDWord = TripleNonInputIdx / 2;
7970
7971     // We use xor with one to compute the adjacent DWord to whichever one the
7972     // OneInput is in.
7973     OneInputDWord = (OneInput / 2) ^ 1;
7974
7975     // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
7976     // and BToA inputs. If there is also such a problem with the BToB and AToB
7977     // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
7978     // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
7979     // is essential that we don't *create* a 3<-1 as then we might oscillate.
7980     if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
7981       // Compute how many inputs will be flipped by swapping these DWords. We
7982       // need
7983       // to balance this to ensure we don't form a 3-1 shuffle in the other
7984       // half.
7985       int NumFlippedAToBInputs =
7986           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
7987           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
7988       int NumFlippedBToBInputs =
7989           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
7990           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
7991       if ((NumFlippedAToBInputs == 1 &&
7992            (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
7993           (NumFlippedBToBInputs == 1 &&
7994            (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
7995         // We choose whether to fix the A half or B half based on whether that
7996         // half has zero flipped inputs. At zero, we may not be able to fix it
7997         // with that half. We also bias towards fixing the B half because that
7998         // will more commonly be the high half, and we have to bias one way.
7999         auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
8000                                                        ArrayRef<int> Inputs) {
8001           int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
8002           bool IsFixIdxInput = std::find(Inputs.begin(), Inputs.end(),
8003                                          PinnedIdx ^ 1) != Inputs.end();
8004           // Determine whether the free index is in the flipped dword or the
8005           // unflipped dword based on where the pinned index is. We use this bit
8006           // in an xor to conditionally select the adjacent dword.
8007           int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
8008           bool IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8009                                              FixFreeIdx) != Inputs.end();
8010           if (IsFixIdxInput == IsFixFreeIdxInput)
8011             FixFreeIdx += 1;
8012           IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8013                                         FixFreeIdx) != Inputs.end();
8014           assert(IsFixIdxInput != IsFixFreeIdxInput &&
8015                  "We need to be changing the number of flipped inputs!");
8016           int PSHUFHalfMask[] = {0, 1, 2, 3};
8017           std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
8018           V = DAG.getNode(FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
8019                           MVT::v8i16, V,
8020                           getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DL, DAG));
8021
8022           for (int &M : Mask)
8023             if (M != -1 && M == FixIdx)
8024               M = FixFreeIdx;
8025             else if (M != -1 && M == FixFreeIdx)
8026               M = FixIdx;
8027         };
8028         if (NumFlippedBToBInputs != 0) {
8029           int BPinnedIdx =
8030               BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8031           FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
8032         } else {
8033           assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
8034           int APinnedIdx =
8035               AToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8036           FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
8037         }
8038       }
8039     }
8040
8041     int PSHUFDMask[] = {0, 1, 2, 3};
8042     PSHUFDMask[ADWord] = BDWord;
8043     PSHUFDMask[BDWord] = ADWord;
8044     V = DAG.getNode(ISD::BITCAST, DL, VT,
8045                     DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT,
8046                                 DAG.getNode(ISD::BITCAST, DL, PSHUFDVT, V),
8047                                 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL,
8048                                                            DAG)));
8049
8050     // Adjust the mask to match the new locations of A and B.
8051     for (int &M : Mask)
8052       if (M != -1 && M/2 == ADWord)
8053         M = 2 * BDWord + M % 2;
8054       else if (M != -1 && M/2 == BDWord)
8055         M = 2 * ADWord + M % 2;
8056
8057     // Recurse back into this routine to re-compute state now that this isn't
8058     // a 3 and 1 problem.
8059     return lowerV8I16GeneralSingleInputVectorShuffle(DL, VT, V, Mask, Subtarget,
8060                                                      DAG);
8061   };
8062   if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
8063     return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
8064   else if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
8065     return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
8066
8067   // At this point there are at most two inputs to the low and high halves from
8068   // each half. That means the inputs can always be grouped into dwords and
8069   // those dwords can then be moved to the correct half with a dword shuffle.
8070   // We use at most one low and one high word shuffle to collect these paired
8071   // inputs into dwords, and finally a dword shuffle to place them.
8072   int PSHUFLMask[4] = {-1, -1, -1, -1};
8073   int PSHUFHMask[4] = {-1, -1, -1, -1};
8074   int PSHUFDMask[4] = {-1, -1, -1, -1};
8075
8076   // First fix the masks for all the inputs that are staying in their
8077   // original halves. This will then dictate the targets of the cross-half
8078   // shuffles.
8079   auto fixInPlaceInputs =
8080       [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
8081                     MutableArrayRef<int> SourceHalfMask,
8082                     MutableArrayRef<int> HalfMask, int HalfOffset) {
8083     if (InPlaceInputs.empty())
8084       return;
8085     if (InPlaceInputs.size() == 1) {
8086       SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8087           InPlaceInputs[0] - HalfOffset;
8088       PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
8089       return;
8090     }
8091     if (IncomingInputs.empty()) {
8092       // Just fix all of the in place inputs.
8093       for (int Input : InPlaceInputs) {
8094         SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
8095         PSHUFDMask[Input / 2] = Input / 2;
8096       }
8097       return;
8098     }
8099
8100     assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
8101     SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8102         InPlaceInputs[0] - HalfOffset;
8103     // Put the second input next to the first so that they are packed into
8104     // a dword. We find the adjacent index by toggling the low bit.
8105     int AdjIndex = InPlaceInputs[0] ^ 1;
8106     SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
8107     std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
8108     PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
8109   };
8110   fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
8111   fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
8112
8113   // Now gather the cross-half inputs and place them into a free dword of
8114   // their target half.
8115   // FIXME: This operation could almost certainly be simplified dramatically to
8116   // look more like the 3-1 fixing operation.
8117   auto moveInputsToRightHalf = [&PSHUFDMask](
8118       MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
8119       MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
8120       MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
8121       int DestOffset) {
8122     auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
8123       return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
8124     };
8125     auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
8126                                                int Word) {
8127       int LowWord = Word & ~1;
8128       int HighWord = Word | 1;
8129       return isWordClobbered(SourceHalfMask, LowWord) ||
8130              isWordClobbered(SourceHalfMask, HighWord);
8131     };
8132
8133     if (IncomingInputs.empty())
8134       return;
8135
8136     if (ExistingInputs.empty()) {
8137       // Map any dwords with inputs from them into the right half.
8138       for (int Input : IncomingInputs) {
8139         // If the source half mask maps over the inputs, turn those into
8140         // swaps and use the swapped lane.
8141         if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
8142           if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
8143             SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
8144                 Input - SourceOffset;
8145             // We have to swap the uses in our half mask in one sweep.
8146             for (int &M : HalfMask)
8147               if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
8148                 M = Input;
8149               else if (M == Input)
8150                 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8151           } else {
8152             assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
8153                        Input - SourceOffset &&
8154                    "Previous placement doesn't match!");
8155           }
8156           // Note that this correctly re-maps both when we do a swap and when
8157           // we observe the other side of the swap above. We rely on that to
8158           // avoid swapping the members of the input list directly.
8159           Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8160         }
8161
8162         // Map the input's dword into the correct half.
8163         if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
8164           PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
8165         else
8166           assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
8167                      Input / 2 &&
8168                  "Previous placement doesn't match!");
8169       }
8170
8171       // And just directly shift any other-half mask elements to be same-half
8172       // as we will have mirrored the dword containing the element into the
8173       // same position within that half.
8174       for (int &M : HalfMask)
8175         if (M >= SourceOffset && M < SourceOffset + 4) {
8176           M = M - SourceOffset + DestOffset;
8177           assert(M >= 0 && "This should never wrap below zero!");
8178         }
8179       return;
8180     }
8181
8182     // Ensure we have the input in a viable dword of its current half. This
8183     // is particularly tricky because the original position may be clobbered
8184     // by inputs being moved and *staying* in that half.
8185     if (IncomingInputs.size() == 1) {
8186       if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8187         int InputFixed = std::find(std::begin(SourceHalfMask),
8188                                    std::end(SourceHalfMask), -1) -
8189                          std::begin(SourceHalfMask) + SourceOffset;
8190         SourceHalfMask[InputFixed - SourceOffset] =
8191             IncomingInputs[0] - SourceOffset;
8192         std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
8193                      InputFixed);
8194         IncomingInputs[0] = InputFixed;
8195       }
8196     } else if (IncomingInputs.size() == 2) {
8197       if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
8198           isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8199         // We have two non-adjacent or clobbered inputs we need to extract from
8200         // the source half. To do this, we need to map them into some adjacent
8201         // dword slot in the source mask.
8202         int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
8203                               IncomingInputs[1] - SourceOffset};
8204
8205         // If there is a free slot in the source half mask adjacent to one of
8206         // the inputs, place the other input in it. We use (Index XOR 1) to
8207         // compute an adjacent index.
8208         if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
8209             SourceHalfMask[InputsFixed[0] ^ 1] == -1) {
8210           SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
8211           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8212           InputsFixed[1] = InputsFixed[0] ^ 1;
8213         } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
8214                    SourceHalfMask[InputsFixed[1] ^ 1] == -1) {
8215           SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
8216           SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
8217           InputsFixed[0] = InputsFixed[1] ^ 1;
8218         } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] == -1 &&
8219                    SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] == -1) {
8220           // The two inputs are in the same DWord but it is clobbered and the
8221           // adjacent DWord isn't used at all. Move both inputs to the free
8222           // slot.
8223           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
8224           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
8225           InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
8226           InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
8227         } else {
8228           // The only way we hit this point is if there is no clobbering
8229           // (because there are no off-half inputs to this half) and there is no
8230           // free slot adjacent to one of the inputs. In this case, we have to
8231           // swap an input with a non-input.
8232           for (int i = 0; i < 4; ++i)
8233             assert((SourceHalfMask[i] == -1 || SourceHalfMask[i] == i) &&
8234                    "We can't handle any clobbers here!");
8235           assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
8236                  "Cannot have adjacent inputs here!");
8237
8238           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8239           SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
8240
8241           // We also have to update the final source mask in this case because
8242           // it may need to undo the above swap.
8243           for (int &M : FinalSourceHalfMask)
8244             if (M == (InputsFixed[0] ^ 1) + SourceOffset)
8245               M = InputsFixed[1] + SourceOffset;
8246             else if (M == InputsFixed[1] + SourceOffset)
8247               M = (InputsFixed[0] ^ 1) + SourceOffset;
8248
8249           InputsFixed[1] = InputsFixed[0] ^ 1;
8250         }
8251
8252         // Point everything at the fixed inputs.
8253         for (int &M : HalfMask)
8254           if (M == IncomingInputs[0])
8255             M = InputsFixed[0] + SourceOffset;
8256           else if (M == IncomingInputs[1])
8257             M = InputsFixed[1] + SourceOffset;
8258
8259         IncomingInputs[0] = InputsFixed[0] + SourceOffset;
8260         IncomingInputs[1] = InputsFixed[1] + SourceOffset;
8261       }
8262     } else {
8263       llvm_unreachable("Unhandled input size!");
8264     }
8265
8266     // Now hoist the DWord down to the right half.
8267     int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
8268     assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
8269     PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
8270     for (int &M : HalfMask)
8271       for (int Input : IncomingInputs)
8272         if (M == Input)
8273           M = FreeDWord * 2 + Input % 2;
8274   };
8275   moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
8276                         /*SourceOffset*/ 4, /*DestOffset*/ 0);
8277   moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
8278                         /*SourceOffset*/ 0, /*DestOffset*/ 4);
8279
8280   // Now enact all the shuffles we've computed to move the inputs into their
8281   // target half.
8282   if (!isNoopShuffleMask(PSHUFLMask))
8283     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8284                     getV4X86ShuffleImm8ForMask(PSHUFLMask, DL, DAG));
8285   if (!isNoopShuffleMask(PSHUFHMask))
8286     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8287                     getV4X86ShuffleImm8ForMask(PSHUFHMask, DL, DAG));
8288   if (!isNoopShuffleMask(PSHUFDMask))
8289     V = DAG.getNode(ISD::BITCAST, DL, VT,
8290                     DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT,
8291                                 DAG.getNode(ISD::BITCAST, DL, PSHUFDVT, V),
8292                                 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL,
8293                                                            DAG)));
8294
8295   // At this point, each half should contain all its inputs, and we can then
8296   // just shuffle them into their final position.
8297   assert(std::count_if(LoMask.begin(), LoMask.end(),
8298                        [](int M) { return M >= 4; }) == 0 &&
8299          "Failed to lift all the high half inputs to the low mask!");
8300   assert(std::count_if(HiMask.begin(), HiMask.end(),
8301                        [](int M) { return M >= 0 && M < 4; }) == 0 &&
8302          "Failed to lift all the low half inputs to the high mask!");
8303
8304   // Do a half shuffle for the low mask.
8305   if (!isNoopShuffleMask(LoMask))
8306     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8307                     getV4X86ShuffleImm8ForMask(LoMask, DL, DAG));
8308
8309   // Do a half shuffle with the high mask after shifting its values down.
8310   for (int &M : HiMask)
8311     if (M >= 0)
8312       M -= 4;
8313   if (!isNoopShuffleMask(HiMask))
8314     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8315                     getV4X86ShuffleImm8ForMask(HiMask, DL, DAG));
8316
8317   return V;
8318 }
8319
8320 /// \brief Helper to form a PSHUFB-based shuffle+blend.
8321 static SDValue lowerVectorShuffleAsPSHUFB(SDLoc DL, MVT VT, SDValue V1,
8322                                           SDValue V2, ArrayRef<int> Mask,
8323                                           SelectionDAG &DAG, bool &V1InUse,
8324                                           bool &V2InUse) {
8325   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
8326   SDValue V1Mask[16];
8327   SDValue V2Mask[16];
8328   V1InUse = false;
8329   V2InUse = false;
8330
8331   int Size = Mask.size();
8332   int Scale = 16 / Size;
8333   for (int i = 0; i < 16; ++i) {
8334     if (Mask[i / Scale] == -1) {
8335       V1Mask[i] = V2Mask[i] = DAG.getUNDEF(MVT::i8);
8336     } else {
8337       const int ZeroMask = 0x80;
8338       int V1Idx = Mask[i / Scale] < Size ? Mask[i / Scale] * Scale + i % Scale
8339                                           : ZeroMask;
8340       int V2Idx = Mask[i / Scale] < Size
8341                       ? ZeroMask
8342                       : (Mask[i / Scale] - Size) * Scale + i % Scale;
8343       if (Zeroable[i / Scale])
8344         V1Idx = V2Idx = ZeroMask;
8345       V1Mask[i] = DAG.getConstant(V1Idx, DL, MVT::i8);
8346       V2Mask[i] = DAG.getConstant(V2Idx, DL, MVT::i8);
8347       V1InUse |= (ZeroMask != V1Idx);
8348       V2InUse |= (ZeroMask != V2Idx);
8349     }
8350   }
8351
8352   if (V1InUse)
8353     V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8354                      DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, V1),
8355                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
8356   if (V2InUse)
8357     V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8358                      DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, V2),
8359                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
8360
8361   // If we need shuffled inputs from both, blend the two.
8362   SDValue V;
8363   if (V1InUse && V2InUse)
8364     V = DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
8365   else
8366     V = V1InUse ? V1 : V2;
8367
8368   // Cast the result back to the correct type.
8369   return DAG.getNode(ISD::BITCAST, DL, VT, V);
8370 }
8371
8372 /// \brief Generic lowering of 8-lane i16 shuffles.
8373 ///
8374 /// This handles both single-input shuffles and combined shuffle/blends with
8375 /// two inputs. The single input shuffles are immediately delegated to
8376 /// a dedicated lowering routine.
8377 ///
8378 /// The blends are lowered in one of three fundamental ways. If there are few
8379 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
8380 /// of the input is significantly cheaper when lowered as an interleaving of
8381 /// the two inputs, try to interleave them. Otherwise, blend the low and high
8382 /// halves of the inputs separately (making them have relatively few inputs)
8383 /// and then concatenate them.
8384 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8385                                        const X86Subtarget *Subtarget,
8386                                        SelectionDAG &DAG) {
8387   SDLoc DL(Op);
8388   assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
8389   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8390   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8391   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8392   ArrayRef<int> OrigMask = SVOp->getMask();
8393   int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
8394                         OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
8395   MutableArrayRef<int> Mask(MaskStorage);
8396
8397   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
8398
8399   // Whenever we can lower this as a zext, that instruction is strictly faster
8400   // than any alternative.
8401   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
8402           DL, MVT::v8i16, V1, V2, OrigMask, Subtarget, DAG))
8403     return ZExt;
8404
8405   auto isV1 = [](int M) { return M >= 0 && M < 8; };
8406   (void)isV1;
8407   auto isV2 = [](int M) { return M >= 8; };
8408
8409   int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
8410
8411   if (NumV2Inputs == 0) {
8412     // Check for being able to broadcast a single element.
8413     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i16, V1,
8414                                                           Mask, Subtarget, DAG))
8415       return Broadcast;
8416
8417     // Try to use shift instructions.
8418     if (SDValue Shift =
8419             lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V1, Mask, DAG))
8420       return Shift;
8421
8422     // Use dedicated unpack instructions for masks that match their pattern.
8423     if (isShuffleEquivalent(V1, V1, Mask, {0, 0, 1, 1, 2, 2, 3, 3}))
8424       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V1);
8425     if (isShuffleEquivalent(V1, V1, Mask, {4, 4, 5, 5, 6, 6, 7, 7}))
8426       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V1);
8427
8428     // Try to use byte rotation instructions.
8429     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(DL, MVT::v8i16, V1, V1,
8430                                                         Mask, Subtarget, DAG))
8431       return Rotate;
8432
8433     return lowerV8I16GeneralSingleInputVectorShuffle(DL, MVT::v8i16, V1, Mask,
8434                                                      Subtarget, DAG);
8435   }
8436
8437   assert(std::any_of(Mask.begin(), Mask.end(), isV1) &&
8438          "All single-input shuffles should be canonicalized to be V1-input "
8439          "shuffles.");
8440
8441   // Try to use shift instructions.
8442   if (SDValue Shift =
8443           lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V2, Mask, DAG))
8444     return Shift;
8445
8446   // There are special ways we can lower some single-element blends.
8447   if (NumV2Inputs == 1)
8448     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v8i16, V1, V2,
8449                                                          Mask, Subtarget, DAG))
8450       return V;
8451
8452   // We have different paths for blend lowering, but they all must use the
8453   // *exact* same predicate.
8454   bool IsBlendSupported = Subtarget->hasSSE41();
8455   if (IsBlendSupported)
8456     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i16, V1, V2, Mask,
8457                                                   Subtarget, DAG))
8458       return Blend;
8459
8460   if (SDValue Masked =
8461           lowerVectorShuffleAsBitMask(DL, MVT::v8i16, V1, V2, Mask, DAG))
8462     return Masked;
8463
8464   // Use dedicated unpack instructions for masks that match their pattern.
8465   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 2, 10, 3, 11}))
8466     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V2);
8467   if (isShuffleEquivalent(V1, V2, Mask, {4, 12, 5, 13, 6, 14, 7, 15}))
8468     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V2);
8469
8470   // Try to use byte rotation instructions.
8471   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8472           DL, MVT::v8i16, V1, V2, Mask, Subtarget, DAG))
8473     return Rotate;
8474
8475   if (SDValue BitBlend =
8476           lowerVectorShuffleAsBitBlend(DL, MVT::v8i16, V1, V2, Mask, DAG))
8477     return BitBlend;
8478
8479   if (SDValue Unpack =
8480           lowerVectorShuffleAsUnpack(DL, MVT::v8i16, V1, V2, Mask, DAG))
8481     return Unpack;
8482
8483   // If we can't directly blend but can use PSHUFB, that will be better as it
8484   // can both shuffle and set up the inefficient blend.
8485   if (!IsBlendSupported && Subtarget->hasSSSE3()) {
8486     bool V1InUse, V2InUse;
8487     return lowerVectorShuffleAsPSHUFB(DL, MVT::v8i16, V1, V2, Mask, DAG,
8488                                       V1InUse, V2InUse);
8489   }
8490
8491   // We can always bit-blend if we have to so the fallback strategy is to
8492   // decompose into single-input permutes and blends.
8493   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i16, V1, V2,
8494                                                       Mask, DAG);
8495 }
8496
8497 /// \brief Check whether a compaction lowering can be done by dropping even
8498 /// elements and compute how many times even elements must be dropped.
8499 ///
8500 /// This handles shuffles which take every Nth element where N is a power of
8501 /// two. Example shuffle masks:
8502 ///
8503 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14,  0,  2,  4,  6,  8, 10, 12, 14
8504 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
8505 ///  N = 2:  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12
8506 ///  N = 2:  0,  4,  8, 12, 16, 20, 24, 28,  0,  4,  8, 12, 16, 20, 24, 28
8507 ///  N = 3:  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8
8508 ///  N = 3:  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24
8509 ///
8510 /// Any of these lanes can of course be undef.
8511 ///
8512 /// This routine only supports N <= 3.
8513 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
8514 /// for larger N.
8515 ///
8516 /// \returns N above, or the number of times even elements must be dropped if
8517 /// there is such a number. Otherwise returns zero.
8518 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
8519   // Figure out whether we're looping over two inputs or just one.
8520   bool IsSingleInput = isSingleInputShuffleMask(Mask);
8521
8522   // The modulus for the shuffle vector entries is based on whether this is
8523   // a single input or not.
8524   int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
8525   assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
8526          "We should only be called with masks with a power-of-2 size!");
8527
8528   uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
8529
8530   // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
8531   // and 2^3 simultaneously. This is because we may have ambiguity with
8532   // partially undef inputs.
8533   bool ViableForN[3] = {true, true, true};
8534
8535   for (int i = 0, e = Mask.size(); i < e; ++i) {
8536     // Ignore undef lanes, we'll optimistically collapse them to the pattern we
8537     // want.
8538     if (Mask[i] == -1)
8539       continue;
8540
8541     bool IsAnyViable = false;
8542     for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8543       if (ViableForN[j]) {
8544         uint64_t N = j + 1;
8545
8546         // The shuffle mask must be equal to (i * 2^N) % M.
8547         if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
8548           IsAnyViable = true;
8549         else
8550           ViableForN[j] = false;
8551       }
8552     // Early exit if we exhaust the possible powers of two.
8553     if (!IsAnyViable)
8554       break;
8555   }
8556
8557   for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8558     if (ViableForN[j])
8559       return j + 1;
8560
8561   // Return 0 as there is no viable power of two.
8562   return 0;
8563 }
8564
8565 /// \brief Generic lowering of v16i8 shuffles.
8566 ///
8567 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
8568 /// detect any complexity reducing interleaving. If that doesn't help, it uses
8569 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
8570 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
8571 /// back together.
8572 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8573                                        const X86Subtarget *Subtarget,
8574                                        SelectionDAG &DAG) {
8575   SDLoc DL(Op);
8576   assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
8577   assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8578   assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8579   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8580   ArrayRef<int> Mask = SVOp->getMask();
8581   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
8582
8583   // Try to use shift instructions.
8584   if (SDValue Shift =
8585           lowerVectorShuffleAsShift(DL, MVT::v16i8, V1, V2, Mask, DAG))
8586     return Shift;
8587
8588   // Try to use byte rotation instructions.
8589   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8590           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
8591     return Rotate;
8592
8593   // Try to use a zext lowering.
8594   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
8595           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
8596     return ZExt;
8597
8598   int NumV2Elements =
8599       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 16; });
8600
8601   // For single-input shuffles, there are some nicer lowering tricks we can use.
8602   if (NumV2Elements == 0) {
8603     // Check for being able to broadcast a single element.
8604     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i8, V1,
8605                                                           Mask, Subtarget, DAG))
8606       return Broadcast;
8607
8608     // Check whether we can widen this to an i16 shuffle by duplicating bytes.
8609     // Notably, this handles splat and partial-splat shuffles more efficiently.
8610     // However, it only makes sense if the pre-duplication shuffle simplifies
8611     // things significantly. Currently, this means we need to be able to
8612     // express the pre-duplication shuffle as an i16 shuffle.
8613     //
8614     // FIXME: We should check for other patterns which can be widened into an
8615     // i16 shuffle as well.
8616     auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
8617       for (int i = 0; i < 16; i += 2)
8618         if (Mask[i] != -1 && Mask[i + 1] != -1 && Mask[i] != Mask[i + 1])
8619           return false;
8620
8621       return true;
8622     };
8623     auto tryToWidenViaDuplication = [&]() -> SDValue {
8624       if (!canWidenViaDuplication(Mask))
8625         return SDValue();
8626       SmallVector<int, 4> LoInputs;
8627       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
8628                    [](int M) { return M >= 0 && M < 8; });
8629       std::sort(LoInputs.begin(), LoInputs.end());
8630       LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
8631                      LoInputs.end());
8632       SmallVector<int, 4> HiInputs;
8633       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
8634                    [](int M) { return M >= 8; });
8635       std::sort(HiInputs.begin(), HiInputs.end());
8636       HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
8637                      HiInputs.end());
8638
8639       bool TargetLo = LoInputs.size() >= HiInputs.size();
8640       ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
8641       ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
8642
8643       int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
8644       SmallDenseMap<int, int, 8> LaneMap;
8645       for (int I : InPlaceInputs) {
8646         PreDupI16Shuffle[I/2] = I/2;
8647         LaneMap[I] = I;
8648       }
8649       int j = TargetLo ? 0 : 4, je = j + 4;
8650       for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
8651         // Check if j is already a shuffle of this input. This happens when
8652         // there are two adjacent bytes after we move the low one.
8653         if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
8654           // If we haven't yet mapped the input, search for a slot into which
8655           // we can map it.
8656           while (j < je && PreDupI16Shuffle[j] != -1)
8657             ++j;
8658
8659           if (j == je)
8660             // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
8661             return SDValue();
8662
8663           // Map this input with the i16 shuffle.
8664           PreDupI16Shuffle[j] = MovingInputs[i] / 2;
8665         }
8666
8667         // Update the lane map based on the mapping we ended up with.
8668         LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
8669       }
8670       V1 = DAG.getNode(
8671           ISD::BITCAST, DL, MVT::v16i8,
8672           DAG.getVectorShuffle(MVT::v8i16, DL,
8673                                DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
8674                                DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
8675
8676       // Unpack the bytes to form the i16s that will be shuffled into place.
8677       V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
8678                        MVT::v16i8, V1, V1);
8679
8680       int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8681       for (int i = 0; i < 16; ++i)
8682         if (Mask[i] != -1) {
8683           int MappedMask = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
8684           assert(MappedMask < 8 && "Invalid v8 shuffle mask!");
8685           if (PostDupI16Shuffle[i / 2] == -1)
8686             PostDupI16Shuffle[i / 2] = MappedMask;
8687           else
8688             assert(PostDupI16Shuffle[i / 2] == MappedMask &&
8689                    "Conflicting entrties in the original shuffle!");
8690         }
8691       return DAG.getNode(
8692           ISD::BITCAST, DL, MVT::v16i8,
8693           DAG.getVectorShuffle(MVT::v8i16, DL,
8694                                DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
8695                                DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
8696     };
8697     if (SDValue V = tryToWidenViaDuplication())
8698       return V;
8699   }
8700
8701   // Use dedicated unpack instructions for masks that match their pattern.
8702   if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
8703                                          0, 16, 1, 17, 2, 18, 3, 19,
8704                                          // High half.
8705                                          4, 20, 5, 21, 6, 22, 7, 23}))
8706     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V1, V2);
8707   if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
8708                                          8, 24, 9, 25, 10, 26, 11, 27,
8709                                          // High half.
8710                                          12, 28, 13, 29, 14, 30, 15, 31}))
8711     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V1, V2);
8712
8713   // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
8714   // with PSHUFB. It is important to do this before we attempt to generate any
8715   // blends but after all of the single-input lowerings. If the single input
8716   // lowerings can find an instruction sequence that is faster than a PSHUFB, we
8717   // want to preserve that and we can DAG combine any longer sequences into
8718   // a PSHUFB in the end. But once we start blending from multiple inputs,
8719   // the complexity of DAG combining bad patterns back into PSHUFB is too high,
8720   // and there are *very* few patterns that would actually be faster than the
8721   // PSHUFB approach because of its ability to zero lanes.
8722   //
8723   // FIXME: The only exceptions to the above are blends which are exact
8724   // interleavings with direct instructions supporting them. We currently don't
8725   // handle those well here.
8726   if (Subtarget->hasSSSE3()) {
8727     bool V1InUse = false;
8728     bool V2InUse = false;
8729
8730     SDValue PSHUFB = lowerVectorShuffleAsPSHUFB(DL, MVT::v16i8, V1, V2, Mask,
8731                                                 DAG, V1InUse, V2InUse);
8732
8733     // If both V1 and V2 are in use and we can use a direct blend or an unpack,
8734     // do so. This avoids using them to handle blends-with-zero which is
8735     // important as a single pshufb is significantly faster for that.
8736     if (V1InUse && V2InUse) {
8737       if (Subtarget->hasSSE41())
8738         if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i8, V1, V2,
8739                                                       Mask, Subtarget, DAG))
8740           return Blend;
8741
8742       // We can use an unpack to do the blending rather than an or in some
8743       // cases. Even though the or may be (very minorly) more efficient, we
8744       // preference this lowering because there are common cases where part of
8745       // the complexity of the shuffles goes away when we do the final blend as
8746       // an unpack.
8747       // FIXME: It might be worth trying to detect if the unpack-feeding
8748       // shuffles will both be pshufb, in which case we shouldn't bother with
8749       // this.
8750       if (SDValue Unpack =
8751               lowerVectorShuffleAsUnpack(DL, MVT::v16i8, V1, V2, Mask, DAG))
8752         return Unpack;
8753     }
8754
8755     return PSHUFB;
8756   }
8757
8758   // There are special ways we can lower some single-element blends.
8759   if (NumV2Elements == 1)
8760     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v16i8, V1, V2,
8761                                                          Mask, Subtarget, DAG))
8762       return V;
8763
8764   if (SDValue BitBlend =
8765           lowerVectorShuffleAsBitBlend(DL, MVT::v16i8, V1, V2, Mask, DAG))
8766     return BitBlend;
8767
8768   // Check whether a compaction lowering can be done. This handles shuffles
8769   // which take every Nth element for some even N. See the helper function for
8770   // details.
8771   //
8772   // We special case these as they can be particularly efficiently handled with
8773   // the PACKUSB instruction on x86 and they show up in common patterns of
8774   // rearranging bytes to truncate wide elements.
8775   if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
8776     // NumEvenDrops is the power of two stride of the elements. Another way of
8777     // thinking about it is that we need to drop the even elements this many
8778     // times to get the original input.
8779     bool IsSingleInput = isSingleInputShuffleMask(Mask);
8780
8781     // First we need to zero all the dropped bytes.
8782     assert(NumEvenDrops <= 3 &&
8783            "No support for dropping even elements more than 3 times.");
8784     // We use the mask type to pick which bytes are preserved based on how many
8785     // elements are dropped.
8786     MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
8787     SDValue ByteClearMask =
8788         DAG.getNode(ISD::BITCAST, DL, MVT::v16i8,
8789                     DAG.getConstant(0xFF, DL, MaskVTs[NumEvenDrops - 1]));
8790     V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
8791     if (!IsSingleInput)
8792       V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
8793
8794     // Now pack things back together.
8795     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1);
8796     V2 = IsSingleInput ? V1 : DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V2);
8797     SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
8798     for (int i = 1; i < NumEvenDrops; ++i) {
8799       Result = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, Result);
8800       Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
8801     }
8802
8803     return Result;
8804   }
8805
8806   // Handle multi-input cases by blending single-input shuffles.
8807   if (NumV2Elements > 0)
8808     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v16i8, V1, V2,
8809                                                       Mask, DAG);
8810
8811   // The fallback path for single-input shuffles widens this into two v8i16
8812   // vectors with unpacks, shuffles those, and then pulls them back together
8813   // with a pack.
8814   SDValue V = V1;
8815
8816   int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8817   int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8818   for (int i = 0; i < 16; ++i)
8819     if (Mask[i] >= 0)
8820       (i < 8 ? LoBlendMask[i] : HiBlendMask[i % 8]) = Mask[i];
8821
8822   SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
8823
8824   SDValue VLoHalf, VHiHalf;
8825   // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
8826   // them out and avoid using UNPCK{L,H} to extract the elements of V as
8827   // i16s.
8828   if (std::none_of(std::begin(LoBlendMask), std::end(LoBlendMask),
8829                    [](int M) { return M >= 0 && M % 2 == 1; }) &&
8830       std::none_of(std::begin(HiBlendMask), std::end(HiBlendMask),
8831                    [](int M) { return M >= 0 && M % 2 == 1; })) {
8832     // Use a mask to drop the high bytes.
8833     VLoHalf = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V);
8834     VLoHalf = DAG.getNode(ISD::AND, DL, MVT::v8i16, VLoHalf,
8835                      DAG.getConstant(0x00FF, DL, MVT::v8i16));
8836
8837     // This will be a single vector shuffle instead of a blend so nuke VHiHalf.
8838     VHiHalf = DAG.getUNDEF(MVT::v8i16);
8839
8840     // Squash the masks to point directly into VLoHalf.
8841     for (int &M : LoBlendMask)
8842       if (M >= 0)
8843         M /= 2;
8844     for (int &M : HiBlendMask)
8845       if (M >= 0)
8846         M /= 2;
8847   } else {
8848     // Otherwise just unpack the low half of V into VLoHalf and the high half into
8849     // VHiHalf so that we can blend them as i16s.
8850     VLoHalf = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8851                      DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
8852     VHiHalf = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8853                      DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
8854   }
8855
8856   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, LoBlendMask);
8857   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, HiBlendMask);
8858
8859   return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
8860 }
8861
8862 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
8863 ///
8864 /// This routine breaks down the specific type of 128-bit shuffle and
8865 /// dispatches to the lowering routines accordingly.
8866 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8867                                         MVT VT, const X86Subtarget *Subtarget,
8868                                         SelectionDAG &DAG) {
8869   switch (VT.SimpleTy) {
8870   case MVT::v2i64:
8871     return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8872   case MVT::v2f64:
8873     return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8874   case MVT::v4i32:
8875     return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
8876   case MVT::v4f32:
8877     return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
8878   case MVT::v8i16:
8879     return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
8880   case MVT::v16i8:
8881     return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
8882
8883   default:
8884     llvm_unreachable("Unimplemented!");
8885   }
8886 }
8887
8888 /// \brief Helper function to test whether a shuffle mask could be
8889 /// simplified by widening the elements being shuffled.
8890 ///
8891 /// Appends the mask for wider elements in WidenedMask if valid. Otherwise
8892 /// leaves it in an unspecified state.
8893 ///
8894 /// NOTE: This must handle normal vector shuffle masks and *target* vector
8895 /// shuffle masks. The latter have the special property of a '-2' representing
8896 /// a zero-ed lane of a vector.
8897 static bool canWidenShuffleElements(ArrayRef<int> Mask,
8898                                     SmallVectorImpl<int> &WidenedMask) {
8899   for (int i = 0, Size = Mask.size(); i < Size; i += 2) {
8900     // If both elements are undef, its trivial.
8901     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] == SM_SentinelUndef) {
8902       WidenedMask.push_back(SM_SentinelUndef);
8903       continue;
8904     }
8905
8906     // Check for an undef mask and a mask value properly aligned to fit with
8907     // a pair of values. If we find such a case, use the non-undef mask's value.
8908     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] >= 0 && Mask[i + 1] % 2 == 1) {
8909       WidenedMask.push_back(Mask[i + 1] / 2);
8910       continue;
8911     }
8912     if (Mask[i + 1] == SM_SentinelUndef && Mask[i] >= 0 && Mask[i] % 2 == 0) {
8913       WidenedMask.push_back(Mask[i] / 2);
8914       continue;
8915     }
8916
8917     // When zeroing, we need to spread the zeroing across both lanes to widen.
8918     if (Mask[i] == SM_SentinelZero || Mask[i + 1] == SM_SentinelZero) {
8919       if ((Mask[i] == SM_SentinelZero || Mask[i] == SM_SentinelUndef) &&
8920           (Mask[i + 1] == SM_SentinelZero || Mask[i + 1] == SM_SentinelUndef)) {
8921         WidenedMask.push_back(SM_SentinelZero);
8922         continue;
8923       }
8924       return false;
8925     }
8926
8927     // Finally check if the two mask values are adjacent and aligned with
8928     // a pair.
8929     if (Mask[i] != SM_SentinelUndef && Mask[i] % 2 == 0 && Mask[i] + 1 == Mask[i + 1]) {
8930       WidenedMask.push_back(Mask[i] / 2);
8931       continue;
8932     }
8933
8934     // Otherwise we can't safely widen the elements used in this shuffle.
8935     return false;
8936   }
8937   assert(WidenedMask.size() == Mask.size() / 2 &&
8938          "Incorrect size of mask after widening the elements!");
8939
8940   return true;
8941 }
8942
8943 /// \brief Generic routine to split vector shuffle into half-sized shuffles.
8944 ///
8945 /// This routine just extracts two subvectors, shuffles them independently, and
8946 /// then concatenates them back together. This should work effectively with all
8947 /// AVX vector shuffle types.
8948 static SDValue splitAndLowerVectorShuffle(SDLoc DL, MVT VT, SDValue V1,
8949                                           SDValue V2, ArrayRef<int> Mask,
8950                                           SelectionDAG &DAG) {
8951   assert(VT.getSizeInBits() >= 256 &&
8952          "Only for 256-bit or wider vector shuffles!");
8953   assert(V1.getSimpleValueType() == VT && "Bad operand type!");
8954   assert(V2.getSimpleValueType() == VT && "Bad operand type!");
8955
8956   ArrayRef<int> LoMask = Mask.slice(0, Mask.size() / 2);
8957   ArrayRef<int> HiMask = Mask.slice(Mask.size() / 2);
8958
8959   int NumElements = VT.getVectorNumElements();
8960   int SplitNumElements = NumElements / 2;
8961   MVT ScalarVT = VT.getScalarType();
8962   MVT SplitVT = MVT::getVectorVT(ScalarVT, NumElements / 2);
8963
8964   // Rather than splitting build-vectors, just build two narrower build
8965   // vectors. This helps shuffling with splats and zeros.
8966   auto SplitVector = [&](SDValue V) {
8967     while (V.getOpcode() == ISD::BITCAST)
8968       V = V->getOperand(0);
8969
8970     MVT OrigVT = V.getSimpleValueType();
8971     int OrigNumElements = OrigVT.getVectorNumElements();
8972     int OrigSplitNumElements = OrigNumElements / 2;
8973     MVT OrigScalarVT = OrigVT.getScalarType();
8974     MVT OrigSplitVT = MVT::getVectorVT(OrigScalarVT, OrigNumElements / 2);
8975
8976     SDValue LoV, HiV;
8977
8978     auto *BV = dyn_cast<BuildVectorSDNode>(V);
8979     if (!BV) {
8980       LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
8981                         DAG.getIntPtrConstant(0, DL));
8982       HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
8983                         DAG.getIntPtrConstant(OrigSplitNumElements, DL));
8984     } else {
8985
8986       SmallVector<SDValue, 16> LoOps, HiOps;
8987       for (int i = 0; i < OrigSplitNumElements; ++i) {
8988         LoOps.push_back(BV->getOperand(i));
8989         HiOps.push_back(BV->getOperand(i + OrigSplitNumElements));
8990       }
8991       LoV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, LoOps);
8992       HiV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, HiOps);
8993     }
8994     return std::make_pair(DAG.getNode(ISD::BITCAST, DL, SplitVT, LoV),
8995                           DAG.getNode(ISD::BITCAST, DL, SplitVT, HiV));
8996   };
8997
8998   SDValue LoV1, HiV1, LoV2, HiV2;
8999   std::tie(LoV1, HiV1) = SplitVector(V1);
9000   std::tie(LoV2, HiV2) = SplitVector(V2);
9001
9002   // Now create two 4-way blends of these half-width vectors.
9003   auto HalfBlend = [&](ArrayRef<int> HalfMask) {
9004     bool UseLoV1 = false, UseHiV1 = false, UseLoV2 = false, UseHiV2 = false;
9005     SmallVector<int, 32> V1BlendMask, V2BlendMask, BlendMask;
9006     for (int i = 0; i < SplitNumElements; ++i) {
9007       int M = HalfMask[i];
9008       if (M >= NumElements) {
9009         if (M >= NumElements + SplitNumElements)
9010           UseHiV2 = true;
9011         else
9012           UseLoV2 = true;
9013         V2BlendMask.push_back(M - NumElements);
9014         V1BlendMask.push_back(-1);
9015         BlendMask.push_back(SplitNumElements + i);
9016       } else if (M >= 0) {
9017         if (M >= SplitNumElements)
9018           UseHiV1 = true;
9019         else
9020           UseLoV1 = true;
9021         V2BlendMask.push_back(-1);
9022         V1BlendMask.push_back(M);
9023         BlendMask.push_back(i);
9024       } else {
9025         V2BlendMask.push_back(-1);
9026         V1BlendMask.push_back(-1);
9027         BlendMask.push_back(-1);
9028       }
9029     }
9030
9031     // Because the lowering happens after all combining takes place, we need to
9032     // manually combine these blend masks as much as possible so that we create
9033     // a minimal number of high-level vector shuffle nodes.
9034
9035     // First try just blending the halves of V1 or V2.
9036     if (!UseLoV1 && !UseHiV1 && !UseLoV2 && !UseHiV2)
9037       return DAG.getUNDEF(SplitVT);
9038     if (!UseLoV2 && !UseHiV2)
9039       return DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9040     if (!UseLoV1 && !UseHiV1)
9041       return DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9042
9043     SDValue V1Blend, V2Blend;
9044     if (UseLoV1 && UseHiV1) {
9045       V1Blend =
9046         DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9047     } else {
9048       // We only use half of V1 so map the usage down into the final blend mask.
9049       V1Blend = UseLoV1 ? LoV1 : HiV1;
9050       for (int i = 0; i < SplitNumElements; ++i)
9051         if (BlendMask[i] >= 0 && BlendMask[i] < SplitNumElements)
9052           BlendMask[i] = V1BlendMask[i] - (UseLoV1 ? 0 : SplitNumElements);
9053     }
9054     if (UseLoV2 && UseHiV2) {
9055       V2Blend =
9056         DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9057     } else {
9058       // We only use half of V2 so map the usage down into the final blend mask.
9059       V2Blend = UseLoV2 ? LoV2 : HiV2;
9060       for (int i = 0; i < SplitNumElements; ++i)
9061         if (BlendMask[i] >= SplitNumElements)
9062           BlendMask[i] = V2BlendMask[i] + (UseLoV2 ? SplitNumElements : 0);
9063     }
9064     return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
9065   };
9066   SDValue Lo = HalfBlend(LoMask);
9067   SDValue Hi = HalfBlend(HiMask);
9068   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
9069 }
9070
9071 /// \brief Either split a vector in halves or decompose the shuffles and the
9072 /// blend.
9073 ///
9074 /// This is provided as a good fallback for many lowerings of non-single-input
9075 /// shuffles with more than one 128-bit lane. In those cases, we want to select
9076 /// between splitting the shuffle into 128-bit components and stitching those
9077 /// back together vs. extracting the single-input shuffles and blending those
9078 /// results.
9079 static SDValue lowerVectorShuffleAsSplitOrBlend(SDLoc DL, MVT VT, SDValue V1,
9080                                                 SDValue V2, ArrayRef<int> Mask,
9081                                                 SelectionDAG &DAG) {
9082   assert(!isSingleInputShuffleMask(Mask) && "This routine must not be used to "
9083                                             "lower single-input shuffles as it "
9084                                             "could then recurse on itself.");
9085   int Size = Mask.size();
9086
9087   // If this can be modeled as a broadcast of two elements followed by a blend,
9088   // prefer that lowering. This is especially important because broadcasts can
9089   // often fold with memory operands.
9090   auto DoBothBroadcast = [&] {
9091     int V1BroadcastIdx = -1, V2BroadcastIdx = -1;
9092     for (int M : Mask)
9093       if (M >= Size) {
9094         if (V2BroadcastIdx == -1)
9095           V2BroadcastIdx = M - Size;
9096         else if (M - Size != V2BroadcastIdx)
9097           return false;
9098       } else if (M >= 0) {
9099         if (V1BroadcastIdx == -1)
9100           V1BroadcastIdx = M;
9101         else if (M != V1BroadcastIdx)
9102           return false;
9103       }
9104     return true;
9105   };
9106   if (DoBothBroadcast())
9107     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask,
9108                                                       DAG);
9109
9110   // If the inputs all stem from a single 128-bit lane of each input, then we
9111   // split them rather than blending because the split will decompose to
9112   // unusually few instructions.
9113   int LaneCount = VT.getSizeInBits() / 128;
9114   int LaneSize = Size / LaneCount;
9115   SmallBitVector LaneInputs[2];
9116   LaneInputs[0].resize(LaneCount, false);
9117   LaneInputs[1].resize(LaneCount, false);
9118   for (int i = 0; i < Size; ++i)
9119     if (Mask[i] >= 0)
9120       LaneInputs[Mask[i] / Size][(Mask[i] % Size) / LaneSize] = true;
9121   if (LaneInputs[0].count() <= 1 && LaneInputs[1].count() <= 1)
9122     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9123
9124   // Otherwise, just fall back to decomposed shuffles and a blend. This requires
9125   // that the decomposed single-input shuffles don't end up here.
9126   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9127 }
9128
9129 /// \brief Lower a vector shuffle crossing multiple 128-bit lanes as
9130 /// a permutation and blend of those lanes.
9131 ///
9132 /// This essentially blends the out-of-lane inputs to each lane into the lane
9133 /// from a permuted copy of the vector. This lowering strategy results in four
9134 /// instructions in the worst case for a single-input cross lane shuffle which
9135 /// is lower than any other fully general cross-lane shuffle strategy I'm aware
9136 /// of. Special cases for each particular shuffle pattern should be handled
9137 /// prior to trying this lowering.
9138 static SDValue lowerVectorShuffleAsLanePermuteAndBlend(SDLoc DL, MVT VT,
9139                                                        SDValue V1, SDValue V2,
9140                                                        ArrayRef<int> Mask,
9141                                                        SelectionDAG &DAG) {
9142   // FIXME: This should probably be generalized for 512-bit vectors as well.
9143   assert(VT.getSizeInBits() == 256 && "Only for 256-bit vector shuffles!");
9144   int LaneSize = Mask.size() / 2;
9145
9146   // If there are only inputs from one 128-bit lane, splitting will in fact be
9147   // less expensive. The flags track whether the given lane contains an element
9148   // that crosses to another lane.
9149   bool LaneCrossing[2] = {false, false};
9150   for (int i = 0, Size = Mask.size(); i < Size; ++i)
9151     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
9152       LaneCrossing[(Mask[i] % Size) / LaneSize] = true;
9153   if (!LaneCrossing[0] || !LaneCrossing[1])
9154     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9155
9156   if (isSingleInputShuffleMask(Mask)) {
9157     SmallVector<int, 32> FlippedBlendMask;
9158     for (int i = 0, Size = Mask.size(); i < Size; ++i)
9159       FlippedBlendMask.push_back(
9160           Mask[i] < 0 ? -1 : (((Mask[i] % Size) / LaneSize == i / LaneSize)
9161                                   ? Mask[i]
9162                                   : Mask[i] % LaneSize +
9163                                         (i / LaneSize) * LaneSize + Size));
9164
9165     // Flip the vector, and blend the results which should now be in-lane. The
9166     // VPERM2X128 mask uses the low 2 bits for the low source and bits 4 and
9167     // 5 for the high source. The value 3 selects the high half of source 2 and
9168     // the value 2 selects the low half of source 2. We only use source 2 to
9169     // allow folding it into a memory operand.
9170     unsigned PERMMask = 3 | 2 << 4;
9171     SDValue Flipped = DAG.getNode(X86ISD::VPERM2X128, DL, VT, DAG.getUNDEF(VT),
9172                                   V1, DAG.getConstant(PERMMask, DL, MVT::i8));
9173     return DAG.getVectorShuffle(VT, DL, V1, Flipped, FlippedBlendMask);
9174   }
9175
9176   // This now reduces to two single-input shuffles of V1 and V2 which at worst
9177   // will be handled by the above logic and a blend of the results, much like
9178   // other patterns in AVX.
9179   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9180 }
9181
9182 /// \brief Handle lowering 2-lane 128-bit shuffles.
9183 static SDValue lowerV2X128VectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9184                                         SDValue V2, ArrayRef<int> Mask,
9185                                         const X86Subtarget *Subtarget,
9186                                         SelectionDAG &DAG) {
9187   // TODO: If minimizing size and one of the inputs is a zero vector and the
9188   // the zero vector has only one use, we could use a VPERM2X128 to save the
9189   // instruction bytes needed to explicitly generate the zero vector.
9190
9191   // Blends are faster and handle all the non-lane-crossing cases.
9192   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, VT, V1, V2, Mask,
9193                                                 Subtarget, DAG))
9194     return Blend;
9195
9196   bool IsV1Zero = ISD::isBuildVectorAllZeros(V1.getNode());
9197   bool IsV2Zero = ISD::isBuildVectorAllZeros(V2.getNode());
9198
9199   // If either input operand is a zero vector, use VPERM2X128 because its mask
9200   // allows us to replace the zero input with an implicit zero.
9201   if (!IsV1Zero && !IsV2Zero) {
9202     // Check for patterns which can be matched with a single insert of a 128-bit
9203     // subvector.
9204     bool OnlyUsesV1 = isShuffleEquivalent(V1, V2, Mask, {0, 1, 0, 1});
9205     if (OnlyUsesV1 || isShuffleEquivalent(V1, V2, Mask, {0, 1, 4, 5})) {
9206       MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(),
9207                                    VT.getVectorNumElements() / 2);
9208       SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
9209                                 DAG.getIntPtrConstant(0, DL));
9210       SDValue HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT,
9211                                 OnlyUsesV1 ? V1 : V2,
9212                                 DAG.getIntPtrConstant(0, DL));
9213       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoV, HiV);
9214     }
9215   }
9216
9217   // Otherwise form a 128-bit permutation. After accounting for undefs,
9218   // convert the 64-bit shuffle mask selection values into 128-bit
9219   // selection bits by dividing the indexes by 2 and shifting into positions
9220   // defined by a vperm2*128 instruction's immediate control byte.
9221
9222   // The immediate permute control byte looks like this:
9223   //    [1:0] - select 128 bits from sources for low half of destination
9224   //    [2]   - ignore
9225   //    [3]   - zero low half of destination
9226   //    [5:4] - select 128 bits from sources for high half of destination
9227   //    [6]   - ignore
9228   //    [7]   - zero high half of destination
9229
9230   int MaskLO = Mask[0];
9231   if (MaskLO == SM_SentinelUndef)
9232     MaskLO = Mask[1] == SM_SentinelUndef ? 0 : Mask[1];
9233
9234   int MaskHI = Mask[2];
9235   if (MaskHI == SM_SentinelUndef)
9236     MaskHI = Mask[3] == SM_SentinelUndef ? 0 : Mask[3];
9237
9238   unsigned PermMask = MaskLO / 2 | (MaskHI / 2) << 4;
9239
9240   // If either input is a zero vector, replace it with an undef input.
9241   // Shuffle mask values <  4 are selecting elements of V1.
9242   // Shuffle mask values >= 4 are selecting elements of V2.
9243   // Adjust each half of the permute mask by clearing the half that was
9244   // selecting the zero vector and setting the zero mask bit.
9245   if (IsV1Zero) {
9246     V1 = DAG.getUNDEF(VT);
9247     if (MaskLO < 4)
9248       PermMask = (PermMask & 0xf0) | 0x08;
9249     if (MaskHI < 4)
9250       PermMask = (PermMask & 0x0f) | 0x80;
9251   }
9252   if (IsV2Zero) {
9253     V2 = DAG.getUNDEF(VT);
9254     if (MaskLO >= 4)
9255       PermMask = (PermMask & 0xf0) | 0x08;
9256     if (MaskHI >= 4)
9257       PermMask = (PermMask & 0x0f) | 0x80;
9258   }
9259
9260   return DAG.getNode(X86ISD::VPERM2X128, DL, VT, V1, V2,
9261                      DAG.getConstant(PermMask, DL, MVT::i8));
9262 }
9263
9264 /// \brief Lower a vector shuffle by first fixing the 128-bit lanes and then
9265 /// shuffling each lane.
9266 ///
9267 /// This will only succeed when the result of fixing the 128-bit lanes results
9268 /// in a single-input non-lane-crossing shuffle with a repeating shuffle mask in
9269 /// each 128-bit lanes. This handles many cases where we can quickly blend away
9270 /// the lane crosses early and then use simpler shuffles within each lane.
9271 ///
9272 /// FIXME: It might be worthwhile at some point to support this without
9273 /// requiring the 128-bit lane-relative shuffles to be repeating, but currently
9274 /// in x86 only floating point has interesting non-repeating shuffles, and even
9275 /// those are still *marginally* more expensive.
9276 static SDValue lowerVectorShuffleByMerging128BitLanes(
9277     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
9278     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
9279   assert(!isSingleInputShuffleMask(Mask) &&
9280          "This is only useful with multiple inputs.");
9281
9282   int Size = Mask.size();
9283   int LaneSize = 128 / VT.getScalarSizeInBits();
9284   int NumLanes = Size / LaneSize;
9285   assert(NumLanes > 1 && "Only handles 256-bit and wider shuffles.");
9286
9287   // See if we can build a hypothetical 128-bit lane-fixing shuffle mask. Also
9288   // check whether the in-128-bit lane shuffles share a repeating pattern.
9289   SmallVector<int, 4> Lanes;
9290   Lanes.resize(NumLanes, -1);
9291   SmallVector<int, 4> InLaneMask;
9292   InLaneMask.resize(LaneSize, -1);
9293   for (int i = 0; i < Size; ++i) {
9294     if (Mask[i] < 0)
9295       continue;
9296
9297     int j = i / LaneSize;
9298
9299     if (Lanes[j] < 0) {
9300       // First entry we've seen for this lane.
9301       Lanes[j] = Mask[i] / LaneSize;
9302     } else if (Lanes[j] != Mask[i] / LaneSize) {
9303       // This doesn't match the lane selected previously!
9304       return SDValue();
9305     }
9306
9307     // Check that within each lane we have a consistent shuffle mask.
9308     int k = i % LaneSize;
9309     if (InLaneMask[k] < 0) {
9310       InLaneMask[k] = Mask[i] % LaneSize;
9311     } else if (InLaneMask[k] != Mask[i] % LaneSize) {
9312       // This doesn't fit a repeating in-lane mask.
9313       return SDValue();
9314     }
9315   }
9316
9317   // First shuffle the lanes into place.
9318   MVT LaneVT = MVT::getVectorVT(VT.isFloatingPoint() ? MVT::f64 : MVT::i64,
9319                                 VT.getSizeInBits() / 64);
9320   SmallVector<int, 8> LaneMask;
9321   LaneMask.resize(NumLanes * 2, -1);
9322   for (int i = 0; i < NumLanes; ++i)
9323     if (Lanes[i] >= 0) {
9324       LaneMask[2 * i + 0] = 2*Lanes[i] + 0;
9325       LaneMask[2 * i + 1] = 2*Lanes[i] + 1;
9326     }
9327
9328   V1 = DAG.getNode(ISD::BITCAST, DL, LaneVT, V1);
9329   V2 = DAG.getNode(ISD::BITCAST, DL, LaneVT, V2);
9330   SDValue LaneShuffle = DAG.getVectorShuffle(LaneVT, DL, V1, V2, LaneMask);
9331
9332   // Cast it back to the type we actually want.
9333   LaneShuffle = DAG.getNode(ISD::BITCAST, DL, VT, LaneShuffle);
9334
9335   // Now do a simple shuffle that isn't lane crossing.
9336   SmallVector<int, 8> NewMask;
9337   NewMask.resize(Size, -1);
9338   for (int i = 0; i < Size; ++i)
9339     if (Mask[i] >= 0)
9340       NewMask[i] = (i / LaneSize) * LaneSize + Mask[i] % LaneSize;
9341   assert(!is128BitLaneCrossingShuffleMask(VT, NewMask) &&
9342          "Must not introduce lane crosses at this point!");
9343
9344   return DAG.getVectorShuffle(VT, DL, LaneShuffle, DAG.getUNDEF(VT), NewMask);
9345 }
9346
9347 /// \brief Test whether the specified input (0 or 1) is in-place blended by the
9348 /// given mask.
9349 ///
9350 /// This returns true if the elements from a particular input are already in the
9351 /// slot required by the given mask and require no permutation.
9352 static bool isShuffleMaskInputInPlace(int Input, ArrayRef<int> Mask) {
9353   assert((Input == 0 || Input == 1) && "Only two inputs to shuffles.");
9354   int Size = Mask.size();
9355   for (int i = 0; i < Size; ++i)
9356     if (Mask[i] >= 0 && Mask[i] / Size == Input && Mask[i] % Size != i)
9357       return false;
9358
9359   return true;
9360 }
9361
9362 /// \brief Handle lowering of 4-lane 64-bit floating point shuffles.
9363 ///
9364 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
9365 /// isn't available.
9366 static SDValue lowerV4F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9367                                        const X86Subtarget *Subtarget,
9368                                        SelectionDAG &DAG) {
9369   SDLoc DL(Op);
9370   assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9371   assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9372   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9373   ArrayRef<int> Mask = SVOp->getMask();
9374   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9375
9376   SmallVector<int, 4> WidenedMask;
9377   if (canWidenShuffleElements(Mask, WidenedMask))
9378     return lowerV2X128VectorShuffle(DL, MVT::v4f64, V1, V2, Mask, Subtarget,
9379                                     DAG);
9380
9381   if (isSingleInputShuffleMask(Mask)) {
9382     // Check for being able to broadcast a single element.
9383     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f64, V1,
9384                                                           Mask, Subtarget, DAG))
9385       return Broadcast;
9386
9387     // Use low duplicate instructions for masks that match their pattern.
9388     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
9389       return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v4f64, V1);
9390
9391     if (!is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask)) {
9392       // Non-half-crossing single input shuffles can be lowerid with an
9393       // interleaved permutation.
9394       unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
9395                               ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
9396       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f64, V1,
9397                          DAG.getConstant(VPERMILPMask, DL, MVT::i8));
9398     }
9399
9400     // With AVX2 we have direct support for this permutation.
9401     if (Subtarget->hasAVX2())
9402       return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4f64, V1,
9403                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
9404
9405     // Otherwise, fall back.
9406     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v4f64, V1, V2, Mask,
9407                                                    DAG);
9408   }
9409
9410   // X86 has dedicated unpack instructions that can handle specific blend
9411   // operations: UNPCKH and UNPCKL.
9412   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9413     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V1, V2);
9414   if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9415     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V1, V2);
9416   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9417     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V2, V1);
9418   if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9419     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V2, V1);
9420
9421   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f64, V1, V2, Mask,
9422                                                 Subtarget, DAG))
9423     return Blend;
9424
9425   // Check if the blend happens to exactly fit that of SHUFPD.
9426   if ((Mask[0] == -1 || Mask[0] < 2) &&
9427       (Mask[1] == -1 || (Mask[1] >= 4 && Mask[1] < 6)) &&
9428       (Mask[2] == -1 || (Mask[2] >= 2 && Mask[2] < 4)) &&
9429       (Mask[3] == -1 || Mask[3] >= 6)) {
9430     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 5) << 1) |
9431                           ((Mask[2] == 3) << 2) | ((Mask[3] == 7) << 3);
9432     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f64, V1, V2,
9433                        DAG.getConstant(SHUFPDMask, DL, MVT::i8));
9434   }
9435   if ((Mask[0] == -1 || (Mask[0] >= 4 && Mask[0] < 6)) &&
9436       (Mask[1] == -1 || Mask[1] < 2) &&
9437       (Mask[2] == -1 || Mask[2] >= 6) &&
9438       (Mask[3] == -1 || (Mask[3] >= 2 && Mask[3] < 4))) {
9439     unsigned SHUFPDMask = (Mask[0] == 5) | ((Mask[1] == 1) << 1) |
9440                           ((Mask[2] == 7) << 2) | ((Mask[3] == 3) << 3);
9441     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f64, V2, V1,
9442                        DAG.getConstant(SHUFPDMask, DL, MVT::i8));
9443   }
9444
9445   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9446   // shuffle. However, if we have AVX2 and either inputs are already in place,
9447   // we will be able to shuffle even across lanes the other input in a single
9448   // instruction so skip this pattern.
9449   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9450                                  isShuffleMaskInputInPlace(1, Mask))))
9451     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9452             DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
9453       return Result;
9454
9455   // If we have AVX2 then we always want to lower with a blend because an v4 we
9456   // can fully permute the elements.
9457   if (Subtarget->hasAVX2())
9458     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4f64, V1, V2,
9459                                                       Mask, DAG);
9460
9461   // Otherwise fall back on generic lowering.
9462   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v4f64, V1, V2, Mask, DAG);
9463 }
9464
9465 /// \brief Handle lowering of 4-lane 64-bit integer shuffles.
9466 ///
9467 /// This routine is only called when we have AVX2 and thus a reasonable
9468 /// instruction set for v4i64 shuffling..
9469 static SDValue lowerV4I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9470                                        const X86Subtarget *Subtarget,
9471                                        SelectionDAG &DAG) {
9472   SDLoc DL(Op);
9473   assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9474   assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9475   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9476   ArrayRef<int> Mask = SVOp->getMask();
9477   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9478   assert(Subtarget->hasAVX2() && "We can only lower v4i64 with AVX2!");
9479
9480   SmallVector<int, 4> WidenedMask;
9481   if (canWidenShuffleElements(Mask, WidenedMask))
9482     return lowerV2X128VectorShuffle(DL, MVT::v4i64, V1, V2, Mask, Subtarget,
9483                                     DAG);
9484
9485   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i64, V1, V2, Mask,
9486                                                 Subtarget, DAG))
9487     return Blend;
9488
9489   // Check for being able to broadcast a single element.
9490   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i64, V1,
9491                                                         Mask, Subtarget, DAG))
9492     return Broadcast;
9493
9494   // When the shuffle is mirrored between the 128-bit lanes of the unit, we can
9495   // use lower latency instructions that will operate on both 128-bit lanes.
9496   SmallVector<int, 2> RepeatedMask;
9497   if (is128BitLaneRepeatedShuffleMask(MVT::v4i64, Mask, RepeatedMask)) {
9498     if (isSingleInputShuffleMask(Mask)) {
9499       int PSHUFDMask[] = {-1, -1, -1, -1};
9500       for (int i = 0; i < 2; ++i)
9501         if (RepeatedMask[i] >= 0) {
9502           PSHUFDMask[2 * i] = 2 * RepeatedMask[i];
9503           PSHUFDMask[2 * i + 1] = 2 * RepeatedMask[i] + 1;
9504         }
9505       return DAG.getNode(
9506           ISD::BITCAST, DL, MVT::v4i64,
9507           DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32,
9508                       DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, V1),
9509                       getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
9510     }
9511   }
9512
9513   // AVX2 provides a direct instruction for permuting a single input across
9514   // lanes.
9515   if (isSingleInputShuffleMask(Mask))
9516     return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4i64, V1,
9517                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
9518
9519   // Try to use shift instructions.
9520   if (SDValue Shift =
9521           lowerVectorShuffleAsShift(DL, MVT::v4i64, V1, V2, Mask, DAG))
9522     return Shift;
9523
9524   // Use dedicated unpack instructions for masks that match their pattern.
9525   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9526     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V1, V2);
9527   if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9528     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V1, V2);
9529   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9530     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V2, V1);
9531   if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9532     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V2, V1);
9533
9534   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9535   // shuffle. However, if we have AVX2 and either inputs are already in place,
9536   // we will be able to shuffle even across lanes the other input in a single
9537   // instruction so skip this pattern.
9538   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9539                                  isShuffleMaskInputInPlace(1, Mask))))
9540     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9541             DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
9542       return Result;
9543
9544   // Otherwise fall back on generic blend lowering.
9545   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i64, V1, V2,
9546                                                     Mask, DAG);
9547 }
9548
9549 /// \brief Handle lowering of 8-lane 32-bit floating point shuffles.
9550 ///
9551 /// Also ends up handling lowering of 8-lane 32-bit integer shuffles when AVX2
9552 /// isn't available.
9553 static SDValue lowerV8F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9554                                        const X86Subtarget *Subtarget,
9555                                        SelectionDAG &DAG) {
9556   SDLoc DL(Op);
9557   assert(V1.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
9558   assert(V2.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
9559   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9560   ArrayRef<int> Mask = SVOp->getMask();
9561   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9562
9563   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8f32, V1, V2, Mask,
9564                                                 Subtarget, DAG))
9565     return Blend;
9566
9567   // Check for being able to broadcast a single element.
9568   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8f32, V1,
9569                                                         Mask, Subtarget, DAG))
9570     return Broadcast;
9571
9572   // If the shuffle mask is repeated in each 128-bit lane, we have many more
9573   // options to efficiently lower the shuffle.
9574   SmallVector<int, 4> RepeatedMask;
9575   if (is128BitLaneRepeatedShuffleMask(MVT::v8f32, Mask, RepeatedMask)) {
9576     assert(RepeatedMask.size() == 4 &&
9577            "Repeated masks must be half the mask width!");
9578
9579     // Use even/odd duplicate instructions for masks that match their pattern.
9580     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2, 4, 4, 6, 6}))
9581       return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v8f32, V1);
9582     if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3, 5, 5, 7, 7}))
9583       return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v8f32, V1);
9584
9585     if (isSingleInputShuffleMask(Mask))
9586       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, V1,
9587                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
9588
9589     // Use dedicated unpack instructions for masks that match their pattern.
9590     if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
9591       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V1, V2);
9592     if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
9593       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V1, V2);
9594     if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
9595       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V2, V1);
9596     if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
9597       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V2, V1);
9598
9599     // Otherwise, fall back to a SHUFPS sequence. Here it is important that we
9600     // have already handled any direct blends. We also need to squash the
9601     // repeated mask into a simulated v4f32 mask.
9602     for (int i = 0; i < 4; ++i)
9603       if (RepeatedMask[i] >= 8)
9604         RepeatedMask[i] -= 4;
9605     return lowerVectorShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask, V1, V2, DAG);
9606   }
9607
9608   // If we have a single input shuffle with different shuffle patterns in the
9609   // two 128-bit lanes use the variable mask to VPERMILPS.
9610   if (isSingleInputShuffleMask(Mask)) {
9611     SDValue VPermMask[8];
9612     for (int i = 0; i < 8; ++i)
9613       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
9614                                  : DAG.getConstant(Mask[i], DL, MVT::i32);
9615     if (!is128BitLaneCrossingShuffleMask(MVT::v8f32, Mask))
9616       return DAG.getNode(
9617           X86ISD::VPERMILPV, DL, MVT::v8f32, V1,
9618           DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask));
9619
9620     if (Subtarget->hasAVX2())
9621       return DAG.getNode(X86ISD::VPERMV, DL, MVT::v8f32,
9622                          DAG.getNode(ISD::BITCAST, DL, MVT::v8f32,
9623                                      DAG.getNode(ISD::BUILD_VECTOR, DL,
9624                                                  MVT::v8i32, VPermMask)),
9625                          V1);
9626
9627     // Otherwise, fall back.
9628     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v8f32, V1, V2, Mask,
9629                                                    DAG);
9630   }
9631
9632   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9633   // shuffle.
9634   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9635           DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
9636     return Result;
9637
9638   // If we have AVX2 then we always want to lower with a blend because at v8 we
9639   // can fully permute the elements.
9640   if (Subtarget->hasAVX2())
9641     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8f32, V1, V2,
9642                                                       Mask, DAG);
9643
9644   // Otherwise fall back on generic lowering.
9645   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask, DAG);
9646 }
9647
9648 /// \brief Handle lowering of 8-lane 32-bit integer shuffles.
9649 ///
9650 /// This routine is only called when we have AVX2 and thus a reasonable
9651 /// instruction set for v8i32 shuffling..
9652 static SDValue lowerV8I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9653                                        const X86Subtarget *Subtarget,
9654                                        SelectionDAG &DAG) {
9655   SDLoc DL(Op);
9656   assert(V1.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
9657   assert(V2.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
9658   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9659   ArrayRef<int> Mask = SVOp->getMask();
9660   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9661   assert(Subtarget->hasAVX2() && "We can only lower v8i32 with AVX2!");
9662
9663   // Whenever we can lower this as a zext, that instruction is strictly faster
9664   // than any alternative. It also allows us to fold memory operands into the
9665   // shuffle in many cases.
9666   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v8i32, V1, V2,
9667                                                          Mask, Subtarget, DAG))
9668     return ZExt;
9669
9670   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i32, V1, V2, Mask,
9671                                                 Subtarget, DAG))
9672     return Blend;
9673
9674   // Check for being able to broadcast a single element.
9675   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i32, V1,
9676                                                         Mask, Subtarget, DAG))
9677     return Broadcast;
9678
9679   // If the shuffle mask is repeated in each 128-bit lane we can use more
9680   // efficient instructions that mirror the shuffles across the two 128-bit
9681   // lanes.
9682   SmallVector<int, 4> RepeatedMask;
9683   if (is128BitLaneRepeatedShuffleMask(MVT::v8i32, Mask, RepeatedMask)) {
9684     assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
9685     if (isSingleInputShuffleMask(Mask))
9686       return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32, V1,
9687                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
9688
9689     // Use dedicated unpack instructions for masks that match their pattern.
9690     if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
9691       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V1, V2);
9692     if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
9693       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V1, V2);
9694     if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
9695       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V2, V1);
9696     if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
9697       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V2, V1);
9698   }
9699
9700   // Try to use shift instructions.
9701   if (SDValue Shift =
9702           lowerVectorShuffleAsShift(DL, MVT::v8i32, V1, V2, Mask, DAG))
9703     return Shift;
9704
9705   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9706           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
9707     return Rotate;
9708
9709   // If the shuffle patterns aren't repeated but it is a single input, directly
9710   // generate a cross-lane VPERMD instruction.
9711   if (isSingleInputShuffleMask(Mask)) {
9712     SDValue VPermMask[8];
9713     for (int i = 0; i < 8; ++i)
9714       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
9715                                  : DAG.getConstant(Mask[i], DL, MVT::i32);
9716     return DAG.getNode(
9717         X86ISD::VPERMV, DL, MVT::v8i32,
9718         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask), V1);
9719   }
9720
9721   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9722   // shuffle.
9723   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9724           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
9725     return Result;
9726
9727   // Otherwise fall back on generic blend lowering.
9728   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i32, V1, V2,
9729                                                     Mask, DAG);
9730 }
9731
9732 /// \brief Handle lowering of 16-lane 16-bit integer shuffles.
9733 ///
9734 /// This routine is only called when we have AVX2 and thus a reasonable
9735 /// instruction set for v16i16 shuffling..
9736 static SDValue lowerV16I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9737                                         const X86Subtarget *Subtarget,
9738                                         SelectionDAG &DAG) {
9739   SDLoc DL(Op);
9740   assert(V1.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
9741   assert(V2.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
9742   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9743   ArrayRef<int> Mask = SVOp->getMask();
9744   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
9745   assert(Subtarget->hasAVX2() && "We can only lower v16i16 with AVX2!");
9746
9747   // Whenever we can lower this as a zext, that instruction is strictly faster
9748   // than any alternative. It also allows us to fold memory operands into the
9749   // shuffle in many cases.
9750   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v16i16, V1, V2,
9751                                                          Mask, Subtarget, DAG))
9752     return ZExt;
9753
9754   // Check for being able to broadcast a single element.
9755   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i16, V1,
9756                                                         Mask, Subtarget, DAG))
9757     return Broadcast;
9758
9759   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i16, V1, V2, Mask,
9760                                                 Subtarget, DAG))
9761     return Blend;
9762
9763   // Use dedicated unpack instructions for masks that match their pattern.
9764   if (isShuffleEquivalent(V1, V2, Mask,
9765                           {// First 128-bit lane:
9766                            0, 16, 1, 17, 2, 18, 3, 19,
9767                            // Second 128-bit lane:
9768                            8, 24, 9, 25, 10, 26, 11, 27}))
9769     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i16, V1, V2);
9770   if (isShuffleEquivalent(V1, V2, Mask,
9771                           {// First 128-bit lane:
9772                            4, 20, 5, 21, 6, 22, 7, 23,
9773                            // Second 128-bit lane:
9774                            12, 28, 13, 29, 14, 30, 15, 31}))
9775     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i16, V1, V2);
9776
9777   // Try to use shift instructions.
9778   if (SDValue Shift =
9779           lowerVectorShuffleAsShift(DL, MVT::v16i16, V1, V2, Mask, DAG))
9780     return Shift;
9781
9782   // Try to use byte rotation instructions.
9783   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9784           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
9785     return Rotate;
9786
9787   if (isSingleInputShuffleMask(Mask)) {
9788     // There are no generalized cross-lane shuffle operations available on i16
9789     // element types.
9790     if (is128BitLaneCrossingShuffleMask(MVT::v16i16, Mask))
9791       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v16i16, V1, V2,
9792                                                      Mask, DAG);
9793
9794     SmallVector<int, 8> RepeatedMask;
9795     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
9796       // As this is a single-input shuffle, the repeated mask should be
9797       // a strictly valid v8i16 mask that we can pass through to the v8i16
9798       // lowering to handle even the v16 case.
9799       return lowerV8I16GeneralSingleInputVectorShuffle(
9800           DL, MVT::v16i16, V1, RepeatedMask, Subtarget, DAG);
9801     }
9802
9803     SDValue PSHUFBMask[32];
9804     for (int i = 0; i < 16; ++i) {
9805       if (Mask[i] == -1) {
9806         PSHUFBMask[2 * i] = PSHUFBMask[2 * i + 1] = DAG.getUNDEF(MVT::i8);
9807         continue;
9808       }
9809
9810       int M = i < 8 ? Mask[i] : Mask[i] - 8;
9811       assert(M >= 0 && M < 8 && "Invalid single-input mask!");
9812       PSHUFBMask[2 * i] = DAG.getConstant(2 * M, DL, MVT::i8);
9813       PSHUFBMask[2 * i + 1] = DAG.getConstant(2 * M + 1, DL, MVT::i8);
9814     }
9815     return DAG.getNode(
9816         ISD::BITCAST, DL, MVT::v16i16,
9817         DAG.getNode(
9818             X86ISD::PSHUFB, DL, MVT::v32i8,
9819             DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, V1),
9820             DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask)));
9821   }
9822
9823   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9824   // shuffle.
9825   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9826           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
9827     return Result;
9828
9829   // Otherwise fall back on generic lowering.
9830   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v16i16, V1, V2, Mask, DAG);
9831 }
9832
9833 /// \brief Handle lowering of 32-lane 8-bit integer shuffles.
9834 ///
9835 /// This routine is only called when we have AVX2 and thus a reasonable
9836 /// instruction set for v32i8 shuffling..
9837 static SDValue lowerV32I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9838                                        const X86Subtarget *Subtarget,
9839                                        SelectionDAG &DAG) {
9840   SDLoc DL(Op);
9841   assert(V1.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
9842   assert(V2.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
9843   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9844   ArrayRef<int> Mask = SVOp->getMask();
9845   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
9846   assert(Subtarget->hasAVX2() && "We can only lower v32i8 with AVX2!");
9847
9848   // Whenever we can lower this as a zext, that instruction is strictly faster
9849   // than any alternative. It also allows us to fold memory operands into the
9850   // shuffle in many cases.
9851   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v32i8, V1, V2,
9852                                                          Mask, Subtarget, DAG))
9853     return ZExt;
9854
9855   // Check for being able to broadcast a single element.
9856   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v32i8, V1,
9857                                                         Mask, Subtarget, DAG))
9858     return Broadcast;
9859
9860   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v32i8, V1, V2, Mask,
9861                                                 Subtarget, DAG))
9862     return Blend;
9863
9864   // Use dedicated unpack instructions for masks that match their pattern.
9865   // Note that these are repeated 128-bit lane unpacks, not unpacks across all
9866   // 256-bit lanes.
9867   if (isShuffleEquivalent(
9868           V1, V2, Mask,
9869           {// First 128-bit lane:
9870            0, 32, 1, 33, 2, 34, 3, 35, 4, 36, 5, 37, 6, 38, 7, 39,
9871            // Second 128-bit lane:
9872            16, 48, 17, 49, 18, 50, 19, 51, 20, 52, 21, 53, 22, 54, 23, 55}))
9873     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v32i8, V1, V2);
9874   if (isShuffleEquivalent(
9875           V1, V2, Mask,
9876           {// First 128-bit lane:
9877            8, 40, 9, 41, 10, 42, 11, 43, 12, 44, 13, 45, 14, 46, 15, 47,
9878            // Second 128-bit lane:
9879            24, 56, 25, 57, 26, 58, 27, 59, 28, 60, 29, 61, 30, 62, 31, 63}))
9880     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v32i8, V1, V2);
9881
9882   // Try to use shift instructions.
9883   if (SDValue Shift =
9884           lowerVectorShuffleAsShift(DL, MVT::v32i8, V1, V2, Mask, DAG))
9885     return Shift;
9886
9887   // Try to use byte rotation instructions.
9888   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9889           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
9890     return Rotate;
9891
9892   if (isSingleInputShuffleMask(Mask)) {
9893     // There are no generalized cross-lane shuffle operations available on i8
9894     // element types.
9895     if (is128BitLaneCrossingShuffleMask(MVT::v32i8, Mask))
9896       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v32i8, V1, V2,
9897                                                      Mask, DAG);
9898
9899     SDValue PSHUFBMask[32];
9900     for (int i = 0; i < 32; ++i)
9901       PSHUFBMask[i] =
9902           Mask[i] < 0
9903               ? DAG.getUNDEF(MVT::i8)
9904               : DAG.getConstant(Mask[i] < 16 ? Mask[i] : Mask[i] - 16, DL,
9905                                 MVT::i8);
9906
9907     return DAG.getNode(
9908         X86ISD::PSHUFB, DL, MVT::v32i8, V1,
9909         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask));
9910   }
9911
9912   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9913   // shuffle.
9914   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9915           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
9916     return Result;
9917
9918   // Otherwise fall back on generic lowering.
9919   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v32i8, V1, V2, Mask, DAG);
9920 }
9921
9922 /// \brief High-level routine to lower various 256-bit x86 vector shuffles.
9923 ///
9924 /// This routine either breaks down the specific type of a 256-bit x86 vector
9925 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
9926 /// together based on the available instructions.
9927 static SDValue lower256BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9928                                         MVT VT, const X86Subtarget *Subtarget,
9929                                         SelectionDAG &DAG) {
9930   SDLoc DL(Op);
9931   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9932   ArrayRef<int> Mask = SVOp->getMask();
9933
9934   // If we have a single input to the zero element, insert that into V1 if we
9935   // can do so cheaply.
9936   int NumElts = VT.getVectorNumElements();
9937   int NumV2Elements = std::count_if(Mask.begin(), Mask.end(), [NumElts](int M) {
9938     return M >= NumElts;
9939   });
9940
9941   if (NumV2Elements == 1 && Mask[0] >= NumElts)
9942     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
9943                               DL, VT, V1, V2, Mask, Subtarget, DAG))
9944       return Insertion;
9945
9946   // There is a really nice hard cut-over between AVX1 and AVX2 that means we can
9947   // check for those subtargets here and avoid much of the subtarget querying in
9948   // the per-vector-type lowering routines. With AVX1 we have essentially *zero*
9949   // ability to manipulate a 256-bit vector with integer types. Since we'll use
9950   // floating point types there eventually, just immediately cast everything to
9951   // a float and operate entirely in that domain.
9952   if (VT.isInteger() && !Subtarget->hasAVX2()) {
9953     int ElementBits = VT.getScalarSizeInBits();
9954     if (ElementBits < 32)
9955       // No floating point type available, decompose into 128-bit vectors.
9956       return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9957
9958     MVT FpVT = MVT::getVectorVT(MVT::getFloatingPointVT(ElementBits),
9959                                 VT.getVectorNumElements());
9960     V1 = DAG.getNode(ISD::BITCAST, DL, FpVT, V1);
9961     V2 = DAG.getNode(ISD::BITCAST, DL, FpVT, V2);
9962     return DAG.getNode(ISD::BITCAST, DL, VT,
9963                        DAG.getVectorShuffle(FpVT, DL, V1, V2, Mask));
9964   }
9965
9966   switch (VT.SimpleTy) {
9967   case MVT::v4f64:
9968     return lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9969   case MVT::v4i64:
9970     return lowerV4I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9971   case MVT::v8f32:
9972     return lowerV8F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9973   case MVT::v8i32:
9974     return lowerV8I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9975   case MVT::v16i16:
9976     return lowerV16I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
9977   case MVT::v32i8:
9978     return lowerV32I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
9979
9980   default:
9981     llvm_unreachable("Not a valid 256-bit x86 vector type!");
9982   }
9983 }
9984
9985 /// \brief Handle lowering of 8-lane 64-bit floating point shuffles.
9986 static SDValue lowerV8F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9987                                        const X86Subtarget *Subtarget,
9988                                        SelectionDAG &DAG) {
9989   SDLoc DL(Op);
9990   assert(V1.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
9991   assert(V2.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
9992   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9993   ArrayRef<int> Mask = SVOp->getMask();
9994   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9995
9996   // X86 has dedicated unpack instructions that can handle specific blend
9997   // operations: UNPCKH and UNPCKL.
9998   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
9999     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f64, V1, V2);
10000   if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
10001     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f64, V1, V2);
10002
10003   // FIXME: Implement direct support for this type!
10004   return splitAndLowerVectorShuffle(DL, MVT::v8f64, V1, V2, Mask, DAG);
10005 }
10006
10007 /// \brief Handle lowering of 16-lane 32-bit floating point shuffles.
10008 static SDValue lowerV16F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10009                                        const X86Subtarget *Subtarget,
10010                                        SelectionDAG &DAG) {
10011   SDLoc DL(Op);
10012   assert(V1.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10013   assert(V2.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10014   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10015   ArrayRef<int> Mask = SVOp->getMask();
10016   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10017
10018   // Use dedicated unpack instructions for masks that match their pattern.
10019   if (isShuffleEquivalent(V1, V2, Mask,
10020                           {// First 128-bit lane.
10021                            0, 16, 1, 17, 4, 20, 5, 21,
10022                            // Second 128-bit lane.
10023                            8, 24, 9, 25, 12, 28, 13, 29}))
10024     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16f32, V1, V2);
10025   if (isShuffleEquivalent(V1, V2, Mask,
10026                           {// First 128-bit lane.
10027                            2, 18, 3, 19, 6, 22, 7, 23,
10028                            // Second 128-bit lane.
10029                            10, 26, 11, 27, 14, 30, 15, 31}))
10030     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16f32, V1, V2);
10031
10032   // FIXME: Implement direct support for this type!
10033   return splitAndLowerVectorShuffle(DL, MVT::v16f32, V1, V2, Mask, DAG);
10034 }
10035
10036 /// \brief Handle lowering of 8-lane 64-bit integer shuffles.
10037 static SDValue lowerV8I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10038                                        const X86Subtarget *Subtarget,
10039                                        SelectionDAG &DAG) {
10040   SDLoc DL(Op);
10041   assert(V1.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10042   assert(V2.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10043   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10044   ArrayRef<int> Mask = SVOp->getMask();
10045   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10046
10047   // X86 has dedicated unpack instructions that can handle specific blend
10048   // operations: UNPCKH and UNPCKL.
10049   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
10050     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i64, V1, V2);
10051   if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
10052     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i64, V1, V2);
10053
10054   // FIXME: Implement direct support for this type!
10055   return splitAndLowerVectorShuffle(DL, MVT::v8i64, V1, V2, Mask, DAG);
10056 }
10057
10058 /// \brief Handle lowering of 16-lane 32-bit integer shuffles.
10059 static SDValue lowerV16I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10060                                        const X86Subtarget *Subtarget,
10061                                        SelectionDAG &DAG) {
10062   SDLoc DL(Op);
10063   assert(V1.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10064   assert(V2.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10065   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10066   ArrayRef<int> Mask = SVOp->getMask();
10067   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10068
10069   // Use dedicated unpack instructions for masks that match their pattern.
10070   if (isShuffleEquivalent(V1, V2, Mask,
10071                           {// First 128-bit lane.
10072                            0, 16, 1, 17, 4, 20, 5, 21,
10073                            // Second 128-bit lane.
10074                            8, 24, 9, 25, 12, 28, 13, 29}))
10075     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i32, V1, V2);
10076   if (isShuffleEquivalent(V1, V2, Mask,
10077                           {// First 128-bit lane.
10078                            2, 18, 3, 19, 6, 22, 7, 23,
10079                            // Second 128-bit lane.
10080                            10, 26, 11, 27, 14, 30, 15, 31}))
10081     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i32, V1, V2);
10082
10083   // FIXME: Implement direct support for this type!
10084   return splitAndLowerVectorShuffle(DL, MVT::v16i32, V1, V2, Mask, DAG);
10085 }
10086
10087 /// \brief Handle lowering of 32-lane 16-bit integer shuffles.
10088 static SDValue lowerV32I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10089                                         const X86Subtarget *Subtarget,
10090                                         SelectionDAG &DAG) {
10091   SDLoc DL(Op);
10092   assert(V1.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10093   assert(V2.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10094   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10095   ArrayRef<int> Mask = SVOp->getMask();
10096   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10097   assert(Subtarget->hasBWI() && "We can only lower v32i16 with AVX-512-BWI!");
10098
10099   // FIXME: Implement direct support for this type!
10100   return splitAndLowerVectorShuffle(DL, MVT::v32i16, V1, V2, Mask, DAG);
10101 }
10102
10103 /// \brief Handle lowering of 64-lane 8-bit integer shuffles.
10104 static SDValue lowerV64I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10105                                        const X86Subtarget *Subtarget,
10106                                        SelectionDAG &DAG) {
10107   SDLoc DL(Op);
10108   assert(V1.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10109   assert(V2.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10110   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10111   ArrayRef<int> Mask = SVOp->getMask();
10112   assert(Mask.size() == 64 && "Unexpected mask size for v64 shuffle!");
10113   assert(Subtarget->hasBWI() && "We can only lower v64i8 with AVX-512-BWI!");
10114
10115   // FIXME: Implement direct support for this type!
10116   return splitAndLowerVectorShuffle(DL, MVT::v64i8, V1, V2, Mask, DAG);
10117 }
10118
10119 /// \brief High-level routine to lower various 512-bit x86 vector shuffles.
10120 ///
10121 /// This routine either breaks down the specific type of a 512-bit x86 vector
10122 /// shuffle or splits it into two 256-bit shuffles and fuses the results back
10123 /// together based on the available instructions.
10124 static SDValue lower512BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10125                                         MVT VT, const X86Subtarget *Subtarget,
10126                                         SelectionDAG &DAG) {
10127   SDLoc DL(Op);
10128   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10129   ArrayRef<int> Mask = SVOp->getMask();
10130   assert(Subtarget->hasAVX512() &&
10131          "Cannot lower 512-bit vectors w/ basic ISA!");
10132
10133   // Check for being able to broadcast a single element.
10134   if (SDValue Broadcast =
10135           lowerVectorShuffleAsBroadcast(DL, VT, V1, Mask, Subtarget, DAG))
10136     return Broadcast;
10137
10138   // Dispatch to each element type for lowering. If we don't have supprot for
10139   // specific element type shuffles at 512 bits, immediately split them and
10140   // lower them. Each lowering routine of a given type is allowed to assume that
10141   // the requisite ISA extensions for that element type are available.
10142   switch (VT.SimpleTy) {
10143   case MVT::v8f64:
10144     return lowerV8F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10145   case MVT::v16f32:
10146     return lowerV16F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10147   case MVT::v8i64:
10148     return lowerV8I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10149   case MVT::v16i32:
10150     return lowerV16I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10151   case MVT::v32i16:
10152     if (Subtarget->hasBWI())
10153       return lowerV32I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10154     break;
10155   case MVT::v64i8:
10156     if (Subtarget->hasBWI())
10157       return lowerV64I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10158     break;
10159
10160   default:
10161     llvm_unreachable("Not a valid 512-bit x86 vector type!");
10162   }
10163
10164   // Otherwise fall back on splitting.
10165   return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10166 }
10167
10168 /// \brief Top-level lowering for x86 vector shuffles.
10169 ///
10170 /// This handles decomposition, canonicalization, and lowering of all x86
10171 /// vector shuffles. Most of the specific lowering strategies are encapsulated
10172 /// above in helper routines. The canonicalization attempts to widen shuffles
10173 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
10174 /// s.t. only one of the two inputs needs to be tested, etc.
10175 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
10176                                   SelectionDAG &DAG) {
10177   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10178   ArrayRef<int> Mask = SVOp->getMask();
10179   SDValue V1 = Op.getOperand(0);
10180   SDValue V2 = Op.getOperand(1);
10181   MVT VT = Op.getSimpleValueType();
10182   int NumElements = VT.getVectorNumElements();
10183   SDLoc dl(Op);
10184
10185   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
10186
10187   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
10188   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
10189   if (V1IsUndef && V2IsUndef)
10190     return DAG.getUNDEF(VT);
10191
10192   // When we create a shuffle node we put the UNDEF node to second operand,
10193   // but in some cases the first operand may be transformed to UNDEF.
10194   // In this case we should just commute the node.
10195   if (V1IsUndef)
10196     return DAG.getCommutedVectorShuffle(*SVOp);
10197
10198   // Check for non-undef masks pointing at an undef vector and make the masks
10199   // undef as well. This makes it easier to match the shuffle based solely on
10200   // the mask.
10201   if (V2IsUndef)
10202     for (int M : Mask)
10203       if (M >= NumElements) {
10204         SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
10205         for (int &M : NewMask)
10206           if (M >= NumElements)
10207             M = -1;
10208         return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
10209       }
10210
10211   // We actually see shuffles that are entirely re-arrangements of a set of
10212   // zero inputs. This mostly happens while decomposing complex shuffles into
10213   // simple ones. Directly lower these as a buildvector of zeros.
10214   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
10215   if (Zeroable.all())
10216     return getZeroVector(VT, Subtarget, DAG, dl);
10217
10218   // Try to collapse shuffles into using a vector type with fewer elements but
10219   // wider element types. We cap this to not form integers or floating point
10220   // elements wider than 64 bits, but it might be interesting to form i128
10221   // integers to handle flipping the low and high halves of AVX 256-bit vectors.
10222   SmallVector<int, 16> WidenedMask;
10223   if (VT.getScalarSizeInBits() < 64 &&
10224       canWidenShuffleElements(Mask, WidenedMask)) {
10225     MVT NewEltVT = VT.isFloatingPoint()
10226                        ? MVT::getFloatingPointVT(VT.getScalarSizeInBits() * 2)
10227                        : MVT::getIntegerVT(VT.getScalarSizeInBits() * 2);
10228     MVT NewVT = MVT::getVectorVT(NewEltVT, VT.getVectorNumElements() / 2);
10229     // Make sure that the new vector type is legal. For example, v2f64 isn't
10230     // legal on SSE1.
10231     if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
10232       V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
10233       V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
10234       return DAG.getNode(ISD::BITCAST, dl, VT,
10235                          DAG.getVectorShuffle(NewVT, dl, V1, V2, WidenedMask));
10236     }
10237   }
10238
10239   int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
10240   for (int M : SVOp->getMask())
10241     if (M < 0)
10242       ++NumUndefElements;
10243     else if (M < NumElements)
10244       ++NumV1Elements;
10245     else
10246       ++NumV2Elements;
10247
10248   // Commute the shuffle as needed such that more elements come from V1 than
10249   // V2. This allows us to match the shuffle pattern strictly on how many
10250   // elements come from V1 without handling the symmetric cases.
10251   if (NumV2Elements > NumV1Elements)
10252     return DAG.getCommutedVectorShuffle(*SVOp);
10253
10254   // When the number of V1 and V2 elements are the same, try to minimize the
10255   // number of uses of V2 in the low half of the vector. When that is tied,
10256   // ensure that the sum of indices for V1 is equal to or lower than the sum
10257   // indices for V2. When those are equal, try to ensure that the number of odd
10258   // indices for V1 is lower than the number of odd indices for V2.
10259   if (NumV1Elements == NumV2Elements) {
10260     int LowV1Elements = 0, LowV2Elements = 0;
10261     for (int M : SVOp->getMask().slice(0, NumElements / 2))
10262       if (M >= NumElements)
10263         ++LowV2Elements;
10264       else if (M >= 0)
10265         ++LowV1Elements;
10266     if (LowV2Elements > LowV1Elements) {
10267       return DAG.getCommutedVectorShuffle(*SVOp);
10268     } else if (LowV2Elements == LowV1Elements) {
10269       int SumV1Indices = 0, SumV2Indices = 0;
10270       for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10271         if (SVOp->getMask()[i] >= NumElements)
10272           SumV2Indices += i;
10273         else if (SVOp->getMask()[i] >= 0)
10274           SumV1Indices += i;
10275       if (SumV2Indices < SumV1Indices) {
10276         return DAG.getCommutedVectorShuffle(*SVOp);
10277       } else if (SumV2Indices == SumV1Indices) {
10278         int NumV1OddIndices = 0, NumV2OddIndices = 0;
10279         for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10280           if (SVOp->getMask()[i] >= NumElements)
10281             NumV2OddIndices += i % 2;
10282           else if (SVOp->getMask()[i] >= 0)
10283             NumV1OddIndices += i % 2;
10284         if (NumV2OddIndices < NumV1OddIndices)
10285           return DAG.getCommutedVectorShuffle(*SVOp);
10286       }
10287     }
10288   }
10289
10290   // For each vector width, delegate to a specialized lowering routine.
10291   if (VT.getSizeInBits() == 128)
10292     return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10293
10294   if (VT.getSizeInBits() == 256)
10295     return lower256BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10296
10297   // Force AVX-512 vectors to be scalarized for now.
10298   // FIXME: Implement AVX-512 support!
10299   if (VT.getSizeInBits() == 512)
10300     return lower512BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10301
10302   llvm_unreachable("Unimplemented!");
10303 }
10304
10305 // This function assumes its argument is a BUILD_VECTOR of constants or
10306 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
10307 // true.
10308 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
10309                                     unsigned &MaskValue) {
10310   MaskValue = 0;
10311   unsigned NumElems = BuildVector->getNumOperands();
10312   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
10313   unsigned NumLanes = (NumElems - 1) / 8 + 1;
10314   unsigned NumElemsInLane = NumElems / NumLanes;
10315
10316   // Blend for v16i16 should be symetric for the both lanes.
10317   for (unsigned i = 0; i < NumElemsInLane; ++i) {
10318     SDValue EltCond = BuildVector->getOperand(i);
10319     SDValue SndLaneEltCond =
10320         (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
10321
10322     int Lane1Cond = -1, Lane2Cond = -1;
10323     if (isa<ConstantSDNode>(EltCond))
10324       Lane1Cond = !isZero(EltCond);
10325     if (isa<ConstantSDNode>(SndLaneEltCond))
10326       Lane2Cond = !isZero(SndLaneEltCond);
10327
10328     if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
10329       // Lane1Cond != 0, means we want the first argument.
10330       // Lane1Cond == 0, means we want the second argument.
10331       // The encoding of this argument is 0 for the first argument, 1
10332       // for the second. Therefore, invert the condition.
10333       MaskValue |= !Lane1Cond << i;
10334     else if (Lane1Cond < 0)
10335       MaskValue |= !Lane2Cond << i;
10336     else
10337       return false;
10338   }
10339   return true;
10340 }
10341
10342 /// \brief Try to lower a VSELECT instruction to a vector shuffle.
10343 static SDValue lowerVSELECTtoVectorShuffle(SDValue Op,
10344                                            const X86Subtarget *Subtarget,
10345                                            SelectionDAG &DAG) {
10346   SDValue Cond = Op.getOperand(0);
10347   SDValue LHS = Op.getOperand(1);
10348   SDValue RHS = Op.getOperand(2);
10349   SDLoc dl(Op);
10350   MVT VT = Op.getSimpleValueType();
10351
10352   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
10353     return SDValue();
10354   auto *CondBV = cast<BuildVectorSDNode>(Cond);
10355
10356   // Only non-legal VSELECTs reach this lowering, convert those into generic
10357   // shuffles and re-use the shuffle lowering path for blends.
10358   SmallVector<int, 32> Mask;
10359   for (int i = 0, Size = VT.getVectorNumElements(); i < Size; ++i) {
10360     SDValue CondElt = CondBV->getOperand(i);
10361     Mask.push_back(
10362         isa<ConstantSDNode>(CondElt) ? i + (isZero(CondElt) ? Size : 0) : -1);
10363   }
10364   return DAG.getVectorShuffle(VT, dl, LHS, RHS, Mask);
10365 }
10366
10367 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
10368   // A vselect where all conditions and data are constants can be optimized into
10369   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
10370   if (ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(0).getNode()) &&
10371       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(1).getNode()) &&
10372       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(2).getNode()))
10373     return SDValue();
10374
10375   // Try to lower this to a blend-style vector shuffle. This can handle all
10376   // constant condition cases.
10377   if (SDValue BlendOp = lowerVSELECTtoVectorShuffle(Op, Subtarget, DAG))
10378     return BlendOp;
10379
10380   // Variable blends are only legal from SSE4.1 onward.
10381   if (!Subtarget->hasSSE41())
10382     return SDValue();
10383
10384   // Only some types will be legal on some subtargets. If we can emit a legal
10385   // VSELECT-matching blend, return Op, and but if we need to expand, return
10386   // a null value.
10387   switch (Op.getSimpleValueType().SimpleTy) {
10388   default:
10389     // Most of the vector types have blends past SSE4.1.
10390     return Op;
10391
10392   case MVT::v32i8:
10393     // The byte blends for AVX vectors were introduced only in AVX2.
10394     if (Subtarget->hasAVX2())
10395       return Op;
10396
10397     return SDValue();
10398
10399   case MVT::v8i16:
10400   case MVT::v16i16:
10401     // AVX-512 BWI and VLX features support VSELECT with i16 elements.
10402     if (Subtarget->hasBWI() && Subtarget->hasVLX())
10403       return Op;
10404
10405     // FIXME: We should custom lower this by fixing the condition and using i8
10406     // blends.
10407     return SDValue();
10408   }
10409 }
10410
10411 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
10412   MVT VT = Op.getSimpleValueType();
10413   SDLoc dl(Op);
10414
10415   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
10416     return SDValue();
10417
10418   if (VT.getSizeInBits() == 8) {
10419     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
10420                                   Op.getOperand(0), Op.getOperand(1));
10421     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10422                                   DAG.getValueType(VT));
10423     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10424   }
10425
10426   if (VT.getSizeInBits() == 16) {
10427     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10428     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
10429     if (Idx == 0)
10430       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
10431                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10432                                      DAG.getNode(ISD::BITCAST, dl,
10433                                                  MVT::v4i32,
10434                                                  Op.getOperand(0)),
10435                                      Op.getOperand(1)));
10436     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
10437                                   Op.getOperand(0), Op.getOperand(1));
10438     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10439                                   DAG.getValueType(VT));
10440     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10441   }
10442
10443   if (VT == MVT::f32) {
10444     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
10445     // the result back to FR32 register. It's only worth matching if the
10446     // result has a single use which is a store or a bitcast to i32.  And in
10447     // the case of a store, it's not worth it if the index is a constant 0,
10448     // because a MOVSSmr can be used instead, which is smaller and faster.
10449     if (!Op.hasOneUse())
10450       return SDValue();
10451     SDNode *User = *Op.getNode()->use_begin();
10452     if ((User->getOpcode() != ISD::STORE ||
10453          (isa<ConstantSDNode>(Op.getOperand(1)) &&
10454           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
10455         (User->getOpcode() != ISD::BITCAST ||
10456          User->getValueType(0) != MVT::i32))
10457       return SDValue();
10458     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10459                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
10460                                               Op.getOperand(0)),
10461                                               Op.getOperand(1));
10462     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
10463   }
10464
10465   if (VT == MVT::i32 || VT == MVT::i64) {
10466     // ExtractPS/pextrq works with constant index.
10467     if (isa<ConstantSDNode>(Op.getOperand(1)))
10468       return Op;
10469   }
10470   return SDValue();
10471 }
10472
10473 /// Extract one bit from mask vector, like v16i1 or v8i1.
10474 /// AVX-512 feature.
10475 SDValue
10476 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
10477   SDValue Vec = Op.getOperand(0);
10478   SDLoc dl(Vec);
10479   MVT VecVT = Vec.getSimpleValueType();
10480   SDValue Idx = Op.getOperand(1);
10481   MVT EltVT = Op.getSimpleValueType();
10482
10483   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
10484   assert((VecVT.getVectorNumElements() <= 16 || Subtarget->hasBWI()) &&
10485          "Unexpected vector type in ExtractBitFromMaskVector");
10486
10487   // variable index can't be handled in mask registers,
10488   // extend vector to VR512
10489   if (!isa<ConstantSDNode>(Idx)) {
10490     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
10491     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
10492     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
10493                               ExtVT.getVectorElementType(), Ext, Idx);
10494     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
10495   }
10496
10497   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10498   const TargetRegisterClass* rc = getRegClassFor(VecVT);
10499   if (!Subtarget->hasDQI() && (VecVT.getVectorNumElements() <= 8))
10500     rc = getRegClassFor(MVT::v16i1);
10501   unsigned MaxSift = rc->getSize()*8 - 1;
10502   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
10503                     DAG.getConstant(MaxSift - IdxVal, dl, MVT::i8));
10504   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
10505                     DAG.getConstant(MaxSift, dl, MVT::i8));
10506   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
10507                        DAG.getIntPtrConstant(0, dl));
10508 }
10509
10510 SDValue
10511 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
10512                                            SelectionDAG &DAG) const {
10513   SDLoc dl(Op);
10514   SDValue Vec = Op.getOperand(0);
10515   MVT VecVT = Vec.getSimpleValueType();
10516   SDValue Idx = Op.getOperand(1);
10517
10518   if (Op.getSimpleValueType() == MVT::i1)
10519     return ExtractBitFromMaskVector(Op, DAG);
10520
10521   if (!isa<ConstantSDNode>(Idx)) {
10522     if (VecVT.is512BitVector() ||
10523         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
10524          VecVT.getVectorElementType().getSizeInBits() == 32)) {
10525
10526       MVT MaskEltVT =
10527         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
10528       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
10529                                     MaskEltVT.getSizeInBits());
10530
10531       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
10532       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
10533                                 getZeroVector(MaskVT, Subtarget, DAG, dl),
10534                                 Idx, DAG.getConstant(0, dl, getPointerTy()));
10535       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
10536       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
10537                         Perm, DAG.getConstant(0, dl, getPointerTy()));
10538     }
10539     return SDValue();
10540   }
10541
10542   // If this is a 256-bit vector result, first extract the 128-bit vector and
10543   // then extract the element from the 128-bit vector.
10544   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
10545
10546     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10547     // Get the 128-bit vector.
10548     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
10549     MVT EltVT = VecVT.getVectorElementType();
10550
10551     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
10552
10553     //if (IdxVal >= NumElems/2)
10554     //  IdxVal -= NumElems/2;
10555     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
10556     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
10557                        DAG.getConstant(IdxVal, dl, MVT::i32));
10558   }
10559
10560   assert(VecVT.is128BitVector() && "Unexpected vector length");
10561
10562   if (Subtarget->hasSSE41()) {
10563     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
10564     if (Res.getNode())
10565       return Res;
10566   }
10567
10568   MVT VT = Op.getSimpleValueType();
10569   // TODO: handle v16i8.
10570   if (VT.getSizeInBits() == 16) {
10571     SDValue Vec = Op.getOperand(0);
10572     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10573     if (Idx == 0)
10574       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
10575                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10576                                      DAG.getNode(ISD::BITCAST, dl,
10577                                                  MVT::v4i32, Vec),
10578                                      Op.getOperand(1)));
10579     // Transform it so it match pextrw which produces a 32-bit result.
10580     MVT EltVT = MVT::i32;
10581     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
10582                                   Op.getOperand(0), Op.getOperand(1));
10583     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
10584                                   DAG.getValueType(VT));
10585     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10586   }
10587
10588   if (VT.getSizeInBits() == 32) {
10589     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10590     if (Idx == 0)
10591       return Op;
10592
10593     // SHUFPS the element to the lowest double word, then movss.
10594     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
10595     MVT VVT = Op.getOperand(0).getSimpleValueType();
10596     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10597                                        DAG.getUNDEF(VVT), Mask);
10598     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10599                        DAG.getIntPtrConstant(0, dl));
10600   }
10601
10602   if (VT.getSizeInBits() == 64) {
10603     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
10604     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
10605     //        to match extract_elt for f64.
10606     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10607     if (Idx == 0)
10608       return Op;
10609
10610     // UNPCKHPD the element to the lowest double word, then movsd.
10611     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
10612     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
10613     int Mask[2] = { 1, -1 };
10614     MVT VVT = Op.getOperand(0).getSimpleValueType();
10615     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10616                                        DAG.getUNDEF(VVT), Mask);
10617     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10618                        DAG.getIntPtrConstant(0, dl));
10619   }
10620
10621   return SDValue();
10622 }
10623
10624 /// Insert one bit to mask vector, like v16i1 or v8i1.
10625 /// AVX-512 feature.
10626 SDValue
10627 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
10628   SDLoc dl(Op);
10629   SDValue Vec = Op.getOperand(0);
10630   SDValue Elt = Op.getOperand(1);
10631   SDValue Idx = Op.getOperand(2);
10632   MVT VecVT = Vec.getSimpleValueType();
10633
10634   if (!isa<ConstantSDNode>(Idx)) {
10635     // Non constant index. Extend source and destination,
10636     // insert element and then truncate the result.
10637     MVT ExtVecVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
10638     MVT ExtEltVT = (VecVT == MVT::v8i1 ?  MVT::i64 : MVT::i32);
10639     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
10640       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
10641       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
10642     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
10643   }
10644
10645   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10646   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
10647   if (Vec.getOpcode() == ISD::UNDEF)
10648     return DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
10649                        DAG.getConstant(IdxVal, dl, MVT::i8));
10650   const TargetRegisterClass* rc = getRegClassFor(VecVT);
10651   unsigned MaxSift = rc->getSize()*8 - 1;
10652   EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
10653                     DAG.getConstant(MaxSift, dl, MVT::i8));
10654   EltInVec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, EltInVec,
10655                     DAG.getConstant(MaxSift - IdxVal, dl, MVT::i8));
10656   return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
10657 }
10658
10659 SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
10660                                                   SelectionDAG &DAG) const {
10661   MVT VT = Op.getSimpleValueType();
10662   MVT EltVT = VT.getVectorElementType();
10663
10664   if (EltVT == MVT::i1)
10665     return InsertBitToMaskVector(Op, DAG);
10666
10667   SDLoc dl(Op);
10668   SDValue N0 = Op.getOperand(0);
10669   SDValue N1 = Op.getOperand(1);
10670   SDValue N2 = Op.getOperand(2);
10671   if (!isa<ConstantSDNode>(N2))
10672     return SDValue();
10673   auto *N2C = cast<ConstantSDNode>(N2);
10674   unsigned IdxVal = N2C->getZExtValue();
10675
10676   // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
10677   // into that, and then insert the subvector back into the result.
10678   if (VT.is256BitVector() || VT.is512BitVector()) {
10679     // With a 256-bit vector, we can insert into the zero element efficiently
10680     // using a blend if we have AVX or AVX2 and the right data type.
10681     if (VT.is256BitVector() && IdxVal == 0) {
10682       // TODO: It is worthwhile to cast integer to floating point and back
10683       // and incur a domain crossing penalty if that's what we'll end up
10684       // doing anyway after extracting to a 128-bit vector.
10685       if ((Subtarget->hasAVX() && (EltVT == MVT::f64 || EltVT == MVT::f32)) ||
10686           (Subtarget->hasAVX2() && EltVT == MVT::i32)) {
10687         SDValue N1Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, N1);
10688         N2 = DAG.getIntPtrConstant(1, dl);
10689         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1Vec, N2);
10690       }
10691     }
10692
10693     // Get the desired 128-bit vector chunk.
10694     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
10695
10696     // Insert the element into the desired chunk.
10697     unsigned NumEltsIn128 = 128 / EltVT.getSizeInBits();
10698     unsigned IdxIn128 = IdxVal - (IdxVal / NumEltsIn128) * NumEltsIn128;
10699
10700     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
10701                     DAG.getConstant(IdxIn128, dl, MVT::i32));
10702
10703     // Insert the changed part back into the bigger vector
10704     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
10705   }
10706   assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
10707
10708   if (Subtarget->hasSSE41()) {
10709     if (EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) {
10710       unsigned Opc;
10711       if (VT == MVT::v8i16) {
10712         Opc = X86ISD::PINSRW;
10713       } else {
10714         assert(VT == MVT::v16i8);
10715         Opc = X86ISD::PINSRB;
10716       }
10717
10718       // Transform it so it match pinsr{b,w} which expects a GR32 as its second
10719       // argument.
10720       if (N1.getValueType() != MVT::i32)
10721         N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
10722       if (N2.getValueType() != MVT::i32)
10723         N2 = DAG.getIntPtrConstant(IdxVal, dl);
10724       return DAG.getNode(Opc, dl, VT, N0, N1, N2);
10725     }
10726
10727     if (EltVT == MVT::f32) {
10728       // Bits [7:6] of the constant are the source select. This will always be
10729       //   zero here. The DAG Combiner may combine an extract_elt index into
10730       //   these bits. For example (insert (extract, 3), 2) could be matched by
10731       //   putting the '3' into bits [7:6] of X86ISD::INSERTPS.
10732       // Bits [5:4] of the constant are the destination select. This is the
10733       //   value of the incoming immediate.
10734       // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
10735       //   combine either bitwise AND or insert of float 0.0 to set these bits.
10736
10737       const Function *F = DAG.getMachineFunction().getFunction();
10738       bool MinSize = F->hasFnAttribute(Attribute::MinSize);
10739       if (IdxVal == 0 && (!MinSize || !MayFoldLoad(N1))) {
10740         // If this is an insertion of 32-bits into the low 32-bits of
10741         // a vector, we prefer to generate a blend with immediate rather
10742         // than an insertps. Blends are simpler operations in hardware and so
10743         // will always have equal or better performance than insertps.
10744         // But if optimizing for size and there's a load folding opportunity,
10745         // generate insertps because blendps does not have a 32-bit memory
10746         // operand form.
10747         N2 = DAG.getIntPtrConstant(1, dl);
10748         N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
10749         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1, N2);
10750       }
10751       N2 = DAG.getIntPtrConstant(IdxVal << 4, dl);
10752       // Create this as a scalar to vector..
10753       N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
10754       return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
10755     }
10756
10757     if (EltVT == MVT::i32 || EltVT == MVT::i64) {
10758       // PINSR* works with constant index.
10759       return Op;
10760     }
10761   }
10762
10763   if (EltVT == MVT::i8)
10764     return SDValue();
10765
10766   if (EltVT.getSizeInBits() == 16) {
10767     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
10768     // as its second argument.
10769     if (N1.getValueType() != MVT::i32)
10770       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
10771     if (N2.getValueType() != MVT::i32)
10772       N2 = DAG.getIntPtrConstant(IdxVal, dl);
10773     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
10774   }
10775   return SDValue();
10776 }
10777
10778 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
10779   SDLoc dl(Op);
10780   MVT OpVT = Op.getSimpleValueType();
10781
10782   // If this is a 256-bit vector result, first insert into a 128-bit
10783   // vector and then insert into the 256-bit vector.
10784   if (!OpVT.is128BitVector()) {
10785     // Insert into a 128-bit vector.
10786     unsigned SizeFactor = OpVT.getSizeInBits()/128;
10787     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
10788                                  OpVT.getVectorNumElements() / SizeFactor);
10789
10790     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
10791
10792     // Insert the 128-bit vector.
10793     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
10794   }
10795
10796   if (OpVT == MVT::v1i64 &&
10797       Op.getOperand(0).getValueType() == MVT::i64)
10798     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
10799
10800   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
10801   assert(OpVT.is128BitVector() && "Expected an SSE type!");
10802   return DAG.getNode(ISD::BITCAST, dl, OpVT,
10803                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
10804 }
10805
10806 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
10807 // a simple subregister reference or explicit instructions to grab
10808 // upper bits of a vector.
10809 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10810                                       SelectionDAG &DAG) {
10811   SDLoc dl(Op);
10812   SDValue In =  Op.getOperand(0);
10813   SDValue Idx = Op.getOperand(1);
10814   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10815   MVT ResVT   = Op.getSimpleValueType();
10816   MVT InVT    = In.getSimpleValueType();
10817
10818   if (Subtarget->hasFp256()) {
10819     if (ResVT.is128BitVector() &&
10820         (InVT.is256BitVector() || InVT.is512BitVector()) &&
10821         isa<ConstantSDNode>(Idx)) {
10822       return Extract128BitVector(In, IdxVal, DAG, dl);
10823     }
10824     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
10825         isa<ConstantSDNode>(Idx)) {
10826       return Extract256BitVector(In, IdxVal, DAG, dl);
10827     }
10828   }
10829   return SDValue();
10830 }
10831
10832 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
10833 // simple superregister reference or explicit instructions to insert
10834 // the upper bits of a vector.
10835 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10836                                      SelectionDAG &DAG) {
10837   if (!Subtarget->hasAVX())
10838     return SDValue();
10839
10840   SDLoc dl(Op);
10841   SDValue Vec = Op.getOperand(0);
10842   SDValue SubVec = Op.getOperand(1);
10843   SDValue Idx = Op.getOperand(2);
10844
10845   if (!isa<ConstantSDNode>(Idx))
10846     return SDValue();
10847
10848   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10849   MVT OpVT = Op.getSimpleValueType();
10850   MVT SubVecVT = SubVec.getSimpleValueType();
10851
10852   // Fold two 16-byte subvector loads into one 32-byte load:
10853   // (insert_subvector (insert_subvector undef, (load addr), 0),
10854   //                   (load addr + 16), Elts/2)
10855   // --> load32 addr
10856   if ((IdxVal == OpVT.getVectorNumElements() / 2) &&
10857       Vec.getOpcode() == ISD::INSERT_SUBVECTOR &&
10858       OpVT.is256BitVector() && SubVecVT.is128BitVector() &&
10859       !Subtarget->isUnalignedMem32Slow()) {
10860     SDValue SubVec2 = Vec.getOperand(1);
10861     if (auto *Idx2 = dyn_cast<ConstantSDNode>(Vec.getOperand(2))) {
10862       if (Idx2->getZExtValue() == 0) {
10863         SDValue Ops[] = { SubVec2, SubVec };
10864         SDValue LD = EltsFromConsecutiveLoads(OpVT, Ops, dl, DAG, false);
10865         if (LD.getNode())
10866           return LD;
10867       }
10868     }
10869   }
10870
10871   if ((OpVT.is256BitVector() || OpVT.is512BitVector()) &&
10872       SubVecVT.is128BitVector())
10873     return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
10874
10875   if (OpVT.is512BitVector() && SubVecVT.is256BitVector())
10876     return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
10877
10878   if (OpVT.getVectorElementType() == MVT::i1) {
10879     if (IdxVal == 0  && Vec.getOpcode() == ISD::UNDEF) // the operation is legal
10880       return Op;
10881     SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
10882     SDValue Undef = DAG.getUNDEF(OpVT);
10883     unsigned NumElems = OpVT.getVectorNumElements();
10884     SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
10885
10886     if (IdxVal == OpVT.getVectorNumElements() / 2) {
10887       // Zero upper bits of the Vec
10888       Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
10889       Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
10890
10891       SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
10892                                  SubVec, ZeroIdx);
10893       Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
10894       return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
10895     }
10896     if (IdxVal == 0) {
10897       SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
10898                                  SubVec, ZeroIdx);
10899       // Zero upper bits of the Vec2
10900       Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
10901       Vec2 = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec2, ShiftBits);
10902       // Zero lower bits of the Vec
10903       Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
10904       Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
10905       // Merge them together
10906       return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
10907     }
10908   }
10909   return SDValue();
10910 }
10911
10912 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
10913 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
10914 // one of the above mentioned nodes. It has to be wrapped because otherwise
10915 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
10916 // be used to form addressing mode. These wrapped nodes will be selected
10917 // into MOV32ri.
10918 SDValue
10919 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
10920   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
10921
10922   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10923   // global base reg.
10924   unsigned char OpFlag = 0;
10925   unsigned WrapperKind = X86ISD::Wrapper;
10926   CodeModel::Model M = DAG.getTarget().getCodeModel();
10927
10928   if (Subtarget->isPICStyleRIPRel() &&
10929       (M == CodeModel::Small || M == CodeModel::Kernel))
10930     WrapperKind = X86ISD::WrapperRIP;
10931   else if (Subtarget->isPICStyleGOT())
10932     OpFlag = X86II::MO_GOTOFF;
10933   else if (Subtarget->isPICStyleStubPIC())
10934     OpFlag = X86II::MO_PIC_BASE_OFFSET;
10935
10936   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
10937                                              CP->getAlignment(),
10938                                              CP->getOffset(), OpFlag);
10939   SDLoc DL(CP);
10940   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10941   // With PIC, the address is actually $g + Offset.
10942   if (OpFlag) {
10943     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10944                          DAG.getNode(X86ISD::GlobalBaseReg,
10945                                      SDLoc(), getPointerTy()),
10946                          Result);
10947   }
10948
10949   return Result;
10950 }
10951
10952 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
10953   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
10954
10955   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10956   // global base reg.
10957   unsigned char OpFlag = 0;
10958   unsigned WrapperKind = X86ISD::Wrapper;
10959   CodeModel::Model M = DAG.getTarget().getCodeModel();
10960
10961   if (Subtarget->isPICStyleRIPRel() &&
10962       (M == CodeModel::Small || M == CodeModel::Kernel))
10963     WrapperKind = X86ISD::WrapperRIP;
10964   else if (Subtarget->isPICStyleGOT())
10965     OpFlag = X86II::MO_GOTOFF;
10966   else if (Subtarget->isPICStyleStubPIC())
10967     OpFlag = X86II::MO_PIC_BASE_OFFSET;
10968
10969   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
10970                                           OpFlag);
10971   SDLoc DL(JT);
10972   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10973
10974   // With PIC, the address is actually $g + Offset.
10975   if (OpFlag)
10976     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10977                          DAG.getNode(X86ISD::GlobalBaseReg,
10978                                      SDLoc(), getPointerTy()),
10979                          Result);
10980
10981   return Result;
10982 }
10983
10984 SDValue
10985 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
10986   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
10987
10988   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10989   // global base reg.
10990   unsigned char OpFlag = 0;
10991   unsigned WrapperKind = X86ISD::Wrapper;
10992   CodeModel::Model M = DAG.getTarget().getCodeModel();
10993
10994   if (Subtarget->isPICStyleRIPRel() &&
10995       (M == CodeModel::Small || M == CodeModel::Kernel)) {
10996     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
10997       OpFlag = X86II::MO_GOTPCREL;
10998     WrapperKind = X86ISD::WrapperRIP;
10999   } else if (Subtarget->isPICStyleGOT()) {
11000     OpFlag = X86II::MO_GOT;
11001   } else if (Subtarget->isPICStyleStubPIC()) {
11002     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
11003   } else if (Subtarget->isPICStyleStubNoDynamic()) {
11004     OpFlag = X86II::MO_DARWIN_NONLAZY;
11005   }
11006
11007   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
11008
11009   SDLoc DL(Op);
11010   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
11011
11012   // With PIC, the address is actually $g + Offset.
11013   if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
11014       !Subtarget->is64Bit()) {
11015     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11016                          DAG.getNode(X86ISD::GlobalBaseReg,
11017                                      SDLoc(), getPointerTy()),
11018                          Result);
11019   }
11020
11021   // For symbols that require a load from a stub to get the address, emit the
11022   // load.
11023   if (isGlobalStubReference(OpFlag))
11024     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
11025                          MachinePointerInfo::getGOT(), false, false, false, 0);
11026
11027   return Result;
11028 }
11029
11030 SDValue
11031 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
11032   // Create the TargetBlockAddressAddress node.
11033   unsigned char OpFlags =
11034     Subtarget->ClassifyBlockAddressReference();
11035   CodeModel::Model M = DAG.getTarget().getCodeModel();
11036   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
11037   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
11038   SDLoc dl(Op);
11039   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
11040                                              OpFlags);
11041
11042   if (Subtarget->isPICStyleRIPRel() &&
11043       (M == CodeModel::Small || M == CodeModel::Kernel))
11044     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
11045   else
11046     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
11047
11048   // With PIC, the address is actually $g + Offset.
11049   if (isGlobalRelativeToPICBase(OpFlags)) {
11050     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
11051                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
11052                          Result);
11053   }
11054
11055   return Result;
11056 }
11057
11058 SDValue
11059 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
11060                                       int64_t Offset, SelectionDAG &DAG) const {
11061   // Create the TargetGlobalAddress node, folding in the constant
11062   // offset if it is legal.
11063   unsigned char OpFlags =
11064       Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
11065   CodeModel::Model M = DAG.getTarget().getCodeModel();
11066   SDValue Result;
11067   if (OpFlags == X86II::MO_NO_FLAG &&
11068       X86::isOffsetSuitableForCodeModel(Offset, M)) {
11069     // A direct static reference to a global.
11070     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
11071     Offset = 0;
11072   } else {
11073     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
11074   }
11075
11076   if (Subtarget->isPICStyleRIPRel() &&
11077       (M == CodeModel::Small || M == CodeModel::Kernel))
11078     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
11079   else
11080     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
11081
11082   // With PIC, the address is actually $g + Offset.
11083   if (isGlobalRelativeToPICBase(OpFlags)) {
11084     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
11085                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
11086                          Result);
11087   }
11088
11089   // For globals that require a load from a stub to get the address, emit the
11090   // load.
11091   if (isGlobalStubReference(OpFlags))
11092     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
11093                          MachinePointerInfo::getGOT(), false, false, false, 0);
11094
11095   // If there was a non-zero offset that we didn't fold, create an explicit
11096   // addition for it.
11097   if (Offset != 0)
11098     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
11099                          DAG.getConstant(Offset, dl, getPointerTy()));
11100
11101   return Result;
11102 }
11103
11104 SDValue
11105 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
11106   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
11107   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
11108   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
11109 }
11110
11111 static SDValue
11112 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
11113            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
11114            unsigned char OperandFlags, bool LocalDynamic = false) {
11115   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11116   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11117   SDLoc dl(GA);
11118   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11119                                            GA->getValueType(0),
11120                                            GA->getOffset(),
11121                                            OperandFlags);
11122
11123   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
11124                                            : X86ISD::TLSADDR;
11125
11126   if (InFlag) {
11127     SDValue Ops[] = { Chain,  TGA, *InFlag };
11128     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11129   } else {
11130     SDValue Ops[]  = { Chain, TGA };
11131     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11132   }
11133
11134   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
11135   MFI->setAdjustsStack(true);
11136   MFI->setHasCalls(true);
11137
11138   SDValue Flag = Chain.getValue(1);
11139   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
11140 }
11141
11142 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
11143 static SDValue
11144 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11145                                 const EVT PtrVT) {
11146   SDValue InFlag;
11147   SDLoc dl(GA);  // ? function entry point might be better
11148   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11149                                    DAG.getNode(X86ISD::GlobalBaseReg,
11150                                                SDLoc(), PtrVT), InFlag);
11151   InFlag = Chain.getValue(1);
11152
11153   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
11154 }
11155
11156 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
11157 static SDValue
11158 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11159                                 const EVT PtrVT) {
11160   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
11161                     X86::RAX, X86II::MO_TLSGD);
11162 }
11163
11164 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
11165                                            SelectionDAG &DAG,
11166                                            const EVT PtrVT,
11167                                            bool is64Bit) {
11168   SDLoc dl(GA);
11169
11170   // Get the start address of the TLS block for this module.
11171   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
11172       .getInfo<X86MachineFunctionInfo>();
11173   MFI->incNumLocalDynamicTLSAccesses();
11174
11175   SDValue Base;
11176   if (is64Bit) {
11177     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
11178                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
11179   } else {
11180     SDValue InFlag;
11181     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11182         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
11183     InFlag = Chain.getValue(1);
11184     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
11185                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
11186   }
11187
11188   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
11189   // of Base.
11190
11191   // Build x@dtpoff.
11192   unsigned char OperandFlags = X86II::MO_DTPOFF;
11193   unsigned WrapperKind = X86ISD::Wrapper;
11194   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11195                                            GA->getValueType(0),
11196                                            GA->getOffset(), OperandFlags);
11197   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11198
11199   // Add x@dtpoff with the base.
11200   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
11201 }
11202
11203 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
11204 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11205                                    const EVT PtrVT, TLSModel::Model model,
11206                                    bool is64Bit, bool isPIC) {
11207   SDLoc dl(GA);
11208
11209   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
11210   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
11211                                                          is64Bit ? 257 : 256));
11212
11213   SDValue ThreadPointer =
11214       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0, dl),
11215                   MachinePointerInfo(Ptr), false, false, false, 0);
11216
11217   unsigned char OperandFlags = 0;
11218   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
11219   // initialexec.
11220   unsigned WrapperKind = X86ISD::Wrapper;
11221   if (model == TLSModel::LocalExec) {
11222     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
11223   } else if (model == TLSModel::InitialExec) {
11224     if (is64Bit) {
11225       OperandFlags = X86II::MO_GOTTPOFF;
11226       WrapperKind = X86ISD::WrapperRIP;
11227     } else {
11228       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
11229     }
11230   } else {
11231     llvm_unreachable("Unexpected model");
11232   }
11233
11234   // emit "addl x@ntpoff,%eax" (local exec)
11235   // or "addl x@indntpoff,%eax" (initial exec)
11236   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
11237   SDValue TGA =
11238       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
11239                                  GA->getOffset(), OperandFlags);
11240   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11241
11242   if (model == TLSModel::InitialExec) {
11243     if (isPIC && !is64Bit) {
11244       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
11245                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
11246                            Offset);
11247     }
11248
11249     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
11250                          MachinePointerInfo::getGOT(), false, false, false, 0);
11251   }
11252
11253   // The address of the thread local variable is the add of the thread
11254   // pointer with the offset of the variable.
11255   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
11256 }
11257
11258 SDValue
11259 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
11260
11261   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
11262   const GlobalValue *GV = GA->getGlobal();
11263
11264   if (Subtarget->isTargetELF()) {
11265     TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
11266
11267     switch (model) {
11268       case TLSModel::GeneralDynamic:
11269         if (Subtarget->is64Bit())
11270           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
11271         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
11272       case TLSModel::LocalDynamic:
11273         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
11274                                            Subtarget->is64Bit());
11275       case TLSModel::InitialExec:
11276       case TLSModel::LocalExec:
11277         return LowerToTLSExecModel(
11278             GA, DAG, getPointerTy(), model, Subtarget->is64Bit(),
11279             DAG.getTarget().getRelocationModel() == Reloc::PIC_);
11280     }
11281     llvm_unreachable("Unknown TLS model.");
11282   }
11283
11284   if (Subtarget->isTargetDarwin()) {
11285     // Darwin only has one model of TLS.  Lower to that.
11286     unsigned char OpFlag = 0;
11287     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
11288                            X86ISD::WrapperRIP : X86ISD::Wrapper;
11289
11290     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11291     // global base reg.
11292     bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
11293                  !Subtarget->is64Bit();
11294     if (PIC32)
11295       OpFlag = X86II::MO_TLVP_PIC_BASE;
11296     else
11297       OpFlag = X86II::MO_TLVP;
11298     SDLoc DL(Op);
11299     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
11300                                                 GA->getValueType(0),
11301                                                 GA->getOffset(), OpFlag);
11302     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
11303
11304     // With PIC32, the address is actually $g + Offset.
11305     if (PIC32)
11306       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11307                            DAG.getNode(X86ISD::GlobalBaseReg,
11308                                        SDLoc(), getPointerTy()),
11309                            Offset);
11310
11311     // Lowering the machine isd will make sure everything is in the right
11312     // location.
11313     SDValue Chain = DAG.getEntryNode();
11314     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11315     SDValue Args[] = { Chain, Offset };
11316     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
11317
11318     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
11319     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11320     MFI->setAdjustsStack(true);
11321
11322     // And our return value (tls address) is in the standard call return value
11323     // location.
11324     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11325     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
11326                               Chain.getValue(1));
11327   }
11328
11329   if (Subtarget->isTargetKnownWindowsMSVC() ||
11330       Subtarget->isTargetWindowsGNU()) {
11331     // Just use the implicit TLS architecture
11332     // Need to generate someting similar to:
11333     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
11334     //                                  ; from TEB
11335     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
11336     //   mov     rcx, qword [rdx+rcx*8]
11337     //   mov     eax, .tls$:tlsvar
11338     //   [rax+rcx] contains the address
11339     // Windows 64bit: gs:0x58
11340     // Windows 32bit: fs:__tls_array
11341
11342     SDLoc dl(GA);
11343     SDValue Chain = DAG.getEntryNode();
11344
11345     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
11346     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
11347     // use its literal value of 0x2C.
11348     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
11349                                         ? Type::getInt8PtrTy(*DAG.getContext(),
11350                                                              256)
11351                                         : Type::getInt32PtrTy(*DAG.getContext(),
11352                                                               257));
11353
11354     SDValue TlsArray =
11355         Subtarget->is64Bit()
11356             ? DAG.getIntPtrConstant(0x58, dl)
11357             : (Subtarget->isTargetWindowsGNU()
11358                    ? DAG.getIntPtrConstant(0x2C, dl)
11359                    : DAG.getExternalSymbol("_tls_array", getPointerTy()));
11360
11361     SDValue ThreadPointer =
11362         DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
11363                     MachinePointerInfo(Ptr), false, false, false, 0);
11364
11365     // Load the _tls_index variable
11366     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
11367     if (Subtarget->is64Bit())
11368       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
11369                            IDX, MachinePointerInfo(), MVT::i32,
11370                            false, false, false, 0);
11371     else
11372       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
11373                         false, false, false, 0);
11374
11375     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()), dl,
11376                                     getPointerTy());
11377     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
11378
11379     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
11380     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
11381                       false, false, false, 0);
11382
11383     // Get the offset of start of .tls section
11384     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11385                                              GA->getValueType(0),
11386                                              GA->getOffset(), X86II::MO_SECREL);
11387     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
11388
11389     // The address of the thread local variable is the add of the thread
11390     // pointer with the offset of the variable.
11391     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
11392   }
11393
11394   llvm_unreachable("TLS not implemented for this target.");
11395 }
11396
11397 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
11398 /// and take a 2 x i32 value to shift plus a shift amount.
11399 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
11400   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
11401   MVT VT = Op.getSimpleValueType();
11402   unsigned VTBits = VT.getSizeInBits();
11403   SDLoc dl(Op);
11404   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
11405   SDValue ShOpLo = Op.getOperand(0);
11406   SDValue ShOpHi = Op.getOperand(1);
11407   SDValue ShAmt  = Op.getOperand(2);
11408   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
11409   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
11410   // during isel.
11411   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11412                                   DAG.getConstant(VTBits - 1, dl, MVT::i8));
11413   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
11414                                      DAG.getConstant(VTBits - 1, dl, MVT::i8))
11415                        : DAG.getConstant(0, dl, VT);
11416
11417   SDValue Tmp2, Tmp3;
11418   if (Op.getOpcode() == ISD::SHL_PARTS) {
11419     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
11420     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
11421   } else {
11422     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
11423     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
11424   }
11425
11426   // If the shift amount is larger or equal than the width of a part we can't
11427   // rely on the results of shld/shrd. Insert a test and select the appropriate
11428   // values for large shift amounts.
11429   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11430                                 DAG.getConstant(VTBits, dl, MVT::i8));
11431   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11432                              AndNode, DAG.getConstant(0, dl, MVT::i8));
11433
11434   SDValue Hi, Lo;
11435   SDValue CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
11436   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
11437   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
11438
11439   if (Op.getOpcode() == ISD::SHL_PARTS) {
11440     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11441     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11442   } else {
11443     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11444     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11445   }
11446
11447   SDValue Ops[2] = { Lo, Hi };
11448   return DAG.getMergeValues(Ops, dl);
11449 }
11450
11451 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
11452                                            SelectionDAG &DAG) const {
11453   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
11454   SDLoc dl(Op);
11455
11456   if (SrcVT.isVector()) {
11457     if (SrcVT.getVectorElementType() == MVT::i1) {
11458       MVT IntegerVT = MVT::getVectorVT(MVT::i32, SrcVT.getVectorNumElements());
11459       return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
11460                          DAG.getNode(ISD::SIGN_EXTEND, dl, IntegerVT,
11461                                      Op.getOperand(0)));
11462     }
11463     return SDValue();
11464   }
11465
11466   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
11467          "Unknown SINT_TO_FP to lower!");
11468
11469   // These are really Legal; return the operand so the caller accepts it as
11470   // Legal.
11471   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
11472     return Op;
11473   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
11474       Subtarget->is64Bit()) {
11475     return Op;
11476   }
11477
11478   unsigned Size = SrcVT.getSizeInBits()/8;
11479   MachineFunction &MF = DAG.getMachineFunction();
11480   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
11481   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11482   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11483                                StackSlot,
11484                                MachinePointerInfo::getFixedStack(SSFI),
11485                                false, false, 0);
11486   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
11487 }
11488
11489 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
11490                                      SDValue StackSlot,
11491                                      SelectionDAG &DAG) const {
11492   // Build the FILD
11493   SDLoc DL(Op);
11494   SDVTList Tys;
11495   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
11496   if (useSSE)
11497     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
11498   else
11499     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
11500
11501   unsigned ByteSize = SrcVT.getSizeInBits()/8;
11502
11503   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
11504   MachineMemOperand *MMO;
11505   if (FI) {
11506     int SSFI = FI->getIndex();
11507     MMO =
11508       DAG.getMachineFunction()
11509       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11510                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
11511   } else {
11512     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
11513     StackSlot = StackSlot.getOperand(1);
11514   }
11515   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
11516   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
11517                                            X86ISD::FILD, DL,
11518                                            Tys, Ops, SrcVT, MMO);
11519
11520   if (useSSE) {
11521     Chain = Result.getValue(1);
11522     SDValue InFlag = Result.getValue(2);
11523
11524     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
11525     // shouldn't be necessary except that RFP cannot be live across
11526     // multiple blocks. When stackifier is fixed, they can be uncoupled.
11527     MachineFunction &MF = DAG.getMachineFunction();
11528     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
11529     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
11530     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11531     Tys = DAG.getVTList(MVT::Other);
11532     SDValue Ops[] = {
11533       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
11534     };
11535     MachineMemOperand *MMO =
11536       DAG.getMachineFunction()
11537       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11538                             MachineMemOperand::MOStore, SSFISize, SSFISize);
11539
11540     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
11541                                     Ops, Op.getValueType(), MMO);
11542     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
11543                          MachinePointerInfo::getFixedStack(SSFI),
11544                          false, false, false, 0);
11545   }
11546
11547   return Result;
11548 }
11549
11550 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
11551 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
11552                                                SelectionDAG &DAG) const {
11553   // This algorithm is not obvious. Here it is what we're trying to output:
11554   /*
11555      movq       %rax,  %xmm0
11556      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
11557      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
11558      #ifdef __SSE3__
11559        haddpd   %xmm0, %xmm0
11560      #else
11561        pshufd   $0x4e, %xmm0, %xmm1
11562        addpd    %xmm1, %xmm0
11563      #endif
11564   */
11565
11566   SDLoc dl(Op);
11567   LLVMContext *Context = DAG.getContext();
11568
11569   // Build some magic constants.
11570   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
11571   Constant *C0 = ConstantDataVector::get(*Context, CV0);
11572   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
11573
11574   SmallVector<Constant*,2> CV1;
11575   CV1.push_back(
11576     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11577                                       APInt(64, 0x4330000000000000ULL))));
11578   CV1.push_back(
11579     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11580                                       APInt(64, 0x4530000000000000ULL))));
11581   Constant *C1 = ConstantVector::get(CV1);
11582   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
11583
11584   // Load the 64-bit value into an XMM register.
11585   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
11586                             Op.getOperand(0));
11587   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
11588                               MachinePointerInfo::getConstantPool(),
11589                               false, false, false, 16);
11590   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
11591                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
11592                               CLod0);
11593
11594   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
11595                               MachinePointerInfo::getConstantPool(),
11596                               false, false, false, 16);
11597   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
11598   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
11599   SDValue Result;
11600
11601   if (Subtarget->hasSSE3()) {
11602     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
11603     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
11604   } else {
11605     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
11606     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
11607                                            S2F, 0x4E, DAG);
11608     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
11609                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
11610                          Sub);
11611   }
11612
11613   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
11614                      DAG.getIntPtrConstant(0, dl));
11615 }
11616
11617 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
11618 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
11619                                                SelectionDAG &DAG) const {
11620   SDLoc dl(Op);
11621   // FP constant to bias correct the final result.
11622   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
11623                                    MVT::f64);
11624
11625   // Load the 32-bit value into an XMM register.
11626   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
11627                              Op.getOperand(0));
11628
11629   // Zero out the upper parts of the register.
11630   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
11631
11632   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11633                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
11634                      DAG.getIntPtrConstant(0, dl));
11635
11636   // Or the load with the bias.
11637   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
11638                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
11639                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
11640                                                    MVT::v2f64, Load)),
11641                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
11642                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
11643                                                    MVT::v2f64, Bias)));
11644   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11645                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
11646                    DAG.getIntPtrConstant(0, dl));
11647
11648   // Subtract the bias.
11649   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
11650
11651   // Handle final rounding.
11652   EVT DestVT = Op.getValueType();
11653
11654   if (DestVT.bitsLT(MVT::f64))
11655     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
11656                        DAG.getIntPtrConstant(0, dl));
11657   if (DestVT.bitsGT(MVT::f64))
11658     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
11659
11660   // Handle final rounding.
11661   return Sub;
11662 }
11663
11664 static SDValue lowerUINT_TO_FP_vXi32(SDValue Op, SelectionDAG &DAG,
11665                                      const X86Subtarget &Subtarget) {
11666   // The algorithm is the following:
11667   // #ifdef __SSE4_1__
11668   //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
11669   //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
11670   //                                 (uint4) 0x53000000, 0xaa);
11671   // #else
11672   //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
11673   //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
11674   // #endif
11675   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
11676   //     return (float4) lo + fhi;
11677
11678   SDLoc DL(Op);
11679   SDValue V = Op->getOperand(0);
11680   EVT VecIntVT = V.getValueType();
11681   bool Is128 = VecIntVT == MVT::v4i32;
11682   EVT VecFloatVT = Is128 ? MVT::v4f32 : MVT::v8f32;
11683   // If we convert to something else than the supported type, e.g., to v4f64,
11684   // abort early.
11685   if (VecFloatVT != Op->getValueType(0))
11686     return SDValue();
11687
11688   unsigned NumElts = VecIntVT.getVectorNumElements();
11689   assert((VecIntVT == MVT::v4i32 || VecIntVT == MVT::v8i32) &&
11690          "Unsupported custom type");
11691   assert(NumElts <= 8 && "The size of the constant array must be fixed");
11692
11693   // In the #idef/#else code, we have in common:
11694   // - The vector of constants:
11695   // -- 0x4b000000
11696   // -- 0x53000000
11697   // - A shift:
11698   // -- v >> 16
11699
11700   // Create the splat vector for 0x4b000000.
11701   SDValue CstLow = DAG.getConstant(0x4b000000, DL, MVT::i32);
11702   SDValue CstLowArray[] = {CstLow, CstLow, CstLow, CstLow,
11703                            CstLow, CstLow, CstLow, CstLow};
11704   SDValue VecCstLow = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
11705                                   makeArrayRef(&CstLowArray[0], NumElts));
11706   // Create the splat vector for 0x53000000.
11707   SDValue CstHigh = DAG.getConstant(0x53000000, DL, MVT::i32);
11708   SDValue CstHighArray[] = {CstHigh, CstHigh, CstHigh, CstHigh,
11709                             CstHigh, CstHigh, CstHigh, CstHigh};
11710   SDValue VecCstHigh = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
11711                                    makeArrayRef(&CstHighArray[0], NumElts));
11712
11713   // Create the right shift.
11714   SDValue CstShift = DAG.getConstant(16, DL, MVT::i32);
11715   SDValue CstShiftArray[] = {CstShift, CstShift, CstShift, CstShift,
11716                              CstShift, CstShift, CstShift, CstShift};
11717   SDValue VecCstShift = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
11718                                     makeArrayRef(&CstShiftArray[0], NumElts));
11719   SDValue HighShift = DAG.getNode(ISD::SRL, DL, VecIntVT, V, VecCstShift);
11720
11721   SDValue Low, High;
11722   if (Subtarget.hasSSE41()) {
11723     EVT VecI16VT = Is128 ? MVT::v8i16 : MVT::v16i16;
11724     //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
11725     SDValue VecCstLowBitcast =
11726         DAG.getNode(ISD::BITCAST, DL, VecI16VT, VecCstLow);
11727     SDValue VecBitcast = DAG.getNode(ISD::BITCAST, DL, VecI16VT, V);
11728     // Low will be bitcasted right away, so do not bother bitcasting back to its
11729     // original type.
11730     Low = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecBitcast,
11731                       VecCstLowBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
11732     //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
11733     //                                 (uint4) 0x53000000, 0xaa);
11734     SDValue VecCstHighBitcast =
11735         DAG.getNode(ISD::BITCAST, DL, VecI16VT, VecCstHigh);
11736     SDValue VecShiftBitcast =
11737         DAG.getNode(ISD::BITCAST, DL, VecI16VT, HighShift);
11738     // High will be bitcasted right away, so do not bother bitcasting back to
11739     // its original type.
11740     High = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecShiftBitcast,
11741                        VecCstHighBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
11742   } else {
11743     SDValue CstMask = DAG.getConstant(0xffff, DL, MVT::i32);
11744     SDValue VecCstMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT, CstMask,
11745                                      CstMask, CstMask, CstMask);
11746     //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
11747     SDValue LowAnd = DAG.getNode(ISD::AND, DL, VecIntVT, V, VecCstMask);
11748     Low = DAG.getNode(ISD::OR, DL, VecIntVT, LowAnd, VecCstLow);
11749
11750     //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
11751     High = DAG.getNode(ISD::OR, DL, VecIntVT, HighShift, VecCstHigh);
11752   }
11753
11754   // Create the vector constant for -(0x1.0p39f + 0x1.0p23f).
11755   SDValue CstFAdd = DAG.getConstantFP(
11756       APFloat(APFloat::IEEEsingle, APInt(32, 0xD3000080)), DL, MVT::f32);
11757   SDValue CstFAddArray[] = {CstFAdd, CstFAdd, CstFAdd, CstFAdd,
11758                             CstFAdd, CstFAdd, CstFAdd, CstFAdd};
11759   SDValue VecCstFAdd = DAG.getNode(ISD::BUILD_VECTOR, DL, VecFloatVT,
11760                                    makeArrayRef(&CstFAddArray[0], NumElts));
11761
11762   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
11763   SDValue HighBitcast = DAG.getNode(ISD::BITCAST, DL, VecFloatVT, High);
11764   SDValue FHigh =
11765       DAG.getNode(ISD::FADD, DL, VecFloatVT, HighBitcast, VecCstFAdd);
11766   //     return (float4) lo + fhi;
11767   SDValue LowBitcast = DAG.getNode(ISD::BITCAST, DL, VecFloatVT, Low);
11768   return DAG.getNode(ISD::FADD, DL, VecFloatVT, LowBitcast, FHigh);
11769 }
11770
11771 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
11772                                                SelectionDAG &DAG) const {
11773   SDValue N0 = Op.getOperand(0);
11774   MVT SVT = N0.getSimpleValueType();
11775   SDLoc dl(Op);
11776
11777   switch (SVT.SimpleTy) {
11778   default:
11779     llvm_unreachable("Custom UINT_TO_FP is not supported!");
11780   case MVT::v4i8:
11781   case MVT::v4i16:
11782   case MVT::v8i8:
11783   case MVT::v8i16: {
11784     MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
11785     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
11786                        DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
11787   }
11788   case MVT::v4i32:
11789   case MVT::v8i32:
11790     return lowerUINT_TO_FP_vXi32(Op, DAG, *Subtarget);
11791   }
11792   llvm_unreachable(nullptr);
11793 }
11794
11795 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
11796                                            SelectionDAG &DAG) const {
11797   SDValue N0 = Op.getOperand(0);
11798   SDLoc dl(Op);
11799
11800   if (Op.getValueType().isVector())
11801     return lowerUINT_TO_FP_vec(Op, DAG);
11802
11803   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
11804   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
11805   // the optimization here.
11806   if (DAG.SignBitIsZero(N0))
11807     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
11808
11809   MVT SrcVT = N0.getSimpleValueType();
11810   MVT DstVT = Op.getSimpleValueType();
11811   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
11812     return LowerUINT_TO_FP_i64(Op, DAG);
11813   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
11814     return LowerUINT_TO_FP_i32(Op, DAG);
11815   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
11816     return SDValue();
11817
11818   // Make a 64-bit buffer, and use it to build an FILD.
11819   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
11820   if (SrcVT == MVT::i32) {
11821     SDValue WordOff = DAG.getConstant(4, dl, getPointerTy());
11822     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
11823                                      getPointerTy(), StackSlot, WordOff);
11824     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11825                                   StackSlot, MachinePointerInfo(),
11826                                   false, false, 0);
11827     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, dl, MVT::i32),
11828                                   OffsetSlot, MachinePointerInfo(),
11829                                   false, false, 0);
11830     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
11831     return Fild;
11832   }
11833
11834   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
11835   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11836                                StackSlot, MachinePointerInfo(),
11837                                false, false, 0);
11838   // For i64 source, we need to add the appropriate power of 2 if the input
11839   // was negative.  This is the same as the optimization in
11840   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
11841   // we must be careful to do the computation in x87 extended precision, not
11842   // in SSE. (The generic code can't know it's OK to do this, or how to.)
11843   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
11844   MachineMemOperand *MMO =
11845     DAG.getMachineFunction()
11846     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11847                           MachineMemOperand::MOLoad, 8, 8);
11848
11849   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
11850   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
11851   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
11852                                          MVT::i64, MMO);
11853
11854   APInt FF(32, 0x5F800000ULL);
11855
11856   // Check whether the sign bit is set.
11857   SDValue SignSet = DAG.getSetCC(dl,
11858                                  getSetCCResultType(*DAG.getContext(), MVT::i64),
11859                                  Op.getOperand(0),
11860                                  DAG.getConstant(0, dl, MVT::i64), ISD::SETLT);
11861
11862   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
11863   SDValue FudgePtr = DAG.getConstantPool(
11864                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
11865                                          getPointerTy());
11866
11867   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
11868   SDValue Zero = DAG.getIntPtrConstant(0, dl);
11869   SDValue Four = DAG.getIntPtrConstant(4, dl);
11870   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
11871                                Zero, Four);
11872   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
11873
11874   // Load the value out, extending it from f32 to f80.
11875   // FIXME: Avoid the extend by constructing the right constant pool?
11876   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
11877                                  FudgePtr, MachinePointerInfo::getConstantPool(),
11878                                  MVT::f32, false, false, false, 4);
11879   // Extend everything to 80 bits to force it to be done on x87.
11880   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
11881   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add,
11882                      DAG.getIntPtrConstant(0, dl));
11883 }
11884
11885 std::pair<SDValue,SDValue>
11886 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
11887                                     bool IsSigned, bool IsReplace) const {
11888   SDLoc DL(Op);
11889
11890   EVT DstTy = Op.getValueType();
11891
11892   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
11893     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
11894     DstTy = MVT::i64;
11895   }
11896
11897   assert(DstTy.getSimpleVT() <= MVT::i64 &&
11898          DstTy.getSimpleVT() >= MVT::i16 &&
11899          "Unknown FP_TO_INT to lower!");
11900
11901   // These are really Legal.
11902   if (DstTy == MVT::i32 &&
11903       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
11904     return std::make_pair(SDValue(), SDValue());
11905   if (Subtarget->is64Bit() &&
11906       DstTy == MVT::i64 &&
11907       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
11908     return std::make_pair(SDValue(), SDValue());
11909
11910   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
11911   // stack slot, or into the FTOL runtime function.
11912   MachineFunction &MF = DAG.getMachineFunction();
11913   unsigned MemSize = DstTy.getSizeInBits()/8;
11914   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
11915   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11916
11917   unsigned Opc;
11918   if (!IsSigned && isIntegerTypeFTOL(DstTy))
11919     Opc = X86ISD::WIN_FTOL;
11920   else
11921     switch (DstTy.getSimpleVT().SimpleTy) {
11922     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
11923     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
11924     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
11925     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
11926     }
11927
11928   SDValue Chain = DAG.getEntryNode();
11929   SDValue Value = Op.getOperand(0);
11930   EVT TheVT = Op.getOperand(0).getValueType();
11931   // FIXME This causes a redundant load/store if the SSE-class value is already
11932   // in memory, such as if it is on the callstack.
11933   if (isScalarFPTypeInSSEReg(TheVT)) {
11934     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
11935     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
11936                          MachinePointerInfo::getFixedStack(SSFI),
11937                          false, false, 0);
11938     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
11939     SDValue Ops[] = {
11940       Chain, StackSlot, DAG.getValueType(TheVT)
11941     };
11942
11943     MachineMemOperand *MMO =
11944       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11945                               MachineMemOperand::MOLoad, MemSize, MemSize);
11946     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
11947     Chain = Value.getValue(1);
11948     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
11949     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11950   }
11951
11952   MachineMemOperand *MMO =
11953     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11954                             MachineMemOperand::MOStore, MemSize, MemSize);
11955
11956   if (Opc != X86ISD::WIN_FTOL) {
11957     // Build the FP_TO_INT*_IN_MEM
11958     SDValue Ops[] = { Chain, Value, StackSlot };
11959     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
11960                                            Ops, DstTy, MMO);
11961     return std::make_pair(FIST, StackSlot);
11962   } else {
11963     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
11964       DAG.getVTList(MVT::Other, MVT::Glue),
11965       Chain, Value);
11966     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
11967       MVT::i32, ftol.getValue(1));
11968     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
11969       MVT::i32, eax.getValue(2));
11970     SDValue Ops[] = { eax, edx };
11971     SDValue pair = IsReplace
11972       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
11973       : DAG.getMergeValues(Ops, DL);
11974     return std::make_pair(pair, SDValue());
11975   }
11976 }
11977
11978 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
11979                               const X86Subtarget *Subtarget) {
11980   MVT VT = Op->getSimpleValueType(0);
11981   SDValue In = Op->getOperand(0);
11982   MVT InVT = In.getSimpleValueType();
11983   SDLoc dl(Op);
11984
11985   if (VT.is512BitVector() || InVT.getScalarType() == MVT::i1)
11986     return DAG.getNode(ISD::ZERO_EXTEND, dl, VT, In);
11987
11988   // Optimize vectors in AVX mode:
11989   //
11990   //   v8i16 -> v8i32
11991   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
11992   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
11993   //   Concat upper and lower parts.
11994   //
11995   //   v4i32 -> v4i64
11996   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
11997   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
11998   //   Concat upper and lower parts.
11999   //
12000
12001   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
12002       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
12003       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
12004     return SDValue();
12005
12006   if (Subtarget->hasInt256())
12007     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
12008
12009   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
12010   SDValue Undef = DAG.getUNDEF(InVT);
12011   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
12012   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12013   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12014
12015   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
12016                              VT.getVectorNumElements()/2);
12017
12018   OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
12019   OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
12020
12021   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
12022 }
12023
12024 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
12025                                         SelectionDAG &DAG) {
12026   MVT VT = Op->getSimpleValueType(0);
12027   SDValue In = Op->getOperand(0);
12028   MVT InVT = In.getSimpleValueType();
12029   SDLoc DL(Op);
12030   unsigned int NumElts = VT.getVectorNumElements();
12031   if (NumElts != 8 && NumElts != 16)
12032     return SDValue();
12033
12034   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
12035     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
12036
12037   assert(InVT.getVectorElementType() == MVT::i1);
12038   MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
12039   SDValue One =
12040    DAG.getConstant(APInt(ExtVT.getScalarSizeInBits(), 1), DL, ExtVT);
12041   SDValue Zero =
12042    DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), DL, ExtVT);
12043
12044   SDValue V = DAG.getNode(ISD::VSELECT, DL, ExtVT, In, One, Zero);
12045   if (VT.is512BitVector())
12046     return V;
12047   return DAG.getNode(X86ISD::VTRUNC, DL, VT, V);
12048 }
12049
12050 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12051                                SelectionDAG &DAG) {
12052   if (Subtarget->hasFp256()) {
12053     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
12054     if (Res.getNode())
12055       return Res;
12056   }
12057
12058   return SDValue();
12059 }
12060
12061 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12062                                 SelectionDAG &DAG) {
12063   SDLoc DL(Op);
12064   MVT VT = Op.getSimpleValueType();
12065   SDValue In = Op.getOperand(0);
12066   MVT SVT = In.getSimpleValueType();
12067
12068   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
12069     return LowerZERO_EXTEND_AVX512(Op, DAG);
12070
12071   if (Subtarget->hasFp256()) {
12072     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
12073     if (Res.getNode())
12074       return Res;
12075   }
12076
12077   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
12078          VT.getVectorNumElements() != SVT.getVectorNumElements());
12079   return SDValue();
12080 }
12081
12082 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
12083   SDLoc DL(Op);
12084   MVT VT = Op.getSimpleValueType();
12085   SDValue In = Op.getOperand(0);
12086   MVT InVT = In.getSimpleValueType();
12087
12088   if (VT == MVT::i1) {
12089     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
12090            "Invalid scalar TRUNCATE operation");
12091     if (InVT.getSizeInBits() >= 32)
12092       return SDValue();
12093     In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
12094     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
12095   }
12096   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
12097          "Invalid TRUNCATE operation");
12098
12099   // move vector to mask - truncate solution for SKX
12100   if (VT.getVectorElementType() == MVT::i1) {
12101     if (InVT.is512BitVector() && InVT.getScalarSizeInBits() <= 16 &&
12102         Subtarget->hasBWI())
12103       return Op; // legal, will go to VPMOVB2M, VPMOVW2M
12104     if ((InVT.is256BitVector() || InVT.is128BitVector()) 
12105         && InVT.getScalarSizeInBits() <= 16 &&
12106         Subtarget->hasBWI() && Subtarget->hasVLX())
12107       return Op; // legal, will go to VPMOVB2M, VPMOVW2M
12108     if (InVT.is512BitVector() && InVT.getScalarSizeInBits() >= 32 &&
12109         Subtarget->hasDQI())
12110       return Op; // legal, will go to VPMOVD2M, VPMOVQ2M
12111     if ((InVT.is256BitVector() || InVT.is128BitVector()) 
12112         && InVT.getScalarSizeInBits() >= 32 &&
12113         Subtarget->hasDQI() && Subtarget->hasVLX())
12114       return Op; // legal, will go to VPMOVB2M, VPMOVQ2M
12115   }
12116   if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
12117     if (VT.getVectorElementType().getSizeInBits() >=8)
12118       return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
12119
12120     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
12121     unsigned NumElts = InVT.getVectorNumElements();
12122     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
12123     if (InVT.getSizeInBits() < 512) {
12124       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
12125       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
12126       InVT = ExtVT;
12127     }
12128
12129     SDValue OneV =
12130      DAG.getConstant(APInt::getSignBit(InVT.getScalarSizeInBits()), DL, InVT);
12131     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
12132     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
12133   }
12134
12135   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
12136     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
12137     if (Subtarget->hasInt256()) {
12138       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
12139       In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
12140       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
12141                                 ShufMask);
12142       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
12143                          DAG.getIntPtrConstant(0, DL));
12144     }
12145
12146     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12147                                DAG.getIntPtrConstant(0, DL));
12148     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12149                                DAG.getIntPtrConstant(2, DL));
12150     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
12151     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
12152     static const int ShufMask[] = {0, 2, 4, 6};
12153     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
12154   }
12155
12156   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
12157     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
12158     if (Subtarget->hasInt256()) {
12159       In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
12160
12161       SmallVector<SDValue,32> pshufbMask;
12162       for (unsigned i = 0; i < 2; ++i) {
12163         pshufbMask.push_back(DAG.getConstant(0x0, DL, MVT::i8));
12164         pshufbMask.push_back(DAG.getConstant(0x1, DL, MVT::i8));
12165         pshufbMask.push_back(DAG.getConstant(0x4, DL, MVT::i8));
12166         pshufbMask.push_back(DAG.getConstant(0x5, DL, MVT::i8));
12167         pshufbMask.push_back(DAG.getConstant(0x8, DL, MVT::i8));
12168         pshufbMask.push_back(DAG.getConstant(0x9, DL, MVT::i8));
12169         pshufbMask.push_back(DAG.getConstant(0xc, DL, MVT::i8));
12170         pshufbMask.push_back(DAG.getConstant(0xd, DL, MVT::i8));
12171         for (unsigned j = 0; j < 8; ++j)
12172           pshufbMask.push_back(DAG.getConstant(0x80, DL, MVT::i8));
12173       }
12174       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
12175       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
12176       In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
12177
12178       static const int ShufMask[] = {0,  2,  -1,  -1};
12179       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
12180                                 &ShufMask[0]);
12181       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12182                        DAG.getIntPtrConstant(0, DL));
12183       return DAG.getNode(ISD::BITCAST, DL, VT, In);
12184     }
12185
12186     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12187                                DAG.getIntPtrConstant(0, DL));
12188
12189     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12190                                DAG.getIntPtrConstant(4, DL));
12191
12192     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
12193     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
12194
12195     // The PSHUFB mask:
12196     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
12197                                    -1, -1, -1, -1, -1, -1, -1, -1};
12198
12199     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
12200     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
12201     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
12202
12203     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
12204     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
12205
12206     // The MOVLHPS Mask:
12207     static const int ShufMask2[] = {0, 1, 4, 5};
12208     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
12209     return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
12210   }
12211
12212   // Handle truncation of V256 to V128 using shuffles.
12213   if (!VT.is128BitVector() || !InVT.is256BitVector())
12214     return SDValue();
12215
12216   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
12217
12218   unsigned NumElems = VT.getVectorNumElements();
12219   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
12220
12221   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
12222   // Prepare truncation shuffle mask
12223   for (unsigned i = 0; i != NumElems; ++i)
12224     MaskVec[i] = i * 2;
12225   SDValue V = DAG.getVectorShuffle(NVT, DL,
12226                                    DAG.getNode(ISD::BITCAST, DL, NVT, In),
12227                                    DAG.getUNDEF(NVT), &MaskVec[0]);
12228   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
12229                      DAG.getIntPtrConstant(0, DL));
12230 }
12231
12232 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
12233                                            SelectionDAG &DAG) const {
12234   assert(!Op.getSimpleValueType().isVector());
12235
12236   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12237     /*IsSigned=*/ true, /*IsReplace=*/ false);
12238   SDValue FIST = Vals.first, StackSlot = Vals.second;
12239   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
12240   if (!FIST.getNode()) return Op;
12241
12242   if (StackSlot.getNode())
12243     // Load the result.
12244     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12245                        FIST, StackSlot, MachinePointerInfo(),
12246                        false, false, false, 0);
12247
12248   // The node is the result.
12249   return FIST;
12250 }
12251
12252 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
12253                                            SelectionDAG &DAG) const {
12254   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12255     /*IsSigned=*/ false, /*IsReplace=*/ false);
12256   SDValue FIST = Vals.first, StackSlot = Vals.second;
12257   assert(FIST.getNode() && "Unexpected failure");
12258
12259   if (StackSlot.getNode())
12260     // Load the result.
12261     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12262                        FIST, StackSlot, MachinePointerInfo(),
12263                        false, false, false, 0);
12264
12265   // The node is the result.
12266   return FIST;
12267 }
12268
12269 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
12270   SDLoc DL(Op);
12271   MVT VT = Op.getSimpleValueType();
12272   SDValue In = Op.getOperand(0);
12273   MVT SVT = In.getSimpleValueType();
12274
12275   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
12276
12277   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
12278                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
12279                                  In, DAG.getUNDEF(SVT)));
12280 }
12281
12282 /// The only differences between FABS and FNEG are the mask and the logic op.
12283 /// FNEG also has a folding opportunity for FNEG(FABS(x)).
12284 static SDValue LowerFABSorFNEG(SDValue Op, SelectionDAG &DAG) {
12285   assert((Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) &&
12286          "Wrong opcode for lowering FABS or FNEG.");
12287
12288   bool IsFABS = (Op.getOpcode() == ISD::FABS);
12289
12290   // If this is a FABS and it has an FNEG user, bail out to fold the combination
12291   // into an FNABS. We'll lower the FABS after that if it is still in use.
12292   if (IsFABS)
12293     for (SDNode *User : Op->uses())
12294       if (User->getOpcode() == ISD::FNEG)
12295         return Op;
12296
12297   SDValue Op0 = Op.getOperand(0);
12298   bool IsFNABS = !IsFABS && (Op0.getOpcode() == ISD::FABS);
12299
12300   SDLoc dl(Op);
12301   MVT VT = Op.getSimpleValueType();
12302   // Assume scalar op for initialization; update for vector if needed.
12303   // Note that there are no scalar bitwise logical SSE/AVX instructions, so we
12304   // generate a 16-byte vector constant and logic op even for the scalar case.
12305   // Using a 16-byte mask allows folding the load of the mask with
12306   // the logic op, so it can save (~4 bytes) on code size.
12307   MVT EltVT = VT;
12308   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
12309   // FIXME: Use function attribute "OptimizeForSize" and/or CodeGenOpt::Level to
12310   // decide if we should generate a 16-byte constant mask when we only need 4 or
12311   // 8 bytes for the scalar case.
12312   if (VT.isVector()) {
12313     EltVT = VT.getVectorElementType();
12314     NumElts = VT.getVectorNumElements();
12315   }
12316
12317   unsigned EltBits = EltVT.getSizeInBits();
12318   LLVMContext *Context = DAG.getContext();
12319   // For FABS, mask is 0x7f...; for FNEG, mask is 0x80...
12320   APInt MaskElt =
12321     IsFABS ? APInt::getSignedMaxValue(EltBits) : APInt::getSignBit(EltBits);
12322   Constant *C = ConstantInt::get(*Context, MaskElt);
12323   C = ConstantVector::getSplat(NumElts, C);
12324   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12325   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
12326   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
12327   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
12328                              MachinePointerInfo::getConstantPool(),
12329                              false, false, false, Alignment);
12330
12331   if (VT.isVector()) {
12332     // For a vector, cast operands to a vector type, perform the logic op,
12333     // and cast the result back to the original value type.
12334     MVT VecVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
12335     SDValue MaskCasted = DAG.getNode(ISD::BITCAST, dl, VecVT, Mask);
12336     SDValue Operand = IsFNABS ?
12337       DAG.getNode(ISD::BITCAST, dl, VecVT, Op0.getOperand(0)) :
12338       DAG.getNode(ISD::BITCAST, dl, VecVT, Op0);
12339     unsigned BitOp = IsFABS ? ISD::AND : IsFNABS ? ISD::OR : ISD::XOR;
12340     return DAG.getNode(ISD::BITCAST, dl, VT,
12341                        DAG.getNode(BitOp, dl, VecVT, Operand, MaskCasted));
12342   }
12343
12344   // If not vector, then scalar.
12345   unsigned BitOp = IsFABS ? X86ISD::FAND : IsFNABS ? X86ISD::FOR : X86ISD::FXOR;
12346   SDValue Operand = IsFNABS ? Op0.getOperand(0) : Op0;
12347   return DAG.getNode(BitOp, dl, VT, Operand, Mask);
12348 }
12349
12350 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
12351   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12352   LLVMContext *Context = DAG.getContext();
12353   SDValue Op0 = Op.getOperand(0);
12354   SDValue Op1 = Op.getOperand(1);
12355   SDLoc dl(Op);
12356   MVT VT = Op.getSimpleValueType();
12357   MVT SrcVT = Op1.getSimpleValueType();
12358
12359   // If second operand is smaller, extend it first.
12360   if (SrcVT.bitsLT(VT)) {
12361     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
12362     SrcVT = VT;
12363   }
12364   // And if it is bigger, shrink it first.
12365   if (SrcVT.bitsGT(VT)) {
12366     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1, dl));
12367     SrcVT = VT;
12368   }
12369
12370   // At this point the operands and the result should have the same
12371   // type, and that won't be f80 since that is not custom lowered.
12372
12373   const fltSemantics &Sem =
12374       VT == MVT::f64 ? APFloat::IEEEdouble : APFloat::IEEEsingle;
12375   const unsigned SizeInBits = VT.getSizeInBits();
12376
12377   SmallVector<Constant *, 4> CV(
12378       VT == MVT::f64 ? 2 : 4,
12379       ConstantFP::get(*Context, APFloat(Sem, APInt(SizeInBits, 0))));
12380
12381   // First, clear all bits but the sign bit from the second operand (sign).
12382   CV[0] = ConstantFP::get(*Context,
12383                           APFloat(Sem, APInt::getHighBitsSet(SizeInBits, 1)));
12384   Constant *C = ConstantVector::get(CV);
12385   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
12386   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
12387                               MachinePointerInfo::getConstantPool(),
12388                               false, false, false, 16);
12389   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
12390
12391   // Next, clear the sign bit from the first operand (magnitude).
12392   // If it's a constant, we can clear it here.
12393   if (ConstantFPSDNode *Op0CN = dyn_cast<ConstantFPSDNode>(Op0)) {
12394     APFloat APF = Op0CN->getValueAPF();
12395     // If the magnitude is a positive zero, the sign bit alone is enough.
12396     if (APF.isPosZero())
12397       return SignBit;
12398     APF.clearSign();
12399     CV[0] = ConstantFP::get(*Context, APF);
12400   } else {
12401     CV[0] = ConstantFP::get(
12402         *Context,
12403         APFloat(Sem, APInt::getLowBitsSet(SizeInBits, SizeInBits - 1)));
12404   }
12405   C = ConstantVector::get(CV);
12406   CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
12407   SDValue Val = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
12408                             MachinePointerInfo::getConstantPool(),
12409                             false, false, false, 16);
12410   // If the magnitude operand wasn't a constant, we need to AND out the sign.
12411   if (!isa<ConstantFPSDNode>(Op0))
12412     Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Val);
12413
12414   // OR the magnitude value with the sign bit.
12415   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
12416 }
12417
12418 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
12419   SDValue N0 = Op.getOperand(0);
12420   SDLoc dl(Op);
12421   MVT VT = Op.getSimpleValueType();
12422
12423   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
12424   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
12425                                   DAG.getConstant(1, dl, VT));
12426   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, dl, VT));
12427 }
12428
12429 // Check whether an OR'd tree is PTEST-able.
12430 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
12431                                       SelectionDAG &DAG) {
12432   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
12433
12434   if (!Subtarget->hasSSE41())
12435     return SDValue();
12436
12437   if (!Op->hasOneUse())
12438     return SDValue();
12439
12440   SDNode *N = Op.getNode();
12441   SDLoc DL(N);
12442
12443   SmallVector<SDValue, 8> Opnds;
12444   DenseMap<SDValue, unsigned> VecInMap;
12445   SmallVector<SDValue, 8> VecIns;
12446   EVT VT = MVT::Other;
12447
12448   // Recognize a special case where a vector is casted into wide integer to
12449   // test all 0s.
12450   Opnds.push_back(N->getOperand(0));
12451   Opnds.push_back(N->getOperand(1));
12452
12453   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
12454     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
12455     // BFS traverse all OR'd operands.
12456     if (I->getOpcode() == ISD::OR) {
12457       Opnds.push_back(I->getOperand(0));
12458       Opnds.push_back(I->getOperand(1));
12459       // Re-evaluate the number of nodes to be traversed.
12460       e += 2; // 2 more nodes (LHS and RHS) are pushed.
12461       continue;
12462     }
12463
12464     // Quit if a non-EXTRACT_VECTOR_ELT
12465     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
12466       return SDValue();
12467
12468     // Quit if without a constant index.
12469     SDValue Idx = I->getOperand(1);
12470     if (!isa<ConstantSDNode>(Idx))
12471       return SDValue();
12472
12473     SDValue ExtractedFromVec = I->getOperand(0);
12474     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
12475     if (M == VecInMap.end()) {
12476       VT = ExtractedFromVec.getValueType();
12477       // Quit if not 128/256-bit vector.
12478       if (!VT.is128BitVector() && !VT.is256BitVector())
12479         return SDValue();
12480       // Quit if not the same type.
12481       if (VecInMap.begin() != VecInMap.end() &&
12482           VT != VecInMap.begin()->first.getValueType())
12483         return SDValue();
12484       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
12485       VecIns.push_back(ExtractedFromVec);
12486     }
12487     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
12488   }
12489
12490   assert((VT.is128BitVector() || VT.is256BitVector()) &&
12491          "Not extracted from 128-/256-bit vector.");
12492
12493   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
12494
12495   for (DenseMap<SDValue, unsigned>::const_iterator
12496         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
12497     // Quit if not all elements are used.
12498     if (I->second != FullMask)
12499       return SDValue();
12500   }
12501
12502   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
12503
12504   // Cast all vectors into TestVT for PTEST.
12505   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
12506     VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
12507
12508   // If more than one full vectors are evaluated, OR them first before PTEST.
12509   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
12510     // Each iteration will OR 2 nodes and append the result until there is only
12511     // 1 node left, i.e. the final OR'd value of all vectors.
12512     SDValue LHS = VecIns[Slot];
12513     SDValue RHS = VecIns[Slot + 1];
12514     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
12515   }
12516
12517   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
12518                      VecIns.back(), VecIns.back());
12519 }
12520
12521 /// \brief return true if \c Op has a use that doesn't just read flags.
12522 static bool hasNonFlagsUse(SDValue Op) {
12523   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
12524        ++UI) {
12525     SDNode *User = *UI;
12526     unsigned UOpNo = UI.getOperandNo();
12527     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
12528       // Look pass truncate.
12529       UOpNo = User->use_begin().getOperandNo();
12530       User = *User->use_begin();
12531     }
12532
12533     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
12534         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
12535       return true;
12536   }
12537   return false;
12538 }
12539
12540 /// Emit nodes that will be selected as "test Op0,Op0", or something
12541 /// equivalent.
12542 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
12543                                     SelectionDAG &DAG) const {
12544   if (Op.getValueType() == MVT::i1) {
12545     SDValue ExtOp = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i8, Op);
12546     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, ExtOp,
12547                        DAG.getConstant(0, dl, MVT::i8));
12548   }
12549   // CF and OF aren't always set the way we want. Determine which
12550   // of these we need.
12551   bool NeedCF = false;
12552   bool NeedOF = false;
12553   switch (X86CC) {
12554   default: break;
12555   case X86::COND_A: case X86::COND_AE:
12556   case X86::COND_B: case X86::COND_BE:
12557     NeedCF = true;
12558     break;
12559   case X86::COND_G: case X86::COND_GE:
12560   case X86::COND_L: case X86::COND_LE:
12561   case X86::COND_O: case X86::COND_NO: {
12562     // Check if we really need to set the
12563     // Overflow flag. If NoSignedWrap is present
12564     // that is not actually needed.
12565     switch (Op->getOpcode()) {
12566     case ISD::ADD:
12567     case ISD::SUB:
12568     case ISD::MUL:
12569     case ISD::SHL: {
12570       const BinaryWithFlagsSDNode *BinNode =
12571           cast<BinaryWithFlagsSDNode>(Op.getNode());
12572       if (BinNode->Flags.hasNoSignedWrap())
12573         break;
12574     }
12575     default:
12576       NeedOF = true;
12577       break;
12578     }
12579     break;
12580   }
12581   }
12582   // See if we can use the EFLAGS value from the operand instead of
12583   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
12584   // we prove that the arithmetic won't overflow, we can't use OF or CF.
12585   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
12586     // Emit a CMP with 0, which is the TEST pattern.
12587     //if (Op.getValueType() == MVT::i1)
12588     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
12589     //                     DAG.getConstant(0, MVT::i1));
12590     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12591                        DAG.getConstant(0, dl, Op.getValueType()));
12592   }
12593   unsigned Opcode = 0;
12594   unsigned NumOperands = 0;
12595
12596   // Truncate operations may prevent the merge of the SETCC instruction
12597   // and the arithmetic instruction before it. Attempt to truncate the operands
12598   // of the arithmetic instruction and use a reduced bit-width instruction.
12599   bool NeedTruncation = false;
12600   SDValue ArithOp = Op;
12601   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
12602     SDValue Arith = Op->getOperand(0);
12603     // Both the trunc and the arithmetic op need to have one user each.
12604     if (Arith->hasOneUse())
12605       switch (Arith.getOpcode()) {
12606         default: break;
12607         case ISD::ADD:
12608         case ISD::SUB:
12609         case ISD::AND:
12610         case ISD::OR:
12611         case ISD::XOR: {
12612           NeedTruncation = true;
12613           ArithOp = Arith;
12614         }
12615       }
12616   }
12617
12618   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
12619   // which may be the result of a CAST.  We use the variable 'Op', which is the
12620   // non-casted variable when we check for possible users.
12621   switch (ArithOp.getOpcode()) {
12622   case ISD::ADD:
12623     // Due to an isel shortcoming, be conservative if this add is likely to be
12624     // selected as part of a load-modify-store instruction. When the root node
12625     // in a match is a store, isel doesn't know how to remap non-chain non-flag
12626     // uses of other nodes in the match, such as the ADD in this case. This
12627     // leads to the ADD being left around and reselected, with the result being
12628     // two adds in the output.  Alas, even if none our users are stores, that
12629     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
12630     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
12631     // climbing the DAG back to the root, and it doesn't seem to be worth the
12632     // effort.
12633     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12634          UE = Op.getNode()->use_end(); UI != UE; ++UI)
12635       if (UI->getOpcode() != ISD::CopyToReg &&
12636           UI->getOpcode() != ISD::SETCC &&
12637           UI->getOpcode() != ISD::STORE)
12638         goto default_case;
12639
12640     if (ConstantSDNode *C =
12641         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
12642       // An add of one will be selected as an INC.
12643       if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
12644         Opcode = X86ISD::INC;
12645         NumOperands = 1;
12646         break;
12647       }
12648
12649       // An add of negative one (subtract of one) will be selected as a DEC.
12650       if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
12651         Opcode = X86ISD::DEC;
12652         NumOperands = 1;
12653         break;
12654       }
12655     }
12656
12657     // Otherwise use a regular EFLAGS-setting add.
12658     Opcode = X86ISD::ADD;
12659     NumOperands = 2;
12660     break;
12661   case ISD::SHL:
12662   case ISD::SRL:
12663     // If we have a constant logical shift that's only used in a comparison
12664     // against zero turn it into an equivalent AND. This allows turning it into
12665     // a TEST instruction later.
12666     if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
12667         isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
12668       EVT VT = Op.getValueType();
12669       unsigned BitWidth = VT.getSizeInBits();
12670       unsigned ShAmt = Op->getConstantOperandVal(1);
12671       if (ShAmt >= BitWidth) // Avoid undefined shifts.
12672         break;
12673       APInt Mask = ArithOp.getOpcode() == ISD::SRL
12674                        ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
12675                        : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
12676       if (!Mask.isSignedIntN(32)) // Avoid large immediates.
12677         break;
12678       SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
12679                                 DAG.getConstant(Mask, dl, VT));
12680       DAG.ReplaceAllUsesWith(Op, New);
12681       Op = New;
12682     }
12683     break;
12684
12685   case ISD::AND:
12686     // If the primary and result isn't used, don't bother using X86ISD::AND,
12687     // because a TEST instruction will be better.
12688     if (!hasNonFlagsUse(Op))
12689       break;
12690     // FALL THROUGH
12691   case ISD::SUB:
12692   case ISD::OR:
12693   case ISD::XOR:
12694     // Due to the ISEL shortcoming noted above, be conservative if this op is
12695     // likely to be selected as part of a load-modify-store instruction.
12696     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12697            UE = Op.getNode()->use_end(); UI != UE; ++UI)
12698       if (UI->getOpcode() == ISD::STORE)
12699         goto default_case;
12700
12701     // Otherwise use a regular EFLAGS-setting instruction.
12702     switch (ArithOp.getOpcode()) {
12703     default: llvm_unreachable("unexpected operator!");
12704     case ISD::SUB: Opcode = X86ISD::SUB; break;
12705     case ISD::XOR: Opcode = X86ISD::XOR; break;
12706     case ISD::AND: Opcode = X86ISD::AND; break;
12707     case ISD::OR: {
12708       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
12709         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
12710         if (EFLAGS.getNode())
12711           return EFLAGS;
12712       }
12713       Opcode = X86ISD::OR;
12714       break;
12715     }
12716     }
12717
12718     NumOperands = 2;
12719     break;
12720   case X86ISD::ADD:
12721   case X86ISD::SUB:
12722   case X86ISD::INC:
12723   case X86ISD::DEC:
12724   case X86ISD::OR:
12725   case X86ISD::XOR:
12726   case X86ISD::AND:
12727     return SDValue(Op.getNode(), 1);
12728   default:
12729   default_case:
12730     break;
12731   }
12732
12733   // If we found that truncation is beneficial, perform the truncation and
12734   // update 'Op'.
12735   if (NeedTruncation) {
12736     EVT VT = Op.getValueType();
12737     SDValue WideVal = Op->getOperand(0);
12738     EVT WideVT = WideVal.getValueType();
12739     unsigned ConvertedOp = 0;
12740     // Use a target machine opcode to prevent further DAGCombine
12741     // optimizations that may separate the arithmetic operations
12742     // from the setcc node.
12743     switch (WideVal.getOpcode()) {
12744       default: break;
12745       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
12746       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
12747       case ISD::AND: ConvertedOp = X86ISD::AND; break;
12748       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
12749       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
12750     }
12751
12752     if (ConvertedOp) {
12753       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12754       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
12755         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
12756         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
12757         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
12758       }
12759     }
12760   }
12761
12762   if (Opcode == 0)
12763     // Emit a CMP with 0, which is the TEST pattern.
12764     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12765                        DAG.getConstant(0, dl, Op.getValueType()));
12766
12767   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12768   SmallVector<SDValue, 4> Ops(Op->op_begin(), Op->op_begin() + NumOperands);
12769
12770   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
12771   DAG.ReplaceAllUsesWith(Op, New);
12772   return SDValue(New.getNode(), 1);
12773 }
12774
12775 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
12776 /// equivalent.
12777 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
12778                                    SDLoc dl, SelectionDAG &DAG) const {
12779   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
12780     if (C->getAPIntValue() == 0)
12781       return EmitTest(Op0, X86CC, dl, DAG);
12782
12783      if (Op0.getValueType() == MVT::i1)
12784        llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
12785   }
12786
12787   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
12788        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
12789     // Do the comparison at i32 if it's smaller, besides the Atom case.
12790     // This avoids subregister aliasing issues. Keep the smaller reference
12791     // if we're optimizing for size, however, as that'll allow better folding
12792     // of memory operations.
12793     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
12794         !DAG.getMachineFunction().getFunction()->hasFnAttribute(
12795             Attribute::MinSize) &&
12796         !Subtarget->isAtom()) {
12797       unsigned ExtendOp =
12798           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
12799       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
12800       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
12801     }
12802     // Use SUB instead of CMP to enable CSE between SUB and CMP.
12803     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
12804     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
12805                               Op0, Op1);
12806     return SDValue(Sub.getNode(), 1);
12807   }
12808   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
12809 }
12810
12811 /// Convert a comparison if required by the subtarget.
12812 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
12813                                                  SelectionDAG &DAG) const {
12814   // If the subtarget does not support the FUCOMI instruction, floating-point
12815   // comparisons have to be converted.
12816   if (Subtarget->hasCMov() ||
12817       Cmp.getOpcode() != X86ISD::CMP ||
12818       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
12819       !Cmp.getOperand(1).getValueType().isFloatingPoint())
12820     return Cmp;
12821
12822   // The instruction selector will select an FUCOM instruction instead of
12823   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
12824   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
12825   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
12826   SDLoc dl(Cmp);
12827   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
12828   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
12829   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
12830                             DAG.getConstant(8, dl, MVT::i8));
12831   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
12832   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
12833 }
12834
12835 /// The minimum architected relative accuracy is 2^-12. We need one
12836 /// Newton-Raphson step to have a good float result (24 bits of precision).
12837 SDValue X86TargetLowering::getRsqrtEstimate(SDValue Op,
12838                                             DAGCombinerInfo &DCI,
12839                                             unsigned &RefinementSteps,
12840                                             bool &UseOneConstNR) const {
12841   // FIXME: We should use instruction latency models to calculate the cost of
12842   // each potential sequence, but this is very hard to do reliably because
12843   // at least Intel's Core* chips have variable timing based on the number of
12844   // significant digits in the divisor and/or sqrt operand.
12845   if (!Subtarget->useSqrtEst())
12846     return SDValue();
12847
12848   EVT VT = Op.getValueType();
12849
12850   // SSE1 has rsqrtss and rsqrtps.
12851   // TODO: Add support for AVX512 (v16f32).
12852   // It is likely not profitable to do this for f64 because a double-precision
12853   // rsqrt estimate with refinement on x86 prior to FMA requires at least 16
12854   // instructions: convert to single, rsqrtss, convert back to double, refine
12855   // (3 steps = at least 13 insts). If an 'rsqrtsd' variant was added to the ISA
12856   // along with FMA, this could be a throughput win.
12857   if ((Subtarget->hasSSE1() && (VT == MVT::f32 || VT == MVT::v4f32)) ||
12858       (Subtarget->hasAVX() && VT == MVT::v8f32)) {
12859     RefinementSteps = 1;
12860     UseOneConstNR = false;
12861     return DCI.DAG.getNode(X86ISD::FRSQRT, SDLoc(Op), VT, Op);
12862   }
12863   return SDValue();
12864 }
12865
12866 /// The minimum architected relative accuracy is 2^-12. We need one
12867 /// Newton-Raphson step to have a good float result (24 bits of precision).
12868 SDValue X86TargetLowering::getRecipEstimate(SDValue Op,
12869                                             DAGCombinerInfo &DCI,
12870                                             unsigned &RefinementSteps) const {
12871   // FIXME: We should use instruction latency models to calculate the cost of
12872   // each potential sequence, but this is very hard to do reliably because
12873   // at least Intel's Core* chips have variable timing based on the number of
12874   // significant digits in the divisor.
12875   if (!Subtarget->useReciprocalEst())
12876     return SDValue();
12877
12878   EVT VT = Op.getValueType();
12879
12880   // SSE1 has rcpss and rcpps. AVX adds a 256-bit variant for rcpps.
12881   // TODO: Add support for AVX512 (v16f32).
12882   // It is likely not profitable to do this for f64 because a double-precision
12883   // reciprocal estimate with refinement on x86 prior to FMA requires
12884   // 15 instructions: convert to single, rcpss, convert back to double, refine
12885   // (3 steps = 12 insts). If an 'rcpsd' variant was added to the ISA
12886   // along with FMA, this could be a throughput win.
12887   if ((Subtarget->hasSSE1() && (VT == MVT::f32 || VT == MVT::v4f32)) ||
12888       (Subtarget->hasAVX() && VT == MVT::v8f32)) {
12889     RefinementSteps = ReciprocalEstimateRefinementSteps;
12890     return DCI.DAG.getNode(X86ISD::FRCP, SDLoc(Op), VT, Op);
12891   }
12892   return SDValue();
12893 }
12894
12895 /// If we have at least two divisions that use the same divisor, convert to
12896 /// multplication by a reciprocal. This may need to be adjusted for a given
12897 /// CPU if a division's cost is not at least twice the cost of a multiplication.
12898 /// This is because we still need one division to calculate the reciprocal and
12899 /// then we need two multiplies by that reciprocal as replacements for the
12900 /// original divisions.
12901 bool X86TargetLowering::combineRepeatedFPDivisors(unsigned NumUsers) const {
12902   return NumUsers > 1;
12903 }
12904
12905 static bool isAllOnes(SDValue V) {
12906   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
12907   return C && C->isAllOnesValue();
12908 }
12909
12910 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
12911 /// if it's possible.
12912 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
12913                                      SDLoc dl, SelectionDAG &DAG) const {
12914   SDValue Op0 = And.getOperand(0);
12915   SDValue Op1 = And.getOperand(1);
12916   if (Op0.getOpcode() == ISD::TRUNCATE)
12917     Op0 = Op0.getOperand(0);
12918   if (Op1.getOpcode() == ISD::TRUNCATE)
12919     Op1 = Op1.getOperand(0);
12920
12921   SDValue LHS, RHS;
12922   if (Op1.getOpcode() == ISD::SHL)
12923     std::swap(Op0, Op1);
12924   if (Op0.getOpcode() == ISD::SHL) {
12925     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
12926       if (And00C->getZExtValue() == 1) {
12927         // If we looked past a truncate, check that it's only truncating away
12928         // known zeros.
12929         unsigned BitWidth = Op0.getValueSizeInBits();
12930         unsigned AndBitWidth = And.getValueSizeInBits();
12931         if (BitWidth > AndBitWidth) {
12932           APInt Zeros, Ones;
12933           DAG.computeKnownBits(Op0, Zeros, Ones);
12934           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
12935             return SDValue();
12936         }
12937         LHS = Op1;
12938         RHS = Op0.getOperand(1);
12939       }
12940   } else if (Op1.getOpcode() == ISD::Constant) {
12941     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
12942     uint64_t AndRHSVal = AndRHS->getZExtValue();
12943     SDValue AndLHS = Op0;
12944
12945     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
12946       LHS = AndLHS.getOperand(0);
12947       RHS = AndLHS.getOperand(1);
12948     }
12949
12950     // Use BT if the immediate can't be encoded in a TEST instruction.
12951     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
12952       LHS = AndLHS;
12953       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), dl, LHS.getValueType());
12954     }
12955   }
12956
12957   if (LHS.getNode()) {
12958     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
12959     // instruction.  Since the shift amount is in-range-or-undefined, we know
12960     // that doing a bittest on the i32 value is ok.  We extend to i32 because
12961     // the encoding for the i16 version is larger than the i32 version.
12962     // Also promote i16 to i32 for performance / code size reason.
12963     if (LHS.getValueType() == MVT::i8 ||
12964         LHS.getValueType() == MVT::i16)
12965       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
12966
12967     // If the operand types disagree, extend the shift amount to match.  Since
12968     // BT ignores high bits (like shifts) we can use anyextend.
12969     if (LHS.getValueType() != RHS.getValueType())
12970       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
12971
12972     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
12973     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
12974     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12975                        DAG.getConstant(Cond, dl, MVT::i8), BT);
12976   }
12977
12978   return SDValue();
12979 }
12980
12981 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
12982 /// mask CMPs.
12983 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
12984                               SDValue &Op1) {
12985   unsigned SSECC;
12986   bool Swap = false;
12987
12988   // SSE Condition code mapping:
12989   //  0 - EQ
12990   //  1 - LT
12991   //  2 - LE
12992   //  3 - UNORD
12993   //  4 - NEQ
12994   //  5 - NLT
12995   //  6 - NLE
12996   //  7 - ORD
12997   switch (SetCCOpcode) {
12998   default: llvm_unreachable("Unexpected SETCC condition");
12999   case ISD::SETOEQ:
13000   case ISD::SETEQ:  SSECC = 0; break;
13001   case ISD::SETOGT:
13002   case ISD::SETGT:  Swap = true; // Fallthrough
13003   case ISD::SETLT:
13004   case ISD::SETOLT: SSECC = 1; break;
13005   case ISD::SETOGE:
13006   case ISD::SETGE:  Swap = true; // Fallthrough
13007   case ISD::SETLE:
13008   case ISD::SETOLE: SSECC = 2; break;
13009   case ISD::SETUO:  SSECC = 3; break;
13010   case ISD::SETUNE:
13011   case ISD::SETNE:  SSECC = 4; break;
13012   case ISD::SETULE: Swap = true; // Fallthrough
13013   case ISD::SETUGE: SSECC = 5; break;
13014   case ISD::SETULT: Swap = true; // Fallthrough
13015   case ISD::SETUGT: SSECC = 6; break;
13016   case ISD::SETO:   SSECC = 7; break;
13017   case ISD::SETUEQ:
13018   case ISD::SETONE: SSECC = 8; break;
13019   }
13020   if (Swap)
13021     std::swap(Op0, Op1);
13022
13023   return SSECC;
13024 }
13025
13026 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
13027 // ones, and then concatenate the result back.
13028 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
13029   MVT VT = Op.getSimpleValueType();
13030
13031   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
13032          "Unsupported value type for operation");
13033
13034   unsigned NumElems = VT.getVectorNumElements();
13035   SDLoc dl(Op);
13036   SDValue CC = Op.getOperand(2);
13037
13038   // Extract the LHS vectors
13039   SDValue LHS = Op.getOperand(0);
13040   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13041   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13042
13043   // Extract the RHS vectors
13044   SDValue RHS = Op.getOperand(1);
13045   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
13046   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
13047
13048   // Issue the operation on the smaller types and concatenate the result back
13049   MVT EltVT = VT.getVectorElementType();
13050   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13051   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
13052                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
13053                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
13054 }
13055
13056 static SDValue LowerBoolVSETCC_AVX512(SDValue Op, SelectionDAG &DAG) {
13057   SDValue Op0 = Op.getOperand(0);
13058   SDValue Op1 = Op.getOperand(1);
13059   SDValue CC = Op.getOperand(2);
13060   MVT VT = Op.getSimpleValueType();
13061   SDLoc dl(Op);
13062
13063   assert(Op0.getValueType().getVectorElementType() == MVT::i1 &&
13064          "Unexpected type for boolean compare operation");
13065   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13066   SDValue NotOp0 = DAG.getNode(ISD::XOR, dl, VT, Op0,
13067                                DAG.getConstant(-1, dl, VT));
13068   SDValue NotOp1 = DAG.getNode(ISD::XOR, dl, VT, Op1,
13069                                DAG.getConstant(-1, dl, VT));
13070   switch (SetCCOpcode) {
13071   default: llvm_unreachable("Unexpected SETCC condition");
13072   case ISD::SETNE:
13073     // (x != y) -> ~(x ^ y)
13074     return DAG.getNode(ISD::XOR, dl, VT,
13075                        DAG.getNode(ISD::XOR, dl, VT, Op0, Op1),
13076                        DAG.getConstant(-1, dl, VT));
13077   case ISD::SETEQ:
13078     // (x == y) -> (x ^ y)
13079     return DAG.getNode(ISD::XOR, dl, VT, Op0, Op1);
13080   case ISD::SETUGT:
13081   case ISD::SETGT:
13082     // (x > y) -> (x & ~y)
13083     return DAG.getNode(ISD::AND, dl, VT, Op0, NotOp1);
13084   case ISD::SETULT:
13085   case ISD::SETLT:
13086     // (x < y) -> (~x & y)
13087     return DAG.getNode(ISD::AND, dl, VT, NotOp0, Op1);
13088   case ISD::SETULE:
13089   case ISD::SETLE:
13090     // (x <= y) -> (~x | y)
13091     return DAG.getNode(ISD::OR, dl, VT, NotOp0, Op1);
13092   case ISD::SETUGE:
13093   case ISD::SETGE:
13094     // (x >=y) -> (x | ~y)
13095     return DAG.getNode(ISD::OR, dl, VT, Op0, NotOp1);
13096   }
13097 }
13098
13099 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
13100                                      const X86Subtarget *Subtarget) {
13101   SDValue Op0 = Op.getOperand(0);
13102   SDValue Op1 = Op.getOperand(1);
13103   SDValue CC = Op.getOperand(2);
13104   MVT VT = Op.getSimpleValueType();
13105   SDLoc dl(Op);
13106
13107   assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 8 &&
13108          Op.getValueType().getScalarType() == MVT::i1 &&
13109          "Cannot set masked compare for this operation");
13110
13111   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13112   unsigned  Opc = 0;
13113   bool Unsigned = false;
13114   bool Swap = false;
13115   unsigned SSECC;
13116   switch (SetCCOpcode) {
13117   default: llvm_unreachable("Unexpected SETCC condition");
13118   case ISD::SETNE:  SSECC = 4; break;
13119   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
13120   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
13121   case ISD::SETLT:  Swap = true; //fall-through
13122   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
13123   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
13124   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
13125   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
13126   case ISD::SETULE: Unsigned = true; //fall-through
13127   case ISD::SETLE:  SSECC = 2; break;
13128   }
13129
13130   if (Swap)
13131     std::swap(Op0, Op1);
13132   if (Opc)
13133     return DAG.getNode(Opc, dl, VT, Op0, Op1);
13134   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
13135   return DAG.getNode(Opc, dl, VT, Op0, Op1,
13136                      DAG.getConstant(SSECC, dl, MVT::i8));
13137 }
13138
13139 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
13140 /// operand \p Op1.  If non-trivial (for example because it's not constant)
13141 /// return an empty value.
13142 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
13143 {
13144   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
13145   if (!BV)
13146     return SDValue();
13147
13148   MVT VT = Op1.getSimpleValueType();
13149   MVT EVT = VT.getVectorElementType();
13150   unsigned n = VT.getVectorNumElements();
13151   SmallVector<SDValue, 8> ULTOp1;
13152
13153   for (unsigned i = 0; i < n; ++i) {
13154     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
13155     if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
13156       return SDValue();
13157
13158     // Avoid underflow.
13159     APInt Val = Elt->getAPIntValue();
13160     if (Val == 0)
13161       return SDValue();
13162
13163     ULTOp1.push_back(DAG.getConstant(Val - 1, dl, EVT));
13164   }
13165
13166   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
13167 }
13168
13169 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
13170                            SelectionDAG &DAG) {
13171   SDValue Op0 = Op.getOperand(0);
13172   SDValue Op1 = Op.getOperand(1);
13173   SDValue CC = Op.getOperand(2);
13174   MVT VT = Op.getSimpleValueType();
13175   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13176   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
13177   SDLoc dl(Op);
13178
13179   if (isFP) {
13180 #ifndef NDEBUG
13181     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
13182     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
13183 #endif
13184
13185     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
13186     unsigned Opc = X86ISD::CMPP;
13187     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
13188       assert(VT.getVectorNumElements() <= 16);
13189       Opc = X86ISD::CMPM;
13190     }
13191     // In the two special cases we can't handle, emit two comparisons.
13192     if (SSECC == 8) {
13193       unsigned CC0, CC1;
13194       unsigned CombineOpc;
13195       if (SetCCOpcode == ISD::SETUEQ) {
13196         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
13197       } else {
13198         assert(SetCCOpcode == ISD::SETONE);
13199         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
13200       }
13201
13202       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13203                                  DAG.getConstant(CC0, dl, MVT::i8));
13204       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13205                                  DAG.getConstant(CC1, dl, MVT::i8));
13206       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
13207     }
13208     // Handle all other FP comparisons here.
13209     return DAG.getNode(Opc, dl, VT, Op0, Op1,
13210                        DAG.getConstant(SSECC, dl, MVT::i8));
13211   }
13212
13213   // Break 256-bit integer vector compare into smaller ones.
13214   if (VT.is256BitVector() && !Subtarget->hasInt256())
13215     return Lower256IntVSETCC(Op, DAG);
13216
13217   EVT OpVT = Op1.getValueType();
13218   if (OpVT.getVectorElementType() == MVT::i1)
13219     return LowerBoolVSETCC_AVX512(Op, DAG);
13220
13221   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
13222   if (Subtarget->hasAVX512()) {
13223     if (Op1.getValueType().is512BitVector() ||
13224         (Subtarget->hasBWI() && Subtarget->hasVLX()) ||
13225         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
13226       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
13227
13228     // In AVX-512 architecture setcc returns mask with i1 elements,
13229     // But there is no compare instruction for i8 and i16 elements in KNL.
13230     // We are not talking about 512-bit operands in this case, these
13231     // types are illegal.
13232     if (MaskResult &&
13233         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
13234          OpVT.getVectorElementType().getSizeInBits() >= 8))
13235       return DAG.getNode(ISD::TRUNCATE, dl, VT,
13236                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
13237   }
13238
13239   // We are handling one of the integer comparisons here.  Since SSE only has
13240   // GT and EQ comparisons for integer, swapping operands and multiple
13241   // operations may be required for some comparisons.
13242   unsigned Opc;
13243   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
13244   bool Subus = false;
13245
13246   switch (SetCCOpcode) {
13247   default: llvm_unreachable("Unexpected SETCC condition");
13248   case ISD::SETNE:  Invert = true;
13249   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
13250   case ISD::SETLT:  Swap = true;
13251   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
13252   case ISD::SETGE:  Swap = true;
13253   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
13254                     Invert = true; break;
13255   case ISD::SETULT: Swap = true;
13256   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
13257                     FlipSigns = true; break;
13258   case ISD::SETUGE: Swap = true;
13259   case ISD::SETULE: Opc = X86ISD::PCMPGT;
13260                     FlipSigns = true; Invert = true; break;
13261   }
13262
13263   // Special case: Use min/max operations for SETULE/SETUGE
13264   MVT VET = VT.getVectorElementType();
13265   bool hasMinMax =
13266        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
13267     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
13268
13269   if (hasMinMax) {
13270     switch (SetCCOpcode) {
13271     default: break;
13272     case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
13273     case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
13274     }
13275
13276     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
13277   }
13278
13279   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
13280   if (!MinMax && hasSubus) {
13281     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
13282     // Op0 u<= Op1:
13283     //   t = psubus Op0, Op1
13284     //   pcmpeq t, <0..0>
13285     switch (SetCCOpcode) {
13286     default: break;
13287     case ISD::SETULT: {
13288       // If the comparison is against a constant we can turn this into a
13289       // setule.  With psubus, setule does not require a swap.  This is
13290       // beneficial because the constant in the register is no longer
13291       // destructed as the destination so it can be hoisted out of a loop.
13292       // Only do this pre-AVX since vpcmp* is no longer destructive.
13293       if (Subtarget->hasAVX())
13294         break;
13295       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
13296       if (ULEOp1.getNode()) {
13297         Op1 = ULEOp1;
13298         Subus = true; Invert = false; Swap = false;
13299       }
13300       break;
13301     }
13302     // Psubus is better than flip-sign because it requires no inversion.
13303     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
13304     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
13305     }
13306
13307     if (Subus) {
13308       Opc = X86ISD::SUBUS;
13309       FlipSigns = false;
13310     }
13311   }
13312
13313   if (Swap)
13314     std::swap(Op0, Op1);
13315
13316   // Check that the operation in question is available (most are plain SSE2,
13317   // but PCMPGTQ and PCMPEQQ have different requirements).
13318   if (VT == MVT::v2i64) {
13319     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
13320       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
13321
13322       // First cast everything to the right type.
13323       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
13324       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
13325
13326       // Since SSE has no unsigned integer comparisons, we need to flip the sign
13327       // bits of the inputs before performing those operations. The lower
13328       // compare is always unsigned.
13329       SDValue SB;
13330       if (FlipSigns) {
13331         SB = DAG.getConstant(0x80000000U, dl, MVT::v4i32);
13332       } else {
13333         SDValue Sign = DAG.getConstant(0x80000000U, dl, MVT::i32);
13334         SDValue Zero = DAG.getConstant(0x00000000U, dl, MVT::i32);
13335         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
13336                          Sign, Zero, Sign, Zero);
13337       }
13338       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
13339       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
13340
13341       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
13342       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
13343       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
13344
13345       // Create masks for only the low parts/high parts of the 64 bit integers.
13346       static const int MaskHi[] = { 1, 1, 3, 3 };
13347       static const int MaskLo[] = { 0, 0, 2, 2 };
13348       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
13349       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
13350       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
13351
13352       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
13353       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
13354
13355       if (Invert)
13356         Result = DAG.getNOT(dl, Result, MVT::v4i32);
13357
13358       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
13359     }
13360
13361     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
13362       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
13363       // pcmpeqd + pshufd + pand.
13364       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
13365
13366       // First cast everything to the right type.
13367       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
13368       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
13369
13370       // Do the compare.
13371       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
13372
13373       // Make sure the lower and upper halves are both all-ones.
13374       static const int Mask[] = { 1, 0, 3, 2 };
13375       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
13376       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
13377
13378       if (Invert)
13379         Result = DAG.getNOT(dl, Result, MVT::v4i32);
13380
13381       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
13382     }
13383   }
13384
13385   // Since SSE has no unsigned integer comparisons, we need to flip the sign
13386   // bits of the inputs before performing those operations.
13387   if (FlipSigns) {
13388     EVT EltVT = VT.getVectorElementType();
13389     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), dl,
13390                                  VT);
13391     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
13392     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
13393   }
13394
13395   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
13396
13397   // If the logical-not of the result is required, perform that now.
13398   if (Invert)
13399     Result = DAG.getNOT(dl, Result, VT);
13400
13401   if (MinMax)
13402     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
13403
13404   if (Subus)
13405     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
13406                          getZeroVector(VT, Subtarget, DAG, dl));
13407
13408   return Result;
13409 }
13410
13411 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
13412
13413   MVT VT = Op.getSimpleValueType();
13414
13415   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
13416
13417   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
13418          && "SetCC type must be 8-bit or 1-bit integer");
13419   SDValue Op0 = Op.getOperand(0);
13420   SDValue Op1 = Op.getOperand(1);
13421   SDLoc dl(Op);
13422   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
13423
13424   // Optimize to BT if possible.
13425   // Lower (X & (1 << N)) == 0 to BT(X, N).
13426   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
13427   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
13428   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
13429       Op1.getOpcode() == ISD::Constant &&
13430       cast<ConstantSDNode>(Op1)->isNullValue() &&
13431       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13432     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
13433     if (NewSetCC.getNode()) {
13434       if (VT == MVT::i1)
13435         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewSetCC);
13436       return NewSetCC;
13437     }
13438   }
13439
13440   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
13441   // these.
13442   if (Op1.getOpcode() == ISD::Constant &&
13443       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
13444        cast<ConstantSDNode>(Op1)->isNullValue()) &&
13445       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13446
13447     // If the input is a setcc, then reuse the input setcc or use a new one with
13448     // the inverted condition.
13449     if (Op0.getOpcode() == X86ISD::SETCC) {
13450       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
13451       bool Invert = (CC == ISD::SETNE) ^
13452         cast<ConstantSDNode>(Op1)->isNullValue();
13453       if (!Invert)
13454         return Op0;
13455
13456       CCode = X86::GetOppositeBranchCondition(CCode);
13457       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13458                                   DAG.getConstant(CCode, dl, MVT::i8),
13459                                   Op0.getOperand(1));
13460       if (VT == MVT::i1)
13461         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13462       return SetCC;
13463     }
13464   }
13465   if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
13466       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
13467       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13468
13469     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
13470     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, dl, MVT::i1), NewCC);
13471   }
13472
13473   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
13474   unsigned X86CC = TranslateX86CC(CC, dl, isFP, Op0, Op1, DAG);
13475   if (X86CC == X86::COND_INVALID)
13476     return SDValue();
13477
13478   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
13479   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
13480   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13481                               DAG.getConstant(X86CC, dl, MVT::i8), EFLAGS);
13482   if (VT == MVT::i1)
13483     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13484   return SetCC;
13485 }
13486
13487 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
13488 static bool isX86LogicalCmp(SDValue Op) {
13489   unsigned Opc = Op.getNode()->getOpcode();
13490   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
13491       Opc == X86ISD::SAHF)
13492     return true;
13493   if (Op.getResNo() == 1 &&
13494       (Opc == X86ISD::ADD ||
13495        Opc == X86ISD::SUB ||
13496        Opc == X86ISD::ADC ||
13497        Opc == X86ISD::SBB ||
13498        Opc == X86ISD::SMUL ||
13499        Opc == X86ISD::UMUL ||
13500        Opc == X86ISD::INC ||
13501        Opc == X86ISD::DEC ||
13502        Opc == X86ISD::OR ||
13503        Opc == X86ISD::XOR ||
13504        Opc == X86ISD::AND))
13505     return true;
13506
13507   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
13508     return true;
13509
13510   return false;
13511 }
13512
13513 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
13514   if (V.getOpcode() != ISD::TRUNCATE)
13515     return false;
13516
13517   SDValue VOp0 = V.getOperand(0);
13518   unsigned InBits = VOp0.getValueSizeInBits();
13519   unsigned Bits = V.getValueSizeInBits();
13520   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
13521 }
13522
13523 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
13524   bool addTest = true;
13525   SDValue Cond  = Op.getOperand(0);
13526   SDValue Op1 = Op.getOperand(1);
13527   SDValue Op2 = Op.getOperand(2);
13528   SDLoc DL(Op);
13529   EVT VT = Op1.getValueType();
13530   SDValue CC;
13531
13532   // Lower FP selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
13533   // are available or VBLENDV if AVX is available.
13534   // Otherwise FP cmovs get lowered into a less efficient branch sequence later.
13535   if (Cond.getOpcode() == ISD::SETCC &&
13536       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
13537        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
13538       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
13539     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
13540     int SSECC = translateX86FSETCC(
13541         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
13542
13543     if (SSECC != 8) {
13544       if (Subtarget->hasAVX512()) {
13545         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
13546                                   DAG.getConstant(SSECC, DL, MVT::i8));
13547         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
13548       }
13549
13550       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
13551                                 DAG.getConstant(SSECC, DL, MVT::i8));
13552
13553       // If we have AVX, we can use a variable vector select (VBLENDV) instead
13554       // of 3 logic instructions for size savings and potentially speed.
13555       // Unfortunately, there is no scalar form of VBLENDV.
13556
13557       // If either operand is a constant, don't try this. We can expect to
13558       // optimize away at least one of the logic instructions later in that
13559       // case, so that sequence would be faster than a variable blend.
13560
13561       // BLENDV was introduced with SSE 4.1, but the 2 register form implicitly
13562       // uses XMM0 as the selection register. That may need just as many
13563       // instructions as the AND/ANDN/OR sequence due to register moves, so
13564       // don't bother.
13565
13566       if (Subtarget->hasAVX() &&
13567           !isa<ConstantFPSDNode>(Op1) && !isa<ConstantFPSDNode>(Op2)) {
13568
13569         // Convert to vectors, do a VSELECT, and convert back to scalar.
13570         // All of the conversions should be optimized away.
13571
13572         EVT VecVT = VT == MVT::f32 ? MVT::v4f32 : MVT::v2f64;
13573         SDValue VOp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op1);
13574         SDValue VOp2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op2);
13575         SDValue VCmp = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Cmp);
13576
13577         EVT VCmpVT = VT == MVT::f32 ? MVT::v4i32 : MVT::v2i64;
13578         VCmp = DAG.getNode(ISD::BITCAST, DL, VCmpVT, VCmp);
13579
13580         SDValue VSel = DAG.getNode(ISD::VSELECT, DL, VecVT, VCmp, VOp1, VOp2);
13581
13582         return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
13583                            VSel, DAG.getIntPtrConstant(0, DL));
13584       }
13585       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
13586       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
13587       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
13588     }
13589   }
13590
13591   if (Cond.getOpcode() == ISD::SETCC) {
13592     SDValue NewCond = LowerSETCC(Cond, DAG);
13593     if (NewCond.getNode())
13594       Cond = NewCond;
13595   }
13596
13597   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
13598   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
13599   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
13600   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
13601   if (Cond.getOpcode() == X86ISD::SETCC &&
13602       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
13603       isZero(Cond.getOperand(1).getOperand(1))) {
13604     SDValue Cmp = Cond.getOperand(1);
13605
13606     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
13607
13608     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
13609         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
13610       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
13611
13612       SDValue CmpOp0 = Cmp.getOperand(0);
13613       // Apply further optimizations for special cases
13614       // (select (x != 0), -1, 0) -> neg & sbb
13615       // (select (x == 0), 0, -1) -> neg & sbb
13616       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
13617         if (YC->isNullValue() &&
13618             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
13619           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
13620           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
13621                                     DAG.getConstant(0, DL,
13622                                                     CmpOp0.getValueType()),
13623                                     CmpOp0);
13624           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13625                                     DAG.getConstant(X86::COND_B, DL, MVT::i8),
13626                                     SDValue(Neg.getNode(), 1));
13627           return Res;
13628         }
13629
13630       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
13631                         CmpOp0, DAG.getConstant(1, DL, CmpOp0.getValueType()));
13632       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
13633
13634       SDValue Res =   // Res = 0 or -1.
13635         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13636                     DAG.getConstant(X86::COND_B, DL, MVT::i8), Cmp);
13637
13638       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
13639         Res = DAG.getNOT(DL, Res, Res.getValueType());
13640
13641       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
13642       if (!N2C || !N2C->isNullValue())
13643         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
13644       return Res;
13645     }
13646   }
13647
13648   // Look past (and (setcc_carry (cmp ...)), 1).
13649   if (Cond.getOpcode() == ISD::AND &&
13650       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
13651     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
13652     if (C && C->getAPIntValue() == 1)
13653       Cond = Cond.getOperand(0);
13654   }
13655
13656   // If condition flag is set by a X86ISD::CMP, then use it as the condition
13657   // setting operand in place of the X86ISD::SETCC.
13658   unsigned CondOpcode = Cond.getOpcode();
13659   if (CondOpcode == X86ISD::SETCC ||
13660       CondOpcode == X86ISD::SETCC_CARRY) {
13661     CC = Cond.getOperand(0);
13662
13663     SDValue Cmp = Cond.getOperand(1);
13664     unsigned Opc = Cmp.getOpcode();
13665     MVT VT = Op.getSimpleValueType();
13666
13667     bool IllegalFPCMov = false;
13668     if (VT.isFloatingPoint() && !VT.isVector() &&
13669         !isScalarFPTypeInSSEReg(VT))  // FPStack?
13670       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
13671
13672     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
13673         Opc == X86ISD::BT) { // FIXME
13674       Cond = Cmp;
13675       addTest = false;
13676     }
13677   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
13678              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
13679              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
13680               Cond.getOperand(0).getValueType() != MVT::i8)) {
13681     SDValue LHS = Cond.getOperand(0);
13682     SDValue RHS = Cond.getOperand(1);
13683     unsigned X86Opcode;
13684     unsigned X86Cond;
13685     SDVTList VTs;
13686     switch (CondOpcode) {
13687     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
13688     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
13689     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
13690     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
13691     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
13692     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
13693     default: llvm_unreachable("unexpected overflowing operator");
13694     }
13695     if (CondOpcode == ISD::UMULO)
13696       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
13697                           MVT::i32);
13698     else
13699       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
13700
13701     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
13702
13703     if (CondOpcode == ISD::UMULO)
13704       Cond = X86Op.getValue(2);
13705     else
13706       Cond = X86Op.getValue(1);
13707
13708     CC = DAG.getConstant(X86Cond, DL, MVT::i8);
13709     addTest = false;
13710   }
13711
13712   if (addTest) {
13713     // Look pass the truncate if the high bits are known zero.
13714     if (isTruncWithZeroHighBitsInput(Cond, DAG))
13715         Cond = Cond.getOperand(0);
13716
13717     // We know the result of AND is compared against zero. Try to match
13718     // it to BT.
13719     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
13720       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
13721       if (NewSetCC.getNode()) {
13722         CC = NewSetCC.getOperand(0);
13723         Cond = NewSetCC.getOperand(1);
13724         addTest = false;
13725       }
13726     }
13727   }
13728
13729   if (addTest) {
13730     CC = DAG.getConstant(X86::COND_NE, DL, MVT::i8);
13731     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
13732   }
13733
13734   // a <  b ? -1 :  0 -> RES = ~setcc_carry
13735   // a <  b ?  0 : -1 -> RES = setcc_carry
13736   // a >= b ? -1 :  0 -> RES = setcc_carry
13737   // a >= b ?  0 : -1 -> RES = ~setcc_carry
13738   if (Cond.getOpcode() == X86ISD::SUB) {
13739     Cond = ConvertCmpIfNecessary(Cond, DAG);
13740     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
13741
13742     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
13743         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
13744       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13745                                 DAG.getConstant(X86::COND_B, DL, MVT::i8),
13746                                 Cond);
13747       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
13748         return DAG.getNOT(DL, Res, Res.getValueType());
13749       return Res;
13750     }
13751   }
13752
13753   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
13754   // widen the cmov and push the truncate through. This avoids introducing a new
13755   // branch during isel and doesn't add any extensions.
13756   if (Op.getValueType() == MVT::i8 &&
13757       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
13758     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
13759     if (T1.getValueType() == T2.getValueType() &&
13760         // Blacklist CopyFromReg to avoid partial register stalls.
13761         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
13762       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
13763       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
13764       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
13765     }
13766   }
13767
13768   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
13769   // condition is true.
13770   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
13771   SDValue Ops[] = { Op2, Op1, CC, Cond };
13772   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
13773 }
13774
13775 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, const X86Subtarget *Subtarget,
13776                                        SelectionDAG &DAG) {
13777   MVT VT = Op->getSimpleValueType(0);
13778   SDValue In = Op->getOperand(0);
13779   MVT InVT = In.getSimpleValueType();
13780   MVT VTElt = VT.getVectorElementType();
13781   MVT InVTElt = InVT.getVectorElementType();
13782   SDLoc dl(Op);
13783
13784   // SKX processor
13785   if ((InVTElt == MVT::i1) &&
13786       (((Subtarget->hasBWI() && Subtarget->hasVLX() &&
13787         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() <= 16)) ||
13788
13789        ((Subtarget->hasBWI() && VT.is512BitVector() &&
13790         VTElt.getSizeInBits() <= 16)) ||
13791
13792        ((Subtarget->hasDQI() && Subtarget->hasVLX() &&
13793         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() >= 32)) ||
13794
13795        ((Subtarget->hasDQI() && VT.is512BitVector() &&
13796         VTElt.getSizeInBits() >= 32))))
13797     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13798
13799   unsigned int NumElts = VT.getVectorNumElements();
13800
13801   if (NumElts != 8 && NumElts != 16)
13802     return SDValue();
13803
13804   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1) {
13805     if (In.getOpcode() == X86ISD::VSEXT || In.getOpcode() == X86ISD::VZEXT)
13806       return DAG.getNode(In.getOpcode(), dl, VT, In.getOperand(0));
13807     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13808   }
13809
13810   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
13811   MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
13812   SDValue NegOne =
13813    DAG.getConstant(APInt::getAllOnesValue(ExtVT.getScalarSizeInBits()), dl,
13814                    ExtVT);
13815   SDValue Zero =
13816    DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), dl, ExtVT);
13817
13818   SDValue V = DAG.getNode(ISD::VSELECT, dl, ExtVT, In, NegOne, Zero);
13819   if (VT.is512BitVector())
13820     return V;
13821   return DAG.getNode(X86ISD::VTRUNC, dl, VT, V);
13822 }
13823
13824 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
13825                                 SelectionDAG &DAG) {
13826   MVT VT = Op->getSimpleValueType(0);
13827   SDValue In = Op->getOperand(0);
13828   MVT InVT = In.getSimpleValueType();
13829   SDLoc dl(Op);
13830
13831   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
13832     return LowerSIGN_EXTEND_AVX512(Op, Subtarget, DAG);
13833
13834   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
13835       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
13836       (VT != MVT::v16i16 || InVT != MVT::v16i8))
13837     return SDValue();
13838
13839   if (Subtarget->hasInt256())
13840     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13841
13842   // Optimize vectors in AVX mode
13843   // Sign extend  v8i16 to v8i32 and
13844   //              v4i32 to v4i64
13845   //
13846   // Divide input vector into two parts
13847   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
13848   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
13849   // concat the vectors to original VT
13850
13851   unsigned NumElems = InVT.getVectorNumElements();
13852   SDValue Undef = DAG.getUNDEF(InVT);
13853
13854   SmallVector<int,8> ShufMask1(NumElems, -1);
13855   for (unsigned i = 0; i != NumElems/2; ++i)
13856     ShufMask1[i] = i;
13857
13858   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
13859
13860   SmallVector<int,8> ShufMask2(NumElems, -1);
13861   for (unsigned i = 0; i != NumElems/2; ++i)
13862     ShufMask2[i] = i + NumElems/2;
13863
13864   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
13865
13866   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
13867                                 VT.getVectorNumElements()/2);
13868
13869   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
13870   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
13871
13872   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
13873 }
13874
13875 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
13876 // may emit an illegal shuffle but the expansion is still better than scalar
13877 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
13878 // we'll emit a shuffle and a arithmetic shift.
13879 // FIXME: Is the expansion actually better than scalar code? It doesn't seem so.
13880 // TODO: It is possible to support ZExt by zeroing the undef values during
13881 // the shuffle phase or after the shuffle.
13882 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
13883                                  SelectionDAG &DAG) {
13884   MVT RegVT = Op.getSimpleValueType();
13885   assert(RegVT.isVector() && "We only custom lower vector sext loads.");
13886   assert(RegVT.isInteger() &&
13887          "We only custom lower integer vector sext loads.");
13888
13889   // Nothing useful we can do without SSE2 shuffles.
13890   assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
13891
13892   LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
13893   SDLoc dl(Ld);
13894   EVT MemVT = Ld->getMemoryVT();
13895   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13896   unsigned RegSz = RegVT.getSizeInBits();
13897
13898   ISD::LoadExtType Ext = Ld->getExtensionType();
13899
13900   assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
13901          && "Only anyext and sext are currently implemented.");
13902   assert(MemVT != RegVT && "Cannot extend to the same type");
13903   assert(MemVT.isVector() && "Must load a vector from memory");
13904
13905   unsigned NumElems = RegVT.getVectorNumElements();
13906   unsigned MemSz = MemVT.getSizeInBits();
13907   assert(RegSz > MemSz && "Register size must be greater than the mem size");
13908
13909   if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
13910     // The only way in which we have a legal 256-bit vector result but not the
13911     // integer 256-bit operations needed to directly lower a sextload is if we
13912     // have AVX1 but not AVX2. In that case, we can always emit a sextload to
13913     // a 128-bit vector and a normal sign_extend to 256-bits that should get
13914     // correctly legalized. We do this late to allow the canonical form of
13915     // sextload to persist throughout the rest of the DAG combiner -- it wants
13916     // to fold together any extensions it can, and so will fuse a sign_extend
13917     // of an sextload into a sextload targeting a wider value.
13918     SDValue Load;
13919     if (MemSz == 128) {
13920       // Just switch this to a normal load.
13921       assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
13922                                        "it must be a legal 128-bit vector "
13923                                        "type!");
13924       Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
13925                   Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
13926                   Ld->isInvariant(), Ld->getAlignment());
13927     } else {
13928       assert(MemSz < 128 &&
13929              "Can't extend a type wider than 128 bits to a 256 bit vector!");
13930       // Do an sext load to a 128-bit vector type. We want to use the same
13931       // number of elements, but elements half as wide. This will end up being
13932       // recursively lowered by this routine, but will succeed as we definitely
13933       // have all the necessary features if we're using AVX1.
13934       EVT HalfEltVT =
13935           EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
13936       EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
13937       Load =
13938           DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
13939                          Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
13940                          Ld->isNonTemporal(), Ld->isInvariant(),
13941                          Ld->getAlignment());
13942     }
13943
13944     // Replace chain users with the new chain.
13945     assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
13946     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
13947
13948     // Finally, do a normal sign-extend to the desired register.
13949     return DAG.getSExtOrTrunc(Load, dl, RegVT);
13950   }
13951
13952   // All sizes must be a power of two.
13953   assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
13954          "Non-power-of-two elements are not custom lowered!");
13955
13956   // Attempt to load the original value using scalar loads.
13957   // Find the largest scalar type that divides the total loaded size.
13958   MVT SclrLoadTy = MVT::i8;
13959   for (MVT Tp : MVT::integer_valuetypes()) {
13960     if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
13961       SclrLoadTy = Tp;
13962     }
13963   }
13964
13965   // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
13966   if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
13967       (64 <= MemSz))
13968     SclrLoadTy = MVT::f64;
13969
13970   // Calculate the number of scalar loads that we need to perform
13971   // in order to load our vector from memory.
13972   unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
13973
13974   assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
13975          "Can only lower sext loads with a single scalar load!");
13976
13977   unsigned loadRegZize = RegSz;
13978   if (Ext == ISD::SEXTLOAD && RegSz == 256)
13979     loadRegZize /= 2;
13980
13981   // Represent our vector as a sequence of elements which are the
13982   // largest scalar that we can load.
13983   EVT LoadUnitVecVT = EVT::getVectorVT(
13984       *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
13985
13986   // Represent the data using the same element type that is stored in
13987   // memory. In practice, we ''widen'' MemVT.
13988   EVT WideVecVT =
13989       EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
13990                        loadRegZize / MemVT.getScalarType().getSizeInBits());
13991
13992   assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
13993          "Invalid vector type");
13994
13995   // We can't shuffle using an illegal type.
13996   assert(TLI.isTypeLegal(WideVecVT) &&
13997          "We only lower types that form legal widened vector types");
13998
13999   SmallVector<SDValue, 8> Chains;
14000   SDValue Ptr = Ld->getBasePtr();
14001   SDValue Increment =
14002       DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, dl, TLI.getPointerTy());
14003   SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
14004
14005   for (unsigned i = 0; i < NumLoads; ++i) {
14006     // Perform a single load.
14007     SDValue ScalarLoad =
14008         DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
14009                     Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
14010                     Ld->getAlignment());
14011     Chains.push_back(ScalarLoad.getValue(1));
14012     // Create the first element type using SCALAR_TO_VECTOR in order to avoid
14013     // another round of DAGCombining.
14014     if (i == 0)
14015       Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
14016     else
14017       Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
14018                         ScalarLoad, DAG.getIntPtrConstant(i, dl));
14019
14020     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
14021   }
14022
14023   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
14024
14025   // Bitcast the loaded value to a vector of the original element type, in
14026   // the size of the target vector type.
14027   SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
14028   unsigned SizeRatio = RegSz / MemSz;
14029
14030   if (Ext == ISD::SEXTLOAD) {
14031     // If we have SSE4.1, we can directly emit a VSEXT node.
14032     if (Subtarget->hasSSE41()) {
14033       SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
14034       DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14035       return Sext;
14036     }
14037
14038     // Otherwise we'll shuffle the small elements in the high bits of the
14039     // larger type and perform an arithmetic shift. If the shift is not legal
14040     // it's better to scalarize.
14041     assert(TLI.isOperationLegalOrCustom(ISD::SRA, RegVT) &&
14042            "We can't implement a sext load without an arithmetic right shift!");
14043
14044     // Redistribute the loaded elements into the different locations.
14045     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
14046     for (unsigned i = 0; i != NumElems; ++i)
14047       ShuffleVec[i * SizeRatio + SizeRatio - 1] = i;
14048
14049     SDValue Shuff = DAG.getVectorShuffle(
14050         WideVecVT, dl, SlicedVec, DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
14051
14052     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
14053
14054     // Build the arithmetic shift.
14055     unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
14056                    MemVT.getVectorElementType().getSizeInBits();
14057     Shuff =
14058         DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
14059                     DAG.getConstant(Amt, dl, RegVT));
14060
14061     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14062     return Shuff;
14063   }
14064
14065   // Redistribute the loaded elements into the different locations.
14066   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
14067   for (unsigned i = 0; i != NumElems; ++i)
14068     ShuffleVec[i * SizeRatio] = i;
14069
14070   SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
14071                                        DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
14072
14073   // Bitcast to the requested type.
14074   Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
14075   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14076   return Shuff;
14077 }
14078
14079 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
14080 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
14081 // from the AND / OR.
14082 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
14083   Opc = Op.getOpcode();
14084   if (Opc != ISD::OR && Opc != ISD::AND)
14085     return false;
14086   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
14087           Op.getOperand(0).hasOneUse() &&
14088           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
14089           Op.getOperand(1).hasOneUse());
14090 }
14091
14092 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
14093 // 1 and that the SETCC node has a single use.
14094 static bool isXor1OfSetCC(SDValue Op) {
14095   if (Op.getOpcode() != ISD::XOR)
14096     return false;
14097   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
14098   if (N1C && N1C->getAPIntValue() == 1) {
14099     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
14100       Op.getOperand(0).hasOneUse();
14101   }
14102   return false;
14103 }
14104
14105 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
14106   bool addTest = true;
14107   SDValue Chain = Op.getOperand(0);
14108   SDValue Cond  = Op.getOperand(1);
14109   SDValue Dest  = Op.getOperand(2);
14110   SDLoc dl(Op);
14111   SDValue CC;
14112   bool Inverted = false;
14113
14114   if (Cond.getOpcode() == ISD::SETCC) {
14115     // Check for setcc([su]{add,sub,mul}o == 0).
14116     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
14117         isa<ConstantSDNode>(Cond.getOperand(1)) &&
14118         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
14119         Cond.getOperand(0).getResNo() == 1 &&
14120         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
14121          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
14122          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
14123          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
14124          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
14125          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
14126       Inverted = true;
14127       Cond = Cond.getOperand(0);
14128     } else {
14129       SDValue NewCond = LowerSETCC(Cond, DAG);
14130       if (NewCond.getNode())
14131         Cond = NewCond;
14132     }
14133   }
14134 #if 0
14135   // FIXME: LowerXALUO doesn't handle these!!
14136   else if (Cond.getOpcode() == X86ISD::ADD  ||
14137            Cond.getOpcode() == X86ISD::SUB  ||
14138            Cond.getOpcode() == X86ISD::SMUL ||
14139            Cond.getOpcode() == X86ISD::UMUL)
14140     Cond = LowerXALUO(Cond, DAG);
14141 #endif
14142
14143   // Look pass (and (setcc_carry (cmp ...)), 1).
14144   if (Cond.getOpcode() == ISD::AND &&
14145       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
14146     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
14147     if (C && C->getAPIntValue() == 1)
14148       Cond = Cond.getOperand(0);
14149   }
14150
14151   // If condition flag is set by a X86ISD::CMP, then use it as the condition
14152   // setting operand in place of the X86ISD::SETCC.
14153   unsigned CondOpcode = Cond.getOpcode();
14154   if (CondOpcode == X86ISD::SETCC ||
14155       CondOpcode == X86ISD::SETCC_CARRY) {
14156     CC = Cond.getOperand(0);
14157
14158     SDValue Cmp = Cond.getOperand(1);
14159     unsigned Opc = Cmp.getOpcode();
14160     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
14161     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
14162       Cond = Cmp;
14163       addTest = false;
14164     } else {
14165       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
14166       default: break;
14167       case X86::COND_O:
14168       case X86::COND_B:
14169         // These can only come from an arithmetic instruction with overflow,
14170         // e.g. SADDO, UADDO.
14171         Cond = Cond.getNode()->getOperand(1);
14172         addTest = false;
14173         break;
14174       }
14175     }
14176   }
14177   CondOpcode = Cond.getOpcode();
14178   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
14179       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
14180       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
14181        Cond.getOperand(0).getValueType() != MVT::i8)) {
14182     SDValue LHS = Cond.getOperand(0);
14183     SDValue RHS = Cond.getOperand(1);
14184     unsigned X86Opcode;
14185     unsigned X86Cond;
14186     SDVTList VTs;
14187     // Keep this in sync with LowerXALUO, otherwise we might create redundant
14188     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
14189     // X86ISD::INC).
14190     switch (CondOpcode) {
14191     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
14192     case ISD::SADDO:
14193       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14194         if (C->isOne()) {
14195           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
14196           break;
14197         }
14198       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
14199     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
14200     case ISD::SSUBO:
14201       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14202         if (C->isOne()) {
14203           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
14204           break;
14205         }
14206       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
14207     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
14208     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
14209     default: llvm_unreachable("unexpected overflowing operator");
14210     }
14211     if (Inverted)
14212       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
14213     if (CondOpcode == ISD::UMULO)
14214       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
14215                           MVT::i32);
14216     else
14217       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14218
14219     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
14220
14221     if (CondOpcode == ISD::UMULO)
14222       Cond = X86Op.getValue(2);
14223     else
14224       Cond = X86Op.getValue(1);
14225
14226     CC = DAG.getConstant(X86Cond, dl, MVT::i8);
14227     addTest = false;
14228   } else {
14229     unsigned CondOpc;
14230     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
14231       SDValue Cmp = Cond.getOperand(0).getOperand(1);
14232       if (CondOpc == ISD::OR) {
14233         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
14234         // two branches instead of an explicit OR instruction with a
14235         // separate test.
14236         if (Cmp == Cond.getOperand(1).getOperand(1) &&
14237             isX86LogicalCmp(Cmp)) {
14238           CC = Cond.getOperand(0).getOperand(0);
14239           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14240                               Chain, Dest, CC, Cmp);
14241           CC = Cond.getOperand(1).getOperand(0);
14242           Cond = Cmp;
14243           addTest = false;
14244         }
14245       } else { // ISD::AND
14246         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
14247         // two branches instead of an explicit AND instruction with a
14248         // separate test. However, we only do this if this block doesn't
14249         // have a fall-through edge, because this requires an explicit
14250         // jmp when the condition is false.
14251         if (Cmp == Cond.getOperand(1).getOperand(1) &&
14252             isX86LogicalCmp(Cmp) &&
14253             Op.getNode()->hasOneUse()) {
14254           X86::CondCode CCode =
14255             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
14256           CCode = X86::GetOppositeBranchCondition(CCode);
14257           CC = DAG.getConstant(CCode, dl, MVT::i8);
14258           SDNode *User = *Op.getNode()->use_begin();
14259           // Look for an unconditional branch following this conditional branch.
14260           // We need this because we need to reverse the successors in order
14261           // to implement FCMP_OEQ.
14262           if (User->getOpcode() == ISD::BR) {
14263             SDValue FalseBB = User->getOperand(1);
14264             SDNode *NewBR =
14265               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14266             assert(NewBR == User);
14267             (void)NewBR;
14268             Dest = FalseBB;
14269
14270             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14271                                 Chain, Dest, CC, Cmp);
14272             X86::CondCode CCode =
14273               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
14274             CCode = X86::GetOppositeBranchCondition(CCode);
14275             CC = DAG.getConstant(CCode, dl, MVT::i8);
14276             Cond = Cmp;
14277             addTest = false;
14278           }
14279         }
14280       }
14281     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
14282       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
14283       // It should be transformed during dag combiner except when the condition
14284       // is set by a arithmetics with overflow node.
14285       X86::CondCode CCode =
14286         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
14287       CCode = X86::GetOppositeBranchCondition(CCode);
14288       CC = DAG.getConstant(CCode, dl, MVT::i8);
14289       Cond = Cond.getOperand(0).getOperand(1);
14290       addTest = false;
14291     } else if (Cond.getOpcode() == ISD::SETCC &&
14292                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
14293       // For FCMP_OEQ, we can emit
14294       // two branches instead of an explicit AND instruction with a
14295       // separate test. However, we only do this if this block doesn't
14296       // have a fall-through edge, because this requires an explicit
14297       // jmp when the condition is false.
14298       if (Op.getNode()->hasOneUse()) {
14299         SDNode *User = *Op.getNode()->use_begin();
14300         // Look for an unconditional branch following this conditional branch.
14301         // We need this because we need to reverse the successors in order
14302         // to implement FCMP_OEQ.
14303         if (User->getOpcode() == ISD::BR) {
14304           SDValue FalseBB = User->getOperand(1);
14305           SDNode *NewBR =
14306             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14307           assert(NewBR == User);
14308           (void)NewBR;
14309           Dest = FalseBB;
14310
14311           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14312                                     Cond.getOperand(0), Cond.getOperand(1));
14313           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14314           CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
14315           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14316                               Chain, Dest, CC, Cmp);
14317           CC = DAG.getConstant(X86::COND_P, dl, MVT::i8);
14318           Cond = Cmp;
14319           addTest = false;
14320         }
14321       }
14322     } else if (Cond.getOpcode() == ISD::SETCC &&
14323                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
14324       // For FCMP_UNE, we can emit
14325       // two branches instead of an explicit AND instruction with a
14326       // separate test. However, we only do this if this block doesn't
14327       // have a fall-through edge, because this requires an explicit
14328       // jmp when the condition is false.
14329       if (Op.getNode()->hasOneUse()) {
14330         SDNode *User = *Op.getNode()->use_begin();
14331         // Look for an unconditional branch following this conditional branch.
14332         // We need this because we need to reverse the successors in order
14333         // to implement FCMP_UNE.
14334         if (User->getOpcode() == ISD::BR) {
14335           SDValue FalseBB = User->getOperand(1);
14336           SDNode *NewBR =
14337             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14338           assert(NewBR == User);
14339           (void)NewBR;
14340
14341           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14342                                     Cond.getOperand(0), Cond.getOperand(1));
14343           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14344           CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
14345           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14346                               Chain, Dest, CC, Cmp);
14347           CC = DAG.getConstant(X86::COND_NP, dl, MVT::i8);
14348           Cond = Cmp;
14349           addTest = false;
14350           Dest = FalseBB;
14351         }
14352       }
14353     }
14354   }
14355
14356   if (addTest) {
14357     // Look pass the truncate if the high bits are known zero.
14358     if (isTruncWithZeroHighBitsInput(Cond, DAG))
14359         Cond = Cond.getOperand(0);
14360
14361     // We know the result of AND is compared against zero. Try to match
14362     // it to BT.
14363     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
14364       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
14365       if (NewSetCC.getNode()) {
14366         CC = NewSetCC.getOperand(0);
14367         Cond = NewSetCC.getOperand(1);
14368         addTest = false;
14369       }
14370     }
14371   }
14372
14373   if (addTest) {
14374     X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
14375     CC = DAG.getConstant(X86Cond, dl, MVT::i8);
14376     Cond = EmitTest(Cond, X86Cond, dl, DAG);
14377   }
14378   Cond = ConvertCmpIfNecessary(Cond, DAG);
14379   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14380                      Chain, Dest, CC, Cond);
14381 }
14382
14383 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
14384 // Calls to _alloca are needed to probe the stack when allocating more than 4k
14385 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
14386 // that the guard pages used by the OS virtual memory manager are allocated in
14387 // correct sequence.
14388 SDValue
14389 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
14390                                            SelectionDAG &DAG) const {
14391   MachineFunction &MF = DAG.getMachineFunction();
14392   bool SplitStack = MF.shouldSplitStack();
14393   bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMachO()) ||
14394                SplitStack;
14395   SDLoc dl(Op);
14396
14397   if (!Lower) {
14398     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14399     SDNode* Node = Op.getNode();
14400
14401     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
14402     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
14403         " not tell us which reg is the stack pointer!");
14404     EVT VT = Node->getValueType(0);
14405     SDValue Tmp1 = SDValue(Node, 0);
14406     SDValue Tmp2 = SDValue(Node, 1);
14407     SDValue Tmp3 = Node->getOperand(2);
14408     SDValue Chain = Tmp1.getOperand(0);
14409
14410     // Chain the dynamic stack allocation so that it doesn't modify the stack
14411     // pointer when other instructions are using the stack.
14412     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, dl, true),
14413         SDLoc(Node));
14414
14415     SDValue Size = Tmp2.getOperand(1);
14416     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
14417     Chain = SP.getValue(1);
14418     unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
14419     const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
14420     unsigned StackAlign = TFI.getStackAlignment();
14421     Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
14422     if (Align > StackAlign)
14423       Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
14424           DAG.getConstant(-(uint64_t)Align, dl, VT));
14425     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
14426
14427     Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
14428         DAG.getIntPtrConstant(0, dl, true), SDValue(),
14429         SDLoc(Node));
14430
14431     SDValue Ops[2] = { Tmp1, Tmp2 };
14432     return DAG.getMergeValues(Ops, dl);
14433   }
14434
14435   // Get the inputs.
14436   SDValue Chain = Op.getOperand(0);
14437   SDValue Size  = Op.getOperand(1);
14438   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
14439   EVT VT = Op.getNode()->getValueType(0);
14440
14441   bool Is64Bit = Subtarget->is64Bit();
14442   EVT SPTy = getPointerTy();
14443
14444   if (SplitStack) {
14445     MachineRegisterInfo &MRI = MF.getRegInfo();
14446
14447     if (Is64Bit) {
14448       // The 64 bit implementation of segmented stacks needs to clobber both r10
14449       // r11. This makes it impossible to use it along with nested parameters.
14450       const Function *F = MF.getFunction();
14451
14452       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
14453            I != E; ++I)
14454         if (I->hasNestAttr())
14455           report_fatal_error("Cannot use segmented stacks with functions that "
14456                              "have nested arguments.");
14457     }
14458
14459     const TargetRegisterClass *AddrRegClass =
14460       getRegClassFor(getPointerTy());
14461     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
14462     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
14463     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
14464                                 DAG.getRegister(Vreg, SPTy));
14465     SDValue Ops1[2] = { Value, Chain };
14466     return DAG.getMergeValues(Ops1, dl);
14467   } else {
14468     SDValue Flag;
14469     const unsigned Reg = (Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX);
14470
14471     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
14472     Flag = Chain.getValue(1);
14473     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
14474
14475     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
14476
14477     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
14478     unsigned SPReg = RegInfo->getStackRegister();
14479     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
14480     Chain = SP.getValue(1);
14481
14482     if (Align) {
14483       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
14484                        DAG.getConstant(-(uint64_t)Align, dl, VT));
14485       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
14486     }
14487
14488     SDValue Ops1[2] = { SP, Chain };
14489     return DAG.getMergeValues(Ops1, dl);
14490   }
14491 }
14492
14493 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
14494   MachineFunction &MF = DAG.getMachineFunction();
14495   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
14496
14497   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
14498   SDLoc DL(Op);
14499
14500   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
14501     // vastart just stores the address of the VarArgsFrameIndex slot into the
14502     // memory location argument.
14503     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
14504                                    getPointerTy());
14505     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
14506                         MachinePointerInfo(SV), false, false, 0);
14507   }
14508
14509   // __va_list_tag:
14510   //   gp_offset         (0 - 6 * 8)
14511   //   fp_offset         (48 - 48 + 8 * 16)
14512   //   overflow_arg_area (point to parameters coming in memory).
14513   //   reg_save_area
14514   SmallVector<SDValue, 8> MemOps;
14515   SDValue FIN = Op.getOperand(1);
14516   // Store gp_offset
14517   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
14518                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
14519                                                DL, MVT::i32),
14520                                FIN, MachinePointerInfo(SV), false, false, 0);
14521   MemOps.push_back(Store);
14522
14523   // Store fp_offset
14524   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14525                     FIN, DAG.getIntPtrConstant(4, DL));
14526   Store = DAG.getStore(Op.getOperand(0), DL,
14527                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(), DL,
14528                                        MVT::i32),
14529                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
14530   MemOps.push_back(Store);
14531
14532   // Store ptr to overflow_arg_area
14533   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14534                     FIN, DAG.getIntPtrConstant(4, DL));
14535   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
14536                                     getPointerTy());
14537   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
14538                        MachinePointerInfo(SV, 8),
14539                        false, false, 0);
14540   MemOps.push_back(Store);
14541
14542   // Store ptr to reg_save_area.
14543   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14544                     FIN, DAG.getIntPtrConstant(8, DL));
14545   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
14546                                     getPointerTy());
14547   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
14548                        MachinePointerInfo(SV, 16), false, false, 0);
14549   MemOps.push_back(Store);
14550   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
14551 }
14552
14553 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
14554   assert(Subtarget->is64Bit() &&
14555          "LowerVAARG only handles 64-bit va_arg!");
14556   assert((Subtarget->isTargetLinux() ||
14557           Subtarget->isTargetDarwin()) &&
14558           "Unhandled target in LowerVAARG");
14559   assert(Op.getNode()->getNumOperands() == 4);
14560   SDValue Chain = Op.getOperand(0);
14561   SDValue SrcPtr = Op.getOperand(1);
14562   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
14563   unsigned Align = Op.getConstantOperandVal(3);
14564   SDLoc dl(Op);
14565
14566   EVT ArgVT = Op.getNode()->getValueType(0);
14567   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
14568   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
14569   uint8_t ArgMode;
14570
14571   // Decide which area this value should be read from.
14572   // TODO: Implement the AMD64 ABI in its entirety. This simple
14573   // selection mechanism works only for the basic types.
14574   if (ArgVT == MVT::f80) {
14575     llvm_unreachable("va_arg for f80 not yet implemented");
14576   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
14577     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
14578   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
14579     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
14580   } else {
14581     llvm_unreachable("Unhandled argument type in LowerVAARG");
14582   }
14583
14584   if (ArgMode == 2) {
14585     // Sanity Check: Make sure using fp_offset makes sense.
14586     assert(!DAG.getTarget().Options.UseSoftFloat &&
14587            !(DAG.getMachineFunction().getFunction()->hasFnAttribute(
14588                Attribute::NoImplicitFloat)) &&
14589            Subtarget->hasSSE1());
14590   }
14591
14592   // Insert VAARG_64 node into the DAG
14593   // VAARG_64 returns two values: Variable Argument Address, Chain
14594   SDValue InstOps[] = {Chain, SrcPtr, DAG.getConstant(ArgSize, dl, MVT::i32),
14595                        DAG.getConstant(ArgMode, dl, MVT::i8),
14596                        DAG.getConstant(Align, dl, MVT::i32)};
14597   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
14598   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
14599                                           VTs, InstOps, MVT::i64,
14600                                           MachinePointerInfo(SV),
14601                                           /*Align=*/0,
14602                                           /*Volatile=*/false,
14603                                           /*ReadMem=*/true,
14604                                           /*WriteMem=*/true);
14605   Chain = VAARG.getValue(1);
14606
14607   // Load the next argument and return it
14608   return DAG.getLoad(ArgVT, dl,
14609                      Chain,
14610                      VAARG,
14611                      MachinePointerInfo(),
14612                      false, false, false, 0);
14613 }
14614
14615 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
14616                            SelectionDAG &DAG) {
14617   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
14618   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
14619   SDValue Chain = Op.getOperand(0);
14620   SDValue DstPtr = Op.getOperand(1);
14621   SDValue SrcPtr = Op.getOperand(2);
14622   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
14623   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
14624   SDLoc DL(Op);
14625
14626   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
14627                        DAG.getIntPtrConstant(24, DL), 8, /*isVolatile*/false,
14628                        false, false,
14629                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
14630 }
14631
14632 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
14633 // amount is a constant. Takes immediate version of shift as input.
14634 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
14635                                           SDValue SrcOp, uint64_t ShiftAmt,
14636                                           SelectionDAG &DAG) {
14637   MVT ElementType = VT.getVectorElementType();
14638
14639   // Fold this packed shift into its first operand if ShiftAmt is 0.
14640   if (ShiftAmt == 0)
14641     return SrcOp;
14642
14643   // Check for ShiftAmt >= element width
14644   if (ShiftAmt >= ElementType.getSizeInBits()) {
14645     if (Opc == X86ISD::VSRAI)
14646       ShiftAmt = ElementType.getSizeInBits() - 1;
14647     else
14648       return DAG.getConstant(0, dl, VT);
14649   }
14650
14651   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
14652          && "Unknown target vector shift-by-constant node");
14653
14654   // Fold this packed vector shift into a build vector if SrcOp is a
14655   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
14656   if (VT == SrcOp.getSimpleValueType() &&
14657       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
14658     SmallVector<SDValue, 8> Elts;
14659     unsigned NumElts = SrcOp->getNumOperands();
14660     ConstantSDNode *ND;
14661
14662     switch(Opc) {
14663     default: llvm_unreachable(nullptr);
14664     case X86ISD::VSHLI:
14665       for (unsigned i=0; i!=NumElts; ++i) {
14666         SDValue CurrentOp = SrcOp->getOperand(i);
14667         if (CurrentOp->getOpcode() == ISD::UNDEF) {
14668           Elts.push_back(CurrentOp);
14669           continue;
14670         }
14671         ND = cast<ConstantSDNode>(CurrentOp);
14672         const APInt &C = ND->getAPIntValue();
14673         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), dl, ElementType));
14674       }
14675       break;
14676     case X86ISD::VSRLI:
14677       for (unsigned i=0; i!=NumElts; ++i) {
14678         SDValue CurrentOp = SrcOp->getOperand(i);
14679         if (CurrentOp->getOpcode() == ISD::UNDEF) {
14680           Elts.push_back(CurrentOp);
14681           continue;
14682         }
14683         ND = cast<ConstantSDNode>(CurrentOp);
14684         const APInt &C = ND->getAPIntValue();
14685         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), dl, ElementType));
14686       }
14687       break;
14688     case X86ISD::VSRAI:
14689       for (unsigned i=0; i!=NumElts; ++i) {
14690         SDValue CurrentOp = SrcOp->getOperand(i);
14691         if (CurrentOp->getOpcode() == ISD::UNDEF) {
14692           Elts.push_back(CurrentOp);
14693           continue;
14694         }
14695         ND = cast<ConstantSDNode>(CurrentOp);
14696         const APInt &C = ND->getAPIntValue();
14697         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), dl, ElementType));
14698       }
14699       break;
14700     }
14701
14702     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
14703   }
14704
14705   return DAG.getNode(Opc, dl, VT, SrcOp,
14706                      DAG.getConstant(ShiftAmt, dl, MVT::i8));
14707 }
14708
14709 // getTargetVShiftNode - Handle vector element shifts where the shift amount
14710 // may or may not be a constant. Takes immediate version of shift as input.
14711 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
14712                                    SDValue SrcOp, SDValue ShAmt,
14713                                    SelectionDAG &DAG) {
14714   MVT SVT = ShAmt.getSimpleValueType();
14715   assert((SVT == MVT::i32 || SVT == MVT::i64) && "Unexpected value type!");
14716
14717   // Catch shift-by-constant.
14718   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
14719     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
14720                                       CShAmt->getZExtValue(), DAG);
14721
14722   // Change opcode to non-immediate version
14723   switch (Opc) {
14724     default: llvm_unreachable("Unknown target vector shift node");
14725     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
14726     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
14727     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
14728   }
14729
14730   const X86Subtarget &Subtarget =
14731       static_cast<const X86Subtarget &>(DAG.getSubtarget());
14732   if (Subtarget.hasSSE41() && ShAmt.getOpcode() == ISD::ZERO_EXTEND &&
14733       ShAmt.getOperand(0).getSimpleValueType() == MVT::i16) {
14734     // Let the shuffle legalizer expand this shift amount node.
14735     SDValue Op0 = ShAmt.getOperand(0);
14736     Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(Op0), MVT::v8i16, Op0);
14737     ShAmt = getShuffleVectorZeroOrUndef(Op0, 0, true, &Subtarget, DAG);
14738   } else {
14739     // Need to build a vector containing shift amount.
14740     // SSE/AVX packed shifts only use the lower 64-bit of the shift count.
14741     SmallVector<SDValue, 4> ShOps;
14742     ShOps.push_back(ShAmt);
14743     if (SVT == MVT::i32) {
14744       ShOps.push_back(DAG.getConstant(0, dl, SVT));
14745       ShOps.push_back(DAG.getUNDEF(SVT));
14746     }
14747     ShOps.push_back(DAG.getUNDEF(SVT));
14748
14749     MVT BVT = SVT == MVT::i32 ? MVT::v4i32 : MVT::v2i64;
14750     ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, BVT, ShOps);
14751   }
14752
14753   // The return type has to be a 128-bit type with the same element
14754   // type as the input type.
14755   MVT EltVT = VT.getVectorElementType();
14756   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
14757
14758   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
14759   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
14760 }
14761
14762 /// \brief Return (and \p Op, \p Mask) for compare instructions or
14763 /// (vselect \p Mask, \p Op, \p PreservedSrc) for others along with the
14764 /// necessary casting for \p Mask when lowering masking intrinsics.
14765 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
14766                                     SDValue PreservedSrc,
14767                                     const X86Subtarget *Subtarget,
14768                                     SelectionDAG &DAG) {
14769     EVT VT = Op.getValueType();
14770     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
14771                                   MVT::i1, VT.getVectorNumElements());
14772     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14773                                      Mask.getValueType().getSizeInBits());
14774     SDLoc dl(Op);
14775
14776     assert(MaskVT.isSimple() && "invalid mask type");
14777
14778     if (isAllOnes(Mask))
14779       return Op;
14780
14781     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
14782     // are extracted by EXTRACT_SUBVECTOR.
14783     SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
14784                               DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
14785                               DAG.getIntPtrConstant(0, dl));
14786
14787     switch (Op.getOpcode()) {
14788       default: break;
14789       case X86ISD::PCMPEQM:
14790       case X86ISD::PCMPGTM:
14791       case X86ISD::CMPM:
14792       case X86ISD::CMPMU:
14793         return DAG.getNode(ISD::AND, dl, VT, Op, VMask);
14794     }
14795     if (PreservedSrc.getOpcode() == ISD::UNDEF)
14796       PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
14797     return DAG.getNode(ISD::VSELECT, dl, VT, VMask, Op, PreservedSrc);
14798 }
14799
14800 /// \brief Creates an SDNode for a predicated scalar operation.
14801 /// \returns (X86vselect \p Mask, \p Op, \p PreservedSrc).
14802 /// The mask is comming as MVT::i8 and it should be truncated
14803 /// to MVT::i1 while lowering masking intrinsics.
14804 /// The main difference between ScalarMaskingNode and VectorMaskingNode is using
14805 /// "X86select" instead of "vselect". We just can't create the "vselect" node for
14806 /// a scalar instruction.
14807 static SDValue getScalarMaskingNode(SDValue Op, SDValue Mask,
14808                                     SDValue PreservedSrc,
14809                                     const X86Subtarget *Subtarget,
14810                                     SelectionDAG &DAG) {
14811     if (isAllOnes(Mask))
14812       return Op;
14813
14814     EVT VT = Op.getValueType();
14815     SDLoc dl(Op);
14816     // The mask should be of type MVT::i1
14817     SDValue IMask = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Mask);
14818
14819     if (PreservedSrc.getOpcode() == ISD::UNDEF)
14820       PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
14821     return DAG.getNode(X86ISD::SELECT, dl, VT, IMask, Op, PreservedSrc);
14822 }
14823
14824 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
14825                                        SelectionDAG &DAG) {
14826   SDLoc dl(Op);
14827   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14828   EVT VT = Op.getValueType();
14829   const IntrinsicData* IntrData = getIntrinsicWithoutChain(IntNo);
14830   if (IntrData) {
14831     switch(IntrData->Type) {
14832     case INTR_TYPE_1OP:
14833       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1));
14834     case INTR_TYPE_2OP:
14835       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
14836         Op.getOperand(2));
14837     case INTR_TYPE_3OP:
14838       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
14839         Op.getOperand(2), Op.getOperand(3));
14840     case INTR_TYPE_1OP_MASK_RM: {
14841       SDValue Src = Op.getOperand(1);
14842       SDValue Src0 = Op.getOperand(2);
14843       SDValue Mask = Op.getOperand(3);
14844       SDValue RoundingMode = Op.getOperand(4);
14845       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src,
14846                                               RoundingMode),
14847                                   Mask, Src0, Subtarget, DAG);
14848     }
14849     case INTR_TYPE_SCALAR_MASK_RM: {
14850       SDValue Src1 = Op.getOperand(1);
14851       SDValue Src2 = Op.getOperand(2);
14852       SDValue Src0 = Op.getOperand(3);
14853       SDValue Mask = Op.getOperand(4);
14854       // There are 2 kinds of intrinsics in this group:
14855       // (1) With supress-all-exceptions (sae) - 6 operands
14856       // (2) With rounding mode and sae - 7 operands.
14857       if (Op.getNumOperands() == 6) {
14858         SDValue Sae  = Op.getOperand(5);
14859         return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
14860                                                 Sae),
14861                                     Mask, Src0, Subtarget, DAG);
14862       }
14863       assert(Op.getNumOperands() == 7 && "Unexpected intrinsic form");
14864       SDValue RoundingMode  = Op.getOperand(5);
14865       SDValue Sae  = Op.getOperand(6);
14866       return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
14867                                               RoundingMode, Sae),
14868                                   Mask, Src0, Subtarget, DAG);
14869     }
14870     case INTR_TYPE_2OP_MASK: {
14871       SDValue Src1 = Op.getOperand(1);
14872       SDValue Src2 = Op.getOperand(2);
14873       SDValue PassThru = Op.getOperand(3);
14874       SDValue Mask = Op.getOperand(4);
14875       // We specify 2 possible opcodes for intrinsics with rounding modes.
14876       // First, we check if the intrinsic may have non-default rounding mode,
14877       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
14878       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
14879       if (IntrWithRoundingModeOpcode != 0) {
14880         SDValue Rnd = Op.getOperand(5);
14881         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
14882         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
14883           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
14884                                       dl, Op.getValueType(),
14885                                       Src1, Src2, Rnd),
14886                                       Mask, PassThru, Subtarget, DAG);
14887         }
14888       }
14889       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
14890                                               Src1,Src2),
14891                                   Mask, PassThru, Subtarget, DAG);
14892     }
14893     case FMA_OP_MASK: {
14894       SDValue Src1 = Op.getOperand(1);
14895       SDValue Src2 = Op.getOperand(2);
14896       SDValue Src3 = Op.getOperand(3);
14897       SDValue Mask = Op.getOperand(4);
14898       // We specify 2 possible opcodes for intrinsics with rounding modes.
14899       // First, we check if the intrinsic may have non-default rounding mode,
14900       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
14901       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
14902       if (IntrWithRoundingModeOpcode != 0) {
14903         SDValue Rnd = Op.getOperand(5);
14904         if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
14905             X86::STATIC_ROUNDING::CUR_DIRECTION)
14906           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
14907                                                   dl, Op.getValueType(),
14908                                                   Src1, Src2, Src3, Rnd),
14909                                       Mask, Src1, Subtarget, DAG);
14910       }
14911       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0,
14912                                               dl, Op.getValueType(),
14913                                               Src1, Src2, Src3),
14914                                   Mask, Src1, Subtarget, DAG);
14915     }
14916     case CMP_MASK:
14917     case CMP_MASK_CC: {
14918       // Comparison intrinsics with masks.
14919       // Example of transformation:
14920       // (i8 (int_x86_avx512_mask_pcmpeq_q_128
14921       //             (v2i64 %a), (v2i64 %b), (i8 %mask))) ->
14922       // (i8 (bitcast
14923       //   (v8i1 (insert_subvector undef,
14924       //           (v2i1 (and (PCMPEQM %a, %b),
14925       //                      (extract_subvector
14926       //                         (v8i1 (bitcast %mask)), 0))), 0))))
14927       EVT VT = Op.getOperand(1).getValueType();
14928       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14929                                     VT.getVectorNumElements());
14930       SDValue Mask = Op.getOperand((IntrData->Type == CMP_MASK_CC) ? 4 : 3);
14931       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14932                                        Mask.getValueType().getSizeInBits());
14933       SDValue Cmp;
14934       if (IntrData->Type == CMP_MASK_CC) {
14935         SDValue CC = Op.getOperand(3);
14936         CC = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, CC);
14937         // We specify 2 possible opcodes for intrinsics with rounding modes.
14938         // First, we check if the intrinsic may have non-default rounding mode,
14939         // (IntrData->Opc1 != 0), then we check the rounding mode operand.
14940         if (IntrData->Opc1 != 0) {
14941           SDValue Rnd = Op.getOperand(5);
14942           if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
14943               X86::STATIC_ROUNDING::CUR_DIRECTION)
14944             Cmp = DAG.getNode(IntrData->Opc1, dl, MaskVT, Op.getOperand(1),
14945                               Op.getOperand(2), CC, Rnd);
14946         }
14947         //default rounding mode
14948         if(!Cmp.getNode())
14949             Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
14950                               Op.getOperand(2), CC);
14951
14952       } else {
14953         assert(IntrData->Type == CMP_MASK && "Unexpected intrinsic type!");
14954         Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
14955                           Op.getOperand(2));
14956       }
14957       SDValue CmpMask = getVectorMaskingNode(Cmp, Mask,
14958                                              DAG.getTargetConstant(0, dl,
14959                                                                    MaskVT),
14960                                              Subtarget, DAG);
14961       SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
14962                                 DAG.getUNDEF(BitcastVT), CmpMask,
14963                                 DAG.getIntPtrConstant(0, dl));
14964       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
14965     }
14966     case COMI: { // Comparison intrinsics
14967       ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
14968       SDValue LHS = Op.getOperand(1);
14969       SDValue RHS = Op.getOperand(2);
14970       unsigned X86CC = TranslateX86CC(CC, dl, true, LHS, RHS, DAG);
14971       assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
14972       SDValue Cond = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
14973       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14974                                   DAG.getConstant(X86CC, dl, MVT::i8), Cond);
14975       return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14976     }
14977     case VSHIFT:
14978       return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
14979                                  Op.getOperand(1), Op.getOperand(2), DAG);
14980     case VSHIFT_MASK:
14981       return getVectorMaskingNode(getTargetVShiftNode(IntrData->Opc0, dl,
14982                                                       Op.getSimpleValueType(),
14983                                                       Op.getOperand(1),
14984                                                       Op.getOperand(2), DAG),
14985                                   Op.getOperand(4), Op.getOperand(3), Subtarget,
14986                                   DAG);
14987     case COMPRESS_EXPAND_IN_REG: {
14988       SDValue Mask = Op.getOperand(3);
14989       SDValue DataToCompress = Op.getOperand(1);
14990       SDValue PassThru = Op.getOperand(2);
14991       if (isAllOnes(Mask)) // return data as is
14992         return Op.getOperand(1);
14993       EVT VT = Op.getValueType();
14994       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14995                                     VT.getVectorNumElements());
14996       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14997                                        Mask.getValueType().getSizeInBits());
14998       SDLoc dl(Op);
14999       SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15000                                   DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
15001                                   DAG.getIntPtrConstant(0, dl));
15002
15003       return DAG.getNode(IntrData->Opc0, dl, VT, VMask, DataToCompress,
15004                          PassThru);
15005     }
15006     case BLEND: {
15007       SDValue Mask = Op.getOperand(3);
15008       EVT VT = Op.getValueType();
15009       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15010                                     VT.getVectorNumElements());
15011       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15012                                        Mask.getValueType().getSizeInBits());
15013       SDLoc dl(Op);
15014       SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15015                                   DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
15016                                   DAG.getIntPtrConstant(0, dl));
15017       return DAG.getNode(IntrData->Opc0, dl, VT, VMask, Op.getOperand(1),
15018                          Op.getOperand(2));
15019     }
15020     default:
15021       break;
15022     }
15023   }
15024
15025   switch (IntNo) {
15026   default: return SDValue();    // Don't custom lower most intrinsics.
15027
15028   case Intrinsic::x86_avx2_permd:
15029   case Intrinsic::x86_avx2_permps:
15030     // Operands intentionally swapped. Mask is last operand to intrinsic,
15031     // but second operand for node/instruction.
15032     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
15033                        Op.getOperand(2), Op.getOperand(1));
15034
15035   case Intrinsic::x86_avx512_mask_valign_q_512:
15036   case Intrinsic::x86_avx512_mask_valign_d_512:
15037     // Vector source operands are swapped.
15038     return getVectorMaskingNode(DAG.getNode(X86ISD::VALIGN, dl,
15039                                             Op.getValueType(), Op.getOperand(2),
15040                                             Op.getOperand(1),
15041                                             Op.getOperand(3)),
15042                                 Op.getOperand(5), Op.getOperand(4),
15043                                 Subtarget, DAG);
15044
15045   // ptest and testp intrinsics. The intrinsic these come from are designed to
15046   // return an integer value, not just an instruction so lower it to the ptest
15047   // or testp pattern and a setcc for the result.
15048   case Intrinsic::x86_sse41_ptestz:
15049   case Intrinsic::x86_sse41_ptestc:
15050   case Intrinsic::x86_sse41_ptestnzc:
15051   case Intrinsic::x86_avx_ptestz_256:
15052   case Intrinsic::x86_avx_ptestc_256:
15053   case Intrinsic::x86_avx_ptestnzc_256:
15054   case Intrinsic::x86_avx_vtestz_ps:
15055   case Intrinsic::x86_avx_vtestc_ps:
15056   case Intrinsic::x86_avx_vtestnzc_ps:
15057   case Intrinsic::x86_avx_vtestz_pd:
15058   case Intrinsic::x86_avx_vtestc_pd:
15059   case Intrinsic::x86_avx_vtestnzc_pd:
15060   case Intrinsic::x86_avx_vtestz_ps_256:
15061   case Intrinsic::x86_avx_vtestc_ps_256:
15062   case Intrinsic::x86_avx_vtestnzc_ps_256:
15063   case Intrinsic::x86_avx_vtestz_pd_256:
15064   case Intrinsic::x86_avx_vtestc_pd_256:
15065   case Intrinsic::x86_avx_vtestnzc_pd_256: {
15066     bool IsTestPacked = false;
15067     unsigned X86CC;
15068     switch (IntNo) {
15069     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
15070     case Intrinsic::x86_avx_vtestz_ps:
15071     case Intrinsic::x86_avx_vtestz_pd:
15072     case Intrinsic::x86_avx_vtestz_ps_256:
15073     case Intrinsic::x86_avx_vtestz_pd_256:
15074       IsTestPacked = true; // Fallthrough
15075     case Intrinsic::x86_sse41_ptestz:
15076     case Intrinsic::x86_avx_ptestz_256:
15077       // ZF = 1
15078       X86CC = X86::COND_E;
15079       break;
15080     case Intrinsic::x86_avx_vtestc_ps:
15081     case Intrinsic::x86_avx_vtestc_pd:
15082     case Intrinsic::x86_avx_vtestc_ps_256:
15083     case Intrinsic::x86_avx_vtestc_pd_256:
15084       IsTestPacked = true; // Fallthrough
15085     case Intrinsic::x86_sse41_ptestc:
15086     case Intrinsic::x86_avx_ptestc_256:
15087       // CF = 1
15088       X86CC = X86::COND_B;
15089       break;
15090     case Intrinsic::x86_avx_vtestnzc_ps:
15091     case Intrinsic::x86_avx_vtestnzc_pd:
15092     case Intrinsic::x86_avx_vtestnzc_ps_256:
15093     case Intrinsic::x86_avx_vtestnzc_pd_256:
15094       IsTestPacked = true; // Fallthrough
15095     case Intrinsic::x86_sse41_ptestnzc:
15096     case Intrinsic::x86_avx_ptestnzc_256:
15097       // ZF and CF = 0
15098       X86CC = X86::COND_A;
15099       break;
15100     }
15101
15102     SDValue LHS = Op.getOperand(1);
15103     SDValue RHS = Op.getOperand(2);
15104     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
15105     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
15106     SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
15107     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
15108     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15109   }
15110   case Intrinsic::x86_avx512_kortestz_w:
15111   case Intrinsic::x86_avx512_kortestc_w: {
15112     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
15113     SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
15114     SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
15115     SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
15116     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
15117     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
15118     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15119   }
15120
15121   case Intrinsic::x86_sse42_pcmpistria128:
15122   case Intrinsic::x86_sse42_pcmpestria128:
15123   case Intrinsic::x86_sse42_pcmpistric128:
15124   case Intrinsic::x86_sse42_pcmpestric128:
15125   case Intrinsic::x86_sse42_pcmpistrio128:
15126   case Intrinsic::x86_sse42_pcmpestrio128:
15127   case Intrinsic::x86_sse42_pcmpistris128:
15128   case Intrinsic::x86_sse42_pcmpestris128:
15129   case Intrinsic::x86_sse42_pcmpistriz128:
15130   case Intrinsic::x86_sse42_pcmpestriz128: {
15131     unsigned Opcode;
15132     unsigned X86CC;
15133     switch (IntNo) {
15134     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
15135     case Intrinsic::x86_sse42_pcmpistria128:
15136       Opcode = X86ISD::PCMPISTRI;
15137       X86CC = X86::COND_A;
15138       break;
15139     case Intrinsic::x86_sse42_pcmpestria128:
15140       Opcode = X86ISD::PCMPESTRI;
15141       X86CC = X86::COND_A;
15142       break;
15143     case Intrinsic::x86_sse42_pcmpistric128:
15144       Opcode = X86ISD::PCMPISTRI;
15145       X86CC = X86::COND_B;
15146       break;
15147     case Intrinsic::x86_sse42_pcmpestric128:
15148       Opcode = X86ISD::PCMPESTRI;
15149       X86CC = X86::COND_B;
15150       break;
15151     case Intrinsic::x86_sse42_pcmpistrio128:
15152       Opcode = X86ISD::PCMPISTRI;
15153       X86CC = X86::COND_O;
15154       break;
15155     case Intrinsic::x86_sse42_pcmpestrio128:
15156       Opcode = X86ISD::PCMPESTRI;
15157       X86CC = X86::COND_O;
15158       break;
15159     case Intrinsic::x86_sse42_pcmpistris128:
15160       Opcode = X86ISD::PCMPISTRI;
15161       X86CC = X86::COND_S;
15162       break;
15163     case Intrinsic::x86_sse42_pcmpestris128:
15164       Opcode = X86ISD::PCMPESTRI;
15165       X86CC = X86::COND_S;
15166       break;
15167     case Intrinsic::x86_sse42_pcmpistriz128:
15168       Opcode = X86ISD::PCMPISTRI;
15169       X86CC = X86::COND_E;
15170       break;
15171     case Intrinsic::x86_sse42_pcmpestriz128:
15172       Opcode = X86ISD::PCMPESTRI;
15173       X86CC = X86::COND_E;
15174       break;
15175     }
15176     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
15177     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
15178     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
15179     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15180                                 DAG.getConstant(X86CC, dl, MVT::i8),
15181                                 SDValue(PCMP.getNode(), 1));
15182     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15183   }
15184
15185   case Intrinsic::x86_sse42_pcmpistri128:
15186   case Intrinsic::x86_sse42_pcmpestri128: {
15187     unsigned Opcode;
15188     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
15189       Opcode = X86ISD::PCMPISTRI;
15190     else
15191       Opcode = X86ISD::PCMPESTRI;
15192
15193     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
15194     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
15195     return DAG.getNode(Opcode, dl, VTs, NewOps);
15196   }
15197   }
15198 }
15199
15200 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15201                               SDValue Src, SDValue Mask, SDValue Base,
15202                               SDValue Index, SDValue ScaleOp, SDValue Chain,
15203                               const X86Subtarget * Subtarget) {
15204   SDLoc dl(Op);
15205   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15206   assert(C && "Invalid scale type");
15207   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
15208   EVT MaskVT = MVT::getVectorVT(MVT::i1,
15209                              Index.getSimpleValueType().getVectorNumElements());
15210   SDValue MaskInReg;
15211   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15212   if (MaskC)
15213     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
15214   else
15215     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
15216   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
15217   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
15218   SDValue Segment = DAG.getRegister(0, MVT::i32);
15219   if (Src.getOpcode() == ISD::UNDEF)
15220     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
15221   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
15222   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
15223   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
15224   return DAG.getMergeValues(RetOps, dl);
15225 }
15226
15227 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15228                                SDValue Src, SDValue Mask, SDValue Base,
15229                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
15230   SDLoc dl(Op);
15231   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15232   assert(C && "Invalid scale type");
15233   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
15234   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
15235   SDValue Segment = DAG.getRegister(0, MVT::i32);
15236   EVT MaskVT = MVT::getVectorVT(MVT::i1,
15237                              Index.getSimpleValueType().getVectorNumElements());
15238   SDValue MaskInReg;
15239   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15240   if (MaskC)
15241     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
15242   else
15243     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
15244   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
15245   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
15246   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
15247   return SDValue(Res, 1);
15248 }
15249
15250 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15251                                SDValue Mask, SDValue Base, SDValue Index,
15252                                SDValue ScaleOp, SDValue Chain) {
15253   SDLoc dl(Op);
15254   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15255   assert(C && "Invalid scale type");
15256   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
15257   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
15258   SDValue Segment = DAG.getRegister(0, MVT::i32);
15259   EVT MaskVT =
15260     MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
15261   SDValue MaskInReg;
15262   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15263   if (MaskC)
15264     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
15265   else
15266     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
15267   //SDVTList VTs = DAG.getVTList(MVT::Other);
15268   SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
15269   SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
15270   return SDValue(Res, 0);
15271 }
15272
15273 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
15274 // read performance monitor counters (x86_rdpmc).
15275 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
15276                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
15277                               SmallVectorImpl<SDValue> &Results) {
15278   assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
15279   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
15280   SDValue LO, HI;
15281
15282   // The ECX register is used to select the index of the performance counter
15283   // to read.
15284   SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
15285                                    N->getOperand(2));
15286   SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
15287
15288   // Reads the content of a 64-bit performance counter and returns it in the
15289   // registers EDX:EAX.
15290   if (Subtarget->is64Bit()) {
15291     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
15292     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
15293                             LO.getValue(2));
15294   } else {
15295     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
15296     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
15297                             LO.getValue(2));
15298   }
15299   Chain = HI.getValue(1);
15300
15301   if (Subtarget->is64Bit()) {
15302     // The EAX register is loaded with the low-order 32 bits. The EDX register
15303     // is loaded with the supported high-order bits of the counter.
15304     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
15305                               DAG.getConstant(32, DL, MVT::i8));
15306     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
15307     Results.push_back(Chain);
15308     return;
15309   }
15310
15311   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
15312   SDValue Ops[] = { LO, HI };
15313   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
15314   Results.push_back(Pair);
15315   Results.push_back(Chain);
15316 }
15317
15318 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
15319 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
15320 // also used to custom lower READCYCLECOUNTER nodes.
15321 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
15322                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
15323                               SmallVectorImpl<SDValue> &Results) {
15324   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
15325   SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
15326   SDValue LO, HI;
15327
15328   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
15329   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
15330   // and the EAX register is loaded with the low-order 32 bits.
15331   if (Subtarget->is64Bit()) {
15332     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
15333     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
15334                             LO.getValue(2));
15335   } else {
15336     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
15337     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
15338                             LO.getValue(2));
15339   }
15340   SDValue Chain = HI.getValue(1);
15341
15342   if (Opcode == X86ISD::RDTSCP_DAG) {
15343     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
15344
15345     // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
15346     // the ECX register. Add 'ecx' explicitly to the chain.
15347     SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
15348                                      HI.getValue(2));
15349     // Explicitly store the content of ECX at the location passed in input
15350     // to the 'rdtscp' intrinsic.
15351     Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
15352                          MachinePointerInfo(), false, false, 0);
15353   }
15354
15355   if (Subtarget->is64Bit()) {
15356     // The EDX register is loaded with the high-order 32 bits of the MSR, and
15357     // the EAX register is loaded with the low-order 32 bits.
15358     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
15359                               DAG.getConstant(32, DL, MVT::i8));
15360     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
15361     Results.push_back(Chain);
15362     return;
15363   }
15364
15365   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
15366   SDValue Ops[] = { LO, HI };
15367   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
15368   Results.push_back(Pair);
15369   Results.push_back(Chain);
15370 }
15371
15372 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
15373                                      SelectionDAG &DAG) {
15374   SmallVector<SDValue, 2> Results;
15375   SDLoc DL(Op);
15376   getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
15377                           Results);
15378   return DAG.getMergeValues(Results, DL);
15379 }
15380
15381
15382 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
15383                                       SelectionDAG &DAG) {
15384   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
15385
15386   const IntrinsicData* IntrData = getIntrinsicWithChain(IntNo);
15387   if (!IntrData)
15388     return SDValue();
15389
15390   SDLoc dl(Op);
15391   switch(IntrData->Type) {
15392   default:
15393     llvm_unreachable("Unknown Intrinsic Type");
15394     break;
15395   case RDSEED:
15396   case RDRAND: {
15397     // Emit the node with the right value type.
15398     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
15399     SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
15400
15401     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
15402     // Otherwise return the value from Rand, which is always 0, casted to i32.
15403     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
15404                       DAG.getConstant(1, dl, Op->getValueType(1)),
15405                       DAG.getConstant(X86::COND_B, dl, MVT::i32),
15406                       SDValue(Result.getNode(), 1) };
15407     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
15408                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
15409                                   Ops);
15410
15411     // Return { result, isValid, chain }.
15412     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
15413                        SDValue(Result.getNode(), 2));
15414   }
15415   case GATHER: {
15416   //gather(v1, mask, index, base, scale);
15417     SDValue Chain = Op.getOperand(0);
15418     SDValue Src   = Op.getOperand(2);
15419     SDValue Base  = Op.getOperand(3);
15420     SDValue Index = Op.getOperand(4);
15421     SDValue Mask  = Op.getOperand(5);
15422     SDValue Scale = Op.getOperand(6);
15423     return getGatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale,
15424                          Chain, Subtarget);
15425   }
15426   case SCATTER: {
15427   //scatter(base, mask, index, v1, scale);
15428     SDValue Chain = Op.getOperand(0);
15429     SDValue Base  = Op.getOperand(2);
15430     SDValue Mask  = Op.getOperand(3);
15431     SDValue Index = Op.getOperand(4);
15432     SDValue Src   = Op.getOperand(5);
15433     SDValue Scale = Op.getOperand(6);
15434     return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index,
15435                           Scale, Chain);
15436   }
15437   case PREFETCH: {
15438     SDValue Hint = Op.getOperand(6);
15439     unsigned HintVal = cast<ConstantSDNode>(Hint)->getZExtValue();
15440     assert(HintVal < 2 && "Wrong prefetch hint in intrinsic: should be 0 or 1");
15441     unsigned Opcode = (HintVal ? IntrData->Opc1 : IntrData->Opc0);
15442     SDValue Chain = Op.getOperand(0);
15443     SDValue Mask  = Op.getOperand(2);
15444     SDValue Index = Op.getOperand(3);
15445     SDValue Base  = Op.getOperand(4);
15446     SDValue Scale = Op.getOperand(5);
15447     return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
15448   }
15449   // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
15450   case RDTSC: {
15451     SmallVector<SDValue, 2> Results;
15452     getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget,
15453                             Results);
15454     return DAG.getMergeValues(Results, dl);
15455   }
15456   // Read Performance Monitoring Counters.
15457   case RDPMC: {
15458     SmallVector<SDValue, 2> Results;
15459     getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
15460     return DAG.getMergeValues(Results, dl);
15461   }
15462   // XTEST intrinsics.
15463   case XTEST: {
15464     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
15465     SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
15466     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15467                                 DAG.getConstant(X86::COND_NE, dl, MVT::i8),
15468                                 InTrans);
15469     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
15470     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
15471                        Ret, SDValue(InTrans.getNode(), 1));
15472   }
15473   // ADC/ADCX/SBB
15474   case ADX: {
15475     SmallVector<SDValue, 2> Results;
15476     SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
15477     SDVTList VTs = DAG.getVTList(Op.getOperand(3)->getValueType(0), MVT::Other);
15478     SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(2),
15479                                 DAG.getConstant(-1, dl, MVT::i8));
15480     SDValue Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(3),
15481                               Op.getOperand(4), GenCF.getValue(1));
15482     SDValue Store = DAG.getStore(Op.getOperand(0), dl, Res.getValue(0),
15483                                  Op.getOperand(5), MachinePointerInfo(),
15484                                  false, false, 0);
15485     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15486                                 DAG.getConstant(X86::COND_B, dl, MVT::i8),
15487                                 Res.getValue(1));
15488     Results.push_back(SetCC);
15489     Results.push_back(Store);
15490     return DAG.getMergeValues(Results, dl);
15491   }
15492   case COMPRESS_TO_MEM: {
15493     SDLoc dl(Op);
15494     SDValue Mask = Op.getOperand(4);
15495     SDValue DataToCompress = Op.getOperand(3);
15496     SDValue Addr = Op.getOperand(2);
15497     SDValue Chain = Op.getOperand(0);
15498
15499     if (isAllOnes(Mask)) // return just a store
15500       return DAG.getStore(Chain, dl, DataToCompress, Addr,
15501                           MachinePointerInfo(), false, false, 0);
15502
15503     EVT VT = DataToCompress.getValueType();
15504     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15505                                   VT.getVectorNumElements());
15506     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15507                                      Mask.getValueType().getSizeInBits());
15508     SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15509                                 DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
15510                                 DAG.getIntPtrConstant(0, dl));
15511
15512     SDValue Compressed =  DAG.getNode(IntrData->Opc0, dl, VT, VMask,
15513                                       DataToCompress, DAG.getUNDEF(VT));
15514     return DAG.getStore(Chain, dl, Compressed, Addr,
15515                         MachinePointerInfo(), false, false, 0);
15516   }
15517   case EXPAND_FROM_MEM: {
15518     SDLoc dl(Op);
15519     SDValue Mask = Op.getOperand(4);
15520     SDValue PathThru = Op.getOperand(3);
15521     SDValue Addr = Op.getOperand(2);
15522     SDValue Chain = Op.getOperand(0);
15523     EVT VT = Op.getValueType();
15524
15525     if (isAllOnes(Mask)) // return just a load
15526       return DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(), false, false,
15527                          false, 0);
15528     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15529                                   VT.getVectorNumElements());
15530     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15531                                      Mask.getValueType().getSizeInBits());
15532     SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15533                                 DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
15534                                 DAG.getIntPtrConstant(0, dl));
15535
15536     SDValue DataToExpand = DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(),
15537                                    false, false, false, 0);
15538
15539     SDValue Results[] = {
15540         DAG.getNode(IntrData->Opc0, dl, VT, VMask, DataToExpand, PathThru),
15541         Chain};
15542     return DAG.getMergeValues(Results, dl);
15543   }
15544   }
15545 }
15546
15547 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
15548                                            SelectionDAG &DAG) const {
15549   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
15550   MFI->setReturnAddressIsTaken(true);
15551
15552   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
15553     return SDValue();
15554
15555   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15556   SDLoc dl(Op);
15557   EVT PtrVT = getPointerTy();
15558
15559   if (Depth > 0) {
15560     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
15561     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15562     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), dl, PtrVT);
15563     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15564                        DAG.getNode(ISD::ADD, dl, PtrVT,
15565                                    FrameAddr, Offset),
15566                        MachinePointerInfo(), false, false, false, 0);
15567   }
15568
15569   // Just load the return address.
15570   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
15571   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15572                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
15573 }
15574
15575 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
15576   MachineFunction &MF = DAG.getMachineFunction();
15577   MachineFrameInfo *MFI = MF.getFrameInfo();
15578   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
15579   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15580   EVT VT = Op.getValueType();
15581
15582   MFI->setFrameAddressIsTaken(true);
15583
15584   if (MF.getTarget().getMCAsmInfo()->usesWindowsCFI()) {
15585     // Depth > 0 makes no sense on targets which use Windows unwind codes.  It
15586     // is not possible to crawl up the stack without looking at the unwind codes
15587     // simultaneously.
15588     int FrameAddrIndex = FuncInfo->getFAIndex();
15589     if (!FrameAddrIndex) {
15590       // Set up a frame object for the return address.
15591       unsigned SlotSize = RegInfo->getSlotSize();
15592       FrameAddrIndex = MF.getFrameInfo()->CreateFixedObject(
15593           SlotSize, /*Offset=*/INT64_MIN, /*IsImmutable=*/false);
15594       FuncInfo->setFAIndex(FrameAddrIndex);
15595     }
15596     return DAG.getFrameIndex(FrameAddrIndex, VT);
15597   }
15598
15599   unsigned FrameReg =
15600       RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
15601   SDLoc dl(Op);  // FIXME probably not meaningful
15602   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15603   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
15604           (FrameReg == X86::EBP && VT == MVT::i32)) &&
15605          "Invalid Frame Register!");
15606   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
15607   while (Depth--)
15608     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
15609                             MachinePointerInfo(),
15610                             false, false, false, 0);
15611   return FrameAddr;
15612 }
15613
15614 // FIXME? Maybe this could be a TableGen attribute on some registers and
15615 // this table could be generated automatically from RegInfo.
15616 unsigned X86TargetLowering::getRegisterByName(const char* RegName,
15617                                               EVT VT) const {
15618   unsigned Reg = StringSwitch<unsigned>(RegName)
15619                        .Case("esp", X86::ESP)
15620                        .Case("rsp", X86::RSP)
15621                        .Default(0);
15622   if (Reg)
15623     return Reg;
15624   report_fatal_error("Invalid register name global variable");
15625 }
15626
15627 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
15628                                                      SelectionDAG &DAG) const {
15629   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15630   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize(), SDLoc(Op));
15631 }
15632
15633 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
15634   SDValue Chain     = Op.getOperand(0);
15635   SDValue Offset    = Op.getOperand(1);
15636   SDValue Handler   = Op.getOperand(2);
15637   SDLoc dl      (Op);
15638
15639   EVT PtrVT = getPointerTy();
15640   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15641   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
15642   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
15643           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
15644          "Invalid Frame Register!");
15645   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
15646   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
15647
15648   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
15649                                  DAG.getIntPtrConstant(RegInfo->getSlotSize(),
15650                                                        dl));
15651   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
15652   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
15653                        false, false, 0);
15654   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
15655
15656   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
15657                      DAG.getRegister(StoreAddrReg, PtrVT));
15658 }
15659
15660 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
15661                                                SelectionDAG &DAG) const {
15662   SDLoc DL(Op);
15663   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
15664                      DAG.getVTList(MVT::i32, MVT::Other),
15665                      Op.getOperand(0), Op.getOperand(1));
15666 }
15667
15668 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
15669                                                 SelectionDAG &DAG) const {
15670   SDLoc DL(Op);
15671   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
15672                      Op.getOperand(0), Op.getOperand(1));
15673 }
15674
15675 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
15676   return Op.getOperand(0);
15677 }
15678
15679 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
15680                                                 SelectionDAG &DAG) const {
15681   SDValue Root = Op.getOperand(0);
15682   SDValue Trmp = Op.getOperand(1); // trampoline
15683   SDValue FPtr = Op.getOperand(2); // nested function
15684   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
15685   SDLoc dl (Op);
15686
15687   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
15688   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
15689
15690   if (Subtarget->is64Bit()) {
15691     SDValue OutChains[6];
15692
15693     // Large code-model.
15694     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
15695     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
15696
15697     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
15698     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
15699
15700     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
15701
15702     // Load the pointer to the nested function into R11.
15703     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
15704     SDValue Addr = Trmp;
15705     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
15706                                 Addr, MachinePointerInfo(TrmpAddr),
15707                                 false, false, 0);
15708
15709     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15710                        DAG.getConstant(2, dl, MVT::i64));
15711     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
15712                                 MachinePointerInfo(TrmpAddr, 2),
15713                                 false, false, 2);
15714
15715     // Load the 'nest' parameter value into R10.
15716     // R10 is specified in X86CallingConv.td
15717     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
15718     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15719                        DAG.getConstant(10, dl, MVT::i64));
15720     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
15721                                 Addr, MachinePointerInfo(TrmpAddr, 10),
15722                                 false, false, 0);
15723
15724     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15725                        DAG.getConstant(12, dl, MVT::i64));
15726     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
15727                                 MachinePointerInfo(TrmpAddr, 12),
15728                                 false, false, 2);
15729
15730     // Jump to the nested function.
15731     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
15732     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15733                        DAG.getConstant(20, dl, MVT::i64));
15734     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
15735                                 Addr, MachinePointerInfo(TrmpAddr, 20),
15736                                 false, false, 0);
15737
15738     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
15739     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15740                        DAG.getConstant(22, dl, MVT::i64));
15741     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, dl, MVT::i8),
15742                                 Addr, MachinePointerInfo(TrmpAddr, 22),
15743                                 false, false, 0);
15744
15745     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
15746   } else {
15747     const Function *Func =
15748       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
15749     CallingConv::ID CC = Func->getCallingConv();
15750     unsigned NestReg;
15751
15752     switch (CC) {
15753     default:
15754       llvm_unreachable("Unsupported calling convention");
15755     case CallingConv::C:
15756     case CallingConv::X86_StdCall: {
15757       // Pass 'nest' parameter in ECX.
15758       // Must be kept in sync with X86CallingConv.td
15759       NestReg = X86::ECX;
15760
15761       // Check that ECX wasn't needed by an 'inreg' parameter.
15762       FunctionType *FTy = Func->getFunctionType();
15763       const AttributeSet &Attrs = Func->getAttributes();
15764
15765       if (!Attrs.isEmpty() && !Func->isVarArg()) {
15766         unsigned InRegCount = 0;
15767         unsigned Idx = 1;
15768
15769         for (FunctionType::param_iterator I = FTy->param_begin(),
15770              E = FTy->param_end(); I != E; ++I, ++Idx)
15771           if (Attrs.hasAttribute(Idx, Attribute::InReg))
15772             // FIXME: should only count parameters that are lowered to integers.
15773             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
15774
15775         if (InRegCount > 2) {
15776           report_fatal_error("Nest register in use - reduce number of inreg"
15777                              " parameters!");
15778         }
15779       }
15780       break;
15781     }
15782     case CallingConv::X86_FastCall:
15783     case CallingConv::X86_ThisCall:
15784     case CallingConv::Fast:
15785       // Pass 'nest' parameter in EAX.
15786       // Must be kept in sync with X86CallingConv.td
15787       NestReg = X86::EAX;
15788       break;
15789     }
15790
15791     SDValue OutChains[4];
15792     SDValue Addr, Disp;
15793
15794     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15795                        DAG.getConstant(10, dl, MVT::i32));
15796     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
15797
15798     // This is storing the opcode for MOV32ri.
15799     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
15800     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
15801     OutChains[0] = DAG.getStore(Root, dl,
15802                                 DAG.getConstant(MOV32ri|N86Reg, dl, MVT::i8),
15803                                 Trmp, MachinePointerInfo(TrmpAddr),
15804                                 false, false, 0);
15805
15806     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15807                        DAG.getConstant(1, dl, MVT::i32));
15808     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
15809                                 MachinePointerInfo(TrmpAddr, 1),
15810                                 false, false, 1);
15811
15812     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
15813     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15814                        DAG.getConstant(5, dl, MVT::i32));
15815     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, dl, MVT::i8),
15816                                 Addr, MachinePointerInfo(TrmpAddr, 5),
15817                                 false, false, 1);
15818
15819     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15820                        DAG.getConstant(6, dl, MVT::i32));
15821     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
15822                                 MachinePointerInfo(TrmpAddr, 6),
15823                                 false, false, 1);
15824
15825     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
15826   }
15827 }
15828
15829 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
15830                                             SelectionDAG &DAG) const {
15831   /*
15832    The rounding mode is in bits 11:10 of FPSR, and has the following
15833    settings:
15834      00 Round to nearest
15835      01 Round to -inf
15836      10 Round to +inf
15837      11 Round to 0
15838
15839   FLT_ROUNDS, on the other hand, expects the following:
15840     -1 Undefined
15841      0 Round to 0
15842      1 Round to nearest
15843      2 Round to +inf
15844      3 Round to -inf
15845
15846   To perform the conversion, we do:
15847     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
15848   */
15849
15850   MachineFunction &MF = DAG.getMachineFunction();
15851   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
15852   unsigned StackAlignment = TFI.getStackAlignment();
15853   MVT VT = Op.getSimpleValueType();
15854   SDLoc DL(Op);
15855
15856   // Save FP Control Word to stack slot
15857   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
15858   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
15859
15860   MachineMemOperand *MMO =
15861    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
15862                            MachineMemOperand::MOStore, 2, 2);
15863
15864   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
15865   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
15866                                           DAG.getVTList(MVT::Other),
15867                                           Ops, MVT::i16, MMO);
15868
15869   // Load FP Control Word from stack slot
15870   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
15871                             MachinePointerInfo(), false, false, false, 0);
15872
15873   // Transform as necessary
15874   SDValue CWD1 =
15875     DAG.getNode(ISD::SRL, DL, MVT::i16,
15876                 DAG.getNode(ISD::AND, DL, MVT::i16,
15877                             CWD, DAG.getConstant(0x800, DL, MVT::i16)),
15878                 DAG.getConstant(11, DL, MVT::i8));
15879   SDValue CWD2 =
15880     DAG.getNode(ISD::SRL, DL, MVT::i16,
15881                 DAG.getNode(ISD::AND, DL, MVT::i16,
15882                             CWD, DAG.getConstant(0x400, DL, MVT::i16)),
15883                 DAG.getConstant(9, DL, MVT::i8));
15884
15885   SDValue RetVal =
15886     DAG.getNode(ISD::AND, DL, MVT::i16,
15887                 DAG.getNode(ISD::ADD, DL, MVT::i16,
15888                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
15889                             DAG.getConstant(1, DL, MVT::i16)),
15890                 DAG.getConstant(3, DL, MVT::i16));
15891
15892   return DAG.getNode((VT.getSizeInBits() < 16 ?
15893                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
15894 }
15895
15896 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
15897   MVT VT = Op.getSimpleValueType();
15898   EVT OpVT = VT;
15899   unsigned NumBits = VT.getSizeInBits();
15900   SDLoc dl(Op);
15901
15902   Op = Op.getOperand(0);
15903   if (VT == MVT::i8) {
15904     // Zero extend to i32 since there is not an i8 bsr.
15905     OpVT = MVT::i32;
15906     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
15907   }
15908
15909   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
15910   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
15911   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
15912
15913   // If src is zero (i.e. bsr sets ZF), returns NumBits.
15914   SDValue Ops[] = {
15915     Op,
15916     DAG.getConstant(NumBits + NumBits - 1, dl, OpVT),
15917     DAG.getConstant(X86::COND_E, dl, MVT::i8),
15918     Op.getValue(1)
15919   };
15920   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
15921
15922   // Finally xor with NumBits-1.
15923   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
15924                    DAG.getConstant(NumBits - 1, dl, OpVT));
15925
15926   if (VT == MVT::i8)
15927     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
15928   return Op;
15929 }
15930
15931 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
15932   MVT VT = Op.getSimpleValueType();
15933   EVT OpVT = VT;
15934   unsigned NumBits = VT.getSizeInBits();
15935   SDLoc dl(Op);
15936
15937   Op = Op.getOperand(0);
15938   if (VT == MVT::i8) {
15939     // Zero extend to i32 since there is not an i8 bsr.
15940     OpVT = MVT::i32;
15941     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
15942   }
15943
15944   // Issue a bsr (scan bits in reverse).
15945   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
15946   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
15947
15948   // And xor with NumBits-1.
15949   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
15950                    DAG.getConstant(NumBits - 1, dl, OpVT));
15951
15952   if (VT == MVT::i8)
15953     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
15954   return Op;
15955 }
15956
15957 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
15958   MVT VT = Op.getSimpleValueType();
15959   unsigned NumBits = VT.getSizeInBits();
15960   SDLoc dl(Op);
15961   Op = Op.getOperand(0);
15962
15963   // Issue a bsf (scan bits forward) which also sets EFLAGS.
15964   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
15965   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
15966
15967   // If src is zero (i.e. bsf sets ZF), returns NumBits.
15968   SDValue Ops[] = {
15969     Op,
15970     DAG.getConstant(NumBits, dl, VT),
15971     DAG.getConstant(X86::COND_E, dl, MVT::i8),
15972     Op.getValue(1)
15973   };
15974   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
15975 }
15976
15977 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
15978 // ones, and then concatenate the result back.
15979 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
15980   MVT VT = Op.getSimpleValueType();
15981
15982   assert(VT.is256BitVector() && VT.isInteger() &&
15983          "Unsupported value type for operation");
15984
15985   unsigned NumElems = VT.getVectorNumElements();
15986   SDLoc dl(Op);
15987
15988   // Extract the LHS vectors
15989   SDValue LHS = Op.getOperand(0);
15990   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
15991   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
15992
15993   // Extract the RHS vectors
15994   SDValue RHS = Op.getOperand(1);
15995   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
15996   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
15997
15998   MVT EltVT = VT.getVectorElementType();
15999   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16000
16001   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
16002                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
16003                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
16004 }
16005
16006 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
16007   assert(Op.getSimpleValueType().is256BitVector() &&
16008          Op.getSimpleValueType().isInteger() &&
16009          "Only handle AVX 256-bit vector integer operation");
16010   return Lower256IntArith(Op, DAG);
16011 }
16012
16013 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
16014   assert(Op.getSimpleValueType().is256BitVector() &&
16015          Op.getSimpleValueType().isInteger() &&
16016          "Only handle AVX 256-bit vector integer operation");
16017   return Lower256IntArith(Op, DAG);
16018 }
16019
16020 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
16021                         SelectionDAG &DAG) {
16022   SDLoc dl(Op);
16023   MVT VT = Op.getSimpleValueType();
16024
16025   // Decompose 256-bit ops into smaller 128-bit ops.
16026   if (VT.is256BitVector() && !Subtarget->hasInt256())
16027     return Lower256IntArith(Op, DAG);
16028
16029   SDValue A = Op.getOperand(0);
16030   SDValue B = Op.getOperand(1);
16031
16032   // Lower v16i8/v32i8 mul as promotion to v8i16/v16i16 vector
16033   // pairs, multiply and truncate.
16034   if (VT == MVT::v16i8 || VT == MVT::v32i8) {
16035     if (Subtarget->hasInt256()) {
16036       if (VT == MVT::v32i8) {
16037         MVT SubVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() / 2);
16038         SDValue Lo = DAG.getIntPtrConstant(0, dl);
16039         SDValue Hi = DAG.getIntPtrConstant(VT.getVectorNumElements() / 2, dl);
16040         SDValue ALo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Lo);
16041         SDValue BLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Lo);
16042         SDValue AHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Hi);
16043         SDValue BHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Hi);
16044         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
16045                            DAG.getNode(ISD::MUL, dl, SubVT, ALo, BLo),
16046                            DAG.getNode(ISD::MUL, dl, SubVT, AHi, BHi));
16047       }
16048
16049       MVT ExVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements());
16050       return DAG.getNode(
16051           ISD::TRUNCATE, dl, VT,
16052           DAG.getNode(ISD::MUL, dl, ExVT,
16053                       DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, A),
16054                       DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, B)));
16055     }
16056
16057     assert(VT == MVT::v16i8 &&
16058            "Pre-AVX2 support only supports v16i8 multiplication");
16059     MVT ExVT = MVT::v8i16;
16060
16061     // Extract the lo parts and sign extend to i16
16062     SDValue ALo, BLo;
16063     if (Subtarget->hasSSE41()) {
16064       ALo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, A);
16065       BLo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, B);
16066     } else {
16067       const int ShufMask[] = {-1, 0, -1, 1, -1, 2, -1, 3,
16068                               -1, 4, -1, 5, -1, 6, -1, 7};
16069       ALo = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16070       BLo = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16071       ALo = DAG.getNode(ISD::BITCAST, dl, ExVT, ALo);
16072       BLo = DAG.getNode(ISD::BITCAST, dl, ExVT, BLo);
16073       ALo = DAG.getNode(ISD::SRA, dl, ExVT, ALo, DAG.getConstant(8, dl, ExVT));
16074       BLo = DAG.getNode(ISD::SRA, dl, ExVT, BLo, DAG.getConstant(8, dl, ExVT));
16075     }
16076
16077     // Extract the hi parts and sign extend to i16
16078     SDValue AHi, BHi;
16079     if (Subtarget->hasSSE41()) {
16080       const int ShufMask[] = {8,  9,  10, 11, 12, 13, 14, 15,
16081                               -1, -1, -1, -1, -1, -1, -1, -1};
16082       AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16083       BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16084       AHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, AHi);
16085       BHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, BHi);
16086     } else {
16087       const int ShufMask[] = {-1, 8,  -1, 9,  -1, 10, -1, 11,
16088                               -1, 12, -1, 13, -1, 14, -1, 15};
16089       AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16090       BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16091       AHi = DAG.getNode(ISD::BITCAST, dl, ExVT, AHi);
16092       BHi = DAG.getNode(ISD::BITCAST, dl, ExVT, BHi);
16093       AHi = DAG.getNode(ISD::SRA, dl, ExVT, AHi, DAG.getConstant(8, dl, ExVT));
16094       BHi = DAG.getNode(ISD::SRA, dl, ExVT, BHi, DAG.getConstant(8, dl, ExVT));
16095     }
16096
16097     // Multiply, mask the lower 8bits of the lo/hi results and pack
16098     SDValue RLo = DAG.getNode(ISD::MUL, dl, ExVT, ALo, BLo);
16099     SDValue RHi = DAG.getNode(ISD::MUL, dl, ExVT, AHi, BHi);
16100     RLo = DAG.getNode(ISD::AND, dl, ExVT, RLo, DAG.getConstant(255, dl, ExVT));
16101     RHi = DAG.getNode(ISD::AND, dl, ExVT, RHi, DAG.getConstant(255, dl, ExVT));
16102     return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
16103   }
16104
16105   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
16106   if (VT == MVT::v4i32) {
16107     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
16108            "Should not custom lower when pmuldq is available!");
16109
16110     // Extract the odd parts.
16111     static const int UnpackMask[] = { 1, -1, 3, -1 };
16112     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
16113     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
16114
16115     // Multiply the even parts.
16116     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
16117     // Now multiply odd parts.
16118     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
16119
16120     Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
16121     Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
16122
16123     // Merge the two vectors back together with a shuffle. This expands into 2
16124     // shuffles.
16125     static const int ShufMask[] = { 0, 4, 2, 6 };
16126     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
16127   }
16128
16129   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
16130          "Only know how to lower V2I64/V4I64/V8I64 multiply");
16131
16132   //  Ahi = psrlqi(a, 32);
16133   //  Bhi = psrlqi(b, 32);
16134   //
16135   //  AloBlo = pmuludq(a, b);
16136   //  AloBhi = pmuludq(a, Bhi);
16137   //  AhiBlo = pmuludq(Ahi, b);
16138
16139   //  AloBhi = psllqi(AloBhi, 32);
16140   //  AhiBlo = psllqi(AhiBlo, 32);
16141   //  return AloBlo + AloBhi + AhiBlo;
16142
16143   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
16144   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
16145
16146   // Bit cast to 32-bit vectors for MULUDQ
16147   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
16148                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
16149   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
16150   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
16151   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
16152   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
16153
16154   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
16155   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
16156   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
16157
16158   AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
16159   AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
16160
16161   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
16162   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
16163 }
16164
16165 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
16166   assert(Subtarget->isTargetWin64() && "Unexpected target");
16167   EVT VT = Op.getValueType();
16168   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
16169          "Unexpected return type for lowering");
16170
16171   RTLIB::Libcall LC;
16172   bool isSigned;
16173   switch (Op->getOpcode()) {
16174   default: llvm_unreachable("Unexpected request for libcall!");
16175   case ISD::SDIV:      isSigned = true;  LC = RTLIB::SDIV_I128;    break;
16176   case ISD::UDIV:      isSigned = false; LC = RTLIB::UDIV_I128;    break;
16177   case ISD::SREM:      isSigned = true;  LC = RTLIB::SREM_I128;    break;
16178   case ISD::UREM:      isSigned = false; LC = RTLIB::UREM_I128;    break;
16179   case ISD::SDIVREM:   isSigned = true;  LC = RTLIB::SDIVREM_I128; break;
16180   case ISD::UDIVREM:   isSigned = false; LC = RTLIB::UDIVREM_I128; break;
16181   }
16182
16183   SDLoc dl(Op);
16184   SDValue InChain = DAG.getEntryNode();
16185
16186   TargetLowering::ArgListTy Args;
16187   TargetLowering::ArgListEntry Entry;
16188   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
16189     EVT ArgVT = Op->getOperand(i).getValueType();
16190     assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
16191            "Unexpected argument type for lowering");
16192     SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
16193     Entry.Node = StackPtr;
16194     InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
16195                            false, false, 16);
16196     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
16197     Entry.Ty = PointerType::get(ArgTy,0);
16198     Entry.isSExt = false;
16199     Entry.isZExt = false;
16200     Args.push_back(Entry);
16201   }
16202
16203   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
16204                                          getPointerTy());
16205
16206   TargetLowering::CallLoweringInfo CLI(DAG);
16207   CLI.setDebugLoc(dl).setChain(InChain)
16208     .setCallee(getLibcallCallingConv(LC),
16209                static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
16210                Callee, std::move(Args), 0)
16211     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
16212
16213   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
16214   return DAG.getNode(ISD::BITCAST, dl, VT, CallInfo.first);
16215 }
16216
16217 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
16218                              SelectionDAG &DAG) {
16219   SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
16220   EVT VT = Op0.getValueType();
16221   SDLoc dl(Op);
16222
16223   assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
16224          (VT == MVT::v8i32 && Subtarget->hasInt256()));
16225
16226   // PMULxD operations multiply each even value (starting at 0) of LHS with
16227   // the related value of RHS and produce a widen result.
16228   // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
16229   // => <2 x i64> <ae|cg>
16230   //
16231   // In other word, to have all the results, we need to perform two PMULxD:
16232   // 1. one with the even values.
16233   // 2. one with the odd values.
16234   // To achieve #2, with need to place the odd values at an even position.
16235   //
16236   // Place the odd value at an even position (basically, shift all values 1
16237   // step to the left):
16238   const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
16239   // <a|b|c|d> => <b|undef|d|undef>
16240   SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
16241   // <e|f|g|h> => <f|undef|h|undef>
16242   SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
16243
16244   // Emit two multiplies, one for the lower 2 ints and one for the higher 2
16245   // ints.
16246   MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
16247   bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
16248   unsigned Opcode =
16249       (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
16250   // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
16251   // => <2 x i64> <ae|cg>
16252   SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
16253                              DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
16254   // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
16255   // => <2 x i64> <bf|dh>
16256   SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
16257                              DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
16258
16259   // Shuffle it back into the right order.
16260   SDValue Highs, Lows;
16261   if (VT == MVT::v8i32) {
16262     const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
16263     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
16264     const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
16265     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
16266   } else {
16267     const int HighMask[] = {1, 5, 3, 7};
16268     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
16269     const int LowMask[] = {0, 4, 2, 6};
16270     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
16271   }
16272
16273   // If we have a signed multiply but no PMULDQ fix up the high parts of a
16274   // unsigned multiply.
16275   if (IsSigned && !Subtarget->hasSSE41()) {
16276     SDValue ShAmt =
16277         DAG.getConstant(31, dl,
16278                         DAG.getTargetLoweringInfo().getShiftAmountTy(VT));
16279     SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
16280                              DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
16281     SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
16282                              DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
16283
16284     SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
16285     Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
16286   }
16287
16288   // The first result of MUL_LOHI is actually the low value, followed by the
16289   // high value.
16290   SDValue Ops[] = {Lows, Highs};
16291   return DAG.getMergeValues(Ops, dl);
16292 }
16293
16294 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
16295                                          const X86Subtarget *Subtarget) {
16296   MVT VT = Op.getSimpleValueType();
16297   SDLoc dl(Op);
16298   SDValue R = Op.getOperand(0);
16299   SDValue Amt = Op.getOperand(1);
16300
16301   // Optimize shl/srl/sra with constant shift amount.
16302   if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
16303     if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
16304       uint64_t ShiftAmt = ShiftConst->getZExtValue();
16305
16306       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
16307           (Subtarget->hasInt256() &&
16308            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
16309           (Subtarget->hasAVX512() &&
16310            (VT == MVT::v8i64 || VT == MVT::v16i32))) {
16311         if (Op.getOpcode() == ISD::SHL)
16312           return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
16313                                             DAG);
16314         if (Op.getOpcode() == ISD::SRL)
16315           return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
16316                                             DAG);
16317         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
16318           return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
16319                                             DAG);
16320       }
16321
16322       if (VT == MVT::v16i8 || (Subtarget->hasInt256() && VT == MVT::v32i8)) {
16323         unsigned NumElts = VT.getVectorNumElements();
16324         MVT ShiftVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
16325
16326         if (Op.getOpcode() == ISD::SHL) {
16327           // Make a large shift.
16328           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ShiftVT,
16329                                                    R, ShiftAmt, DAG);
16330           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
16331           // Zero out the rightmost bits.
16332           SmallVector<SDValue, 32> V(
16333               NumElts, DAG.getConstant(uint8_t(-1U << ShiftAmt), dl, MVT::i8));
16334           return DAG.getNode(ISD::AND, dl, VT, SHL,
16335                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
16336         }
16337         if (Op.getOpcode() == ISD::SRL) {
16338           // Make a large shift.
16339           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ShiftVT,
16340                                                    R, ShiftAmt, DAG);
16341           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
16342           // Zero out the leftmost bits.
16343           SmallVector<SDValue, 32> V(
16344               NumElts, DAG.getConstant(uint8_t(-1U) >> ShiftAmt, dl, MVT::i8));
16345           return DAG.getNode(ISD::AND, dl, VT, SRL,
16346                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
16347         }
16348         if (Op.getOpcode() == ISD::SRA) {
16349           if (ShiftAmt == 7) {
16350             // R s>> 7  ===  R s< 0
16351             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
16352             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
16353           }
16354
16355           // R s>> a === ((R u>> a) ^ m) - m
16356           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
16357           SmallVector<SDValue, 32> V(NumElts,
16358                                      DAG.getConstant(128 >> ShiftAmt, dl,
16359                                                      MVT::i8));
16360           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
16361           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
16362           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
16363           return Res;
16364         }
16365         llvm_unreachable("Unknown shift opcode.");
16366       }
16367     }
16368   }
16369
16370   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
16371   if (!Subtarget->is64Bit() &&
16372       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
16373       Amt.getOpcode() == ISD::BITCAST &&
16374       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
16375     Amt = Amt.getOperand(0);
16376     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
16377                      VT.getVectorNumElements();
16378     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
16379     uint64_t ShiftAmt = 0;
16380     for (unsigned i = 0; i != Ratio; ++i) {
16381       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
16382       if (!C)
16383         return SDValue();
16384       // 6 == Log2(64)
16385       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
16386     }
16387     // Check remaining shift amounts.
16388     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
16389       uint64_t ShAmt = 0;
16390       for (unsigned j = 0; j != Ratio; ++j) {
16391         ConstantSDNode *C =
16392           dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
16393         if (!C)
16394           return SDValue();
16395         // 6 == Log2(64)
16396         ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
16397       }
16398       if (ShAmt != ShiftAmt)
16399         return SDValue();
16400     }
16401     switch (Op.getOpcode()) {
16402     default:
16403       llvm_unreachable("Unknown shift opcode!");
16404     case ISD::SHL:
16405       return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
16406                                         DAG);
16407     case ISD::SRL:
16408       return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
16409                                         DAG);
16410     case ISD::SRA:
16411       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
16412                                         DAG);
16413     }
16414   }
16415
16416   return SDValue();
16417 }
16418
16419 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
16420                                         const X86Subtarget* Subtarget) {
16421   MVT VT = Op.getSimpleValueType();
16422   SDLoc dl(Op);
16423   SDValue R = Op.getOperand(0);
16424   SDValue Amt = Op.getOperand(1);
16425
16426   if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
16427       VT == MVT::v4i32 || VT == MVT::v8i16 ||
16428       (Subtarget->hasInt256() &&
16429        ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
16430         VT == MVT::v8i32 || VT == MVT::v16i16)) ||
16431        (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
16432     SDValue BaseShAmt;
16433     EVT EltVT = VT.getVectorElementType();
16434
16435     if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Amt)) {
16436       // Check if this build_vector node is doing a splat.
16437       // If so, then set BaseShAmt equal to the splat value.
16438       BaseShAmt = BV->getSplatValue();
16439       if (BaseShAmt && BaseShAmt.getOpcode() == ISD::UNDEF)
16440         BaseShAmt = SDValue();
16441     } else {
16442       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
16443         Amt = Amt.getOperand(0);
16444
16445       ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt);
16446       if (SVN && SVN->isSplat()) {
16447         unsigned SplatIdx = (unsigned)SVN->getSplatIndex();
16448         SDValue InVec = Amt.getOperand(0);
16449         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
16450           assert((SplatIdx < InVec.getValueType().getVectorNumElements()) &&
16451                  "Unexpected shuffle index found!");
16452           BaseShAmt = InVec.getOperand(SplatIdx);
16453         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
16454            if (ConstantSDNode *C =
16455                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
16456              if (C->getZExtValue() == SplatIdx)
16457                BaseShAmt = InVec.getOperand(1);
16458            }
16459         }
16460
16461         if (!BaseShAmt)
16462           // Avoid introducing an extract element from a shuffle.
16463           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InVec,
16464                                   DAG.getIntPtrConstant(SplatIdx, dl));
16465       }
16466     }
16467
16468     if (BaseShAmt.getNode()) {
16469       assert(EltVT.bitsLE(MVT::i64) && "Unexpected element type!");
16470       if (EltVT != MVT::i64 && EltVT.bitsGT(MVT::i32))
16471         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, BaseShAmt);
16472       else if (EltVT.bitsLT(MVT::i32))
16473         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
16474
16475       switch (Op.getOpcode()) {
16476       default:
16477         llvm_unreachable("Unknown shift opcode!");
16478       case ISD::SHL:
16479         switch (VT.SimpleTy) {
16480         default: return SDValue();
16481         case MVT::v2i64:
16482         case MVT::v4i32:
16483         case MVT::v8i16:
16484         case MVT::v4i64:
16485         case MVT::v8i32:
16486         case MVT::v16i16:
16487         case MVT::v16i32:
16488         case MVT::v8i64:
16489           return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
16490         }
16491       case ISD::SRA:
16492         switch (VT.SimpleTy) {
16493         default: return SDValue();
16494         case MVT::v4i32:
16495         case MVT::v8i16:
16496         case MVT::v8i32:
16497         case MVT::v16i16:
16498         case MVT::v16i32:
16499         case MVT::v8i64:
16500           return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
16501         }
16502       case ISD::SRL:
16503         switch (VT.SimpleTy) {
16504         default: return SDValue();
16505         case MVT::v2i64:
16506         case MVT::v4i32:
16507         case MVT::v8i16:
16508         case MVT::v4i64:
16509         case MVT::v8i32:
16510         case MVT::v16i16:
16511         case MVT::v16i32:
16512         case MVT::v8i64:
16513           return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
16514         }
16515       }
16516     }
16517   }
16518
16519   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
16520   if (!Subtarget->is64Bit() && VT == MVT::v2i64  &&
16521       Amt.getOpcode() == ISD::BITCAST &&
16522       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
16523     Amt = Amt.getOperand(0);
16524     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
16525                      VT.getVectorNumElements();
16526     std::vector<SDValue> Vals(Ratio);
16527     for (unsigned i = 0; i != Ratio; ++i)
16528       Vals[i] = Amt.getOperand(i);
16529     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
16530       for (unsigned j = 0; j != Ratio; ++j)
16531         if (Vals[j] != Amt.getOperand(i + j))
16532           return SDValue();
16533     }
16534     switch (Op.getOpcode()) {
16535     default:
16536       llvm_unreachable("Unknown shift opcode!");
16537     case ISD::SHL:
16538       return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
16539     case ISD::SRL:
16540       return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
16541     case ISD::SRA:
16542       return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
16543     }
16544   }
16545
16546   return SDValue();
16547 }
16548
16549 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
16550                           SelectionDAG &DAG) {
16551   MVT VT = Op.getSimpleValueType();
16552   SDLoc dl(Op);
16553   SDValue R = Op.getOperand(0);
16554   SDValue Amt = Op.getOperand(1);
16555
16556   assert(VT.isVector() && "Custom lowering only for vector shifts!");
16557   assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
16558
16559   if (SDValue V = LowerScalarImmediateShift(Op, DAG, Subtarget))
16560     return V;
16561
16562   if (SDValue V = LowerScalarVariableShift(Op, DAG, Subtarget))
16563       return V;
16564
16565   if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
16566     return Op;
16567
16568   // AVX2 has VPSLLV/VPSRAV/VPSRLV.
16569   if (Subtarget->hasInt256()) {
16570     if (Op.getOpcode() == ISD::SRL &&
16571         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
16572          VT == MVT::v4i64 || VT == MVT::v8i32))
16573       return Op;
16574     if (Op.getOpcode() == ISD::SHL &&
16575         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
16576          VT == MVT::v4i64 || VT == MVT::v8i32))
16577       return Op;
16578     if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
16579       return Op;
16580   }
16581
16582   // 2i64 vector logical shifts can efficiently avoid scalarization - do the
16583   // shifts per-lane and then shuffle the partial results back together.
16584   if (VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) {
16585     // Splat the shift amounts so the scalar shifts above will catch it.
16586     SDValue Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {0, 0});
16587     SDValue Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {1, 1});
16588     SDValue R0 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt0);
16589     SDValue R1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt1);
16590     return DAG.getVectorShuffle(VT, dl, R0, R1, {0, 3});
16591   }
16592
16593   // If possible, lower this packed shift into a vector multiply instead of
16594   // expanding it into a sequence of scalar shifts.
16595   // Do this only if the vector shift count is a constant build_vector.
16596   if (Op.getOpcode() == ISD::SHL &&
16597       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
16598        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
16599       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
16600     SmallVector<SDValue, 8> Elts;
16601     EVT SVT = VT.getScalarType();
16602     unsigned SVTBits = SVT.getSizeInBits();
16603     const APInt &One = APInt(SVTBits, 1);
16604     unsigned NumElems = VT.getVectorNumElements();
16605
16606     for (unsigned i=0; i !=NumElems; ++i) {
16607       SDValue Op = Amt->getOperand(i);
16608       if (Op->getOpcode() == ISD::UNDEF) {
16609         Elts.push_back(Op);
16610         continue;
16611       }
16612
16613       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
16614       const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
16615       uint64_t ShAmt = C.getZExtValue();
16616       if (ShAmt >= SVTBits) {
16617         Elts.push_back(DAG.getUNDEF(SVT));
16618         continue;
16619       }
16620       Elts.push_back(DAG.getConstant(One.shl(ShAmt), dl, SVT));
16621     }
16622     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
16623     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
16624   }
16625
16626   // Lower SHL with variable shift amount.
16627   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
16628     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, dl, VT));
16629
16630     Op = DAG.getNode(ISD::ADD, dl, VT, Op,
16631                      DAG.getConstant(0x3f800000U, dl, VT));
16632     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
16633     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
16634     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
16635   }
16636
16637   // If possible, lower this shift as a sequence of two shifts by
16638   // constant plus a MOVSS/MOVSD instead of scalarizing it.
16639   // Example:
16640   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
16641   //
16642   // Could be rewritten as:
16643   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
16644   //
16645   // The advantage is that the two shifts from the example would be
16646   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
16647   // the vector shift into four scalar shifts plus four pairs of vector
16648   // insert/extract.
16649   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
16650       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
16651     unsigned TargetOpcode = X86ISD::MOVSS;
16652     bool CanBeSimplified;
16653     // The splat value for the first packed shift (the 'X' from the example).
16654     SDValue Amt1 = Amt->getOperand(0);
16655     // The splat value for the second packed shift (the 'Y' from the example).
16656     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
16657                                         Amt->getOperand(2);
16658
16659     // See if it is possible to replace this node with a sequence of
16660     // two shifts followed by a MOVSS/MOVSD
16661     if (VT == MVT::v4i32) {
16662       // Check if it is legal to use a MOVSS.
16663       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
16664                         Amt2 == Amt->getOperand(3);
16665       if (!CanBeSimplified) {
16666         // Otherwise, check if we can still simplify this node using a MOVSD.
16667         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
16668                           Amt->getOperand(2) == Amt->getOperand(3);
16669         TargetOpcode = X86ISD::MOVSD;
16670         Amt2 = Amt->getOperand(2);
16671       }
16672     } else {
16673       // Do similar checks for the case where the machine value type
16674       // is MVT::v8i16.
16675       CanBeSimplified = Amt1 == Amt->getOperand(1);
16676       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
16677         CanBeSimplified = Amt2 == Amt->getOperand(i);
16678
16679       if (!CanBeSimplified) {
16680         TargetOpcode = X86ISD::MOVSD;
16681         CanBeSimplified = true;
16682         Amt2 = Amt->getOperand(4);
16683         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
16684           CanBeSimplified = Amt1 == Amt->getOperand(i);
16685         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
16686           CanBeSimplified = Amt2 == Amt->getOperand(j);
16687       }
16688     }
16689
16690     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
16691         isa<ConstantSDNode>(Amt2)) {
16692       // Replace this node with two shifts followed by a MOVSS/MOVSD.
16693       EVT CastVT = MVT::v4i32;
16694       SDValue Splat1 =
16695         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), dl, VT);
16696       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
16697       SDValue Splat2 =
16698         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), dl, VT);
16699       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
16700       if (TargetOpcode == X86ISD::MOVSD)
16701         CastVT = MVT::v2i64;
16702       SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
16703       SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
16704       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
16705                                             BitCast1, DAG);
16706       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
16707     }
16708   }
16709
16710   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
16711     // Turn 'a' into a mask suitable for VSELECT: a = a << 5;
16712     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, dl, VT));
16713
16714     SDValue VSelM = DAG.getConstant(0x80, dl, VT);
16715     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16716     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16717
16718     // r = VSELECT(r, shl(r, 4), a);
16719     SDValue M = DAG.getNode(ISD::SHL, dl, VT, R, DAG.getConstant(4, dl, VT));
16720     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
16721
16722     // a += a
16723     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
16724     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16725     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16726
16727     // r = VSELECT(r, shl(r, 2), a);
16728     M = DAG.getNode(ISD::SHL, dl, VT, R, DAG.getConstant(2, dl, VT));
16729     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
16730
16731     // a += a
16732     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
16733     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16734     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16735
16736     // return VSELECT(r, r+r, a);
16737     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
16738                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
16739     return R;
16740   }
16741
16742   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
16743   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
16744   // solution better.
16745   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
16746     MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
16747     unsigned ExtOpc =
16748         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
16749     R = DAG.getNode(ExtOpc, dl, NewVT, R);
16750     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
16751     return DAG.getNode(ISD::TRUNCATE, dl, VT,
16752                        DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
16753   }
16754
16755   // Decompose 256-bit shifts into smaller 128-bit shifts.
16756   if (VT.is256BitVector()) {
16757     unsigned NumElems = VT.getVectorNumElements();
16758     MVT EltVT = VT.getVectorElementType();
16759     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16760
16761     // Extract the two vectors
16762     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
16763     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
16764
16765     // Recreate the shift amount vectors
16766     SDValue Amt1, Amt2;
16767     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
16768       // Constant shift amount
16769       SmallVector<SDValue, 8> Ops(Amt->op_begin(), Amt->op_begin() + NumElems);
16770       ArrayRef<SDValue> Amt1Csts = makeArrayRef(Ops).slice(0, NumElems / 2);
16771       ArrayRef<SDValue> Amt2Csts = makeArrayRef(Ops).slice(NumElems / 2);
16772
16773       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
16774       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
16775     } else {
16776       // Variable shift amount
16777       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
16778       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
16779     }
16780
16781     // Issue new vector shifts for the smaller types
16782     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
16783     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
16784
16785     // Concatenate the result back
16786     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
16787   }
16788
16789   return SDValue();
16790 }
16791
16792 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
16793   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
16794   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
16795   // looks for this combo and may remove the "setcc" instruction if the "setcc"
16796   // has only one use.
16797   SDNode *N = Op.getNode();
16798   SDValue LHS = N->getOperand(0);
16799   SDValue RHS = N->getOperand(1);
16800   unsigned BaseOp = 0;
16801   unsigned Cond = 0;
16802   SDLoc DL(Op);
16803   switch (Op.getOpcode()) {
16804   default: llvm_unreachable("Unknown ovf instruction!");
16805   case ISD::SADDO:
16806     // A subtract of one will be selected as a INC. Note that INC doesn't
16807     // set CF, so we can't do this for UADDO.
16808     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16809       if (C->isOne()) {
16810         BaseOp = X86ISD::INC;
16811         Cond = X86::COND_O;
16812         break;
16813       }
16814     BaseOp = X86ISD::ADD;
16815     Cond = X86::COND_O;
16816     break;
16817   case ISD::UADDO:
16818     BaseOp = X86ISD::ADD;
16819     Cond = X86::COND_B;
16820     break;
16821   case ISD::SSUBO:
16822     // A subtract of one will be selected as a DEC. Note that DEC doesn't
16823     // set CF, so we can't do this for USUBO.
16824     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16825       if (C->isOne()) {
16826         BaseOp = X86ISD::DEC;
16827         Cond = X86::COND_O;
16828         break;
16829       }
16830     BaseOp = X86ISD::SUB;
16831     Cond = X86::COND_O;
16832     break;
16833   case ISD::USUBO:
16834     BaseOp = X86ISD::SUB;
16835     Cond = X86::COND_B;
16836     break;
16837   case ISD::SMULO:
16838     BaseOp = N->getValueType(0) == MVT::i8 ? X86ISD::SMUL8 : X86ISD::SMUL;
16839     Cond = X86::COND_O;
16840     break;
16841   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
16842     if (N->getValueType(0) == MVT::i8) {
16843       BaseOp = X86ISD::UMUL8;
16844       Cond = X86::COND_O;
16845       break;
16846     }
16847     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
16848                                  MVT::i32);
16849     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
16850
16851     SDValue SetCC =
16852       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16853                   DAG.getConstant(X86::COND_O, DL, MVT::i32),
16854                   SDValue(Sum.getNode(), 2));
16855
16856     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
16857   }
16858   }
16859
16860   // Also sets EFLAGS.
16861   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
16862   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
16863
16864   SDValue SetCC =
16865     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
16866                 DAG.getConstant(Cond, DL, MVT::i32),
16867                 SDValue(Sum.getNode(), 1));
16868
16869   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
16870 }
16871
16872 /// Returns true if the operand type is exactly twice the native width, and
16873 /// the corresponding cmpxchg8b or cmpxchg16b instruction is available.
16874 /// Used to know whether to use cmpxchg8/16b when expanding atomic operations
16875 /// (otherwise we leave them alone to become __sync_fetch_and_... calls).
16876 bool X86TargetLowering::needsCmpXchgNb(const Type *MemType) const {
16877   unsigned OpWidth = MemType->getPrimitiveSizeInBits();
16878
16879   if (OpWidth == 64)
16880     return !Subtarget->is64Bit(); // FIXME this should be Subtarget.hasCmpxchg8b
16881   else if (OpWidth == 128)
16882     return Subtarget->hasCmpxchg16b();
16883   else
16884     return false;
16885 }
16886
16887 bool X86TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
16888   return needsCmpXchgNb(SI->getValueOperand()->getType());
16889 }
16890
16891 // Note: this turns large loads into lock cmpxchg8b/16b.
16892 // FIXME: On 32 bits x86, fild/movq might be faster than lock cmpxchg8b.
16893 bool X86TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
16894   auto PTy = cast<PointerType>(LI->getPointerOperand()->getType());
16895   return needsCmpXchgNb(PTy->getElementType());
16896 }
16897
16898 TargetLoweringBase::AtomicRMWExpansionKind
16899 X86TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
16900   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
16901   const Type *MemType = AI->getType();
16902
16903   // If the operand is too big, we must see if cmpxchg8/16b is available
16904   // and default to library calls otherwise.
16905   if (MemType->getPrimitiveSizeInBits() > NativeWidth) {
16906     return needsCmpXchgNb(MemType) ? AtomicRMWExpansionKind::CmpXChg
16907                                    : AtomicRMWExpansionKind::None;
16908   }
16909
16910   AtomicRMWInst::BinOp Op = AI->getOperation();
16911   switch (Op) {
16912   default:
16913     llvm_unreachable("Unknown atomic operation");
16914   case AtomicRMWInst::Xchg:
16915   case AtomicRMWInst::Add:
16916   case AtomicRMWInst::Sub:
16917     // It's better to use xadd, xsub or xchg for these in all cases.
16918     return AtomicRMWExpansionKind::None;
16919   case AtomicRMWInst::Or:
16920   case AtomicRMWInst::And:
16921   case AtomicRMWInst::Xor:
16922     // If the atomicrmw's result isn't actually used, we can just add a "lock"
16923     // prefix to a normal instruction for these operations.
16924     return !AI->use_empty() ? AtomicRMWExpansionKind::CmpXChg
16925                             : AtomicRMWExpansionKind::None;
16926   case AtomicRMWInst::Nand:
16927   case AtomicRMWInst::Max:
16928   case AtomicRMWInst::Min:
16929   case AtomicRMWInst::UMax:
16930   case AtomicRMWInst::UMin:
16931     // These always require a non-trivial set of data operations on x86. We must
16932     // use a cmpxchg loop.
16933     return AtomicRMWExpansionKind::CmpXChg;
16934   }
16935 }
16936
16937 static bool hasMFENCE(const X86Subtarget& Subtarget) {
16938   // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
16939   // no-sse2). There isn't any reason to disable it if the target processor
16940   // supports it.
16941   return Subtarget.hasSSE2() || Subtarget.is64Bit();
16942 }
16943
16944 LoadInst *
16945 X86TargetLowering::lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *AI) const {
16946   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
16947   const Type *MemType = AI->getType();
16948   // Accesses larger than the native width are turned into cmpxchg/libcalls, so
16949   // there is no benefit in turning such RMWs into loads, and it is actually
16950   // harmful as it introduces a mfence.
16951   if (MemType->getPrimitiveSizeInBits() > NativeWidth)
16952     return nullptr;
16953
16954   auto Builder = IRBuilder<>(AI);
16955   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
16956   auto SynchScope = AI->getSynchScope();
16957   // We must restrict the ordering to avoid generating loads with Release or
16958   // ReleaseAcquire orderings.
16959   auto Order = AtomicCmpXchgInst::getStrongestFailureOrdering(AI->getOrdering());
16960   auto Ptr = AI->getPointerOperand();
16961
16962   // Before the load we need a fence. Here is an example lifted from
16963   // http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf showing why a fence
16964   // is required:
16965   // Thread 0:
16966   //   x.store(1, relaxed);
16967   //   r1 = y.fetch_add(0, release);
16968   // Thread 1:
16969   //   y.fetch_add(42, acquire);
16970   //   r2 = x.load(relaxed);
16971   // r1 = r2 = 0 is impossible, but becomes possible if the idempotent rmw is
16972   // lowered to just a load without a fence. A mfence flushes the store buffer,
16973   // making the optimization clearly correct.
16974   // FIXME: it is required if isAtLeastRelease(Order) but it is not clear
16975   // otherwise, we might be able to be more agressive on relaxed idempotent
16976   // rmw. In practice, they do not look useful, so we don't try to be
16977   // especially clever.
16978   if (SynchScope == SingleThread) {
16979     // FIXME: we could just insert an X86ISD::MEMBARRIER here, except we are at
16980     // the IR level, so we must wrap it in an intrinsic.
16981     return nullptr;
16982   } else if (hasMFENCE(*Subtarget)) {
16983     Function *MFence = llvm::Intrinsic::getDeclaration(M,
16984             Intrinsic::x86_sse2_mfence);
16985     Builder.CreateCall(MFence);
16986   } else {
16987     // FIXME: it might make sense to use a locked operation here but on a
16988     // different cache-line to prevent cache-line bouncing. In practice it
16989     // is probably a small win, and x86 processors without mfence are rare
16990     // enough that we do not bother.
16991     return nullptr;
16992   }
16993
16994   // Finally we can emit the atomic load.
16995   LoadInst *Loaded = Builder.CreateAlignedLoad(Ptr,
16996           AI->getType()->getPrimitiveSizeInBits());
16997   Loaded->setAtomic(Order, SynchScope);
16998   AI->replaceAllUsesWith(Loaded);
16999   AI->eraseFromParent();
17000   return Loaded;
17001 }
17002
17003 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
17004                                  SelectionDAG &DAG) {
17005   SDLoc dl(Op);
17006   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
17007     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
17008   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
17009     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
17010
17011   // The only fence that needs an instruction is a sequentially-consistent
17012   // cross-thread fence.
17013   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
17014     if (hasMFENCE(*Subtarget))
17015       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
17016
17017     SDValue Chain = Op.getOperand(0);
17018     SDValue Zero = DAG.getConstant(0, dl, MVT::i32);
17019     SDValue Ops[] = {
17020       DAG.getRegister(X86::ESP, MVT::i32),     // Base
17021       DAG.getTargetConstant(1, dl, MVT::i8),   // Scale
17022       DAG.getRegister(0, MVT::i32),            // Index
17023       DAG.getTargetConstant(0, dl, MVT::i32),  // Disp
17024       DAG.getRegister(0, MVT::i32),            // Segment.
17025       Zero,
17026       Chain
17027     };
17028     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
17029     return SDValue(Res, 0);
17030   }
17031
17032   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
17033   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
17034 }
17035
17036 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
17037                              SelectionDAG &DAG) {
17038   MVT T = Op.getSimpleValueType();
17039   SDLoc DL(Op);
17040   unsigned Reg = 0;
17041   unsigned size = 0;
17042   switch(T.SimpleTy) {
17043   default: llvm_unreachable("Invalid value type!");
17044   case MVT::i8:  Reg = X86::AL;  size = 1; break;
17045   case MVT::i16: Reg = X86::AX;  size = 2; break;
17046   case MVT::i32: Reg = X86::EAX; size = 4; break;
17047   case MVT::i64:
17048     assert(Subtarget->is64Bit() && "Node not type legal!");
17049     Reg = X86::RAX; size = 8;
17050     break;
17051   }
17052   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
17053                                   Op.getOperand(2), SDValue());
17054   SDValue Ops[] = { cpIn.getValue(0),
17055                     Op.getOperand(1),
17056                     Op.getOperand(3),
17057                     DAG.getTargetConstant(size, DL, MVT::i8),
17058                     cpIn.getValue(1) };
17059   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
17060   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
17061   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
17062                                            Ops, T, MMO);
17063
17064   SDValue cpOut =
17065     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
17066   SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
17067                                       MVT::i32, cpOut.getValue(2));
17068   SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
17069                                 DAG.getConstant(X86::COND_E, DL, MVT::i8),
17070                                 EFLAGS);
17071
17072   DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
17073   DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
17074   DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
17075   return SDValue();
17076 }
17077
17078 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
17079                             SelectionDAG &DAG) {
17080   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
17081   MVT DstVT = Op.getSimpleValueType();
17082
17083   if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
17084     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
17085     if (DstVT != MVT::f64)
17086       // This conversion needs to be expanded.
17087       return SDValue();
17088
17089     SDValue InVec = Op->getOperand(0);
17090     SDLoc dl(Op);
17091     unsigned NumElts = SrcVT.getVectorNumElements();
17092     EVT SVT = SrcVT.getVectorElementType();
17093
17094     // Widen the vector in input in the case of MVT::v2i32.
17095     // Example: from MVT::v2i32 to MVT::v4i32.
17096     SmallVector<SDValue, 16> Elts;
17097     for (unsigned i = 0, e = NumElts; i != e; ++i)
17098       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
17099                                  DAG.getIntPtrConstant(i, dl)));
17100
17101     // Explicitly mark the extra elements as Undef.
17102     Elts.append(NumElts, DAG.getUNDEF(SVT));
17103
17104     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
17105     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
17106     SDValue ToV2F64 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, BV);
17107     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
17108                        DAG.getIntPtrConstant(0, dl));
17109   }
17110
17111   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
17112          Subtarget->hasMMX() && "Unexpected custom BITCAST");
17113   assert((DstVT == MVT::i64 ||
17114           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
17115          "Unexpected custom BITCAST");
17116   // i64 <=> MMX conversions are Legal.
17117   if (SrcVT==MVT::i64 && DstVT.isVector())
17118     return Op;
17119   if (DstVT==MVT::i64 && SrcVT.isVector())
17120     return Op;
17121   // MMX <=> MMX conversions are Legal.
17122   if (SrcVT.isVector() && DstVT.isVector())
17123     return Op;
17124   // All other conversions need to be expanded.
17125   return SDValue();
17126 }
17127
17128 static SDValue LowerCTPOP(SDValue Op, const X86Subtarget *Subtarget,
17129                           SelectionDAG &DAG) {
17130   SDNode *Node = Op.getNode();
17131   SDLoc dl(Node);
17132
17133   Op = Op.getOperand(0);
17134   EVT VT = Op.getValueType();
17135   assert((VT.is128BitVector() || VT.is256BitVector()) &&
17136          "CTPOP lowering only implemented for 128/256-bit wide vector types");
17137
17138   unsigned NumElts = VT.getVectorNumElements();
17139   EVT EltVT = VT.getVectorElementType();
17140   unsigned Len = EltVT.getSizeInBits();
17141
17142   // This is the vectorized version of the "best" algorithm from
17143   // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
17144   // with a minor tweak to use a series of adds + shifts instead of vector
17145   // multiplications. Implemented for the v2i64, v4i64, v4i32, v8i32 types:
17146   //
17147   //  v2i64, v4i64, v4i32 => Only profitable w/ popcnt disabled
17148   //  v8i32 => Always profitable
17149   //
17150   // FIXME: There a couple of possible improvements:
17151   //
17152   // 1) Support for i8 and i16 vectors (needs measurements if popcnt enabled).
17153   // 2) Use strategies from http://wm.ite.pl/articles/sse-popcount.html
17154   //
17155   assert(EltVT.isInteger() && (Len == 32 || Len == 64) && Len % 8 == 0 &&
17156          "CTPOP not implemented for this vector element type.");
17157
17158   // X86 canonicalize ANDs to vXi64, generate the appropriate bitcasts to avoid
17159   // extra legalization.
17160   bool NeedsBitcast = EltVT == MVT::i32;
17161   MVT BitcastVT = VT.is256BitVector() ? MVT::v4i64 : MVT::v2i64;
17162
17163   SDValue Cst55 = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x55)), dl,
17164                                   EltVT);
17165   SDValue Cst33 = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x33)), dl,
17166                                   EltVT);
17167   SDValue Cst0F = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x0F)), dl,
17168                                   EltVT);
17169
17170   // v = v - ((v >> 1) & 0x55555555...)
17171   SmallVector<SDValue, 8> Ones(NumElts, DAG.getConstant(1, dl, EltVT));
17172   SDValue OnesV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ones);
17173   SDValue Srl = DAG.getNode(ISD::SRL, dl, VT, Op, OnesV);
17174   if (NeedsBitcast)
17175     Srl = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Srl);
17176
17177   SmallVector<SDValue, 8> Mask55(NumElts, Cst55);
17178   SDValue M55 = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Mask55);
17179   if (NeedsBitcast)
17180     M55 = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M55);
17181
17182   SDValue And = DAG.getNode(ISD::AND, dl, Srl.getValueType(), Srl, M55);
17183   if (VT != And.getValueType())
17184     And = DAG.getNode(ISD::BITCAST, dl, VT, And);
17185   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, Op, And);
17186
17187   // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
17188   SmallVector<SDValue, 8> Mask33(NumElts, Cst33);
17189   SDValue M33 = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Mask33);
17190   SmallVector<SDValue, 8> Twos(NumElts, DAG.getConstant(2, dl, EltVT));
17191   SDValue TwosV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Twos);
17192
17193   Srl = DAG.getNode(ISD::SRL, dl, VT, Sub, TwosV);
17194   if (NeedsBitcast) {
17195     Srl = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Srl);
17196     M33 = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M33);
17197     Sub = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Sub);
17198   }
17199
17200   SDValue AndRHS = DAG.getNode(ISD::AND, dl, M33.getValueType(), Srl, M33);
17201   SDValue AndLHS = DAG.getNode(ISD::AND, dl, M33.getValueType(), Sub, M33);
17202   if (VT != AndRHS.getValueType()) {
17203     AndRHS = DAG.getNode(ISD::BITCAST, dl, VT, AndRHS);
17204     AndLHS = DAG.getNode(ISD::BITCAST, dl, VT, AndLHS);
17205   }
17206   SDValue Add = DAG.getNode(ISD::ADD, dl, VT, AndLHS, AndRHS);
17207
17208   // v = (v + (v >> 4)) & 0x0F0F0F0F...
17209   SmallVector<SDValue, 8> Fours(NumElts, DAG.getConstant(4, dl, EltVT));
17210   SDValue FoursV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Fours);
17211   Srl = DAG.getNode(ISD::SRL, dl, VT, Add, FoursV);
17212   Add = DAG.getNode(ISD::ADD, dl, VT, Add, Srl);
17213
17214   SmallVector<SDValue, 8> Mask0F(NumElts, Cst0F);
17215   SDValue M0F = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Mask0F);
17216   if (NeedsBitcast) {
17217     Add = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Add);
17218     M0F = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M0F);
17219   }
17220   And = DAG.getNode(ISD::AND, dl, M0F.getValueType(), Add, M0F);
17221   if (VT != And.getValueType())
17222     And = DAG.getNode(ISD::BITCAST, dl, VT, And);
17223
17224   // The algorithm mentioned above uses:
17225   //    v = (v * 0x01010101...) >> (Len - 8)
17226   //
17227   // Change it to use vector adds + vector shifts which yield faster results on
17228   // Haswell than using vector integer multiplication.
17229   //
17230   // For i32 elements:
17231   //    v = v + (v >> 8)
17232   //    v = v + (v >> 16)
17233   //
17234   // For i64 elements:
17235   //    v = v + (v >> 8)
17236   //    v = v + (v >> 16)
17237   //    v = v + (v >> 32)
17238   //
17239   Add = And;
17240   SmallVector<SDValue, 8> Csts;
17241   for (unsigned i = 8; i <= Len/2; i *= 2) {
17242     Csts.assign(NumElts, DAG.getConstant(i, dl, EltVT));
17243     SDValue CstsV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Csts);
17244     Srl = DAG.getNode(ISD::SRL, dl, VT, Add, CstsV);
17245     Add = DAG.getNode(ISD::ADD, dl, VT, Add, Srl);
17246     Csts.clear();
17247   }
17248
17249   // The result is on the least significant 6-bits on i32 and 7-bits on i64.
17250   SDValue Cst3F = DAG.getConstant(APInt(Len, Len == 32 ? 0x3F : 0x7F), dl,
17251                                   EltVT);
17252   SmallVector<SDValue, 8> Cst3FV(NumElts, Cst3F);
17253   SDValue M3F = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Cst3FV);
17254   if (NeedsBitcast) {
17255     Add = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Add);
17256     M3F = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M3F);
17257   }
17258   And = DAG.getNode(ISD::AND, dl, M3F.getValueType(), Add, M3F);
17259   if (VT != And.getValueType())
17260     And = DAG.getNode(ISD::BITCAST, dl, VT, And);
17261
17262   return And;
17263 }
17264
17265 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
17266   SDNode *Node = Op.getNode();
17267   SDLoc dl(Node);
17268   EVT T = Node->getValueType(0);
17269   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
17270                               DAG.getConstant(0, dl, T), Node->getOperand(2));
17271   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
17272                        cast<AtomicSDNode>(Node)->getMemoryVT(),
17273                        Node->getOperand(0),
17274                        Node->getOperand(1), negOp,
17275                        cast<AtomicSDNode>(Node)->getMemOperand(),
17276                        cast<AtomicSDNode>(Node)->getOrdering(),
17277                        cast<AtomicSDNode>(Node)->getSynchScope());
17278 }
17279
17280 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
17281   SDNode *Node = Op.getNode();
17282   SDLoc dl(Node);
17283   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
17284
17285   // Convert seq_cst store -> xchg
17286   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
17287   // FIXME: On 32-bit, store -> fist or movq would be more efficient
17288   //        (The only way to get a 16-byte store is cmpxchg16b)
17289   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
17290   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
17291       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
17292     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
17293                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
17294                                  Node->getOperand(0),
17295                                  Node->getOperand(1), Node->getOperand(2),
17296                                  cast<AtomicSDNode>(Node)->getMemOperand(),
17297                                  cast<AtomicSDNode>(Node)->getOrdering(),
17298                                  cast<AtomicSDNode>(Node)->getSynchScope());
17299     return Swap.getValue(1);
17300   }
17301   // Other atomic stores have a simple pattern.
17302   return Op;
17303 }
17304
17305 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
17306   EVT VT = Op.getNode()->getSimpleValueType(0);
17307
17308   // Let legalize expand this if it isn't a legal type yet.
17309   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
17310     return SDValue();
17311
17312   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
17313
17314   unsigned Opc;
17315   bool ExtraOp = false;
17316   switch (Op.getOpcode()) {
17317   default: llvm_unreachable("Invalid code");
17318   case ISD::ADDC: Opc = X86ISD::ADD; break;
17319   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
17320   case ISD::SUBC: Opc = X86ISD::SUB; break;
17321   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
17322   }
17323
17324   if (!ExtraOp)
17325     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
17326                        Op.getOperand(1));
17327   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
17328                      Op.getOperand(1), Op.getOperand(2));
17329 }
17330
17331 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
17332                             SelectionDAG &DAG) {
17333   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
17334
17335   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
17336   // which returns the values as { float, float } (in XMM0) or
17337   // { double, double } (which is returned in XMM0, XMM1).
17338   SDLoc dl(Op);
17339   SDValue Arg = Op.getOperand(0);
17340   EVT ArgVT = Arg.getValueType();
17341   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
17342
17343   TargetLowering::ArgListTy Args;
17344   TargetLowering::ArgListEntry Entry;
17345
17346   Entry.Node = Arg;
17347   Entry.Ty = ArgTy;
17348   Entry.isSExt = false;
17349   Entry.isZExt = false;
17350   Args.push_back(Entry);
17351
17352   bool isF64 = ArgVT == MVT::f64;
17353   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
17354   // the small struct {f32, f32} is returned in (eax, edx). For f64,
17355   // the results are returned via SRet in memory.
17356   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
17357   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17358   SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
17359
17360   Type *RetTy = isF64
17361     ? (Type*)StructType::get(ArgTy, ArgTy, nullptr)
17362     : (Type*)VectorType::get(ArgTy, 4);
17363
17364   TargetLowering::CallLoweringInfo CLI(DAG);
17365   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
17366     .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
17367
17368   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
17369
17370   if (isF64)
17371     // Returned in xmm0 and xmm1.
17372     return CallResult.first;
17373
17374   // Returned in bits 0:31 and 32:64 xmm0.
17375   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
17376                                CallResult.first, DAG.getIntPtrConstant(0, dl));
17377   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
17378                                CallResult.first, DAG.getIntPtrConstant(1, dl));
17379   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
17380   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
17381 }
17382
17383 static SDValue LowerMSCATTER(SDValue Op, const X86Subtarget *Subtarget,
17384                              SelectionDAG &DAG) {
17385   assert(Subtarget->hasAVX512() &&
17386          "MGATHER/MSCATTER are supported on AVX-512 arch only");
17387
17388   MaskedScatterSDNode *N = cast<MaskedScatterSDNode>(Op.getNode());
17389   EVT VT = N->getValue().getValueType();
17390   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported scatter op");
17391   SDLoc dl(Op);
17392
17393   // X86 scatter kills mask register, so its type should be added to
17394   // the list of return values
17395   if (N->getNumValues() == 1) {
17396     SDValue Index = N->getIndex();
17397     if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
17398         !Index.getValueType().is512BitVector())
17399       Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
17400
17401     SDVTList VTs = DAG.getVTList(N->getMask().getValueType(), MVT::Other);
17402     SDValue Ops[] = { N->getOperand(0), N->getOperand(1),  N->getOperand(2),
17403                       N->getOperand(3), Index };
17404
17405     SDValue NewScatter = DAG.getMaskedScatter(VTs, VT, dl, Ops, N->getMemOperand());
17406     DAG.ReplaceAllUsesWith(Op, SDValue(NewScatter.getNode(), 1));
17407     return SDValue(NewScatter.getNode(), 0);
17408   }
17409   return Op;
17410 }
17411
17412 static SDValue LowerMGATHER(SDValue Op, const X86Subtarget *Subtarget,
17413                             SelectionDAG &DAG) {
17414   assert(Subtarget->hasAVX512() &&
17415          "MGATHER/MSCATTER are supported on AVX-512 arch only");
17416
17417   MaskedGatherSDNode *N = cast<MaskedGatherSDNode>(Op.getNode());
17418   EVT VT = Op.getValueType();
17419   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported gather op");
17420   SDLoc dl(Op);
17421
17422   SDValue Index = N->getIndex();
17423   if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
17424       !Index.getValueType().is512BitVector()) {
17425     Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
17426     SDValue Ops[] = { N->getOperand(0), N->getOperand(1),  N->getOperand(2),
17427                       N->getOperand(3), Index };
17428     DAG.UpdateNodeOperands(N, Ops);
17429   }
17430   return Op;
17431 }
17432
17433 SDValue X86TargetLowering::LowerGC_TRANSITION_START(SDValue Op,
17434                                                     SelectionDAG &DAG) const {
17435   // TODO: Eventually, the lowering of these nodes should be informed by or
17436   // deferred to the GC strategy for the function in which they appear. For
17437   // now, however, they must be lowered to something. Since they are logically
17438   // no-ops in the case of a null GC strategy (or a GC strategy which does not
17439   // require special handling for these nodes), lower them as literal NOOPs for
17440   // the time being.
17441   SmallVector<SDValue, 2> Ops;
17442
17443   Ops.push_back(Op.getOperand(0));
17444   if (Op->getGluedNode())
17445     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
17446
17447   SDLoc OpDL(Op);
17448   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
17449   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
17450
17451   return NOOP;
17452 }
17453
17454 SDValue X86TargetLowering::LowerGC_TRANSITION_END(SDValue Op,
17455                                                   SelectionDAG &DAG) const {
17456   // TODO: Eventually, the lowering of these nodes should be informed by or
17457   // deferred to the GC strategy for the function in which they appear. For
17458   // now, however, they must be lowered to something. Since they are logically
17459   // no-ops in the case of a null GC strategy (or a GC strategy which does not
17460   // require special handling for these nodes), lower them as literal NOOPs for
17461   // the time being.
17462   SmallVector<SDValue, 2> Ops;
17463
17464   Ops.push_back(Op.getOperand(0));
17465   if (Op->getGluedNode())
17466     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
17467
17468   SDLoc OpDL(Op);
17469   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
17470   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
17471
17472   return NOOP;
17473 }
17474
17475 /// LowerOperation - Provide custom lowering hooks for some operations.
17476 ///
17477 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
17478   switch (Op.getOpcode()) {
17479   default: llvm_unreachable("Should not custom lower this!");
17480   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
17481   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
17482     return LowerCMP_SWAP(Op, Subtarget, DAG);
17483   case ISD::CTPOP:              return LowerCTPOP(Op, Subtarget, DAG);
17484   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
17485   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
17486   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
17487   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, Subtarget, DAG);
17488   case ISD::VECTOR_SHUFFLE:     return lowerVectorShuffle(Op, Subtarget, DAG);
17489   case ISD::VSELECT:            return LowerVSELECT(Op, DAG);
17490   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
17491   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
17492   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
17493   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
17494   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
17495   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
17496   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
17497   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
17498   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
17499   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
17500   case ISD::SHL_PARTS:
17501   case ISD::SRA_PARTS:
17502   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
17503   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
17504   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
17505   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
17506   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
17507   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
17508   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
17509   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
17510   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
17511   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
17512   case ISD::LOAD:               return LowerExtendedLoad(Op, Subtarget, DAG);
17513   case ISD::FABS:
17514   case ISD::FNEG:               return LowerFABSorFNEG(Op, DAG);
17515   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
17516   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
17517   case ISD::SETCC:              return LowerSETCC(Op, DAG);
17518   case ISD::SELECT:             return LowerSELECT(Op, DAG);
17519   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
17520   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
17521   case ISD::VASTART:            return LowerVASTART(Op, DAG);
17522   case ISD::VAARG:              return LowerVAARG(Op, DAG);
17523   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
17524   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, Subtarget, DAG);
17525   case ISD::INTRINSIC_VOID:
17526   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
17527   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
17528   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
17529   case ISD::FRAME_TO_ARGS_OFFSET:
17530                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
17531   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
17532   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
17533   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
17534   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
17535   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
17536   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
17537   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
17538   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
17539   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
17540   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
17541   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
17542   case ISD::UMUL_LOHI:
17543   case ISD::SMUL_LOHI:          return LowerMUL_LOHI(Op, Subtarget, DAG);
17544   case ISD::SRA:
17545   case ISD::SRL:
17546   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
17547   case ISD::SADDO:
17548   case ISD::UADDO:
17549   case ISD::SSUBO:
17550   case ISD::USUBO:
17551   case ISD::SMULO:
17552   case ISD::UMULO:              return LowerXALUO(Op, DAG);
17553   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
17554   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
17555   case ISD::ADDC:
17556   case ISD::ADDE:
17557   case ISD::SUBC:
17558   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
17559   case ISD::ADD:                return LowerADD(Op, DAG);
17560   case ISD::SUB:                return LowerSUB(Op, DAG);
17561   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
17562   case ISD::MGATHER:            return LowerMGATHER(Op, Subtarget, DAG);
17563   case ISD::MSCATTER:           return LowerMSCATTER(Op, Subtarget, DAG);
17564   case ISD::GC_TRANSITION_START:
17565                                 return LowerGC_TRANSITION_START(Op, DAG);
17566   case ISD::GC_TRANSITION_END:  return LowerGC_TRANSITION_END(Op, DAG);
17567   }
17568 }
17569
17570 /// ReplaceNodeResults - Replace a node with an illegal result type
17571 /// with a new node built out of custom code.
17572 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
17573                                            SmallVectorImpl<SDValue>&Results,
17574                                            SelectionDAG &DAG) const {
17575   SDLoc dl(N);
17576   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17577   switch (N->getOpcode()) {
17578   default:
17579     llvm_unreachable("Do not know how to custom type legalize this operation!");
17580   // We might have generated v2f32 FMIN/FMAX operations. Widen them to v4f32.
17581   case X86ISD::FMINC:
17582   case X86ISD::FMIN:
17583   case X86ISD::FMAXC:
17584   case X86ISD::FMAX: {
17585     EVT VT = N->getValueType(0);
17586     if (VT != MVT::v2f32)
17587       llvm_unreachable("Unexpected type (!= v2f32) on FMIN/FMAX.");
17588     SDValue UNDEF = DAG.getUNDEF(VT);
17589     SDValue LHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
17590                               N->getOperand(0), UNDEF);
17591     SDValue RHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
17592                               N->getOperand(1), UNDEF);
17593     Results.push_back(DAG.getNode(N->getOpcode(), dl, MVT::v4f32, LHS, RHS));
17594     return;
17595   }
17596   case ISD::SIGN_EXTEND_INREG:
17597   case ISD::ADDC:
17598   case ISD::ADDE:
17599   case ISD::SUBC:
17600   case ISD::SUBE:
17601     // We don't want to expand or promote these.
17602     return;
17603   case ISD::SDIV:
17604   case ISD::UDIV:
17605   case ISD::SREM:
17606   case ISD::UREM:
17607   case ISD::SDIVREM:
17608   case ISD::UDIVREM: {
17609     SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
17610     Results.push_back(V);
17611     return;
17612   }
17613   case ISD::FP_TO_SINT:
17614   case ISD::FP_TO_UINT: {
17615     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
17616
17617     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
17618       return;
17619
17620     std::pair<SDValue,SDValue> Vals =
17621         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
17622     SDValue FIST = Vals.first, StackSlot = Vals.second;
17623     if (FIST.getNode()) {
17624       EVT VT = N->getValueType(0);
17625       // Return a load from the stack slot.
17626       if (StackSlot.getNode())
17627         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
17628                                       MachinePointerInfo(),
17629                                       false, false, false, 0));
17630       else
17631         Results.push_back(FIST);
17632     }
17633     return;
17634   }
17635   case ISD::UINT_TO_FP: {
17636     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
17637     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
17638         N->getValueType(0) != MVT::v2f32)
17639       return;
17640     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
17641                                  N->getOperand(0));
17642     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
17643                                      MVT::f64);
17644     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
17645     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
17646                              DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
17647     Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
17648     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
17649     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
17650     return;
17651   }
17652   case ISD::FP_ROUND: {
17653     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
17654         return;
17655     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
17656     Results.push_back(V);
17657     return;
17658   }
17659   case ISD::INTRINSIC_W_CHAIN: {
17660     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
17661     switch (IntNo) {
17662     default : llvm_unreachable("Do not know how to custom type "
17663                                "legalize this intrinsic operation!");
17664     case Intrinsic::x86_rdtsc:
17665       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
17666                                      Results);
17667     case Intrinsic::x86_rdtscp:
17668       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
17669                                      Results);
17670     case Intrinsic::x86_rdpmc:
17671       return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
17672     }
17673   }
17674   case ISD::READCYCLECOUNTER: {
17675     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
17676                                    Results);
17677   }
17678   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
17679     EVT T = N->getValueType(0);
17680     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
17681     bool Regs64bit = T == MVT::i128;
17682     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
17683     SDValue cpInL, cpInH;
17684     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
17685                         DAG.getConstant(0, dl, HalfT));
17686     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
17687                         DAG.getConstant(1, dl, HalfT));
17688     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
17689                              Regs64bit ? X86::RAX : X86::EAX,
17690                              cpInL, SDValue());
17691     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
17692                              Regs64bit ? X86::RDX : X86::EDX,
17693                              cpInH, cpInL.getValue(1));
17694     SDValue swapInL, swapInH;
17695     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
17696                           DAG.getConstant(0, dl, HalfT));
17697     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
17698                           DAG.getConstant(1, dl, HalfT));
17699     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
17700                                Regs64bit ? X86::RBX : X86::EBX,
17701                                swapInL, cpInH.getValue(1));
17702     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
17703                                Regs64bit ? X86::RCX : X86::ECX,
17704                                swapInH, swapInL.getValue(1));
17705     SDValue Ops[] = { swapInH.getValue(0),
17706                       N->getOperand(1),
17707                       swapInH.getValue(1) };
17708     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
17709     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
17710     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
17711                                   X86ISD::LCMPXCHG8_DAG;
17712     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
17713     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
17714                                         Regs64bit ? X86::RAX : X86::EAX,
17715                                         HalfT, Result.getValue(1));
17716     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
17717                                         Regs64bit ? X86::RDX : X86::EDX,
17718                                         HalfT, cpOutL.getValue(2));
17719     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
17720
17721     SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
17722                                         MVT::i32, cpOutH.getValue(2));
17723     SDValue Success =
17724         DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17725                     DAG.getConstant(X86::COND_E, dl, MVT::i8), EFLAGS);
17726     Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
17727
17728     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
17729     Results.push_back(Success);
17730     Results.push_back(EFLAGS.getValue(1));
17731     return;
17732   }
17733   case ISD::ATOMIC_SWAP:
17734   case ISD::ATOMIC_LOAD_ADD:
17735   case ISD::ATOMIC_LOAD_SUB:
17736   case ISD::ATOMIC_LOAD_AND:
17737   case ISD::ATOMIC_LOAD_OR:
17738   case ISD::ATOMIC_LOAD_XOR:
17739   case ISD::ATOMIC_LOAD_NAND:
17740   case ISD::ATOMIC_LOAD_MIN:
17741   case ISD::ATOMIC_LOAD_MAX:
17742   case ISD::ATOMIC_LOAD_UMIN:
17743   case ISD::ATOMIC_LOAD_UMAX:
17744   case ISD::ATOMIC_LOAD: {
17745     // Delegate to generic TypeLegalization. Situations we can really handle
17746     // should have already been dealt with by AtomicExpandPass.cpp.
17747     break;
17748   }
17749   case ISD::BITCAST: {
17750     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
17751     EVT DstVT = N->getValueType(0);
17752     EVT SrcVT = N->getOperand(0)->getValueType(0);
17753
17754     if (SrcVT != MVT::f64 ||
17755         (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
17756       return;
17757
17758     unsigned NumElts = DstVT.getVectorNumElements();
17759     EVT SVT = DstVT.getVectorElementType();
17760     EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
17761     SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
17762                                    MVT::v2f64, N->getOperand(0));
17763     SDValue ToVecInt = DAG.getNode(ISD::BITCAST, dl, WiderVT, Expanded);
17764
17765     if (ExperimentalVectorWideningLegalization) {
17766       // If we are legalizing vectors by widening, we already have the desired
17767       // legal vector type, just return it.
17768       Results.push_back(ToVecInt);
17769       return;
17770     }
17771
17772     SmallVector<SDValue, 8> Elts;
17773     for (unsigned i = 0, e = NumElts; i != e; ++i)
17774       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
17775                                    ToVecInt, DAG.getIntPtrConstant(i, dl)));
17776
17777     Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
17778   }
17779   }
17780 }
17781
17782 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
17783   switch ((X86ISD::NodeType)Opcode) {
17784   case X86ISD::FIRST_NUMBER:       break;
17785   case X86ISD::BSF:                return "X86ISD::BSF";
17786   case X86ISD::BSR:                return "X86ISD::BSR";
17787   case X86ISD::SHLD:               return "X86ISD::SHLD";
17788   case X86ISD::SHRD:               return "X86ISD::SHRD";
17789   case X86ISD::FAND:               return "X86ISD::FAND";
17790   case X86ISD::FANDN:              return "X86ISD::FANDN";
17791   case X86ISD::FOR:                return "X86ISD::FOR";
17792   case X86ISD::FXOR:               return "X86ISD::FXOR";
17793   case X86ISD::FSRL:               return "X86ISD::FSRL";
17794   case X86ISD::FILD:               return "X86ISD::FILD";
17795   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
17796   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
17797   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
17798   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
17799   case X86ISD::FLD:                return "X86ISD::FLD";
17800   case X86ISD::FST:                return "X86ISD::FST";
17801   case X86ISD::CALL:               return "X86ISD::CALL";
17802   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
17803   case X86ISD::RDTSCP_DAG:         return "X86ISD::RDTSCP_DAG";
17804   case X86ISD::RDPMC_DAG:          return "X86ISD::RDPMC_DAG";
17805   case X86ISD::BT:                 return "X86ISD::BT";
17806   case X86ISD::CMP:                return "X86ISD::CMP";
17807   case X86ISD::COMI:               return "X86ISD::COMI";
17808   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
17809   case X86ISD::CMPM:               return "X86ISD::CMPM";
17810   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
17811   case X86ISD::CMPM_RND:           return "X86ISD::CMPM_RND";
17812   case X86ISD::SETCC:              return "X86ISD::SETCC";
17813   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
17814   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
17815   case X86ISD::FGETSIGNx86:        return "X86ISD::FGETSIGNx86";
17816   case X86ISD::CMOV:               return "X86ISD::CMOV";
17817   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
17818   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
17819   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
17820   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
17821   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
17822   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
17823   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
17824   case X86ISD::MOVDQ2Q:            return "X86ISD::MOVDQ2Q";
17825   case X86ISD::MMX_MOVD2W:         return "X86ISD::MMX_MOVD2W";
17826   case X86ISD::MMX_MOVW2D:         return "X86ISD::MMX_MOVW2D";
17827   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
17828   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
17829   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
17830   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
17831   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
17832   case X86ISD::MMX_PINSRW:         return "X86ISD::MMX_PINSRW";
17833   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
17834   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
17835   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
17836   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
17837   case X86ISD::SHRUNKBLEND:        return "X86ISD::SHRUNKBLEND";
17838   case X86ISD::ADDUS:              return "X86ISD::ADDUS";
17839   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
17840   case X86ISD::HADD:               return "X86ISD::HADD";
17841   case X86ISD::HSUB:               return "X86ISD::HSUB";
17842   case X86ISD::FHADD:              return "X86ISD::FHADD";
17843   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
17844   case X86ISD::UMAX:               return "X86ISD::UMAX";
17845   case X86ISD::UMIN:               return "X86ISD::UMIN";
17846   case X86ISD::SMAX:               return "X86ISD::SMAX";
17847   case X86ISD::SMIN:               return "X86ISD::SMIN";
17848   case X86ISD::FMAX:               return "X86ISD::FMAX";
17849   case X86ISD::FMIN:               return "X86ISD::FMIN";
17850   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
17851   case X86ISD::FMINC:              return "X86ISD::FMINC";
17852   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
17853   case X86ISD::FRCP:               return "X86ISD::FRCP";
17854   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
17855   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
17856   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
17857   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
17858   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
17859   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
17860   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
17861   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
17862   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
17863   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
17864   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
17865   case X86ISD::LCMPXCHG16_DAG:     return "X86ISD::LCMPXCHG16_DAG";
17866   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
17867   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
17868   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
17869   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
17870   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
17871   case X86ISD::VTRUNCM:            return "X86ISD::VTRUNCM";
17872   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
17873   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
17874   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
17875   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
17876   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
17877   case X86ISD::VSHL:               return "X86ISD::VSHL";
17878   case X86ISD::VSRL:               return "X86ISD::VSRL";
17879   case X86ISD::VSRA:               return "X86ISD::VSRA";
17880   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
17881   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
17882   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
17883   case X86ISD::CMPP:               return "X86ISD::CMPP";
17884   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
17885   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
17886   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
17887   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
17888   case X86ISD::ADD:                return "X86ISD::ADD";
17889   case X86ISD::SUB:                return "X86ISD::SUB";
17890   case X86ISD::ADC:                return "X86ISD::ADC";
17891   case X86ISD::SBB:                return "X86ISD::SBB";
17892   case X86ISD::SMUL:               return "X86ISD::SMUL";
17893   case X86ISD::UMUL:               return "X86ISD::UMUL";
17894   case X86ISD::SMUL8:              return "X86ISD::SMUL8";
17895   case X86ISD::UMUL8:              return "X86ISD::UMUL8";
17896   case X86ISD::SDIVREM8_SEXT_HREG: return "X86ISD::SDIVREM8_SEXT_HREG";
17897   case X86ISD::UDIVREM8_ZEXT_HREG: return "X86ISD::UDIVREM8_ZEXT_HREG";
17898   case X86ISD::INC:                return "X86ISD::INC";
17899   case X86ISD::DEC:                return "X86ISD::DEC";
17900   case X86ISD::OR:                 return "X86ISD::OR";
17901   case X86ISD::XOR:                return "X86ISD::XOR";
17902   case X86ISD::AND:                return "X86ISD::AND";
17903   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
17904   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
17905   case X86ISD::PTEST:              return "X86ISD::PTEST";
17906   case X86ISD::TESTP:              return "X86ISD::TESTP";
17907   case X86ISD::TESTM:              return "X86ISD::TESTM";
17908   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
17909   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
17910   case X86ISD::PACKSS:             return "X86ISD::PACKSS";
17911   case X86ISD::PACKUS:             return "X86ISD::PACKUS";
17912   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
17913   case X86ISD::VALIGN:             return "X86ISD::VALIGN";
17914   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
17915   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
17916   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
17917   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
17918   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
17919   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
17920   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
17921   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
17922   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
17923   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
17924   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
17925   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
17926   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
17927   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
17928   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
17929   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
17930   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
17931   case X86ISD::VEXTRACT:           return "X86ISD::VEXTRACT";
17932   case X86ISD::VPERMILPV:          return "X86ISD::VPERMILPV";
17933   case X86ISD::VPERMILPI:          return "X86ISD::VPERMILPI";
17934   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
17935   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
17936   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
17937   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
17938   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
17939   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
17940   case X86ISD::PMULDQ:             return "X86ISD::PMULDQ";
17941   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
17942   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
17943   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
17944   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
17945   case X86ISD::MFENCE:             return "X86ISD::MFENCE";
17946   case X86ISD::SFENCE:             return "X86ISD::SFENCE";
17947   case X86ISD::LFENCE:             return "X86ISD::LFENCE";
17948   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
17949   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
17950   case X86ISD::SAHF:               return "X86ISD::SAHF";
17951   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
17952   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
17953   case X86ISD::FMADD:              return "X86ISD::FMADD";
17954   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
17955   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
17956   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
17957   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
17958   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
17959   case X86ISD::FMADD_RND:          return "X86ISD::FMADD_RND";
17960   case X86ISD::FNMADD_RND:         return "X86ISD::FNMADD_RND";
17961   case X86ISD::FMSUB_RND:          return "X86ISD::FMSUB_RND";
17962   case X86ISD::FNMSUB_RND:         return "X86ISD::FNMSUB_RND";
17963   case X86ISD::FMADDSUB_RND:       return "X86ISD::FMADDSUB_RND";
17964   case X86ISD::FMSUBADD_RND:       return "X86ISD::FMSUBADD_RND";
17965   case X86ISD::RNDSCALE:           return "X86ISD::RNDSCALE";
17966   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
17967   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
17968   case X86ISD::XTEST:              return "X86ISD::XTEST";
17969   case X86ISD::COMPRESS:           return "X86ISD::COMPRESS";
17970   case X86ISD::EXPAND:             return "X86ISD::EXPAND";
17971   case X86ISD::SELECT:             return "X86ISD::SELECT";
17972   case X86ISD::ADDSUB:             return "X86ISD::ADDSUB";
17973   case X86ISD::RCP28:              return "X86ISD::RCP28";
17974   case X86ISD::EXP2:               return "X86ISD::EXP2";
17975   case X86ISD::RSQRT28:            return "X86ISD::RSQRT28";
17976   case X86ISD::FADD_RND:           return "X86ISD::FADD_RND";
17977   case X86ISD::FSUB_RND:           return "X86ISD::FSUB_RND";
17978   case X86ISD::FMUL_RND:           return "X86ISD::FMUL_RND";
17979   case X86ISD::FDIV_RND:           return "X86ISD::FDIV_RND";
17980   case X86ISD::ADDS:               return "X86ISD::ADDS";
17981   case X86ISD::SUBS:               return "X86ISD::SUBS";
17982   }
17983   return nullptr;
17984 }
17985
17986 // isLegalAddressingMode - Return true if the addressing mode represented
17987 // by AM is legal for this target, for a load/store of the specified type.
17988 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
17989                                               Type *Ty) const {
17990   // X86 supports extremely general addressing modes.
17991   CodeModel::Model M = getTargetMachine().getCodeModel();
17992   Reloc::Model R = getTargetMachine().getRelocationModel();
17993
17994   // X86 allows a sign-extended 32-bit immediate field as a displacement.
17995   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
17996     return false;
17997
17998   if (AM.BaseGV) {
17999     unsigned GVFlags =
18000       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
18001
18002     // If a reference to this global requires an extra load, we can't fold it.
18003     if (isGlobalStubReference(GVFlags))
18004       return false;
18005
18006     // If BaseGV requires a register for the PIC base, we cannot also have a
18007     // BaseReg specified.
18008     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
18009       return false;
18010
18011     // If lower 4G is not available, then we must use rip-relative addressing.
18012     if ((M != CodeModel::Small || R != Reloc::Static) &&
18013         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
18014       return false;
18015   }
18016
18017   switch (AM.Scale) {
18018   case 0:
18019   case 1:
18020   case 2:
18021   case 4:
18022   case 8:
18023     // These scales always work.
18024     break;
18025   case 3:
18026   case 5:
18027   case 9:
18028     // These scales are formed with basereg+scalereg.  Only accept if there is
18029     // no basereg yet.
18030     if (AM.HasBaseReg)
18031       return false;
18032     break;
18033   default:  // Other stuff never works.
18034     return false;
18035   }
18036
18037   return true;
18038 }
18039
18040 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
18041   unsigned Bits = Ty->getScalarSizeInBits();
18042
18043   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
18044   // particularly cheaper than those without.
18045   if (Bits == 8)
18046     return false;
18047
18048   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
18049   // variable shifts just as cheap as scalar ones.
18050   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
18051     return false;
18052
18053   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
18054   // fully general vector.
18055   return true;
18056 }
18057
18058 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
18059   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
18060     return false;
18061   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
18062   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
18063   return NumBits1 > NumBits2;
18064 }
18065
18066 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
18067   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
18068     return false;
18069
18070   if (!isTypeLegal(EVT::getEVT(Ty1)))
18071     return false;
18072
18073   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
18074
18075   // Assuming the caller doesn't have a zeroext or signext return parameter,
18076   // truncation all the way down to i1 is valid.
18077   return true;
18078 }
18079
18080 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
18081   return isInt<32>(Imm);
18082 }
18083
18084 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
18085   // Can also use sub to handle negated immediates.
18086   return isInt<32>(Imm);
18087 }
18088
18089 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
18090   if (!VT1.isInteger() || !VT2.isInteger())
18091     return false;
18092   unsigned NumBits1 = VT1.getSizeInBits();
18093   unsigned NumBits2 = VT2.getSizeInBits();
18094   return NumBits1 > NumBits2;
18095 }
18096
18097 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
18098   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
18099   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
18100 }
18101
18102 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
18103   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
18104   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
18105 }
18106
18107 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
18108   EVT VT1 = Val.getValueType();
18109   if (isZExtFree(VT1, VT2))
18110     return true;
18111
18112   if (Val.getOpcode() != ISD::LOAD)
18113     return false;
18114
18115   if (!VT1.isSimple() || !VT1.isInteger() ||
18116       !VT2.isSimple() || !VT2.isInteger())
18117     return false;
18118
18119   switch (VT1.getSimpleVT().SimpleTy) {
18120   default: break;
18121   case MVT::i8:
18122   case MVT::i16:
18123   case MVT::i32:
18124     // X86 has 8, 16, and 32-bit zero-extending loads.
18125     return true;
18126   }
18127
18128   return false;
18129 }
18130
18131 bool X86TargetLowering::isVectorLoadExtDesirable(SDValue) const { return true; }
18132
18133 bool
18134 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
18135   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
18136     return false;
18137
18138   VT = VT.getScalarType();
18139
18140   if (!VT.isSimple())
18141     return false;
18142
18143   switch (VT.getSimpleVT().SimpleTy) {
18144   case MVT::f32:
18145   case MVT::f64:
18146     return true;
18147   default:
18148     break;
18149   }
18150
18151   return false;
18152 }
18153
18154 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
18155   // i16 instructions are longer (0x66 prefix) and potentially slower.
18156   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
18157 }
18158
18159 /// isShuffleMaskLegal - Targets can use this to indicate that they only
18160 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
18161 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
18162 /// are assumed to be legal.
18163 bool
18164 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
18165                                       EVT VT) const {
18166   if (!VT.isSimple())
18167     return false;
18168
18169   // Very little shuffling can be done for 64-bit vectors right now.
18170   if (VT.getSizeInBits() == 64)
18171     return false;
18172
18173   // We only care that the types being shuffled are legal. The lowering can
18174   // handle any possible shuffle mask that results.
18175   return isTypeLegal(VT.getSimpleVT());
18176 }
18177
18178 bool
18179 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
18180                                           EVT VT) const {
18181   // Just delegate to the generic legality, clear masks aren't special.
18182   return isShuffleMaskLegal(Mask, VT);
18183 }
18184
18185 //===----------------------------------------------------------------------===//
18186 //                           X86 Scheduler Hooks
18187 //===----------------------------------------------------------------------===//
18188
18189 /// Utility function to emit xbegin specifying the start of an RTM region.
18190 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
18191                                      const TargetInstrInfo *TII) {
18192   DebugLoc DL = MI->getDebugLoc();
18193
18194   const BasicBlock *BB = MBB->getBasicBlock();
18195   MachineFunction::iterator I = MBB;
18196   ++I;
18197
18198   // For the v = xbegin(), we generate
18199   //
18200   // thisMBB:
18201   //  xbegin sinkMBB
18202   //
18203   // mainMBB:
18204   //  eax = -1
18205   //
18206   // sinkMBB:
18207   //  v = eax
18208
18209   MachineBasicBlock *thisMBB = MBB;
18210   MachineFunction *MF = MBB->getParent();
18211   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
18212   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
18213   MF->insert(I, mainMBB);
18214   MF->insert(I, sinkMBB);
18215
18216   // Transfer the remainder of BB and its successor edges to sinkMBB.
18217   sinkMBB->splice(sinkMBB->begin(), MBB,
18218                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
18219   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
18220
18221   // thisMBB:
18222   //  xbegin sinkMBB
18223   //  # fallthrough to mainMBB
18224   //  # abortion to sinkMBB
18225   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
18226   thisMBB->addSuccessor(mainMBB);
18227   thisMBB->addSuccessor(sinkMBB);
18228
18229   // mainMBB:
18230   //  EAX = -1
18231   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
18232   mainMBB->addSuccessor(sinkMBB);
18233
18234   // sinkMBB:
18235   // EAX is live into the sinkMBB
18236   sinkMBB->addLiveIn(X86::EAX);
18237   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
18238           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
18239     .addReg(X86::EAX);
18240
18241   MI->eraseFromParent();
18242   return sinkMBB;
18243 }
18244
18245 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
18246 // or XMM0_V32I8 in AVX all of this code can be replaced with that
18247 // in the .td file.
18248 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
18249                                        const TargetInstrInfo *TII) {
18250   unsigned Opc;
18251   switch (MI->getOpcode()) {
18252   default: llvm_unreachable("illegal opcode!");
18253   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
18254   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
18255   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
18256   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
18257   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
18258   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
18259   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
18260   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
18261   }
18262
18263   DebugLoc dl = MI->getDebugLoc();
18264   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
18265
18266   unsigned NumArgs = MI->getNumOperands();
18267   for (unsigned i = 1; i < NumArgs; ++i) {
18268     MachineOperand &Op = MI->getOperand(i);
18269     if (!(Op.isReg() && Op.isImplicit()))
18270       MIB.addOperand(Op);
18271   }
18272   if (MI->hasOneMemOperand())
18273     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
18274
18275   BuildMI(*BB, MI, dl,
18276     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
18277     .addReg(X86::XMM0);
18278
18279   MI->eraseFromParent();
18280   return BB;
18281 }
18282
18283 // FIXME: Custom handling because TableGen doesn't support multiple implicit
18284 // defs in an instruction pattern
18285 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
18286                                        const TargetInstrInfo *TII) {
18287   unsigned Opc;
18288   switch (MI->getOpcode()) {
18289   default: llvm_unreachable("illegal opcode!");
18290   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
18291   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
18292   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
18293   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
18294   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
18295   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
18296   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
18297   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
18298   }
18299
18300   DebugLoc dl = MI->getDebugLoc();
18301   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
18302
18303   unsigned NumArgs = MI->getNumOperands(); // remove the results
18304   for (unsigned i = 1; i < NumArgs; ++i) {
18305     MachineOperand &Op = MI->getOperand(i);
18306     if (!(Op.isReg() && Op.isImplicit()))
18307       MIB.addOperand(Op);
18308   }
18309   if (MI->hasOneMemOperand())
18310     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
18311
18312   BuildMI(*BB, MI, dl,
18313     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
18314     .addReg(X86::ECX);
18315
18316   MI->eraseFromParent();
18317   return BB;
18318 }
18319
18320 static MachineBasicBlock *EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
18321                                       const X86Subtarget *Subtarget) {
18322   DebugLoc dl = MI->getDebugLoc();
18323   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18324   // Address into RAX/EAX, other two args into ECX, EDX.
18325   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
18326   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
18327   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
18328   for (int i = 0; i < X86::AddrNumOperands; ++i)
18329     MIB.addOperand(MI->getOperand(i));
18330
18331   unsigned ValOps = X86::AddrNumOperands;
18332   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
18333     .addReg(MI->getOperand(ValOps).getReg());
18334   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
18335     .addReg(MI->getOperand(ValOps+1).getReg());
18336
18337   // The instruction doesn't actually take any operands though.
18338   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
18339
18340   MI->eraseFromParent(); // The pseudo is gone now.
18341   return BB;
18342 }
18343
18344 MachineBasicBlock *
18345 X86TargetLowering::EmitVAARG64WithCustomInserter(MachineInstr *MI,
18346                                                  MachineBasicBlock *MBB) const {
18347   // Emit va_arg instruction on X86-64.
18348
18349   // Operands to this pseudo-instruction:
18350   // 0  ) Output        : destination address (reg)
18351   // 1-5) Input         : va_list address (addr, i64mem)
18352   // 6  ) ArgSize       : Size (in bytes) of vararg type
18353   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
18354   // 8  ) Align         : Alignment of type
18355   // 9  ) EFLAGS (implicit-def)
18356
18357   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
18358   static_assert(X86::AddrNumOperands == 5,
18359                 "VAARG_64 assumes 5 address operands");
18360
18361   unsigned DestReg = MI->getOperand(0).getReg();
18362   MachineOperand &Base = MI->getOperand(1);
18363   MachineOperand &Scale = MI->getOperand(2);
18364   MachineOperand &Index = MI->getOperand(3);
18365   MachineOperand &Disp = MI->getOperand(4);
18366   MachineOperand &Segment = MI->getOperand(5);
18367   unsigned ArgSize = MI->getOperand(6).getImm();
18368   unsigned ArgMode = MI->getOperand(7).getImm();
18369   unsigned Align = MI->getOperand(8).getImm();
18370
18371   // Memory Reference
18372   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
18373   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
18374   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
18375
18376   // Machine Information
18377   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18378   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
18379   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
18380   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
18381   DebugLoc DL = MI->getDebugLoc();
18382
18383   // struct va_list {
18384   //   i32   gp_offset
18385   //   i32   fp_offset
18386   //   i64   overflow_area (address)
18387   //   i64   reg_save_area (address)
18388   // }
18389   // sizeof(va_list) = 24
18390   // alignment(va_list) = 8
18391
18392   unsigned TotalNumIntRegs = 6;
18393   unsigned TotalNumXMMRegs = 8;
18394   bool UseGPOffset = (ArgMode == 1);
18395   bool UseFPOffset = (ArgMode == 2);
18396   unsigned MaxOffset = TotalNumIntRegs * 8 +
18397                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
18398
18399   /* Align ArgSize to a multiple of 8 */
18400   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
18401   bool NeedsAlign = (Align > 8);
18402
18403   MachineBasicBlock *thisMBB = MBB;
18404   MachineBasicBlock *overflowMBB;
18405   MachineBasicBlock *offsetMBB;
18406   MachineBasicBlock *endMBB;
18407
18408   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
18409   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
18410   unsigned OffsetReg = 0;
18411
18412   if (!UseGPOffset && !UseFPOffset) {
18413     // If we only pull from the overflow region, we don't create a branch.
18414     // We don't need to alter control flow.
18415     OffsetDestReg = 0; // unused
18416     OverflowDestReg = DestReg;
18417
18418     offsetMBB = nullptr;
18419     overflowMBB = thisMBB;
18420     endMBB = thisMBB;
18421   } else {
18422     // First emit code to check if gp_offset (or fp_offset) is below the bound.
18423     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
18424     // If not, pull from overflow_area. (branch to overflowMBB)
18425     //
18426     //       thisMBB
18427     //         |     .
18428     //         |        .
18429     //     offsetMBB   overflowMBB
18430     //         |        .
18431     //         |     .
18432     //        endMBB
18433
18434     // Registers for the PHI in endMBB
18435     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
18436     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
18437
18438     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
18439     MachineFunction *MF = MBB->getParent();
18440     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18441     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18442     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18443
18444     MachineFunction::iterator MBBIter = MBB;
18445     ++MBBIter;
18446
18447     // Insert the new basic blocks
18448     MF->insert(MBBIter, offsetMBB);
18449     MF->insert(MBBIter, overflowMBB);
18450     MF->insert(MBBIter, endMBB);
18451
18452     // Transfer the remainder of MBB and its successor edges to endMBB.
18453     endMBB->splice(endMBB->begin(), thisMBB,
18454                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
18455     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
18456
18457     // Make offsetMBB and overflowMBB successors of thisMBB
18458     thisMBB->addSuccessor(offsetMBB);
18459     thisMBB->addSuccessor(overflowMBB);
18460
18461     // endMBB is a successor of both offsetMBB and overflowMBB
18462     offsetMBB->addSuccessor(endMBB);
18463     overflowMBB->addSuccessor(endMBB);
18464
18465     // Load the offset value into a register
18466     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
18467     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
18468       .addOperand(Base)
18469       .addOperand(Scale)
18470       .addOperand(Index)
18471       .addDisp(Disp, UseFPOffset ? 4 : 0)
18472       .addOperand(Segment)
18473       .setMemRefs(MMOBegin, MMOEnd);
18474
18475     // Check if there is enough room left to pull this argument.
18476     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
18477       .addReg(OffsetReg)
18478       .addImm(MaxOffset + 8 - ArgSizeA8);
18479
18480     // Branch to "overflowMBB" if offset >= max
18481     // Fall through to "offsetMBB" otherwise
18482     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
18483       .addMBB(overflowMBB);
18484   }
18485
18486   // In offsetMBB, emit code to use the reg_save_area.
18487   if (offsetMBB) {
18488     assert(OffsetReg != 0);
18489
18490     // Read the reg_save_area address.
18491     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
18492     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
18493       .addOperand(Base)
18494       .addOperand(Scale)
18495       .addOperand(Index)
18496       .addDisp(Disp, 16)
18497       .addOperand(Segment)
18498       .setMemRefs(MMOBegin, MMOEnd);
18499
18500     // Zero-extend the offset
18501     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
18502       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
18503         .addImm(0)
18504         .addReg(OffsetReg)
18505         .addImm(X86::sub_32bit);
18506
18507     // Add the offset to the reg_save_area to get the final address.
18508     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
18509       .addReg(OffsetReg64)
18510       .addReg(RegSaveReg);
18511
18512     // Compute the offset for the next argument
18513     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
18514     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
18515       .addReg(OffsetReg)
18516       .addImm(UseFPOffset ? 16 : 8);
18517
18518     // Store it back into the va_list.
18519     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
18520       .addOperand(Base)
18521       .addOperand(Scale)
18522       .addOperand(Index)
18523       .addDisp(Disp, UseFPOffset ? 4 : 0)
18524       .addOperand(Segment)
18525       .addReg(NextOffsetReg)
18526       .setMemRefs(MMOBegin, MMOEnd);
18527
18528     // Jump to endMBB
18529     BuildMI(offsetMBB, DL, TII->get(X86::JMP_1))
18530       .addMBB(endMBB);
18531   }
18532
18533   //
18534   // Emit code to use overflow area
18535   //
18536
18537   // Load the overflow_area address into a register.
18538   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
18539   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
18540     .addOperand(Base)
18541     .addOperand(Scale)
18542     .addOperand(Index)
18543     .addDisp(Disp, 8)
18544     .addOperand(Segment)
18545     .setMemRefs(MMOBegin, MMOEnd);
18546
18547   // If we need to align it, do so. Otherwise, just copy the address
18548   // to OverflowDestReg.
18549   if (NeedsAlign) {
18550     // Align the overflow address
18551     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
18552     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
18553
18554     // aligned_addr = (addr + (align-1)) & ~(align-1)
18555     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
18556       .addReg(OverflowAddrReg)
18557       .addImm(Align-1);
18558
18559     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
18560       .addReg(TmpReg)
18561       .addImm(~(uint64_t)(Align-1));
18562   } else {
18563     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
18564       .addReg(OverflowAddrReg);
18565   }
18566
18567   // Compute the next overflow address after this argument.
18568   // (the overflow address should be kept 8-byte aligned)
18569   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
18570   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
18571     .addReg(OverflowDestReg)
18572     .addImm(ArgSizeA8);
18573
18574   // Store the new overflow address.
18575   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
18576     .addOperand(Base)
18577     .addOperand(Scale)
18578     .addOperand(Index)
18579     .addDisp(Disp, 8)
18580     .addOperand(Segment)
18581     .addReg(NextAddrReg)
18582     .setMemRefs(MMOBegin, MMOEnd);
18583
18584   // If we branched, emit the PHI to the front of endMBB.
18585   if (offsetMBB) {
18586     BuildMI(*endMBB, endMBB->begin(), DL,
18587             TII->get(X86::PHI), DestReg)
18588       .addReg(OffsetDestReg).addMBB(offsetMBB)
18589       .addReg(OverflowDestReg).addMBB(overflowMBB);
18590   }
18591
18592   // Erase the pseudo instruction
18593   MI->eraseFromParent();
18594
18595   return endMBB;
18596 }
18597
18598 MachineBasicBlock *
18599 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
18600                                                  MachineInstr *MI,
18601                                                  MachineBasicBlock *MBB) const {
18602   // Emit code to save XMM registers to the stack. The ABI says that the
18603   // number of registers to save is given in %al, so it's theoretically
18604   // possible to do an indirect jump trick to avoid saving all of them,
18605   // however this code takes a simpler approach and just executes all
18606   // of the stores if %al is non-zero. It's less code, and it's probably
18607   // easier on the hardware branch predictor, and stores aren't all that
18608   // expensive anyway.
18609
18610   // Create the new basic blocks. One block contains all the XMM stores,
18611   // and one block is the final destination regardless of whether any
18612   // stores were performed.
18613   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
18614   MachineFunction *F = MBB->getParent();
18615   MachineFunction::iterator MBBIter = MBB;
18616   ++MBBIter;
18617   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
18618   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
18619   F->insert(MBBIter, XMMSaveMBB);
18620   F->insert(MBBIter, EndMBB);
18621
18622   // Transfer the remainder of MBB and its successor edges to EndMBB.
18623   EndMBB->splice(EndMBB->begin(), MBB,
18624                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
18625   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
18626
18627   // The original block will now fall through to the XMM save block.
18628   MBB->addSuccessor(XMMSaveMBB);
18629   // The XMMSaveMBB will fall through to the end block.
18630   XMMSaveMBB->addSuccessor(EndMBB);
18631
18632   // Now add the instructions.
18633   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18634   DebugLoc DL = MI->getDebugLoc();
18635
18636   unsigned CountReg = MI->getOperand(0).getReg();
18637   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
18638   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
18639
18640   if (!Subtarget->isTargetWin64()) {
18641     // If %al is 0, branch around the XMM save block.
18642     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
18643     BuildMI(MBB, DL, TII->get(X86::JE_1)).addMBB(EndMBB);
18644     MBB->addSuccessor(EndMBB);
18645   }
18646
18647   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
18648   // that was just emitted, but clearly shouldn't be "saved".
18649   assert((MI->getNumOperands() <= 3 ||
18650           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
18651           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
18652          && "Expected last argument to be EFLAGS");
18653   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
18654   // In the XMM save block, save all the XMM argument registers.
18655   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
18656     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
18657     MachineMemOperand *MMO =
18658       F->getMachineMemOperand(
18659           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
18660         MachineMemOperand::MOStore,
18661         /*Size=*/16, /*Align=*/16);
18662     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
18663       .addFrameIndex(RegSaveFrameIndex)
18664       .addImm(/*Scale=*/1)
18665       .addReg(/*IndexReg=*/0)
18666       .addImm(/*Disp=*/Offset)
18667       .addReg(/*Segment=*/0)
18668       .addReg(MI->getOperand(i).getReg())
18669       .addMemOperand(MMO);
18670   }
18671
18672   MI->eraseFromParent();   // The pseudo instruction is gone now.
18673
18674   return EndMBB;
18675 }
18676
18677 // The EFLAGS operand of SelectItr might be missing a kill marker
18678 // because there were multiple uses of EFLAGS, and ISel didn't know
18679 // which to mark. Figure out whether SelectItr should have had a
18680 // kill marker, and set it if it should. Returns the correct kill
18681 // marker value.
18682 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
18683                                      MachineBasicBlock* BB,
18684                                      const TargetRegisterInfo* TRI) {
18685   // Scan forward through BB for a use/def of EFLAGS.
18686   MachineBasicBlock::iterator miI(std::next(SelectItr));
18687   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
18688     const MachineInstr& mi = *miI;
18689     if (mi.readsRegister(X86::EFLAGS))
18690       return false;
18691     if (mi.definesRegister(X86::EFLAGS))
18692       break; // Should have kill-flag - update below.
18693   }
18694
18695   // If we hit the end of the block, check whether EFLAGS is live into a
18696   // successor.
18697   if (miI == BB->end()) {
18698     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
18699                                           sEnd = BB->succ_end();
18700          sItr != sEnd; ++sItr) {
18701       MachineBasicBlock* succ = *sItr;
18702       if (succ->isLiveIn(X86::EFLAGS))
18703         return false;
18704     }
18705   }
18706
18707   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
18708   // out. SelectMI should have a kill flag on EFLAGS.
18709   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
18710   return true;
18711 }
18712
18713 MachineBasicBlock *
18714 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
18715                                      MachineBasicBlock *BB) const {
18716   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18717   DebugLoc DL = MI->getDebugLoc();
18718
18719   // To "insert" a SELECT_CC instruction, we actually have to insert the
18720   // diamond control-flow pattern.  The incoming instruction knows the
18721   // destination vreg to set, the condition code register to branch on, the
18722   // true/false values to select between, and a branch opcode to use.
18723   const BasicBlock *LLVM_BB = BB->getBasicBlock();
18724   MachineFunction::iterator It = BB;
18725   ++It;
18726
18727   //  thisMBB:
18728   //  ...
18729   //   TrueVal = ...
18730   //   cmpTY ccX, r1, r2
18731   //   bCC copy1MBB
18732   //   fallthrough --> copy0MBB
18733   MachineBasicBlock *thisMBB = BB;
18734   MachineFunction *F = BB->getParent();
18735
18736   // We also lower double CMOVs:
18737   //   (CMOV (CMOV F, T, cc1), T, cc2)
18738   // to two successives branches.  For that, we look for another CMOV as the
18739   // following instruction.
18740   //
18741   // Without this, we would add a PHI between the two jumps, which ends up
18742   // creating a few copies all around. For instance, for
18743   //
18744   //    (sitofp (zext (fcmp une)))
18745   //
18746   // we would generate:
18747   //
18748   //         ucomiss %xmm1, %xmm0
18749   //         movss  <1.0f>, %xmm0
18750   //         movaps  %xmm0, %xmm1
18751   //         jne     .LBB5_2
18752   //         xorps   %xmm1, %xmm1
18753   // .LBB5_2:
18754   //         jp      .LBB5_4
18755   //         movaps  %xmm1, %xmm0
18756   // .LBB5_4:
18757   //         retq
18758   //
18759   // because this custom-inserter would have generated:
18760   //
18761   //   A
18762   //   | \
18763   //   |  B
18764   //   | /
18765   //   C
18766   //   | \
18767   //   |  D
18768   //   | /
18769   //   E
18770   //
18771   // A: X = ...; Y = ...
18772   // B: empty
18773   // C: Z = PHI [X, A], [Y, B]
18774   // D: empty
18775   // E: PHI [X, C], [Z, D]
18776   //
18777   // If we lower both CMOVs in a single step, we can instead generate:
18778   //
18779   //   A
18780   //   | \
18781   //   |  C
18782   //   | /|
18783   //   |/ |
18784   //   |  |
18785   //   |  D
18786   //   | /
18787   //   E
18788   //
18789   // A: X = ...; Y = ...
18790   // D: empty
18791   // E: PHI [X, A], [X, C], [Y, D]
18792   //
18793   // Which, in our sitofp/fcmp example, gives us something like:
18794   //
18795   //         ucomiss %xmm1, %xmm0
18796   //         movss  <1.0f>, %xmm0
18797   //         jne     .LBB5_4
18798   //         jp      .LBB5_4
18799   //         xorps   %xmm0, %xmm0
18800   // .LBB5_4:
18801   //         retq
18802   //
18803   MachineInstr *NextCMOV = nullptr;
18804   MachineBasicBlock::iterator NextMIIt =
18805       std::next(MachineBasicBlock::iterator(MI));
18806   if (NextMIIt != BB->end() && NextMIIt->getOpcode() == MI->getOpcode() &&
18807       NextMIIt->getOperand(2).getReg() == MI->getOperand(2).getReg() &&
18808       NextMIIt->getOperand(1).getReg() == MI->getOperand(0).getReg())
18809     NextCMOV = &*NextMIIt;
18810
18811   MachineBasicBlock *jcc1MBB = nullptr;
18812
18813   // If we have a double CMOV, we lower it to two successive branches to
18814   // the same block.  EFLAGS is used by both, so mark it as live in the second.
18815   if (NextCMOV) {
18816     jcc1MBB = F->CreateMachineBasicBlock(LLVM_BB);
18817     F->insert(It, jcc1MBB);
18818     jcc1MBB->addLiveIn(X86::EFLAGS);
18819   }
18820
18821   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
18822   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
18823   F->insert(It, copy0MBB);
18824   F->insert(It, sinkMBB);
18825
18826   // If the EFLAGS register isn't dead in the terminator, then claim that it's
18827   // live into the sink and copy blocks.
18828   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
18829
18830   MachineInstr *LastEFLAGSUser = NextCMOV ? NextCMOV : MI;
18831   if (!LastEFLAGSUser->killsRegister(X86::EFLAGS) &&
18832       !checkAndUpdateEFLAGSKill(LastEFLAGSUser, BB, TRI)) {
18833     copy0MBB->addLiveIn(X86::EFLAGS);
18834     sinkMBB->addLiveIn(X86::EFLAGS);
18835   }
18836
18837   // Transfer the remainder of BB and its successor edges to sinkMBB.
18838   sinkMBB->splice(sinkMBB->begin(), BB,
18839                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
18840   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
18841
18842   // Add the true and fallthrough blocks as its successors.
18843   if (NextCMOV) {
18844     // The fallthrough block may be jcc1MBB, if we have a double CMOV.
18845     BB->addSuccessor(jcc1MBB);
18846
18847     // In that case, jcc1MBB will itself fallthrough the copy0MBB, and
18848     // jump to the sinkMBB.
18849     jcc1MBB->addSuccessor(copy0MBB);
18850     jcc1MBB->addSuccessor(sinkMBB);
18851   } else {
18852     BB->addSuccessor(copy0MBB);
18853   }
18854
18855   // The true block target of the first (or only) branch is always sinkMBB.
18856   BB->addSuccessor(sinkMBB);
18857
18858   // Create the conditional branch instruction.
18859   unsigned Opc =
18860     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
18861   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
18862
18863   if (NextCMOV) {
18864     unsigned Opc2 = X86::GetCondBranchFromCond(
18865         (X86::CondCode)NextCMOV->getOperand(3).getImm());
18866     BuildMI(jcc1MBB, DL, TII->get(Opc2)).addMBB(sinkMBB);
18867   }
18868
18869   //  copy0MBB:
18870   //   %FalseValue = ...
18871   //   # fallthrough to sinkMBB
18872   copy0MBB->addSuccessor(sinkMBB);
18873
18874   //  sinkMBB:
18875   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
18876   //  ...
18877   MachineInstrBuilder MIB =
18878       BuildMI(*sinkMBB, sinkMBB->begin(), DL, TII->get(X86::PHI),
18879               MI->getOperand(0).getReg())
18880           .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
18881           .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
18882
18883   // If we have a double CMOV, the second Jcc provides the same incoming
18884   // value as the first Jcc (the True operand of the SELECT_CC/CMOV nodes).
18885   if (NextCMOV) {
18886     MIB.addReg(MI->getOperand(2).getReg()).addMBB(jcc1MBB);
18887     // Copy the PHI result to the register defined by the second CMOV.
18888     BuildMI(*sinkMBB, std::next(MachineBasicBlock::iterator(MIB.getInstr())),
18889             DL, TII->get(TargetOpcode::COPY), NextCMOV->getOperand(0).getReg())
18890         .addReg(MI->getOperand(0).getReg());
18891     NextCMOV->eraseFromParent();
18892   }
18893
18894   MI->eraseFromParent();   // The pseudo instruction is gone now.
18895   return sinkMBB;
18896 }
18897
18898 MachineBasicBlock *
18899 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI,
18900                                         MachineBasicBlock *BB) const {
18901   MachineFunction *MF = BB->getParent();
18902   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18903   DebugLoc DL = MI->getDebugLoc();
18904   const BasicBlock *LLVM_BB = BB->getBasicBlock();
18905
18906   assert(MF->shouldSplitStack());
18907
18908   const bool Is64Bit = Subtarget->is64Bit();
18909   const bool IsLP64 = Subtarget->isTarget64BitLP64();
18910
18911   const unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
18912   const unsigned TlsOffset = IsLP64 ? 0x70 : Is64Bit ? 0x40 : 0x30;
18913
18914   // BB:
18915   //  ... [Till the alloca]
18916   // If stacklet is not large enough, jump to mallocMBB
18917   //
18918   // bumpMBB:
18919   //  Allocate by subtracting from RSP
18920   //  Jump to continueMBB
18921   //
18922   // mallocMBB:
18923   //  Allocate by call to runtime
18924   //
18925   // continueMBB:
18926   //  ...
18927   //  [rest of original BB]
18928   //
18929
18930   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18931   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18932   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18933
18934   MachineRegisterInfo &MRI = MF->getRegInfo();
18935   const TargetRegisterClass *AddrRegClass =
18936     getRegClassFor(getPointerTy());
18937
18938   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
18939     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
18940     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
18941     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
18942     sizeVReg = MI->getOperand(1).getReg(),
18943     physSPReg = IsLP64 || Subtarget->isTargetNaCl64() ? X86::RSP : X86::ESP;
18944
18945   MachineFunction::iterator MBBIter = BB;
18946   ++MBBIter;
18947
18948   MF->insert(MBBIter, bumpMBB);
18949   MF->insert(MBBIter, mallocMBB);
18950   MF->insert(MBBIter, continueMBB);
18951
18952   continueMBB->splice(continueMBB->begin(), BB,
18953                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
18954   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
18955
18956   // Add code to the main basic block to check if the stack limit has been hit,
18957   // and if so, jump to mallocMBB otherwise to bumpMBB.
18958   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
18959   BuildMI(BB, DL, TII->get(IsLP64 ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
18960     .addReg(tmpSPVReg).addReg(sizeVReg);
18961   BuildMI(BB, DL, TII->get(IsLP64 ? X86::CMP64mr:X86::CMP32mr))
18962     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
18963     .addReg(SPLimitVReg);
18964   BuildMI(BB, DL, TII->get(X86::JG_1)).addMBB(mallocMBB);
18965
18966   // bumpMBB simply decreases the stack pointer, since we know the current
18967   // stacklet has enough space.
18968   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
18969     .addReg(SPLimitVReg);
18970   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
18971     .addReg(SPLimitVReg);
18972   BuildMI(bumpMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
18973
18974   // Calls into a routine in libgcc to allocate more space from the heap.
18975   const uint32_t *RegMask =
18976       Subtarget->getRegisterInfo()->getCallPreservedMask(*MF, CallingConv::C);
18977   if (IsLP64) {
18978     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
18979       .addReg(sizeVReg);
18980     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
18981       .addExternalSymbol("__morestack_allocate_stack_space")
18982       .addRegMask(RegMask)
18983       .addReg(X86::RDI, RegState::Implicit)
18984       .addReg(X86::RAX, RegState::ImplicitDefine);
18985   } else if (Is64Bit) {
18986     BuildMI(mallocMBB, DL, TII->get(X86::MOV32rr), X86::EDI)
18987       .addReg(sizeVReg);
18988     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
18989       .addExternalSymbol("__morestack_allocate_stack_space")
18990       .addRegMask(RegMask)
18991       .addReg(X86::EDI, RegState::Implicit)
18992       .addReg(X86::EAX, RegState::ImplicitDefine);
18993   } else {
18994     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
18995       .addImm(12);
18996     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
18997     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
18998       .addExternalSymbol("__morestack_allocate_stack_space")
18999       .addRegMask(RegMask)
19000       .addReg(X86::EAX, RegState::ImplicitDefine);
19001   }
19002
19003   if (!Is64Bit)
19004     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
19005       .addImm(16);
19006
19007   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
19008     .addReg(IsLP64 ? X86::RAX : X86::EAX);
19009   BuildMI(mallocMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
19010
19011   // Set up the CFG correctly.
19012   BB->addSuccessor(bumpMBB);
19013   BB->addSuccessor(mallocMBB);
19014   mallocMBB->addSuccessor(continueMBB);
19015   bumpMBB->addSuccessor(continueMBB);
19016
19017   // Take care of the PHI nodes.
19018   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
19019           MI->getOperand(0).getReg())
19020     .addReg(mallocPtrVReg).addMBB(mallocMBB)
19021     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
19022
19023   // Delete the original pseudo instruction.
19024   MI->eraseFromParent();
19025
19026   // And we're done.
19027   return continueMBB;
19028 }
19029
19030 MachineBasicBlock *
19031 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
19032                                         MachineBasicBlock *BB) const {
19033   DebugLoc DL = MI->getDebugLoc();
19034
19035   assert(!Subtarget->isTargetMachO());
19036
19037   X86FrameLowering::emitStackProbeCall(*BB->getParent(), *BB, MI, DL);
19038
19039   MI->eraseFromParent();   // The pseudo instruction is gone now.
19040   return BB;
19041 }
19042
19043 MachineBasicBlock *
19044 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
19045                                       MachineBasicBlock *BB) const {
19046   // This is pretty easy.  We're taking the value that we received from
19047   // our load from the relocation, sticking it in either RDI (x86-64)
19048   // or EAX and doing an indirect call.  The return value will then
19049   // be in the normal return register.
19050   MachineFunction *F = BB->getParent();
19051   const X86InstrInfo *TII = Subtarget->getInstrInfo();
19052   DebugLoc DL = MI->getDebugLoc();
19053
19054   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
19055   assert(MI->getOperand(3).isGlobal() && "This should be a global");
19056
19057   // Get a register mask for the lowered call.
19058   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
19059   // proper register mask.
19060   const uint32_t *RegMask =
19061       Subtarget->getRegisterInfo()->getCallPreservedMask(*F, CallingConv::C);
19062   if (Subtarget->is64Bit()) {
19063     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
19064                                       TII->get(X86::MOV64rm), X86::RDI)
19065     .addReg(X86::RIP)
19066     .addImm(0).addReg(0)
19067     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
19068                       MI->getOperand(3).getTargetFlags())
19069     .addReg(0);
19070     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
19071     addDirectMem(MIB, X86::RDI);
19072     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
19073   } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
19074     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
19075                                       TII->get(X86::MOV32rm), X86::EAX)
19076     .addReg(0)
19077     .addImm(0).addReg(0)
19078     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
19079                       MI->getOperand(3).getTargetFlags())
19080     .addReg(0);
19081     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
19082     addDirectMem(MIB, X86::EAX);
19083     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
19084   } else {
19085     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
19086                                       TII->get(X86::MOV32rm), X86::EAX)
19087     .addReg(TII->getGlobalBaseReg(F))
19088     .addImm(0).addReg(0)
19089     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
19090                       MI->getOperand(3).getTargetFlags())
19091     .addReg(0);
19092     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
19093     addDirectMem(MIB, X86::EAX);
19094     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
19095   }
19096
19097   MI->eraseFromParent(); // The pseudo instruction is gone now.
19098   return BB;
19099 }
19100
19101 MachineBasicBlock *
19102 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
19103                                     MachineBasicBlock *MBB) const {
19104   DebugLoc DL = MI->getDebugLoc();
19105   MachineFunction *MF = MBB->getParent();
19106   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19107   MachineRegisterInfo &MRI = MF->getRegInfo();
19108
19109   const BasicBlock *BB = MBB->getBasicBlock();
19110   MachineFunction::iterator I = MBB;
19111   ++I;
19112
19113   // Memory Reference
19114   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
19115   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
19116
19117   unsigned DstReg;
19118   unsigned MemOpndSlot = 0;
19119
19120   unsigned CurOp = 0;
19121
19122   DstReg = MI->getOperand(CurOp++).getReg();
19123   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
19124   assert(RC->hasType(MVT::i32) && "Invalid destination!");
19125   unsigned mainDstReg = MRI.createVirtualRegister(RC);
19126   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
19127
19128   MemOpndSlot = CurOp;
19129
19130   MVT PVT = getPointerTy();
19131   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
19132          "Invalid Pointer Size!");
19133
19134   // For v = setjmp(buf), we generate
19135   //
19136   // thisMBB:
19137   //  buf[LabelOffset] = restoreMBB
19138   //  SjLjSetup restoreMBB
19139   //
19140   // mainMBB:
19141   //  v_main = 0
19142   //
19143   // sinkMBB:
19144   //  v = phi(main, restore)
19145   //
19146   // restoreMBB:
19147   //  if base pointer being used, load it from frame
19148   //  v_restore = 1
19149
19150   MachineBasicBlock *thisMBB = MBB;
19151   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
19152   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
19153   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
19154   MF->insert(I, mainMBB);
19155   MF->insert(I, sinkMBB);
19156   MF->push_back(restoreMBB);
19157
19158   MachineInstrBuilder MIB;
19159
19160   // Transfer the remainder of BB and its successor edges to sinkMBB.
19161   sinkMBB->splice(sinkMBB->begin(), MBB,
19162                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
19163   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
19164
19165   // thisMBB:
19166   unsigned PtrStoreOpc = 0;
19167   unsigned LabelReg = 0;
19168   const int64_t LabelOffset = 1 * PVT.getStoreSize();
19169   Reloc::Model RM = MF->getTarget().getRelocationModel();
19170   bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
19171                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
19172
19173   // Prepare IP either in reg or imm.
19174   if (!UseImmLabel) {
19175     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
19176     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
19177     LabelReg = MRI.createVirtualRegister(PtrRC);
19178     if (Subtarget->is64Bit()) {
19179       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
19180               .addReg(X86::RIP)
19181               .addImm(0)
19182               .addReg(0)
19183               .addMBB(restoreMBB)
19184               .addReg(0);
19185     } else {
19186       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
19187       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
19188               .addReg(XII->getGlobalBaseReg(MF))
19189               .addImm(0)
19190               .addReg(0)
19191               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
19192               .addReg(0);
19193     }
19194   } else
19195     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
19196   // Store IP
19197   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
19198   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
19199     if (i == X86::AddrDisp)
19200       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
19201     else
19202       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
19203   }
19204   if (!UseImmLabel)
19205     MIB.addReg(LabelReg);
19206   else
19207     MIB.addMBB(restoreMBB);
19208   MIB.setMemRefs(MMOBegin, MMOEnd);
19209   // Setup
19210   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
19211           .addMBB(restoreMBB);
19212
19213   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
19214   MIB.addRegMask(RegInfo->getNoPreservedMask());
19215   thisMBB->addSuccessor(mainMBB);
19216   thisMBB->addSuccessor(restoreMBB);
19217
19218   // mainMBB:
19219   //  EAX = 0
19220   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
19221   mainMBB->addSuccessor(sinkMBB);
19222
19223   // sinkMBB:
19224   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
19225           TII->get(X86::PHI), DstReg)
19226     .addReg(mainDstReg).addMBB(mainMBB)
19227     .addReg(restoreDstReg).addMBB(restoreMBB);
19228
19229   // restoreMBB:
19230   if (RegInfo->hasBasePointer(*MF)) {
19231     const bool Uses64BitFramePtr =
19232         Subtarget->isTarget64BitLP64() || Subtarget->isTargetNaCl64();
19233     X86MachineFunctionInfo *X86FI = MF->getInfo<X86MachineFunctionInfo>();
19234     X86FI->setRestoreBasePointer(MF);
19235     unsigned FramePtr = RegInfo->getFrameRegister(*MF);
19236     unsigned BasePtr = RegInfo->getBaseRegister();
19237     unsigned Opm = Uses64BitFramePtr ? X86::MOV64rm : X86::MOV32rm;
19238     addRegOffset(BuildMI(restoreMBB, DL, TII->get(Opm), BasePtr),
19239                  FramePtr, true, X86FI->getRestoreBasePointerOffset())
19240       .setMIFlag(MachineInstr::FrameSetup);
19241   }
19242   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
19243   BuildMI(restoreMBB, DL, TII->get(X86::JMP_1)).addMBB(sinkMBB);
19244   restoreMBB->addSuccessor(sinkMBB);
19245
19246   MI->eraseFromParent();
19247   return sinkMBB;
19248 }
19249
19250 MachineBasicBlock *
19251 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
19252                                      MachineBasicBlock *MBB) const {
19253   DebugLoc DL = MI->getDebugLoc();
19254   MachineFunction *MF = MBB->getParent();
19255   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19256   MachineRegisterInfo &MRI = MF->getRegInfo();
19257
19258   // Memory Reference
19259   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
19260   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
19261
19262   MVT PVT = getPointerTy();
19263   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
19264          "Invalid Pointer Size!");
19265
19266   const TargetRegisterClass *RC =
19267     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
19268   unsigned Tmp = MRI.createVirtualRegister(RC);
19269   // Since FP is only updated here but NOT referenced, it's treated as GPR.
19270   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
19271   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
19272   unsigned SP = RegInfo->getStackRegister();
19273
19274   MachineInstrBuilder MIB;
19275
19276   const int64_t LabelOffset = 1 * PVT.getStoreSize();
19277   const int64_t SPOffset = 2 * PVT.getStoreSize();
19278
19279   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
19280   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
19281
19282   // Reload FP
19283   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
19284   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
19285     MIB.addOperand(MI->getOperand(i));
19286   MIB.setMemRefs(MMOBegin, MMOEnd);
19287   // Reload IP
19288   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
19289   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
19290     if (i == X86::AddrDisp)
19291       MIB.addDisp(MI->getOperand(i), LabelOffset);
19292     else
19293       MIB.addOperand(MI->getOperand(i));
19294   }
19295   MIB.setMemRefs(MMOBegin, MMOEnd);
19296   // Reload SP
19297   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
19298   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
19299     if (i == X86::AddrDisp)
19300       MIB.addDisp(MI->getOperand(i), SPOffset);
19301     else
19302       MIB.addOperand(MI->getOperand(i));
19303   }
19304   MIB.setMemRefs(MMOBegin, MMOEnd);
19305   // Jump
19306   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
19307
19308   MI->eraseFromParent();
19309   return MBB;
19310 }
19311
19312 // Replace 213-type (isel default) FMA3 instructions with 231-type for
19313 // accumulator loops. Writing back to the accumulator allows the coalescer
19314 // to remove extra copies in the loop.
19315 MachineBasicBlock *
19316 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
19317                                  MachineBasicBlock *MBB) const {
19318   MachineOperand &AddendOp = MI->getOperand(3);
19319
19320   // Bail out early if the addend isn't a register - we can't switch these.
19321   if (!AddendOp.isReg())
19322     return MBB;
19323
19324   MachineFunction &MF = *MBB->getParent();
19325   MachineRegisterInfo &MRI = MF.getRegInfo();
19326
19327   // Check whether the addend is defined by a PHI:
19328   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
19329   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
19330   if (!AddendDef.isPHI())
19331     return MBB;
19332
19333   // Look for the following pattern:
19334   // loop:
19335   //   %addend = phi [%entry, 0], [%loop, %result]
19336   //   ...
19337   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
19338
19339   // Replace with:
19340   //   loop:
19341   //   %addend = phi [%entry, 0], [%loop, %result]
19342   //   ...
19343   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
19344
19345   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
19346     assert(AddendDef.getOperand(i).isReg());
19347     MachineOperand PHISrcOp = AddendDef.getOperand(i);
19348     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
19349     if (&PHISrcInst == MI) {
19350       // Found a matching instruction.
19351       unsigned NewFMAOpc = 0;
19352       switch (MI->getOpcode()) {
19353         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
19354         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
19355         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
19356         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
19357         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
19358         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
19359         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
19360         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
19361         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
19362         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
19363         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
19364         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
19365         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
19366         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
19367         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
19368         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
19369         case X86::VFMADDSUBPDr213r: NewFMAOpc = X86::VFMADDSUBPDr231r; break;
19370         case X86::VFMADDSUBPSr213r: NewFMAOpc = X86::VFMADDSUBPSr231r; break;
19371         case X86::VFMSUBADDPDr213r: NewFMAOpc = X86::VFMSUBADDPDr231r; break;
19372         case X86::VFMSUBADDPSr213r: NewFMAOpc = X86::VFMSUBADDPSr231r; break;
19373
19374         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
19375         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
19376         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
19377         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
19378         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
19379         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
19380         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
19381         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
19382         case X86::VFMADDSUBPDr213rY: NewFMAOpc = X86::VFMADDSUBPDr231rY; break;
19383         case X86::VFMADDSUBPSr213rY: NewFMAOpc = X86::VFMADDSUBPSr231rY; break;
19384         case X86::VFMSUBADDPDr213rY: NewFMAOpc = X86::VFMSUBADDPDr231rY; break;
19385         case X86::VFMSUBADDPSr213rY: NewFMAOpc = X86::VFMSUBADDPSr231rY; break;
19386         default: llvm_unreachable("Unrecognized FMA variant.");
19387       }
19388
19389       const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
19390       MachineInstrBuilder MIB =
19391         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
19392         .addOperand(MI->getOperand(0))
19393         .addOperand(MI->getOperand(3))
19394         .addOperand(MI->getOperand(2))
19395         .addOperand(MI->getOperand(1));
19396       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
19397       MI->eraseFromParent();
19398     }
19399   }
19400
19401   return MBB;
19402 }
19403
19404 MachineBasicBlock *
19405 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
19406                                                MachineBasicBlock *BB) const {
19407   switch (MI->getOpcode()) {
19408   default: llvm_unreachable("Unexpected instr type to insert");
19409   case X86::TAILJMPd64:
19410   case X86::TAILJMPr64:
19411   case X86::TAILJMPm64:
19412   case X86::TAILJMPd64_REX:
19413   case X86::TAILJMPr64_REX:
19414   case X86::TAILJMPm64_REX:
19415     llvm_unreachable("TAILJMP64 would not be touched here.");
19416   case X86::TCRETURNdi64:
19417   case X86::TCRETURNri64:
19418   case X86::TCRETURNmi64:
19419     return BB;
19420   case X86::WIN_ALLOCA:
19421     return EmitLoweredWinAlloca(MI, BB);
19422   case X86::SEG_ALLOCA_32:
19423   case X86::SEG_ALLOCA_64:
19424     return EmitLoweredSegAlloca(MI, BB);
19425   case X86::TLSCall_32:
19426   case X86::TLSCall_64:
19427     return EmitLoweredTLSCall(MI, BB);
19428   case X86::CMOV_GR8:
19429   case X86::CMOV_FR32:
19430   case X86::CMOV_FR64:
19431   case X86::CMOV_V4F32:
19432   case X86::CMOV_V2F64:
19433   case X86::CMOV_V2I64:
19434   case X86::CMOV_V8F32:
19435   case X86::CMOV_V4F64:
19436   case X86::CMOV_V4I64:
19437   case X86::CMOV_V16F32:
19438   case X86::CMOV_V8F64:
19439   case X86::CMOV_V8I64:
19440   case X86::CMOV_GR16:
19441   case X86::CMOV_GR32:
19442   case X86::CMOV_RFP32:
19443   case X86::CMOV_RFP64:
19444   case X86::CMOV_RFP80:
19445     return EmitLoweredSelect(MI, BB);
19446
19447   case X86::FP32_TO_INT16_IN_MEM:
19448   case X86::FP32_TO_INT32_IN_MEM:
19449   case X86::FP32_TO_INT64_IN_MEM:
19450   case X86::FP64_TO_INT16_IN_MEM:
19451   case X86::FP64_TO_INT32_IN_MEM:
19452   case X86::FP64_TO_INT64_IN_MEM:
19453   case X86::FP80_TO_INT16_IN_MEM:
19454   case X86::FP80_TO_INT32_IN_MEM:
19455   case X86::FP80_TO_INT64_IN_MEM: {
19456     MachineFunction *F = BB->getParent();
19457     const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19458     DebugLoc DL = MI->getDebugLoc();
19459
19460     // Change the floating point control register to use "round towards zero"
19461     // mode when truncating to an integer value.
19462     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
19463     addFrameReference(BuildMI(*BB, MI, DL,
19464                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
19465
19466     // Load the old value of the high byte of the control word...
19467     unsigned OldCW =
19468       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
19469     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
19470                       CWFrameIdx);
19471
19472     // Set the high part to be round to zero...
19473     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
19474       .addImm(0xC7F);
19475
19476     // Reload the modified control word now...
19477     addFrameReference(BuildMI(*BB, MI, DL,
19478                               TII->get(X86::FLDCW16m)), CWFrameIdx);
19479
19480     // Restore the memory image of control word to original value
19481     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
19482       .addReg(OldCW);
19483
19484     // Get the X86 opcode to use.
19485     unsigned Opc;
19486     switch (MI->getOpcode()) {
19487     default: llvm_unreachable("illegal opcode!");
19488     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
19489     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
19490     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
19491     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
19492     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
19493     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
19494     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
19495     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
19496     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
19497     }
19498
19499     X86AddressMode AM;
19500     MachineOperand &Op = MI->getOperand(0);
19501     if (Op.isReg()) {
19502       AM.BaseType = X86AddressMode::RegBase;
19503       AM.Base.Reg = Op.getReg();
19504     } else {
19505       AM.BaseType = X86AddressMode::FrameIndexBase;
19506       AM.Base.FrameIndex = Op.getIndex();
19507     }
19508     Op = MI->getOperand(1);
19509     if (Op.isImm())
19510       AM.Scale = Op.getImm();
19511     Op = MI->getOperand(2);
19512     if (Op.isImm())
19513       AM.IndexReg = Op.getImm();
19514     Op = MI->getOperand(3);
19515     if (Op.isGlobal()) {
19516       AM.GV = Op.getGlobal();
19517     } else {
19518       AM.Disp = Op.getImm();
19519     }
19520     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
19521                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
19522
19523     // Reload the original control word now.
19524     addFrameReference(BuildMI(*BB, MI, DL,
19525                               TII->get(X86::FLDCW16m)), CWFrameIdx);
19526
19527     MI->eraseFromParent();   // The pseudo instruction is gone now.
19528     return BB;
19529   }
19530     // String/text processing lowering.
19531   case X86::PCMPISTRM128REG:
19532   case X86::VPCMPISTRM128REG:
19533   case X86::PCMPISTRM128MEM:
19534   case X86::VPCMPISTRM128MEM:
19535   case X86::PCMPESTRM128REG:
19536   case X86::VPCMPESTRM128REG:
19537   case X86::PCMPESTRM128MEM:
19538   case X86::VPCMPESTRM128MEM:
19539     assert(Subtarget->hasSSE42() &&
19540            "Target must have SSE4.2 or AVX features enabled");
19541     return EmitPCMPSTRM(MI, BB, Subtarget->getInstrInfo());
19542
19543   // String/text processing lowering.
19544   case X86::PCMPISTRIREG:
19545   case X86::VPCMPISTRIREG:
19546   case X86::PCMPISTRIMEM:
19547   case X86::VPCMPISTRIMEM:
19548   case X86::PCMPESTRIREG:
19549   case X86::VPCMPESTRIREG:
19550   case X86::PCMPESTRIMEM:
19551   case X86::VPCMPESTRIMEM:
19552     assert(Subtarget->hasSSE42() &&
19553            "Target must have SSE4.2 or AVX features enabled");
19554     return EmitPCMPSTRI(MI, BB, Subtarget->getInstrInfo());
19555
19556   // Thread synchronization.
19557   case X86::MONITOR:
19558     return EmitMonitor(MI, BB, Subtarget);
19559
19560   // xbegin
19561   case X86::XBEGIN:
19562     return EmitXBegin(MI, BB, Subtarget->getInstrInfo());
19563
19564   case X86::VASTART_SAVE_XMM_REGS:
19565     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
19566
19567   case X86::VAARG_64:
19568     return EmitVAARG64WithCustomInserter(MI, BB);
19569
19570   case X86::EH_SjLj_SetJmp32:
19571   case X86::EH_SjLj_SetJmp64:
19572     return emitEHSjLjSetJmp(MI, BB);
19573
19574   case X86::EH_SjLj_LongJmp32:
19575   case X86::EH_SjLj_LongJmp64:
19576     return emitEHSjLjLongJmp(MI, BB);
19577
19578   case TargetOpcode::STATEPOINT:
19579     // As an implementation detail, STATEPOINT shares the STACKMAP format at
19580     // this point in the process.  We diverge later.
19581     return emitPatchPoint(MI, BB);
19582
19583   case TargetOpcode::STACKMAP:
19584   case TargetOpcode::PATCHPOINT:
19585     return emitPatchPoint(MI, BB);
19586
19587   case X86::VFMADDPDr213r:
19588   case X86::VFMADDPSr213r:
19589   case X86::VFMADDSDr213r:
19590   case X86::VFMADDSSr213r:
19591   case X86::VFMSUBPDr213r:
19592   case X86::VFMSUBPSr213r:
19593   case X86::VFMSUBSDr213r:
19594   case X86::VFMSUBSSr213r:
19595   case X86::VFNMADDPDr213r:
19596   case X86::VFNMADDPSr213r:
19597   case X86::VFNMADDSDr213r:
19598   case X86::VFNMADDSSr213r:
19599   case X86::VFNMSUBPDr213r:
19600   case X86::VFNMSUBPSr213r:
19601   case X86::VFNMSUBSDr213r:
19602   case X86::VFNMSUBSSr213r:
19603   case X86::VFMADDSUBPDr213r:
19604   case X86::VFMADDSUBPSr213r:
19605   case X86::VFMSUBADDPDr213r:
19606   case X86::VFMSUBADDPSr213r:
19607   case X86::VFMADDPDr213rY:
19608   case X86::VFMADDPSr213rY:
19609   case X86::VFMSUBPDr213rY:
19610   case X86::VFMSUBPSr213rY:
19611   case X86::VFNMADDPDr213rY:
19612   case X86::VFNMADDPSr213rY:
19613   case X86::VFNMSUBPDr213rY:
19614   case X86::VFNMSUBPSr213rY:
19615   case X86::VFMADDSUBPDr213rY:
19616   case X86::VFMADDSUBPSr213rY:
19617   case X86::VFMSUBADDPDr213rY:
19618   case X86::VFMSUBADDPSr213rY:
19619     return emitFMA3Instr(MI, BB);
19620   }
19621 }
19622
19623 //===----------------------------------------------------------------------===//
19624 //                           X86 Optimization Hooks
19625 //===----------------------------------------------------------------------===//
19626
19627 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
19628                                                       APInt &KnownZero,
19629                                                       APInt &KnownOne,
19630                                                       const SelectionDAG &DAG,
19631                                                       unsigned Depth) const {
19632   unsigned BitWidth = KnownZero.getBitWidth();
19633   unsigned Opc = Op.getOpcode();
19634   assert((Opc >= ISD::BUILTIN_OP_END ||
19635           Opc == ISD::INTRINSIC_WO_CHAIN ||
19636           Opc == ISD::INTRINSIC_W_CHAIN ||
19637           Opc == ISD::INTRINSIC_VOID) &&
19638          "Should use MaskedValueIsZero if you don't know whether Op"
19639          " is a target node!");
19640
19641   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
19642   switch (Opc) {
19643   default: break;
19644   case X86ISD::ADD:
19645   case X86ISD::SUB:
19646   case X86ISD::ADC:
19647   case X86ISD::SBB:
19648   case X86ISD::SMUL:
19649   case X86ISD::UMUL:
19650   case X86ISD::INC:
19651   case X86ISD::DEC:
19652   case X86ISD::OR:
19653   case X86ISD::XOR:
19654   case X86ISD::AND:
19655     // These nodes' second result is a boolean.
19656     if (Op.getResNo() == 0)
19657       break;
19658     // Fallthrough
19659   case X86ISD::SETCC:
19660     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
19661     break;
19662   case ISD::INTRINSIC_WO_CHAIN: {
19663     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
19664     unsigned NumLoBits = 0;
19665     switch (IntId) {
19666     default: break;
19667     case Intrinsic::x86_sse_movmsk_ps:
19668     case Intrinsic::x86_avx_movmsk_ps_256:
19669     case Intrinsic::x86_sse2_movmsk_pd:
19670     case Intrinsic::x86_avx_movmsk_pd_256:
19671     case Intrinsic::x86_mmx_pmovmskb:
19672     case Intrinsic::x86_sse2_pmovmskb_128:
19673     case Intrinsic::x86_avx2_pmovmskb: {
19674       // High bits of movmskp{s|d}, pmovmskb are known zero.
19675       switch (IntId) {
19676         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
19677         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
19678         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
19679         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
19680         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
19681         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
19682         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
19683         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
19684       }
19685       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
19686       break;
19687     }
19688     }
19689     break;
19690   }
19691   }
19692 }
19693
19694 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
19695   SDValue Op,
19696   const SelectionDAG &,
19697   unsigned Depth) const {
19698   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
19699   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
19700     return Op.getValueType().getScalarType().getSizeInBits();
19701
19702   // Fallback case.
19703   return 1;
19704 }
19705
19706 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
19707 /// node is a GlobalAddress + offset.
19708 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
19709                                        const GlobalValue* &GA,
19710                                        int64_t &Offset) const {
19711   if (N->getOpcode() == X86ISD::Wrapper) {
19712     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
19713       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
19714       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
19715       return true;
19716     }
19717   }
19718   return TargetLowering::isGAPlusOffset(N, GA, Offset);
19719 }
19720
19721 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
19722 /// same as extracting the high 128-bit part of 256-bit vector and then
19723 /// inserting the result into the low part of a new 256-bit vector
19724 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
19725   EVT VT = SVOp->getValueType(0);
19726   unsigned NumElems = VT.getVectorNumElements();
19727
19728   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
19729   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
19730     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
19731         SVOp->getMaskElt(j) >= 0)
19732       return false;
19733
19734   return true;
19735 }
19736
19737 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
19738 /// same as extracting the low 128-bit part of 256-bit vector and then
19739 /// inserting the result into the high part of a new 256-bit vector
19740 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
19741   EVT VT = SVOp->getValueType(0);
19742   unsigned NumElems = VT.getVectorNumElements();
19743
19744   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
19745   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
19746     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
19747         SVOp->getMaskElt(j) >= 0)
19748       return false;
19749
19750   return true;
19751 }
19752
19753 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
19754 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
19755                                         TargetLowering::DAGCombinerInfo &DCI,
19756                                         const X86Subtarget* Subtarget) {
19757   SDLoc dl(N);
19758   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
19759   SDValue V1 = SVOp->getOperand(0);
19760   SDValue V2 = SVOp->getOperand(1);
19761   EVT VT = SVOp->getValueType(0);
19762   unsigned NumElems = VT.getVectorNumElements();
19763
19764   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
19765       V2.getOpcode() == ISD::CONCAT_VECTORS) {
19766     //
19767     //                   0,0,0,...
19768     //                      |
19769     //    V      UNDEF    BUILD_VECTOR    UNDEF
19770     //     \      /           \           /
19771     //  CONCAT_VECTOR         CONCAT_VECTOR
19772     //         \                  /
19773     //          \                /
19774     //          RESULT: V + zero extended
19775     //
19776     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
19777         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
19778         V1.getOperand(1).getOpcode() != ISD::UNDEF)
19779       return SDValue();
19780
19781     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
19782       return SDValue();
19783
19784     // To match the shuffle mask, the first half of the mask should
19785     // be exactly the first vector, and all the rest a splat with the
19786     // first element of the second one.
19787     for (unsigned i = 0; i != NumElems/2; ++i)
19788       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
19789           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
19790         return SDValue();
19791
19792     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
19793     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
19794       if (Ld->hasNUsesOfValue(1, 0)) {
19795         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
19796         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
19797         SDValue ResNode =
19798           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
19799                                   Ld->getMemoryVT(),
19800                                   Ld->getPointerInfo(),
19801                                   Ld->getAlignment(),
19802                                   false/*isVolatile*/, true/*ReadMem*/,
19803                                   false/*WriteMem*/);
19804
19805         // Make sure the newly-created LOAD is in the same position as Ld in
19806         // terms of dependency. We create a TokenFactor for Ld and ResNode,
19807         // and update uses of Ld's output chain to use the TokenFactor.
19808         if (Ld->hasAnyUseOfValue(1)) {
19809           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
19810                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
19811           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
19812           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
19813                                  SDValue(ResNode.getNode(), 1));
19814         }
19815
19816         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
19817       }
19818     }
19819
19820     // Emit a zeroed vector and insert the desired subvector on its
19821     // first half.
19822     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
19823     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
19824     return DCI.CombineTo(N, InsV);
19825   }
19826
19827   //===--------------------------------------------------------------------===//
19828   // Combine some shuffles into subvector extracts and inserts:
19829   //
19830
19831   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
19832   if (isShuffleHigh128VectorInsertLow(SVOp)) {
19833     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
19834     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
19835     return DCI.CombineTo(N, InsV);
19836   }
19837
19838   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
19839   if (isShuffleLow128VectorInsertHigh(SVOp)) {
19840     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
19841     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
19842     return DCI.CombineTo(N, InsV);
19843   }
19844
19845   return SDValue();
19846 }
19847
19848 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
19849 /// possible.
19850 ///
19851 /// This is the leaf of the recursive combinine below. When we have found some
19852 /// chain of single-use x86 shuffle instructions and accumulated the combined
19853 /// shuffle mask represented by them, this will try to pattern match that mask
19854 /// into either a single instruction if there is a special purpose instruction
19855 /// for this operation, or into a PSHUFB instruction which is a fully general
19856 /// instruction but should only be used to replace chains over a certain depth.
19857 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
19858                                    int Depth, bool HasPSHUFB, SelectionDAG &DAG,
19859                                    TargetLowering::DAGCombinerInfo &DCI,
19860                                    const X86Subtarget *Subtarget) {
19861   assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
19862
19863   // Find the operand that enters the chain. Note that multiple uses are OK
19864   // here, we're not going to remove the operand we find.
19865   SDValue Input = Op.getOperand(0);
19866   while (Input.getOpcode() == ISD::BITCAST)
19867     Input = Input.getOperand(0);
19868
19869   MVT VT = Input.getSimpleValueType();
19870   MVT RootVT = Root.getSimpleValueType();
19871   SDLoc DL(Root);
19872
19873   // Just remove no-op shuffle masks.
19874   if (Mask.size() == 1) {
19875     DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Input),
19876                   /*AddTo*/ true);
19877     return true;
19878   }
19879
19880   // Use the float domain if the operand type is a floating point type.
19881   bool FloatDomain = VT.isFloatingPoint();
19882
19883   // For floating point shuffles, we don't have free copies in the shuffle
19884   // instructions or the ability to load as part of the instruction, so
19885   // canonicalize their shuffles to UNPCK or MOV variants.
19886   //
19887   // Note that even with AVX we prefer the PSHUFD form of shuffle for integer
19888   // vectors because it can have a load folded into it that UNPCK cannot. This
19889   // doesn't preclude something switching to the shorter encoding post-RA.
19890   //
19891   // FIXME: Should teach these routines about AVX vector widths.
19892   if (FloatDomain && VT.getSizeInBits() == 128) {
19893     if (Mask.equals({0, 0}) || Mask.equals({1, 1})) {
19894       bool Lo = Mask.equals({0, 0});
19895       unsigned Shuffle;
19896       MVT ShuffleVT;
19897       // Check if we have SSE3 which will let us use MOVDDUP. That instruction
19898       // is no slower than UNPCKLPD but has the option to fold the input operand
19899       // into even an unaligned memory load.
19900       if (Lo && Subtarget->hasSSE3()) {
19901         Shuffle = X86ISD::MOVDDUP;
19902         ShuffleVT = MVT::v2f64;
19903       } else {
19904         // We have MOVLHPS and MOVHLPS throughout SSE and they encode smaller
19905         // than the UNPCK variants.
19906         Shuffle = Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS;
19907         ShuffleVT = MVT::v4f32;
19908       }
19909       if (Depth == 1 && Root->getOpcode() == Shuffle)
19910         return false; // Nothing to do!
19911       Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19912       DCI.AddToWorklist(Op.getNode());
19913       if (Shuffle == X86ISD::MOVDDUP)
19914         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
19915       else
19916         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
19917       DCI.AddToWorklist(Op.getNode());
19918       DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19919                     /*AddTo*/ true);
19920       return true;
19921     }
19922     if (Subtarget->hasSSE3() &&
19923         (Mask.equals({0, 0, 2, 2}) || Mask.equals({1, 1, 3, 3}))) {
19924       bool Lo = Mask.equals({0, 0, 2, 2});
19925       unsigned Shuffle = Lo ? X86ISD::MOVSLDUP : X86ISD::MOVSHDUP;
19926       MVT ShuffleVT = MVT::v4f32;
19927       if (Depth == 1 && Root->getOpcode() == Shuffle)
19928         return false; // Nothing to do!
19929       Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19930       DCI.AddToWorklist(Op.getNode());
19931       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
19932       DCI.AddToWorklist(Op.getNode());
19933       DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19934                     /*AddTo*/ true);
19935       return true;
19936     }
19937     if (Mask.equals({0, 0, 1, 1}) || Mask.equals({2, 2, 3, 3})) {
19938       bool Lo = Mask.equals({0, 0, 1, 1});
19939       unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
19940       MVT ShuffleVT = MVT::v4f32;
19941       if (Depth == 1 && Root->getOpcode() == Shuffle)
19942         return false; // Nothing to do!
19943       Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19944       DCI.AddToWorklist(Op.getNode());
19945       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
19946       DCI.AddToWorklist(Op.getNode());
19947       DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19948                     /*AddTo*/ true);
19949       return true;
19950     }
19951   }
19952
19953   // We always canonicalize the 8 x i16 and 16 x i8 shuffles into their UNPCK
19954   // variants as none of these have single-instruction variants that are
19955   // superior to the UNPCK formulation.
19956   if (!FloatDomain && VT.getSizeInBits() == 128 &&
19957       (Mask.equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
19958        Mask.equals({4, 4, 5, 5, 6, 6, 7, 7}) ||
19959        Mask.equals({0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7}) ||
19960        Mask.equals(
19961            {8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15}))) {
19962     bool Lo = Mask[0] == 0;
19963     unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
19964     if (Depth == 1 && Root->getOpcode() == Shuffle)
19965       return false; // Nothing to do!
19966     MVT ShuffleVT;
19967     switch (Mask.size()) {
19968     case 8:
19969       ShuffleVT = MVT::v8i16;
19970       break;
19971     case 16:
19972       ShuffleVT = MVT::v16i8;
19973       break;
19974     default:
19975       llvm_unreachable("Impossible mask size!");
19976     };
19977     Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19978     DCI.AddToWorklist(Op.getNode());
19979     Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
19980     DCI.AddToWorklist(Op.getNode());
19981     DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19982                   /*AddTo*/ true);
19983     return true;
19984   }
19985
19986   // Don't try to re-form single instruction chains under any circumstances now
19987   // that we've done encoding canonicalization for them.
19988   if (Depth < 2)
19989     return false;
19990
19991   // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
19992   // can replace them with a single PSHUFB instruction profitably. Intel's
19993   // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
19994   // in practice PSHUFB tends to be *very* fast so we're more aggressive.
19995   if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
19996     SmallVector<SDValue, 16> PSHUFBMask;
19997     int NumBytes = VT.getSizeInBits() / 8;
19998     int Ratio = NumBytes / Mask.size();
19999     for (int i = 0; i < NumBytes; ++i) {
20000       if (Mask[i / Ratio] == SM_SentinelUndef) {
20001         PSHUFBMask.push_back(DAG.getUNDEF(MVT::i8));
20002         continue;
20003       }
20004       int M = Mask[i / Ratio] != SM_SentinelZero
20005                   ? Ratio * Mask[i / Ratio] + i % Ratio
20006                   : 255;
20007       PSHUFBMask.push_back(DAG.getConstant(M, DL, MVT::i8));
20008     }
20009     MVT ByteVT = MVT::getVectorVT(MVT::i8, NumBytes);
20010     Op = DAG.getNode(ISD::BITCAST, DL, ByteVT, Input);
20011     DCI.AddToWorklist(Op.getNode());
20012     SDValue PSHUFBMaskOp =
20013         DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVT, PSHUFBMask);
20014     DCI.AddToWorklist(PSHUFBMaskOp.getNode());
20015     Op = DAG.getNode(X86ISD::PSHUFB, DL, ByteVT, Op, PSHUFBMaskOp);
20016     DCI.AddToWorklist(Op.getNode());
20017     DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
20018                   /*AddTo*/ true);
20019     return true;
20020   }
20021
20022   // Failed to find any combines.
20023   return false;
20024 }
20025
20026 /// \brief Fully generic combining of x86 shuffle instructions.
20027 ///
20028 /// This should be the last combine run over the x86 shuffle instructions. Once
20029 /// they have been fully optimized, this will recursively consider all chains
20030 /// of single-use shuffle instructions, build a generic model of the cumulative
20031 /// shuffle operation, and check for simpler instructions which implement this
20032 /// operation. We use this primarily for two purposes:
20033 ///
20034 /// 1) Collapse generic shuffles to specialized single instructions when
20035 ///    equivalent. In most cases, this is just an encoding size win, but
20036 ///    sometimes we will collapse multiple generic shuffles into a single
20037 ///    special-purpose shuffle.
20038 /// 2) Look for sequences of shuffle instructions with 3 or more total
20039 ///    instructions, and replace them with the slightly more expensive SSSE3
20040 ///    PSHUFB instruction if available. We do this as the last combining step
20041 ///    to ensure we avoid using PSHUFB if we can implement the shuffle with
20042 ///    a suitable short sequence of other instructions. The PHUFB will either
20043 ///    use a register or have to read from memory and so is slightly (but only
20044 ///    slightly) more expensive than the other shuffle instructions.
20045 ///
20046 /// Because this is inherently a quadratic operation (for each shuffle in
20047 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
20048 /// This should never be an issue in practice as the shuffle lowering doesn't
20049 /// produce sequences of more than 8 instructions.
20050 ///
20051 /// FIXME: We will currently miss some cases where the redundant shuffling
20052 /// would simplify under the threshold for PSHUFB formation because of
20053 /// combine-ordering. To fix this, we should do the redundant instruction
20054 /// combining in this recursive walk.
20055 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
20056                                           ArrayRef<int> RootMask,
20057                                           int Depth, bool HasPSHUFB,
20058                                           SelectionDAG &DAG,
20059                                           TargetLowering::DAGCombinerInfo &DCI,
20060                                           const X86Subtarget *Subtarget) {
20061   // Bound the depth of our recursive combine because this is ultimately
20062   // quadratic in nature.
20063   if (Depth > 8)
20064     return false;
20065
20066   // Directly rip through bitcasts to find the underlying operand.
20067   while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
20068     Op = Op.getOperand(0);
20069
20070   MVT VT = Op.getSimpleValueType();
20071   if (!VT.isVector())
20072     return false; // Bail if we hit a non-vector.
20073
20074   assert(Root.getSimpleValueType().isVector() &&
20075          "Shuffles operate on vector types!");
20076   assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
20077          "Can only combine shuffles of the same vector register size.");
20078
20079   if (!isTargetShuffle(Op.getOpcode()))
20080     return false;
20081   SmallVector<int, 16> OpMask;
20082   bool IsUnary;
20083   bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, OpMask, IsUnary);
20084   // We only can combine unary shuffles which we can decode the mask for.
20085   if (!HaveMask || !IsUnary)
20086     return false;
20087
20088   assert(VT.getVectorNumElements() == OpMask.size() &&
20089          "Different mask size from vector size!");
20090   assert(((RootMask.size() > OpMask.size() &&
20091            RootMask.size() % OpMask.size() == 0) ||
20092           (OpMask.size() > RootMask.size() &&
20093            OpMask.size() % RootMask.size() == 0) ||
20094           OpMask.size() == RootMask.size()) &&
20095          "The smaller number of elements must divide the larger.");
20096   int RootRatio = std::max<int>(1, OpMask.size() / RootMask.size());
20097   int OpRatio = std::max<int>(1, RootMask.size() / OpMask.size());
20098   assert(((RootRatio == 1 && OpRatio == 1) ||
20099           (RootRatio == 1) != (OpRatio == 1)) &&
20100          "Must not have a ratio for both incoming and op masks!");
20101
20102   SmallVector<int, 16> Mask;
20103   Mask.reserve(std::max(OpMask.size(), RootMask.size()));
20104
20105   // Merge this shuffle operation's mask into our accumulated mask. Note that
20106   // this shuffle's mask will be the first applied to the input, followed by the
20107   // root mask to get us all the way to the root value arrangement. The reason
20108   // for this order is that we are recursing up the operation chain.
20109   for (int i = 0, e = std::max(OpMask.size(), RootMask.size()); i < e; ++i) {
20110     int RootIdx = i / RootRatio;
20111     if (RootMask[RootIdx] < 0) {
20112       // This is a zero or undef lane, we're done.
20113       Mask.push_back(RootMask[RootIdx]);
20114       continue;
20115     }
20116
20117     int RootMaskedIdx = RootMask[RootIdx] * RootRatio + i % RootRatio;
20118     int OpIdx = RootMaskedIdx / OpRatio;
20119     if (OpMask[OpIdx] < 0) {
20120       // The incoming lanes are zero or undef, it doesn't matter which ones we
20121       // are using.
20122       Mask.push_back(OpMask[OpIdx]);
20123       continue;
20124     }
20125
20126     // Ok, we have non-zero lanes, map them through.
20127     Mask.push_back(OpMask[OpIdx] * OpRatio +
20128                    RootMaskedIdx % OpRatio);
20129   }
20130
20131   // See if we can recurse into the operand to combine more things.
20132   switch (Op.getOpcode()) {
20133     case X86ISD::PSHUFB:
20134       HasPSHUFB = true;
20135     case X86ISD::PSHUFD:
20136     case X86ISD::PSHUFHW:
20137     case X86ISD::PSHUFLW:
20138       if (Op.getOperand(0).hasOneUse() &&
20139           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
20140                                         HasPSHUFB, DAG, DCI, Subtarget))
20141         return true;
20142       break;
20143
20144     case X86ISD::UNPCKL:
20145     case X86ISD::UNPCKH:
20146       assert(Op.getOperand(0) == Op.getOperand(1) && "We only combine unary shuffles!");
20147       // We can't check for single use, we have to check that this shuffle is the only user.
20148       if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
20149           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
20150                                         HasPSHUFB, DAG, DCI, Subtarget))
20151           return true;
20152       break;
20153   }
20154
20155   // Minor canonicalization of the accumulated shuffle mask to make it easier
20156   // to match below. All this does is detect masks with squential pairs of
20157   // elements, and shrink them to the half-width mask. It does this in a loop
20158   // so it will reduce the size of the mask to the minimal width mask which
20159   // performs an equivalent shuffle.
20160   SmallVector<int, 16> WidenedMask;
20161   while (Mask.size() > 1 && canWidenShuffleElements(Mask, WidenedMask)) {
20162     Mask = std::move(WidenedMask);
20163     WidenedMask.clear();
20164   }
20165
20166   return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
20167                                 Subtarget);
20168 }
20169
20170 /// \brief Get the PSHUF-style mask from PSHUF node.
20171 ///
20172 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
20173 /// PSHUF-style masks that can be reused with such instructions.
20174 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
20175   MVT VT = N.getSimpleValueType();
20176   SmallVector<int, 4> Mask;
20177   bool IsUnary;
20178   bool HaveMask = getTargetShuffleMask(N.getNode(), VT, Mask, IsUnary);
20179   (void)HaveMask;
20180   assert(HaveMask);
20181
20182   // If we have more than 128-bits, only the low 128-bits of shuffle mask
20183   // matter. Check that the upper masks are repeats and remove them.
20184   if (VT.getSizeInBits() > 128) {
20185     int LaneElts = 128 / VT.getScalarSizeInBits();
20186 #ifndef NDEBUG
20187     for (int i = 1, NumLanes = VT.getSizeInBits() / 128; i < NumLanes; ++i)
20188       for (int j = 0; j < LaneElts; ++j)
20189         assert(Mask[j] == Mask[i * LaneElts + j] - LaneElts &&
20190                "Mask doesn't repeat in high 128-bit lanes!");
20191 #endif
20192     Mask.resize(LaneElts);
20193   }
20194
20195   switch (N.getOpcode()) {
20196   case X86ISD::PSHUFD:
20197     return Mask;
20198   case X86ISD::PSHUFLW:
20199     Mask.resize(4);
20200     return Mask;
20201   case X86ISD::PSHUFHW:
20202     Mask.erase(Mask.begin(), Mask.begin() + 4);
20203     for (int &M : Mask)
20204       M -= 4;
20205     return Mask;
20206   default:
20207     llvm_unreachable("No valid shuffle instruction found!");
20208   }
20209 }
20210
20211 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
20212 ///
20213 /// We walk up the chain and look for a combinable shuffle, skipping over
20214 /// shuffles that we could hoist this shuffle's transformation past without
20215 /// altering anything.
20216 static SDValue
20217 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
20218                              SelectionDAG &DAG,
20219                              TargetLowering::DAGCombinerInfo &DCI) {
20220   assert(N.getOpcode() == X86ISD::PSHUFD &&
20221          "Called with something other than an x86 128-bit half shuffle!");
20222   SDLoc DL(N);
20223
20224   // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
20225   // of the shuffles in the chain so that we can form a fresh chain to replace
20226   // this one.
20227   SmallVector<SDValue, 8> Chain;
20228   SDValue V = N.getOperand(0);
20229   for (; V.hasOneUse(); V = V.getOperand(0)) {
20230     switch (V.getOpcode()) {
20231     default:
20232       return SDValue(); // Nothing combined!
20233
20234     case ISD::BITCAST:
20235       // Skip bitcasts as we always know the type for the target specific
20236       // instructions.
20237       continue;
20238
20239     case X86ISD::PSHUFD:
20240       // Found another dword shuffle.
20241       break;
20242
20243     case X86ISD::PSHUFLW:
20244       // Check that the low words (being shuffled) are the identity in the
20245       // dword shuffle, and the high words are self-contained.
20246       if (Mask[0] != 0 || Mask[1] != 1 ||
20247           !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
20248         return SDValue();
20249
20250       Chain.push_back(V);
20251       continue;
20252
20253     case X86ISD::PSHUFHW:
20254       // Check that the high words (being shuffled) are the identity in the
20255       // dword shuffle, and the low words are self-contained.
20256       if (Mask[2] != 2 || Mask[3] != 3 ||
20257           !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
20258         return SDValue();
20259
20260       Chain.push_back(V);
20261       continue;
20262
20263     case X86ISD::UNPCKL:
20264     case X86ISD::UNPCKH:
20265       // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
20266       // shuffle into a preceding word shuffle.
20267       if (V.getSimpleValueType().getScalarType() != MVT::i8 &&
20268           V.getSimpleValueType().getScalarType() != MVT::i16)
20269         return SDValue();
20270
20271       // Search for a half-shuffle which we can combine with.
20272       unsigned CombineOp =
20273           V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
20274       if (V.getOperand(0) != V.getOperand(1) ||
20275           !V->isOnlyUserOf(V.getOperand(0).getNode()))
20276         return SDValue();
20277       Chain.push_back(V);
20278       V = V.getOperand(0);
20279       do {
20280         switch (V.getOpcode()) {
20281         default:
20282           return SDValue(); // Nothing to combine.
20283
20284         case X86ISD::PSHUFLW:
20285         case X86ISD::PSHUFHW:
20286           if (V.getOpcode() == CombineOp)
20287             break;
20288
20289           Chain.push_back(V);
20290
20291           // Fallthrough!
20292         case ISD::BITCAST:
20293           V = V.getOperand(0);
20294           continue;
20295         }
20296         break;
20297       } while (V.hasOneUse());
20298       break;
20299     }
20300     // Break out of the loop if we break out of the switch.
20301     break;
20302   }
20303
20304   if (!V.hasOneUse())
20305     // We fell out of the loop without finding a viable combining instruction.
20306     return SDValue();
20307
20308   // Merge this node's mask and our incoming mask.
20309   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
20310   for (int &M : Mask)
20311     M = VMask[M];
20312   V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
20313                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
20314
20315   // Rebuild the chain around this new shuffle.
20316   while (!Chain.empty()) {
20317     SDValue W = Chain.pop_back_val();
20318
20319     if (V.getValueType() != W.getOperand(0).getValueType())
20320       V = DAG.getNode(ISD::BITCAST, DL, W.getOperand(0).getValueType(), V);
20321
20322     switch (W.getOpcode()) {
20323     default:
20324       llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
20325
20326     case X86ISD::UNPCKL:
20327     case X86ISD::UNPCKH:
20328       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
20329       break;
20330
20331     case X86ISD::PSHUFD:
20332     case X86ISD::PSHUFLW:
20333     case X86ISD::PSHUFHW:
20334       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
20335       break;
20336     }
20337   }
20338   if (V.getValueType() != N.getValueType())
20339     V = DAG.getNode(ISD::BITCAST, DL, N.getValueType(), V);
20340
20341   // Return the new chain to replace N.
20342   return V;
20343 }
20344
20345 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or pshufhw.
20346 ///
20347 /// We walk up the chain, skipping shuffles of the other half and looking
20348 /// through shuffles which switch halves trying to find a shuffle of the same
20349 /// pair of dwords.
20350 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
20351                                         SelectionDAG &DAG,
20352                                         TargetLowering::DAGCombinerInfo &DCI) {
20353   assert(
20354       (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
20355       "Called with something other than an x86 128-bit half shuffle!");
20356   SDLoc DL(N);
20357   unsigned CombineOpcode = N.getOpcode();
20358
20359   // Walk up a single-use chain looking for a combinable shuffle.
20360   SDValue V = N.getOperand(0);
20361   for (; V.hasOneUse(); V = V.getOperand(0)) {
20362     switch (V.getOpcode()) {
20363     default:
20364       return false; // Nothing combined!
20365
20366     case ISD::BITCAST:
20367       // Skip bitcasts as we always know the type for the target specific
20368       // instructions.
20369       continue;
20370
20371     case X86ISD::PSHUFLW:
20372     case X86ISD::PSHUFHW:
20373       if (V.getOpcode() == CombineOpcode)
20374         break;
20375
20376       // Other-half shuffles are no-ops.
20377       continue;
20378     }
20379     // Break out of the loop if we break out of the switch.
20380     break;
20381   }
20382
20383   if (!V.hasOneUse())
20384     // We fell out of the loop without finding a viable combining instruction.
20385     return false;
20386
20387   // Combine away the bottom node as its shuffle will be accumulated into
20388   // a preceding shuffle.
20389   DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
20390
20391   // Record the old value.
20392   SDValue Old = V;
20393
20394   // Merge this node's mask and our incoming mask (adjusted to account for all
20395   // the pshufd instructions encountered).
20396   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
20397   for (int &M : Mask)
20398     M = VMask[M];
20399   V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
20400                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
20401
20402   // Check that the shuffles didn't cancel each other out. If not, we need to
20403   // combine to the new one.
20404   if (Old != V)
20405     // Replace the combinable shuffle with the combined one, updating all users
20406     // so that we re-evaluate the chain here.
20407     DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
20408
20409   return true;
20410 }
20411
20412 /// \brief Try to combine x86 target specific shuffles.
20413 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
20414                                            TargetLowering::DAGCombinerInfo &DCI,
20415                                            const X86Subtarget *Subtarget) {
20416   SDLoc DL(N);
20417   MVT VT = N.getSimpleValueType();
20418   SmallVector<int, 4> Mask;
20419
20420   switch (N.getOpcode()) {
20421   case X86ISD::PSHUFD:
20422   case X86ISD::PSHUFLW:
20423   case X86ISD::PSHUFHW:
20424     Mask = getPSHUFShuffleMask(N);
20425     assert(Mask.size() == 4);
20426     break;
20427   default:
20428     return SDValue();
20429   }
20430
20431   // Nuke no-op shuffles that show up after combining.
20432   if (isNoopShuffleMask(Mask))
20433     return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
20434
20435   // Look for simplifications involving one or two shuffle instructions.
20436   SDValue V = N.getOperand(0);
20437   switch (N.getOpcode()) {
20438   default:
20439     break;
20440   case X86ISD::PSHUFLW:
20441   case X86ISD::PSHUFHW:
20442     assert(VT.getScalarType() == MVT::i16 && "Bad word shuffle type!");
20443
20444     if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
20445       return SDValue(); // We combined away this shuffle, so we're done.
20446
20447     // See if this reduces to a PSHUFD which is no more expensive and can
20448     // combine with more operations. Note that it has to at least flip the
20449     // dwords as otherwise it would have been removed as a no-op.
20450     if (makeArrayRef(Mask).equals({2, 3, 0, 1})) {
20451       int DMask[] = {0, 1, 2, 3};
20452       int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
20453       DMask[DOffset + 0] = DOffset + 1;
20454       DMask[DOffset + 1] = DOffset + 0;
20455       MVT DVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
20456       V = DAG.getNode(ISD::BITCAST, DL, DVT, V);
20457       DCI.AddToWorklist(V.getNode());
20458       V = DAG.getNode(X86ISD::PSHUFD, DL, DVT, V,
20459                       getV4X86ShuffleImm8ForMask(DMask, DL, DAG));
20460       DCI.AddToWorklist(V.getNode());
20461       return DAG.getNode(ISD::BITCAST, DL, VT, V);
20462     }
20463
20464     // Look for shuffle patterns which can be implemented as a single unpack.
20465     // FIXME: This doesn't handle the location of the PSHUFD generically, and
20466     // only works when we have a PSHUFD followed by two half-shuffles.
20467     if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
20468         (V.getOpcode() == X86ISD::PSHUFLW ||
20469          V.getOpcode() == X86ISD::PSHUFHW) &&
20470         V.getOpcode() != N.getOpcode() &&
20471         V.hasOneUse()) {
20472       SDValue D = V.getOperand(0);
20473       while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
20474         D = D.getOperand(0);
20475       if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
20476         SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
20477         SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
20478         int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
20479         int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
20480         int WordMask[8];
20481         for (int i = 0; i < 4; ++i) {
20482           WordMask[i + NOffset] = Mask[i] + NOffset;
20483           WordMask[i + VOffset] = VMask[i] + VOffset;
20484         }
20485         // Map the word mask through the DWord mask.
20486         int MappedMask[8];
20487         for (int i = 0; i < 8; ++i)
20488           MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
20489         if (makeArrayRef(MappedMask).equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
20490             makeArrayRef(MappedMask).equals({4, 4, 5, 5, 6, 6, 7, 7})) {
20491           // We can replace all three shuffles with an unpack.
20492           V = DAG.getNode(ISD::BITCAST, DL, VT, D.getOperand(0));
20493           DCI.AddToWorklist(V.getNode());
20494           return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
20495                                                 : X86ISD::UNPCKH,
20496                              DL, VT, V, V);
20497         }
20498       }
20499     }
20500
20501     break;
20502
20503   case X86ISD::PSHUFD:
20504     if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG, DCI))
20505       return NewN;
20506
20507     break;
20508   }
20509
20510   return SDValue();
20511 }
20512
20513 /// \brief Try to combine a shuffle into a target-specific add-sub node.
20514 ///
20515 /// We combine this directly on the abstract vector shuffle nodes so it is
20516 /// easier to generically match. We also insert dummy vector shuffle nodes for
20517 /// the operands which explicitly discard the lanes which are unused by this
20518 /// operation to try to flow through the rest of the combiner the fact that
20519 /// they're unused.
20520 static SDValue combineShuffleToAddSub(SDNode *N, SelectionDAG &DAG) {
20521   SDLoc DL(N);
20522   EVT VT = N->getValueType(0);
20523
20524   // We only handle target-independent shuffles.
20525   // FIXME: It would be easy and harmless to use the target shuffle mask
20526   // extraction tool to support more.
20527   if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
20528     return SDValue();
20529
20530   auto *SVN = cast<ShuffleVectorSDNode>(N);
20531   ArrayRef<int> Mask = SVN->getMask();
20532   SDValue V1 = N->getOperand(0);
20533   SDValue V2 = N->getOperand(1);
20534
20535   // We require the first shuffle operand to be the SUB node, and the second to
20536   // be the ADD node.
20537   // FIXME: We should support the commuted patterns.
20538   if (V1->getOpcode() != ISD::FSUB || V2->getOpcode() != ISD::FADD)
20539     return SDValue();
20540
20541   // If there are other uses of these operations we can't fold them.
20542   if (!V1->hasOneUse() || !V2->hasOneUse())
20543     return SDValue();
20544
20545   // Ensure that both operations have the same operands. Note that we can
20546   // commute the FADD operands.
20547   SDValue LHS = V1->getOperand(0), RHS = V1->getOperand(1);
20548   if ((V2->getOperand(0) != LHS || V2->getOperand(1) != RHS) &&
20549       (V2->getOperand(0) != RHS || V2->getOperand(1) != LHS))
20550     return SDValue();
20551
20552   // We're looking for blends between FADD and FSUB nodes. We insist on these
20553   // nodes being lined up in a specific expected pattern.
20554   if (!(isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
20555         isShuffleEquivalent(V1, V2, Mask, {0, 5, 2, 7}) ||
20556         isShuffleEquivalent(V1, V2, Mask, {0, 9, 2, 11, 4, 13, 6, 15})))
20557     return SDValue();
20558
20559   // Only specific types are legal at this point, assert so we notice if and
20560   // when these change.
20561   assert((VT == MVT::v4f32 || VT == MVT::v2f64 || VT == MVT::v8f32 ||
20562           VT == MVT::v4f64) &&
20563          "Unknown vector type encountered!");
20564
20565   return DAG.getNode(X86ISD::ADDSUB, DL, VT, LHS, RHS);
20566 }
20567
20568 /// PerformShuffleCombine - Performs several different shuffle combines.
20569 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
20570                                      TargetLowering::DAGCombinerInfo &DCI,
20571                                      const X86Subtarget *Subtarget) {
20572   SDLoc dl(N);
20573   SDValue N0 = N->getOperand(0);
20574   SDValue N1 = N->getOperand(1);
20575   EVT VT = N->getValueType(0);
20576
20577   // Don't create instructions with illegal types after legalize types has run.
20578   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20579   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
20580     return SDValue();
20581
20582   // If we have legalized the vector types, look for blends of FADD and FSUB
20583   // nodes that we can fuse into an ADDSUB node.
20584   if (TLI.isTypeLegal(VT) && Subtarget->hasSSE3())
20585     if (SDValue AddSub = combineShuffleToAddSub(N, DAG))
20586       return AddSub;
20587
20588   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
20589   if (Subtarget->hasFp256() && VT.is256BitVector() &&
20590       N->getOpcode() == ISD::VECTOR_SHUFFLE)
20591     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
20592
20593   // During Type Legalization, when promoting illegal vector types,
20594   // the backend might introduce new shuffle dag nodes and bitcasts.
20595   //
20596   // This code performs the following transformation:
20597   // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
20598   //       (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
20599   //
20600   // We do this only if both the bitcast and the BINOP dag nodes have
20601   // one use. Also, perform this transformation only if the new binary
20602   // operation is legal. This is to avoid introducing dag nodes that
20603   // potentially need to be further expanded (or custom lowered) into a
20604   // less optimal sequence of dag nodes.
20605   if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
20606       N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
20607       N0.getOpcode() == ISD::BITCAST) {
20608     SDValue BC0 = N0.getOperand(0);
20609     EVT SVT = BC0.getValueType();
20610     unsigned Opcode = BC0.getOpcode();
20611     unsigned NumElts = VT.getVectorNumElements();
20612
20613     if (BC0.hasOneUse() && SVT.isVector() &&
20614         SVT.getVectorNumElements() * 2 == NumElts &&
20615         TLI.isOperationLegal(Opcode, VT)) {
20616       bool CanFold = false;
20617       switch (Opcode) {
20618       default : break;
20619       case ISD::ADD :
20620       case ISD::FADD :
20621       case ISD::SUB :
20622       case ISD::FSUB :
20623       case ISD::MUL :
20624       case ISD::FMUL :
20625         CanFold = true;
20626       }
20627
20628       unsigned SVTNumElts = SVT.getVectorNumElements();
20629       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
20630       for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
20631         CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
20632       for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
20633         CanFold = SVOp->getMaskElt(i) < 0;
20634
20635       if (CanFold) {
20636         SDValue BC00 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(0));
20637         SDValue BC01 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(1));
20638         SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
20639         return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
20640       }
20641     }
20642   }
20643
20644   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
20645   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
20646   // consecutive, non-overlapping, and in the right order.
20647   SmallVector<SDValue, 16> Elts;
20648   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
20649     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
20650
20651   SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
20652   if (LD.getNode())
20653     return LD;
20654
20655   if (isTargetShuffle(N->getOpcode())) {
20656     SDValue Shuffle =
20657         PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
20658     if (Shuffle.getNode())
20659       return Shuffle;
20660
20661     // Try recursively combining arbitrary sequences of x86 shuffle
20662     // instructions into higher-order shuffles. We do this after combining
20663     // specific PSHUF instruction sequences into their minimal form so that we
20664     // can evaluate how many specialized shuffle instructions are involved in
20665     // a particular chain.
20666     SmallVector<int, 1> NonceMask; // Just a placeholder.
20667     NonceMask.push_back(0);
20668     if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
20669                                       /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
20670                                       DCI, Subtarget))
20671       return SDValue(); // This routine will use CombineTo to replace N.
20672   }
20673
20674   return SDValue();
20675 }
20676
20677 /// PerformTruncateCombine - Converts truncate operation to
20678 /// a sequence of vector shuffle operations.
20679 /// It is possible when we truncate 256-bit vector to 128-bit vector
20680 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
20681                                       TargetLowering::DAGCombinerInfo &DCI,
20682                                       const X86Subtarget *Subtarget)  {
20683   return SDValue();
20684 }
20685
20686 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
20687 /// specific shuffle of a load can be folded into a single element load.
20688 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
20689 /// shuffles have been custom lowered so we need to handle those here.
20690 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
20691                                          TargetLowering::DAGCombinerInfo &DCI) {
20692   if (DCI.isBeforeLegalizeOps())
20693     return SDValue();
20694
20695   SDValue InVec = N->getOperand(0);
20696   SDValue EltNo = N->getOperand(1);
20697
20698   if (!isa<ConstantSDNode>(EltNo))
20699     return SDValue();
20700
20701   EVT OriginalVT = InVec.getValueType();
20702
20703   if (InVec.getOpcode() == ISD::BITCAST) {
20704     // Don't duplicate a load with other uses.
20705     if (!InVec.hasOneUse())
20706       return SDValue();
20707     EVT BCVT = InVec.getOperand(0).getValueType();
20708     if (BCVT.getVectorNumElements() != OriginalVT.getVectorNumElements())
20709       return SDValue();
20710     InVec = InVec.getOperand(0);
20711   }
20712
20713   EVT CurrentVT = InVec.getValueType();
20714
20715   if (!isTargetShuffle(InVec.getOpcode()))
20716     return SDValue();
20717
20718   // Don't duplicate a load with other uses.
20719   if (!InVec.hasOneUse())
20720     return SDValue();
20721
20722   SmallVector<int, 16> ShuffleMask;
20723   bool UnaryShuffle;
20724   if (!getTargetShuffleMask(InVec.getNode(), CurrentVT.getSimpleVT(),
20725                             ShuffleMask, UnaryShuffle))
20726     return SDValue();
20727
20728   // Select the input vector, guarding against out of range extract vector.
20729   unsigned NumElems = CurrentVT.getVectorNumElements();
20730   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
20731   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
20732   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
20733                                          : InVec.getOperand(1);
20734
20735   // If inputs to shuffle are the same for both ops, then allow 2 uses
20736   unsigned AllowedUses = InVec.getNumOperands() > 1 &&
20737                          InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
20738
20739   if (LdNode.getOpcode() == ISD::BITCAST) {
20740     // Don't duplicate a load with other uses.
20741     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
20742       return SDValue();
20743
20744     AllowedUses = 1; // only allow 1 load use if we have a bitcast
20745     LdNode = LdNode.getOperand(0);
20746   }
20747
20748   if (!ISD::isNormalLoad(LdNode.getNode()))
20749     return SDValue();
20750
20751   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
20752
20753   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
20754     return SDValue();
20755
20756   EVT EltVT = N->getValueType(0);
20757   // If there's a bitcast before the shuffle, check if the load type and
20758   // alignment is valid.
20759   unsigned Align = LN0->getAlignment();
20760   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20761   unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
20762       EltVT.getTypeForEVT(*DAG.getContext()));
20763
20764   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, EltVT))
20765     return SDValue();
20766
20767   // All checks match so transform back to vector_shuffle so that DAG combiner
20768   // can finish the job
20769   SDLoc dl(N);
20770
20771   // Create shuffle node taking into account the case that its a unary shuffle
20772   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(CurrentVT)
20773                                    : InVec.getOperand(1);
20774   Shuffle = DAG.getVectorShuffle(CurrentVT, dl,
20775                                  InVec.getOperand(0), Shuffle,
20776                                  &ShuffleMask[0]);
20777   Shuffle = DAG.getNode(ISD::BITCAST, dl, OriginalVT, Shuffle);
20778   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
20779                      EltNo);
20780 }
20781
20782 /// \brief Detect bitcasts between i32 to x86mmx low word. Since MMX types are
20783 /// special and don't usually play with other vector types, it's better to
20784 /// handle them early to be sure we emit efficient code by avoiding
20785 /// store-load conversions.
20786 static SDValue PerformBITCASTCombine(SDNode *N, SelectionDAG &DAG) {
20787   if (N->getValueType(0) != MVT::x86mmx ||
20788       N->getOperand(0)->getOpcode() != ISD::BUILD_VECTOR ||
20789       N->getOperand(0)->getValueType(0) != MVT::v2i32)
20790     return SDValue();
20791
20792   SDValue V = N->getOperand(0);
20793   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V.getOperand(1));
20794   if (C && C->getZExtValue() == 0 && V.getOperand(0).getValueType() == MVT::i32)
20795     return DAG.getNode(X86ISD::MMX_MOVW2D, SDLoc(V.getOperand(0)),
20796                        N->getValueType(0), V.getOperand(0));
20797
20798   return SDValue();
20799 }
20800
20801 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
20802 /// generation and convert it from being a bunch of shuffles and extracts
20803 /// into a somewhat faster sequence. For i686, the best sequence is apparently
20804 /// storing the value and loading scalars back, while for x64 we should
20805 /// use 64-bit extracts and shifts.
20806 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
20807                                          TargetLowering::DAGCombinerInfo &DCI) {
20808   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
20809   if (NewOp.getNode())
20810     return NewOp;
20811
20812   SDValue InputVector = N->getOperand(0);
20813
20814   // Detect mmx to i32 conversion through a v2i32 elt extract.
20815   if (InputVector.getOpcode() == ISD::BITCAST && InputVector.hasOneUse() &&
20816       N->getValueType(0) == MVT::i32 &&
20817       InputVector.getValueType() == MVT::v2i32) {
20818
20819     // The bitcast source is a direct mmx result.
20820     SDValue MMXSrc = InputVector.getNode()->getOperand(0);
20821     if (MMXSrc.getValueType() == MVT::x86mmx)
20822       return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
20823                          N->getValueType(0),
20824                          InputVector.getNode()->getOperand(0));
20825
20826     // The mmx is indirect: (i64 extract_elt (v1i64 bitcast (x86mmx ...))).
20827     SDValue MMXSrcOp = MMXSrc.getOperand(0);
20828     if (MMXSrc.getOpcode() == ISD::EXTRACT_VECTOR_ELT && MMXSrc.hasOneUse() &&
20829         MMXSrc.getValueType() == MVT::i64 && MMXSrcOp.hasOneUse() &&
20830         MMXSrcOp.getOpcode() == ISD::BITCAST &&
20831         MMXSrcOp.getValueType() == MVT::v1i64 &&
20832         MMXSrcOp.getOperand(0).getValueType() == MVT::x86mmx)
20833       return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
20834                          N->getValueType(0),
20835                          MMXSrcOp.getOperand(0));
20836   }
20837
20838   // Only operate on vectors of 4 elements, where the alternative shuffling
20839   // gets to be more expensive.
20840   if (InputVector.getValueType() != MVT::v4i32)
20841     return SDValue();
20842
20843   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
20844   // single use which is a sign-extend or zero-extend, and all elements are
20845   // used.
20846   SmallVector<SDNode *, 4> Uses;
20847   unsigned ExtractedElements = 0;
20848   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
20849        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
20850     if (UI.getUse().getResNo() != InputVector.getResNo())
20851       return SDValue();
20852
20853     SDNode *Extract = *UI;
20854     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
20855       return SDValue();
20856
20857     if (Extract->getValueType(0) != MVT::i32)
20858       return SDValue();
20859     if (!Extract->hasOneUse())
20860       return SDValue();
20861     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
20862         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
20863       return SDValue();
20864     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
20865       return SDValue();
20866
20867     // Record which element was extracted.
20868     ExtractedElements |=
20869       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
20870
20871     Uses.push_back(Extract);
20872   }
20873
20874   // If not all the elements were used, this may not be worthwhile.
20875   if (ExtractedElements != 15)
20876     return SDValue();
20877
20878   // Ok, we've now decided to do the transformation.
20879   // If 64-bit shifts are legal, use the extract-shift sequence,
20880   // otherwise bounce the vector off the cache.
20881   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20882   SDValue Vals[4];
20883   SDLoc dl(InputVector);
20884
20885   if (TLI.isOperationLegal(ISD::SRA, MVT::i64)) {
20886     SDValue Cst = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, InputVector);
20887     EVT VecIdxTy = DAG.getTargetLoweringInfo().getVectorIdxTy();
20888     SDValue BottomHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
20889       DAG.getConstant(0, dl, VecIdxTy));
20890     SDValue TopHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
20891       DAG.getConstant(1, dl, VecIdxTy));
20892
20893     SDValue ShAmt = DAG.getConstant(32, dl,
20894       DAG.getTargetLoweringInfo().getShiftAmountTy(MVT::i64));
20895     Vals[0] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BottomHalf);
20896     Vals[1] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
20897       DAG.getNode(ISD::SRA, dl, MVT::i64, BottomHalf, ShAmt));
20898     Vals[2] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, TopHalf);
20899     Vals[3] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
20900       DAG.getNode(ISD::SRA, dl, MVT::i64, TopHalf, ShAmt));
20901   } else {
20902     // Store the value to a temporary stack slot.
20903     SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
20904     SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
20905       MachinePointerInfo(), false, false, 0);
20906
20907     EVT ElementType = InputVector.getValueType().getVectorElementType();
20908     unsigned EltSize = ElementType.getSizeInBits() / 8;
20909
20910     // Replace each use (extract) with a load of the appropriate element.
20911     for (unsigned i = 0; i < 4; ++i) {
20912       uint64_t Offset = EltSize * i;
20913       SDValue OffsetVal = DAG.getConstant(Offset, dl, TLI.getPointerTy());
20914
20915       SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
20916                                        StackPtr, OffsetVal);
20917
20918       // Load the scalar.
20919       Vals[i] = DAG.getLoad(ElementType, dl, Ch,
20920                             ScalarAddr, MachinePointerInfo(),
20921                             false, false, false, 0);
20922
20923     }
20924   }
20925
20926   // Replace the extracts
20927   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
20928     UE = Uses.end(); UI != UE; ++UI) {
20929     SDNode *Extract = *UI;
20930
20931     SDValue Idx = Extract->getOperand(1);
20932     uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
20933     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), Vals[IdxVal]);
20934   }
20935
20936   // The replacement was made in place; don't return anything.
20937   return SDValue();
20938 }
20939
20940 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
20941 static std::pair<unsigned, bool>
20942 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
20943                    SelectionDAG &DAG, const X86Subtarget *Subtarget) {
20944   if (!VT.isVector())
20945     return std::make_pair(0, false);
20946
20947   bool NeedSplit = false;
20948   switch (VT.getSimpleVT().SimpleTy) {
20949   default: return std::make_pair(0, false);
20950   case MVT::v4i64:
20951   case MVT::v2i64:
20952     if (!Subtarget->hasVLX())
20953       return std::make_pair(0, false);
20954     break;
20955   case MVT::v64i8:
20956   case MVT::v32i16:
20957     if (!Subtarget->hasBWI())
20958       return std::make_pair(0, false);
20959     break;
20960   case MVT::v16i32:
20961   case MVT::v8i64:
20962     if (!Subtarget->hasAVX512())
20963       return std::make_pair(0, false);
20964     break;
20965   case MVT::v32i8:
20966   case MVT::v16i16:
20967   case MVT::v8i32:
20968     if (!Subtarget->hasAVX2())
20969       NeedSplit = true;
20970     if (!Subtarget->hasAVX())
20971       return std::make_pair(0, false);
20972     break;
20973   case MVT::v16i8:
20974   case MVT::v8i16:
20975   case MVT::v4i32:
20976     if (!Subtarget->hasSSE2())
20977       return std::make_pair(0, false);
20978   }
20979
20980   // SSE2 has only a small subset of the operations.
20981   bool hasUnsigned = Subtarget->hasSSE41() ||
20982                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
20983   bool hasSigned = Subtarget->hasSSE41() ||
20984                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
20985
20986   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20987
20988   unsigned Opc = 0;
20989   // Check for x CC y ? x : y.
20990   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
20991       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
20992     switch (CC) {
20993     default: break;
20994     case ISD::SETULT:
20995     case ISD::SETULE:
20996       Opc = hasUnsigned ? X86ISD::UMIN : 0u; break;
20997     case ISD::SETUGT:
20998     case ISD::SETUGE:
20999       Opc = hasUnsigned ? X86ISD::UMAX : 0u; break;
21000     case ISD::SETLT:
21001     case ISD::SETLE:
21002       Opc = hasSigned ? X86ISD::SMIN : 0u; break;
21003     case ISD::SETGT:
21004     case ISD::SETGE:
21005       Opc = hasSigned ? X86ISD::SMAX : 0u; break;
21006     }
21007   // Check for x CC y ? y : x -- a min/max with reversed arms.
21008   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
21009              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
21010     switch (CC) {
21011     default: break;
21012     case ISD::SETULT:
21013     case ISD::SETULE:
21014       Opc = hasUnsigned ? X86ISD::UMAX : 0u; break;
21015     case ISD::SETUGT:
21016     case ISD::SETUGE:
21017       Opc = hasUnsigned ? X86ISD::UMIN : 0u; break;
21018     case ISD::SETLT:
21019     case ISD::SETLE:
21020       Opc = hasSigned ? X86ISD::SMAX : 0u; break;
21021     case ISD::SETGT:
21022     case ISD::SETGE:
21023       Opc = hasSigned ? X86ISD::SMIN : 0u; break;
21024     }
21025   }
21026
21027   return std::make_pair(Opc, NeedSplit);
21028 }
21029
21030 static SDValue
21031 transformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
21032                                       const X86Subtarget *Subtarget) {
21033   SDLoc dl(N);
21034   SDValue Cond = N->getOperand(0);
21035   SDValue LHS = N->getOperand(1);
21036   SDValue RHS = N->getOperand(2);
21037
21038   if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
21039     SDValue CondSrc = Cond->getOperand(0);
21040     if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
21041       Cond = CondSrc->getOperand(0);
21042   }
21043
21044   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
21045     return SDValue();
21046
21047   // A vselect where all conditions and data are constants can be optimized into
21048   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
21049   if (ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
21050       ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
21051     return SDValue();
21052
21053   unsigned MaskValue = 0;
21054   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
21055     return SDValue();
21056
21057   MVT VT = N->getSimpleValueType(0);
21058   unsigned NumElems = VT.getVectorNumElements();
21059   SmallVector<int, 8> ShuffleMask(NumElems, -1);
21060   for (unsigned i = 0; i < NumElems; ++i) {
21061     // Be sure we emit undef where we can.
21062     if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
21063       ShuffleMask[i] = -1;
21064     else
21065       ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
21066   }
21067
21068   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21069   if (!TLI.isShuffleMaskLegal(ShuffleMask, VT))
21070     return SDValue();
21071   return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
21072 }
21073
21074 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
21075 /// nodes.
21076 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
21077                                     TargetLowering::DAGCombinerInfo &DCI,
21078                                     const X86Subtarget *Subtarget) {
21079   SDLoc DL(N);
21080   SDValue Cond = N->getOperand(0);
21081   // Get the LHS/RHS of the select.
21082   SDValue LHS = N->getOperand(1);
21083   SDValue RHS = N->getOperand(2);
21084   EVT VT = LHS.getValueType();
21085   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21086
21087   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
21088   // instructions match the semantics of the common C idiom x<y?x:y but not
21089   // x<=y?x:y, because of how they handle negative zero (which can be
21090   // ignored in unsafe-math mode).
21091   // We also try to create v2f32 min/max nodes, which we later widen to v4f32.
21092   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
21093       VT != MVT::f80 && (TLI.isTypeLegal(VT) || VT == MVT::v2f32) &&
21094       (Subtarget->hasSSE2() ||
21095        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
21096     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
21097
21098     unsigned Opcode = 0;
21099     // Check for x CC y ? x : y.
21100     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
21101         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
21102       switch (CC) {
21103       default: break;
21104       case ISD::SETULT:
21105         // Converting this to a min would handle NaNs incorrectly, and swapping
21106         // the operands would cause it to handle comparisons between positive
21107         // and negative zero incorrectly.
21108         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
21109           if (!DAG.getTarget().Options.UnsafeFPMath &&
21110               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
21111             break;
21112           std::swap(LHS, RHS);
21113         }
21114         Opcode = X86ISD::FMIN;
21115         break;
21116       case ISD::SETOLE:
21117         // Converting this to a min would handle comparisons between positive
21118         // and negative zero incorrectly.
21119         if (!DAG.getTarget().Options.UnsafeFPMath &&
21120             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
21121           break;
21122         Opcode = X86ISD::FMIN;
21123         break;
21124       case ISD::SETULE:
21125         // Converting this to a min would handle both negative zeros and NaNs
21126         // incorrectly, but we can swap the operands to fix both.
21127         std::swap(LHS, RHS);
21128       case ISD::SETOLT:
21129       case ISD::SETLT:
21130       case ISD::SETLE:
21131         Opcode = X86ISD::FMIN;
21132         break;
21133
21134       case ISD::SETOGE:
21135         // Converting this to a max would handle comparisons between positive
21136         // and negative zero incorrectly.
21137         if (!DAG.getTarget().Options.UnsafeFPMath &&
21138             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
21139           break;
21140         Opcode = X86ISD::FMAX;
21141         break;
21142       case ISD::SETUGT:
21143         // Converting this to a max would handle NaNs incorrectly, and swapping
21144         // the operands would cause it to handle comparisons between positive
21145         // and negative zero incorrectly.
21146         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
21147           if (!DAG.getTarget().Options.UnsafeFPMath &&
21148               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
21149             break;
21150           std::swap(LHS, RHS);
21151         }
21152         Opcode = X86ISD::FMAX;
21153         break;
21154       case ISD::SETUGE:
21155         // Converting this to a max would handle both negative zeros and NaNs
21156         // incorrectly, but we can swap the operands to fix both.
21157         std::swap(LHS, RHS);
21158       case ISD::SETOGT:
21159       case ISD::SETGT:
21160       case ISD::SETGE:
21161         Opcode = X86ISD::FMAX;
21162         break;
21163       }
21164     // Check for x CC y ? y : x -- a min/max with reversed arms.
21165     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
21166                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
21167       switch (CC) {
21168       default: break;
21169       case ISD::SETOGE:
21170         // Converting this to a min would handle comparisons between positive
21171         // and negative zero incorrectly, and swapping the operands would
21172         // cause it to handle NaNs incorrectly.
21173         if (!DAG.getTarget().Options.UnsafeFPMath &&
21174             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
21175           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
21176             break;
21177           std::swap(LHS, RHS);
21178         }
21179         Opcode = X86ISD::FMIN;
21180         break;
21181       case ISD::SETUGT:
21182         // Converting this to a min would handle NaNs incorrectly.
21183         if (!DAG.getTarget().Options.UnsafeFPMath &&
21184             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
21185           break;
21186         Opcode = X86ISD::FMIN;
21187         break;
21188       case ISD::SETUGE:
21189         // Converting this to a min would handle both negative zeros and NaNs
21190         // incorrectly, but we can swap the operands to fix both.
21191         std::swap(LHS, RHS);
21192       case ISD::SETOGT:
21193       case ISD::SETGT:
21194       case ISD::SETGE:
21195         Opcode = X86ISD::FMIN;
21196         break;
21197
21198       case ISD::SETULT:
21199         // Converting this to a max would handle NaNs incorrectly.
21200         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
21201           break;
21202         Opcode = X86ISD::FMAX;
21203         break;
21204       case ISD::SETOLE:
21205         // Converting this to a max would handle comparisons between positive
21206         // and negative zero incorrectly, and swapping the operands would
21207         // cause it to handle NaNs incorrectly.
21208         if (!DAG.getTarget().Options.UnsafeFPMath &&
21209             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
21210           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
21211             break;
21212           std::swap(LHS, RHS);
21213         }
21214         Opcode = X86ISD::FMAX;
21215         break;
21216       case ISD::SETULE:
21217         // Converting this to a max would handle both negative zeros and NaNs
21218         // incorrectly, but we can swap the operands to fix both.
21219         std::swap(LHS, RHS);
21220       case ISD::SETOLT:
21221       case ISD::SETLT:
21222       case ISD::SETLE:
21223         Opcode = X86ISD::FMAX;
21224         break;
21225       }
21226     }
21227
21228     if (Opcode)
21229       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
21230   }
21231
21232   EVT CondVT = Cond.getValueType();
21233   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
21234       CondVT.getVectorElementType() == MVT::i1) {
21235     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
21236     // lowering on KNL. In this case we convert it to
21237     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
21238     // The same situation for all 128 and 256-bit vectors of i8 and i16.
21239     // Since SKX these selects have a proper lowering.
21240     EVT OpVT = LHS.getValueType();
21241     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
21242         (OpVT.getVectorElementType() == MVT::i8 ||
21243          OpVT.getVectorElementType() == MVT::i16) &&
21244         !(Subtarget->hasBWI() && Subtarget->hasVLX())) {
21245       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
21246       DCI.AddToWorklist(Cond.getNode());
21247       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
21248     }
21249   }
21250   // If this is a select between two integer constants, try to do some
21251   // optimizations.
21252   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
21253     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
21254       // Don't do this for crazy integer types.
21255       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
21256         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
21257         // so that TrueC (the true value) is larger than FalseC.
21258         bool NeedsCondInvert = false;
21259
21260         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
21261             // Efficiently invertible.
21262             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
21263              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
21264               isa<ConstantSDNode>(Cond.getOperand(1))))) {
21265           NeedsCondInvert = true;
21266           std::swap(TrueC, FalseC);
21267         }
21268
21269         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
21270         if (FalseC->getAPIntValue() == 0 &&
21271             TrueC->getAPIntValue().isPowerOf2()) {
21272           if (NeedsCondInvert) // Invert the condition if needed.
21273             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
21274                                DAG.getConstant(1, DL, Cond.getValueType()));
21275
21276           // Zero extend the condition if needed.
21277           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
21278
21279           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
21280           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
21281                              DAG.getConstant(ShAmt, DL, MVT::i8));
21282         }
21283
21284         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
21285         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
21286           if (NeedsCondInvert) // Invert the condition if needed.
21287             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
21288                                DAG.getConstant(1, DL, Cond.getValueType()));
21289
21290           // Zero extend the condition if needed.
21291           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
21292                              FalseC->getValueType(0), Cond);
21293           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
21294                              SDValue(FalseC, 0));
21295         }
21296
21297         // Optimize cases that will turn into an LEA instruction.  This requires
21298         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
21299         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
21300           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
21301           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
21302
21303           bool isFastMultiplier = false;
21304           if (Diff < 10) {
21305             switch ((unsigned char)Diff) {
21306               default: break;
21307               case 1:  // result = add base, cond
21308               case 2:  // result = lea base(    , cond*2)
21309               case 3:  // result = lea base(cond, cond*2)
21310               case 4:  // result = lea base(    , cond*4)
21311               case 5:  // result = lea base(cond, cond*4)
21312               case 8:  // result = lea base(    , cond*8)
21313               case 9:  // result = lea base(cond, cond*8)
21314                 isFastMultiplier = true;
21315                 break;
21316             }
21317           }
21318
21319           if (isFastMultiplier) {
21320             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
21321             if (NeedsCondInvert) // Invert the condition if needed.
21322               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
21323                                  DAG.getConstant(1, DL, Cond.getValueType()));
21324
21325             // Zero extend the condition if needed.
21326             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
21327                                Cond);
21328             // Scale the condition by the difference.
21329             if (Diff != 1)
21330               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
21331                                  DAG.getConstant(Diff, DL,
21332                                                  Cond.getValueType()));
21333
21334             // Add the base if non-zero.
21335             if (FalseC->getAPIntValue() != 0)
21336               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
21337                                  SDValue(FalseC, 0));
21338             return Cond;
21339           }
21340         }
21341       }
21342   }
21343
21344   // Canonicalize max and min:
21345   // (x > y) ? x : y -> (x >= y) ? x : y
21346   // (x < y) ? x : y -> (x <= y) ? x : y
21347   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
21348   // the need for an extra compare
21349   // against zero. e.g.
21350   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
21351   // subl   %esi, %edi
21352   // testl  %edi, %edi
21353   // movl   $0, %eax
21354   // cmovgl %edi, %eax
21355   // =>
21356   // xorl   %eax, %eax
21357   // subl   %esi, $edi
21358   // cmovsl %eax, %edi
21359   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
21360       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
21361       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
21362     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
21363     switch (CC) {
21364     default: break;
21365     case ISD::SETLT:
21366     case ISD::SETGT: {
21367       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
21368       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
21369                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
21370       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
21371     }
21372     }
21373   }
21374
21375   // Early exit check
21376   if (!TLI.isTypeLegal(VT))
21377     return SDValue();
21378
21379   // Match VSELECTs into subs with unsigned saturation.
21380   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
21381       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
21382       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
21383        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
21384     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
21385
21386     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
21387     // left side invert the predicate to simplify logic below.
21388     SDValue Other;
21389     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
21390       Other = RHS;
21391       CC = ISD::getSetCCInverse(CC, true);
21392     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
21393       Other = LHS;
21394     }
21395
21396     if (Other.getNode() && Other->getNumOperands() == 2 &&
21397         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
21398       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
21399       SDValue CondRHS = Cond->getOperand(1);
21400
21401       // Look for a general sub with unsigned saturation first.
21402       // x >= y ? x-y : 0 --> subus x, y
21403       // x >  y ? x-y : 0 --> subus x, y
21404       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
21405           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
21406         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
21407
21408       if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
21409         if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
21410           if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
21411             if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
21412               // If the RHS is a constant we have to reverse the const
21413               // canonicalization.
21414               // x > C-1 ? x+-C : 0 --> subus x, C
21415               if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
21416                   CondRHSConst->getAPIntValue() ==
21417                       (-OpRHSConst->getAPIntValue() - 1))
21418                 return DAG.getNode(
21419                     X86ISD::SUBUS, DL, VT, OpLHS,
21420                     DAG.getConstant(-OpRHSConst->getAPIntValue(), DL, VT));
21421
21422           // Another special case: If C was a sign bit, the sub has been
21423           // canonicalized into a xor.
21424           // FIXME: Would it be better to use computeKnownBits to determine
21425           //        whether it's safe to decanonicalize the xor?
21426           // x s< 0 ? x^C : 0 --> subus x, C
21427           if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
21428               ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
21429               OpRHSConst->getAPIntValue().isSignBit())
21430             // Note that we have to rebuild the RHS constant here to ensure we
21431             // don't rely on particular values of undef lanes.
21432             return DAG.getNode(
21433                 X86ISD::SUBUS, DL, VT, OpLHS,
21434                 DAG.getConstant(OpRHSConst->getAPIntValue(), DL, VT));
21435         }
21436     }
21437   }
21438
21439   // Try to match a min/max vector operation.
21440   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
21441     std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
21442     unsigned Opc = ret.first;
21443     bool NeedSplit = ret.second;
21444
21445     if (Opc && NeedSplit) {
21446       unsigned NumElems = VT.getVectorNumElements();
21447       // Extract the LHS vectors
21448       SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
21449       SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
21450
21451       // Extract the RHS vectors
21452       SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
21453       SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
21454
21455       // Create min/max for each subvector
21456       LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
21457       RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
21458
21459       // Merge the result
21460       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
21461     } else if (Opc)
21462       return DAG.getNode(Opc, DL, VT, LHS, RHS);
21463   }
21464
21465   // Simplify vector selection if condition value type matches vselect
21466   // operand type
21467   if (N->getOpcode() == ISD::VSELECT && CondVT == VT) {
21468     assert(Cond.getValueType().isVector() &&
21469            "vector select expects a vector selector!");
21470
21471     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
21472     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
21473
21474     // Try invert the condition if true value is not all 1s and false value
21475     // is not all 0s.
21476     if (!TValIsAllOnes && !FValIsAllZeros &&
21477         // Check if the selector will be produced by CMPP*/PCMP*
21478         Cond.getOpcode() == ISD::SETCC &&
21479         // Check if SETCC has already been promoted
21480         TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT) {
21481       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
21482       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
21483
21484       if (TValIsAllZeros || FValIsAllOnes) {
21485         SDValue CC = Cond.getOperand(2);
21486         ISD::CondCode NewCC =
21487           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
21488                                Cond.getOperand(0).getValueType().isInteger());
21489         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
21490         std::swap(LHS, RHS);
21491         TValIsAllOnes = FValIsAllOnes;
21492         FValIsAllZeros = TValIsAllZeros;
21493       }
21494     }
21495
21496     if (TValIsAllOnes || FValIsAllZeros) {
21497       SDValue Ret;
21498
21499       if (TValIsAllOnes && FValIsAllZeros)
21500         Ret = Cond;
21501       else if (TValIsAllOnes)
21502         Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
21503                           DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
21504       else if (FValIsAllZeros)
21505         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
21506                           DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
21507
21508       return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
21509     }
21510   }
21511
21512   // We should generate an X86ISD::BLENDI from a vselect if its argument
21513   // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
21514   // constants. This specific pattern gets generated when we split a
21515   // selector for a 512 bit vector in a machine without AVX512 (but with
21516   // 256-bit vectors), during legalization:
21517   //
21518   // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
21519   //
21520   // Iff we find this pattern and the build_vectors are built from
21521   // constants, we translate the vselect into a shuffle_vector that we
21522   // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
21523   if ((N->getOpcode() == ISD::VSELECT ||
21524        N->getOpcode() == X86ISD::SHRUNKBLEND) &&
21525       !DCI.isBeforeLegalize()) {
21526     SDValue Shuffle = transformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
21527     if (Shuffle.getNode())
21528       return Shuffle;
21529   }
21530
21531   // If this is a *dynamic* select (non-constant condition) and we can match
21532   // this node with one of the variable blend instructions, restructure the
21533   // condition so that the blends can use the high bit of each element and use
21534   // SimplifyDemandedBits to simplify the condition operand.
21535   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
21536       !DCI.isBeforeLegalize() &&
21537       !ISD::isBuildVectorOfConstantSDNodes(Cond.getNode())) {
21538     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
21539
21540     // Don't optimize vector selects that map to mask-registers.
21541     if (BitWidth == 1)
21542       return SDValue();
21543
21544     // We can only handle the cases where VSELECT is directly legal on the
21545     // subtarget. We custom lower VSELECT nodes with constant conditions and
21546     // this makes it hard to see whether a dynamic VSELECT will correctly
21547     // lower, so we both check the operation's status and explicitly handle the
21548     // cases where a *dynamic* blend will fail even though a constant-condition
21549     // blend could be custom lowered.
21550     // FIXME: We should find a better way to handle this class of problems.
21551     // Potentially, we should combine constant-condition vselect nodes
21552     // pre-legalization into shuffles and not mark as many types as custom
21553     // lowered.
21554     if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
21555       return SDValue();
21556     // FIXME: We don't support i16-element blends currently. We could and
21557     // should support them by making *all* the bits in the condition be set
21558     // rather than just the high bit and using an i8-element blend.
21559     if (VT.getScalarType() == MVT::i16)
21560       return SDValue();
21561     // Dynamic blending was only available from SSE4.1 onward.
21562     if (VT.getSizeInBits() == 128 && !Subtarget->hasSSE41())
21563       return SDValue();
21564     // Byte blends are only available in AVX2
21565     if (VT.getSizeInBits() == 256 && VT.getScalarType() == MVT::i8 &&
21566         !Subtarget->hasAVX2())
21567       return SDValue();
21568
21569     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
21570     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
21571
21572     APInt KnownZero, KnownOne;
21573     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
21574                                           DCI.isBeforeLegalizeOps());
21575     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
21576         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne,
21577                                  TLO)) {
21578       // If we changed the computation somewhere in the DAG, this change
21579       // will affect all users of Cond.
21580       // Make sure it is fine and update all the nodes so that we do not
21581       // use the generic VSELECT anymore. Otherwise, we may perform
21582       // wrong optimizations as we messed up with the actual expectation
21583       // for the vector boolean values.
21584       if (Cond != TLO.Old) {
21585         // Check all uses of that condition operand to check whether it will be
21586         // consumed by non-BLEND instructions, which may depend on all bits are
21587         // set properly.
21588         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
21589              I != E; ++I)
21590           if (I->getOpcode() != ISD::VSELECT)
21591             // TODO: Add other opcodes eventually lowered into BLEND.
21592             return SDValue();
21593
21594         // Update all the users of the condition, before committing the change,
21595         // so that the VSELECT optimizations that expect the correct vector
21596         // boolean value will not be triggered.
21597         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
21598              I != E; ++I)
21599           DAG.ReplaceAllUsesOfValueWith(
21600               SDValue(*I, 0),
21601               DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(*I), I->getValueType(0),
21602                           Cond, I->getOperand(1), I->getOperand(2)));
21603         DCI.CommitTargetLoweringOpt(TLO);
21604         return SDValue();
21605       }
21606       // At this point, only Cond is changed. Change the condition
21607       // just for N to keep the opportunity to optimize all other
21608       // users their own way.
21609       DAG.ReplaceAllUsesOfValueWith(
21610           SDValue(N, 0),
21611           DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(N), N->getValueType(0),
21612                       TLO.New, N->getOperand(1), N->getOperand(2)));
21613       return SDValue();
21614     }
21615   }
21616
21617   return SDValue();
21618 }
21619
21620 // Check whether a boolean test is testing a boolean value generated by
21621 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
21622 // code.
21623 //
21624 // Simplify the following patterns:
21625 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
21626 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
21627 // to (Op EFLAGS Cond)
21628 //
21629 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
21630 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
21631 // to (Op EFLAGS !Cond)
21632 //
21633 // where Op could be BRCOND or CMOV.
21634 //
21635 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
21636   // Quit if not CMP and SUB with its value result used.
21637   if (Cmp.getOpcode() != X86ISD::CMP &&
21638       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
21639       return SDValue();
21640
21641   // Quit if not used as a boolean value.
21642   if (CC != X86::COND_E && CC != X86::COND_NE)
21643     return SDValue();
21644
21645   // Check CMP operands. One of them should be 0 or 1 and the other should be
21646   // an SetCC or extended from it.
21647   SDValue Op1 = Cmp.getOperand(0);
21648   SDValue Op2 = Cmp.getOperand(1);
21649
21650   SDValue SetCC;
21651   const ConstantSDNode* C = nullptr;
21652   bool needOppositeCond = (CC == X86::COND_E);
21653   bool checkAgainstTrue = false; // Is it a comparison against 1?
21654
21655   if ((C = dyn_cast<ConstantSDNode>(Op1)))
21656     SetCC = Op2;
21657   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
21658     SetCC = Op1;
21659   else // Quit if all operands are not constants.
21660     return SDValue();
21661
21662   if (C->getZExtValue() == 1) {
21663     needOppositeCond = !needOppositeCond;
21664     checkAgainstTrue = true;
21665   } else if (C->getZExtValue() != 0)
21666     // Quit if the constant is neither 0 or 1.
21667     return SDValue();
21668
21669   bool truncatedToBoolWithAnd = false;
21670   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
21671   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
21672          SetCC.getOpcode() == ISD::TRUNCATE ||
21673          SetCC.getOpcode() == ISD::AND) {
21674     if (SetCC.getOpcode() == ISD::AND) {
21675       int OpIdx = -1;
21676       ConstantSDNode *CS;
21677       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
21678           CS->getZExtValue() == 1)
21679         OpIdx = 1;
21680       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
21681           CS->getZExtValue() == 1)
21682         OpIdx = 0;
21683       if (OpIdx == -1)
21684         break;
21685       SetCC = SetCC.getOperand(OpIdx);
21686       truncatedToBoolWithAnd = true;
21687     } else
21688       SetCC = SetCC.getOperand(0);
21689   }
21690
21691   switch (SetCC.getOpcode()) {
21692   case X86ISD::SETCC_CARRY:
21693     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
21694     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
21695     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
21696     // truncated to i1 using 'and'.
21697     if (checkAgainstTrue && !truncatedToBoolWithAnd)
21698       break;
21699     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
21700            "Invalid use of SETCC_CARRY!");
21701     // FALL THROUGH
21702   case X86ISD::SETCC:
21703     // Set the condition code or opposite one if necessary.
21704     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
21705     if (needOppositeCond)
21706       CC = X86::GetOppositeBranchCondition(CC);
21707     return SetCC.getOperand(1);
21708   case X86ISD::CMOV: {
21709     // Check whether false/true value has canonical one, i.e. 0 or 1.
21710     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
21711     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
21712     // Quit if true value is not a constant.
21713     if (!TVal)
21714       return SDValue();
21715     // Quit if false value is not a constant.
21716     if (!FVal) {
21717       SDValue Op = SetCC.getOperand(0);
21718       // Skip 'zext' or 'trunc' node.
21719       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
21720           Op.getOpcode() == ISD::TRUNCATE)
21721         Op = Op.getOperand(0);
21722       // A special case for rdrand/rdseed, where 0 is set if false cond is
21723       // found.
21724       if ((Op.getOpcode() != X86ISD::RDRAND &&
21725            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
21726         return SDValue();
21727     }
21728     // Quit if false value is not the constant 0 or 1.
21729     bool FValIsFalse = true;
21730     if (FVal && FVal->getZExtValue() != 0) {
21731       if (FVal->getZExtValue() != 1)
21732         return SDValue();
21733       // If FVal is 1, opposite cond is needed.
21734       needOppositeCond = !needOppositeCond;
21735       FValIsFalse = false;
21736     }
21737     // Quit if TVal is not the constant opposite of FVal.
21738     if (FValIsFalse && TVal->getZExtValue() != 1)
21739       return SDValue();
21740     if (!FValIsFalse && TVal->getZExtValue() != 0)
21741       return SDValue();
21742     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
21743     if (needOppositeCond)
21744       CC = X86::GetOppositeBranchCondition(CC);
21745     return SetCC.getOperand(3);
21746   }
21747   }
21748
21749   return SDValue();
21750 }
21751
21752 /// Check whether Cond is an AND/OR of SETCCs off of the same EFLAGS.
21753 /// Match:
21754 ///   (X86or (X86setcc) (X86setcc))
21755 ///   (X86cmp (and (X86setcc) (X86setcc)), 0)
21756 static bool checkBoolTestAndOrSetCCCombine(SDValue Cond, X86::CondCode &CC0,
21757                                            X86::CondCode &CC1, SDValue &Flags,
21758                                            bool &isAnd) {
21759   if (Cond->getOpcode() == X86ISD::CMP) {
21760     ConstantSDNode *CondOp1C = dyn_cast<ConstantSDNode>(Cond->getOperand(1));
21761     if (!CondOp1C || !CondOp1C->isNullValue())
21762       return false;
21763
21764     Cond = Cond->getOperand(0);
21765   }
21766
21767   isAnd = false;
21768
21769   SDValue SetCC0, SetCC1;
21770   switch (Cond->getOpcode()) {
21771   default: return false;
21772   case ISD::AND:
21773   case X86ISD::AND:
21774     isAnd = true;
21775     // fallthru
21776   case ISD::OR:
21777   case X86ISD::OR:
21778     SetCC0 = Cond->getOperand(0);
21779     SetCC1 = Cond->getOperand(1);
21780     break;
21781   };
21782
21783   // Make sure we have SETCC nodes, using the same flags value.
21784   if (SetCC0.getOpcode() != X86ISD::SETCC ||
21785       SetCC1.getOpcode() != X86ISD::SETCC ||
21786       SetCC0->getOperand(1) != SetCC1->getOperand(1))
21787     return false;
21788
21789   CC0 = (X86::CondCode)SetCC0->getConstantOperandVal(0);
21790   CC1 = (X86::CondCode)SetCC1->getConstantOperandVal(0);
21791   Flags = SetCC0->getOperand(1);
21792   return true;
21793 }
21794
21795 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
21796 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
21797                                   TargetLowering::DAGCombinerInfo &DCI,
21798                                   const X86Subtarget *Subtarget) {
21799   SDLoc DL(N);
21800
21801   // If the flag operand isn't dead, don't touch this CMOV.
21802   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
21803     return SDValue();
21804
21805   SDValue FalseOp = N->getOperand(0);
21806   SDValue TrueOp = N->getOperand(1);
21807   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
21808   SDValue Cond = N->getOperand(3);
21809
21810   if (CC == X86::COND_E || CC == X86::COND_NE) {
21811     switch (Cond.getOpcode()) {
21812     default: break;
21813     case X86ISD::BSR:
21814     case X86ISD::BSF:
21815       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
21816       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
21817         return (CC == X86::COND_E) ? FalseOp : TrueOp;
21818     }
21819   }
21820
21821   SDValue Flags;
21822
21823   Flags = checkBoolTestSetCCCombine(Cond, CC);
21824   if (Flags.getNode() &&
21825       // Extra check as FCMOV only supports a subset of X86 cond.
21826       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
21827     SDValue Ops[] = { FalseOp, TrueOp,
21828                       DAG.getConstant(CC, DL, MVT::i8), Flags };
21829     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
21830   }
21831
21832   // If this is a select between two integer constants, try to do some
21833   // optimizations.  Note that the operands are ordered the opposite of SELECT
21834   // operands.
21835   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
21836     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
21837       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
21838       // larger than FalseC (the false value).
21839       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
21840         CC = X86::GetOppositeBranchCondition(CC);
21841         std::swap(TrueC, FalseC);
21842         std::swap(TrueOp, FalseOp);
21843       }
21844
21845       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
21846       // This is efficient for any integer data type (including i8/i16) and
21847       // shift amount.
21848       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
21849         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
21850                            DAG.getConstant(CC, DL, MVT::i8), Cond);
21851
21852         // Zero extend the condition if needed.
21853         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
21854
21855         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
21856         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
21857                            DAG.getConstant(ShAmt, DL, MVT::i8));
21858         if (N->getNumValues() == 2)  // Dead flag value?
21859           return DCI.CombineTo(N, Cond, SDValue());
21860         return Cond;
21861       }
21862
21863       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
21864       // for any integer data type, including i8/i16.
21865       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
21866         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
21867                            DAG.getConstant(CC, DL, MVT::i8), Cond);
21868
21869         // Zero extend the condition if needed.
21870         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
21871                            FalseC->getValueType(0), Cond);
21872         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
21873                            SDValue(FalseC, 0));
21874
21875         if (N->getNumValues() == 2)  // Dead flag value?
21876           return DCI.CombineTo(N, Cond, SDValue());
21877         return Cond;
21878       }
21879
21880       // Optimize cases that will turn into an LEA instruction.  This requires
21881       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
21882       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
21883         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
21884         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
21885
21886         bool isFastMultiplier = false;
21887         if (Diff < 10) {
21888           switch ((unsigned char)Diff) {
21889           default: break;
21890           case 1:  // result = add base, cond
21891           case 2:  // result = lea base(    , cond*2)
21892           case 3:  // result = lea base(cond, cond*2)
21893           case 4:  // result = lea base(    , cond*4)
21894           case 5:  // result = lea base(cond, cond*4)
21895           case 8:  // result = lea base(    , cond*8)
21896           case 9:  // result = lea base(cond, cond*8)
21897             isFastMultiplier = true;
21898             break;
21899           }
21900         }
21901
21902         if (isFastMultiplier) {
21903           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
21904           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
21905                              DAG.getConstant(CC, DL, MVT::i8), Cond);
21906           // Zero extend the condition if needed.
21907           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
21908                              Cond);
21909           // Scale the condition by the difference.
21910           if (Diff != 1)
21911             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
21912                                DAG.getConstant(Diff, DL, Cond.getValueType()));
21913
21914           // Add the base if non-zero.
21915           if (FalseC->getAPIntValue() != 0)
21916             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
21917                                SDValue(FalseC, 0));
21918           if (N->getNumValues() == 2)  // Dead flag value?
21919             return DCI.CombineTo(N, Cond, SDValue());
21920           return Cond;
21921         }
21922       }
21923     }
21924   }
21925
21926   // Handle these cases:
21927   //   (select (x != c), e, c) -> select (x != c), e, x),
21928   //   (select (x == c), c, e) -> select (x == c), x, e)
21929   // where the c is an integer constant, and the "select" is the combination
21930   // of CMOV and CMP.
21931   //
21932   // The rationale for this change is that the conditional-move from a constant
21933   // needs two instructions, however, conditional-move from a register needs
21934   // only one instruction.
21935   //
21936   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
21937   //  some instruction-combining opportunities. This opt needs to be
21938   //  postponed as late as possible.
21939   //
21940   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
21941     // the DCI.xxxx conditions are provided to postpone the optimization as
21942     // late as possible.
21943
21944     ConstantSDNode *CmpAgainst = nullptr;
21945     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
21946         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
21947         !isa<ConstantSDNode>(Cond.getOperand(0))) {
21948
21949       if (CC == X86::COND_NE &&
21950           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
21951         CC = X86::GetOppositeBranchCondition(CC);
21952         std::swap(TrueOp, FalseOp);
21953       }
21954
21955       if (CC == X86::COND_E &&
21956           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
21957         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
21958                           DAG.getConstant(CC, DL, MVT::i8), Cond };
21959         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
21960       }
21961     }
21962   }
21963
21964   // Fold and/or of setcc's to double CMOV:
21965   //   (CMOV F, T, ((cc1 | cc2) != 0)) -> (CMOV (CMOV F, T, cc1), T, cc2)
21966   //   (CMOV F, T, ((cc1 & cc2) != 0)) -> (CMOV (CMOV T, F, !cc1), F, !cc2)
21967   //
21968   // This combine lets us generate:
21969   //   cmovcc1 (jcc1 if we don't have CMOV)
21970   //   cmovcc2 (same)
21971   // instead of:
21972   //   setcc1
21973   //   setcc2
21974   //   and/or
21975   //   cmovne (jne if we don't have CMOV)
21976   // When we can't use the CMOV instruction, it might increase branch
21977   // mispredicts.
21978   // When we can use CMOV, or when there is no mispredict, this improves
21979   // throughput and reduces register pressure.
21980   //
21981   if (CC == X86::COND_NE) {
21982     SDValue Flags;
21983     X86::CondCode CC0, CC1;
21984     bool isAndSetCC;
21985     if (checkBoolTestAndOrSetCCCombine(Cond, CC0, CC1, Flags, isAndSetCC)) {
21986       if (isAndSetCC) {
21987         std::swap(FalseOp, TrueOp);
21988         CC0 = X86::GetOppositeBranchCondition(CC0);
21989         CC1 = X86::GetOppositeBranchCondition(CC1);
21990       }
21991
21992       SDValue LOps[] = {FalseOp, TrueOp, DAG.getConstant(CC0, DL, MVT::i8),
21993         Flags};
21994       SDValue LCMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), LOps);
21995       SDValue Ops[] = {LCMOV, TrueOp, DAG.getConstant(CC1, DL, MVT::i8), Flags};
21996       SDValue CMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
21997       DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SDValue(CMOV.getNode(), 1));
21998       return CMOV;
21999     }
22000   }
22001
22002   return SDValue();
22003 }
22004
22005 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
22006                                                 const X86Subtarget *Subtarget) {
22007   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
22008   switch (IntNo) {
22009   default: return SDValue();
22010   // SSE/AVX/AVX2 blend intrinsics.
22011   case Intrinsic::x86_avx2_pblendvb:
22012     // Don't try to simplify this intrinsic if we don't have AVX2.
22013     if (!Subtarget->hasAVX2())
22014       return SDValue();
22015     // FALL-THROUGH
22016   case Intrinsic::x86_avx_blendv_pd_256:
22017   case Intrinsic::x86_avx_blendv_ps_256:
22018     // Don't try to simplify this intrinsic if we don't have AVX.
22019     if (!Subtarget->hasAVX())
22020       return SDValue();
22021     // FALL-THROUGH
22022   case Intrinsic::x86_sse41_blendvps:
22023   case Intrinsic::x86_sse41_blendvpd:
22024   case Intrinsic::x86_sse41_pblendvb: {
22025     SDValue Op0 = N->getOperand(1);
22026     SDValue Op1 = N->getOperand(2);
22027     SDValue Mask = N->getOperand(3);
22028
22029     // Don't try to simplify this intrinsic if we don't have SSE4.1.
22030     if (!Subtarget->hasSSE41())
22031       return SDValue();
22032
22033     // fold (blend A, A, Mask) -> A
22034     if (Op0 == Op1)
22035       return Op0;
22036     // fold (blend A, B, allZeros) -> A
22037     if (ISD::isBuildVectorAllZeros(Mask.getNode()))
22038       return Op0;
22039     // fold (blend A, B, allOnes) -> B
22040     if (ISD::isBuildVectorAllOnes(Mask.getNode()))
22041       return Op1;
22042
22043     // Simplify the case where the mask is a constant i32 value.
22044     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
22045       if (C->isNullValue())
22046         return Op0;
22047       if (C->isAllOnesValue())
22048         return Op1;
22049     }
22050
22051     return SDValue();
22052   }
22053
22054   // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
22055   case Intrinsic::x86_sse2_psrai_w:
22056   case Intrinsic::x86_sse2_psrai_d:
22057   case Intrinsic::x86_avx2_psrai_w:
22058   case Intrinsic::x86_avx2_psrai_d:
22059   case Intrinsic::x86_sse2_psra_w:
22060   case Intrinsic::x86_sse2_psra_d:
22061   case Intrinsic::x86_avx2_psra_w:
22062   case Intrinsic::x86_avx2_psra_d: {
22063     SDValue Op0 = N->getOperand(1);
22064     SDValue Op1 = N->getOperand(2);
22065     EVT VT = Op0.getValueType();
22066     assert(VT.isVector() && "Expected a vector type!");
22067
22068     if (isa<BuildVectorSDNode>(Op1))
22069       Op1 = Op1.getOperand(0);
22070
22071     if (!isa<ConstantSDNode>(Op1))
22072       return SDValue();
22073
22074     EVT SVT = VT.getVectorElementType();
22075     unsigned SVTBits = SVT.getSizeInBits();
22076
22077     ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
22078     const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
22079     uint64_t ShAmt = C.getZExtValue();
22080
22081     // Don't try to convert this shift into a ISD::SRA if the shift
22082     // count is bigger than or equal to the element size.
22083     if (ShAmt >= SVTBits)
22084       return SDValue();
22085
22086     // Trivial case: if the shift count is zero, then fold this
22087     // into the first operand.
22088     if (ShAmt == 0)
22089       return Op0;
22090
22091     // Replace this packed shift intrinsic with a target independent
22092     // shift dag node.
22093     SDLoc DL(N);
22094     SDValue Splat = DAG.getConstant(C, DL, VT);
22095     return DAG.getNode(ISD::SRA, DL, VT, Op0, Splat);
22096   }
22097   }
22098 }
22099
22100 /// PerformMulCombine - Optimize a single multiply with constant into two
22101 /// in order to implement it with two cheaper instructions, e.g.
22102 /// LEA + SHL, LEA + LEA.
22103 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
22104                                  TargetLowering::DAGCombinerInfo &DCI) {
22105   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
22106     return SDValue();
22107
22108   EVT VT = N->getValueType(0);
22109   if (VT != MVT::i64 && VT != MVT::i32)
22110     return SDValue();
22111
22112   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
22113   if (!C)
22114     return SDValue();
22115   uint64_t MulAmt = C->getZExtValue();
22116   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
22117     return SDValue();
22118
22119   uint64_t MulAmt1 = 0;
22120   uint64_t MulAmt2 = 0;
22121   if ((MulAmt % 9) == 0) {
22122     MulAmt1 = 9;
22123     MulAmt2 = MulAmt / 9;
22124   } else if ((MulAmt % 5) == 0) {
22125     MulAmt1 = 5;
22126     MulAmt2 = MulAmt / 5;
22127   } else if ((MulAmt % 3) == 0) {
22128     MulAmt1 = 3;
22129     MulAmt2 = MulAmt / 3;
22130   }
22131   if (MulAmt2 &&
22132       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
22133     SDLoc DL(N);
22134
22135     if (isPowerOf2_64(MulAmt2) &&
22136         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
22137       // If second multiplifer is pow2, issue it first. We want the multiply by
22138       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
22139       // is an add.
22140       std::swap(MulAmt1, MulAmt2);
22141
22142     SDValue NewMul;
22143     if (isPowerOf2_64(MulAmt1))
22144       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
22145                            DAG.getConstant(Log2_64(MulAmt1), DL, MVT::i8));
22146     else
22147       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
22148                            DAG.getConstant(MulAmt1, DL, VT));
22149
22150     if (isPowerOf2_64(MulAmt2))
22151       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
22152                            DAG.getConstant(Log2_64(MulAmt2), DL, MVT::i8));
22153     else
22154       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
22155                            DAG.getConstant(MulAmt2, DL, VT));
22156
22157     // Do not add new nodes to DAG combiner worklist.
22158     DCI.CombineTo(N, NewMul, false);
22159   }
22160   return SDValue();
22161 }
22162
22163 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
22164   SDValue N0 = N->getOperand(0);
22165   SDValue N1 = N->getOperand(1);
22166   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
22167   EVT VT = N0.getValueType();
22168
22169   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
22170   // since the result of setcc_c is all zero's or all ones.
22171   if (VT.isInteger() && !VT.isVector() &&
22172       N1C && N0.getOpcode() == ISD::AND &&
22173       N0.getOperand(1).getOpcode() == ISD::Constant) {
22174     SDValue N00 = N0.getOperand(0);
22175     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
22176         ((N00.getOpcode() == ISD::ANY_EXTEND ||
22177           N00.getOpcode() == ISD::ZERO_EXTEND) &&
22178          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
22179       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
22180       APInt ShAmt = N1C->getAPIntValue();
22181       Mask = Mask.shl(ShAmt);
22182       if (Mask != 0) {
22183         SDLoc DL(N);
22184         return DAG.getNode(ISD::AND, DL, VT,
22185                            N00, DAG.getConstant(Mask, DL, VT));
22186       }
22187     }
22188   }
22189
22190   // Hardware support for vector shifts is sparse which makes us scalarize the
22191   // vector operations in many cases. Also, on sandybridge ADD is faster than
22192   // shl.
22193   // (shl V, 1) -> add V,V
22194   if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
22195     if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
22196       assert(N0.getValueType().isVector() && "Invalid vector shift type");
22197       // We shift all of the values by one. In many cases we do not have
22198       // hardware support for this operation. This is better expressed as an ADD
22199       // of two values.
22200       if (N1SplatC->getZExtValue() == 1)
22201         return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
22202     }
22203
22204   return SDValue();
22205 }
22206
22207 /// \brief Returns a vector of 0s if the node in input is a vector logical
22208 /// shift by a constant amount which is known to be bigger than or equal
22209 /// to the vector element size in bits.
22210 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
22211                                       const X86Subtarget *Subtarget) {
22212   EVT VT = N->getValueType(0);
22213
22214   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
22215       (!Subtarget->hasInt256() ||
22216        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
22217     return SDValue();
22218
22219   SDValue Amt = N->getOperand(1);
22220   SDLoc DL(N);
22221   if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
22222     if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
22223       APInt ShiftAmt = AmtSplat->getAPIntValue();
22224       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
22225
22226       // SSE2/AVX2 logical shifts always return a vector of 0s
22227       // if the shift amount is bigger than or equal to
22228       // the element size. The constant shift amount will be
22229       // encoded as a 8-bit immediate.
22230       if (ShiftAmt.trunc(8).uge(MaxAmount))
22231         return getZeroVector(VT, Subtarget, DAG, DL);
22232     }
22233
22234   return SDValue();
22235 }
22236
22237 /// PerformShiftCombine - Combine shifts.
22238 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
22239                                    TargetLowering::DAGCombinerInfo &DCI,
22240                                    const X86Subtarget *Subtarget) {
22241   if (N->getOpcode() == ISD::SHL) {
22242     SDValue V = PerformSHLCombine(N, DAG);
22243     if (V.getNode()) return V;
22244   }
22245
22246   if (N->getOpcode() != ISD::SRA) {
22247     // Try to fold this logical shift into a zero vector.
22248     SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
22249     if (V.getNode()) return V;
22250   }
22251
22252   return SDValue();
22253 }
22254
22255 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
22256 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
22257 // and friends.  Likewise for OR -> CMPNEQSS.
22258 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
22259                             TargetLowering::DAGCombinerInfo &DCI,
22260                             const X86Subtarget *Subtarget) {
22261   unsigned opcode;
22262
22263   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
22264   // we're requiring SSE2 for both.
22265   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
22266     SDValue N0 = N->getOperand(0);
22267     SDValue N1 = N->getOperand(1);
22268     SDValue CMP0 = N0->getOperand(1);
22269     SDValue CMP1 = N1->getOperand(1);
22270     SDLoc DL(N);
22271
22272     // The SETCCs should both refer to the same CMP.
22273     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
22274       return SDValue();
22275
22276     SDValue CMP00 = CMP0->getOperand(0);
22277     SDValue CMP01 = CMP0->getOperand(1);
22278     EVT     VT    = CMP00.getValueType();
22279
22280     if (VT == MVT::f32 || VT == MVT::f64) {
22281       bool ExpectingFlags = false;
22282       // Check for any users that want flags:
22283       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
22284            !ExpectingFlags && UI != UE; ++UI)
22285         switch (UI->getOpcode()) {
22286         default:
22287         case ISD::BR_CC:
22288         case ISD::BRCOND:
22289         case ISD::SELECT:
22290           ExpectingFlags = true;
22291           break;
22292         case ISD::CopyToReg:
22293         case ISD::SIGN_EXTEND:
22294         case ISD::ZERO_EXTEND:
22295         case ISD::ANY_EXTEND:
22296           break;
22297         }
22298
22299       if (!ExpectingFlags) {
22300         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
22301         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
22302
22303         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
22304           X86::CondCode tmp = cc0;
22305           cc0 = cc1;
22306           cc1 = tmp;
22307         }
22308
22309         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
22310             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
22311           // FIXME: need symbolic constants for these magic numbers.
22312           // See X86ATTInstPrinter.cpp:printSSECC().
22313           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
22314           if (Subtarget->hasAVX512()) {
22315             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
22316                                          CMP01,
22317                                          DAG.getConstant(x86cc, DL, MVT::i8));
22318             if (N->getValueType(0) != MVT::i1)
22319               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
22320                                  FSetCC);
22321             return FSetCC;
22322           }
22323           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
22324                                               CMP00.getValueType(), CMP00, CMP01,
22325                                               DAG.getConstant(x86cc, DL,
22326                                                               MVT::i8));
22327
22328           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
22329           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
22330
22331           if (is64BitFP && !Subtarget->is64Bit()) {
22332             // On a 32-bit target, we cannot bitcast the 64-bit float to a
22333             // 64-bit integer, since that's not a legal type. Since
22334             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
22335             // bits, but can do this little dance to extract the lowest 32 bits
22336             // and work with those going forward.
22337             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
22338                                            OnesOrZeroesF);
22339             SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
22340                                            Vector64);
22341             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
22342                                         Vector32, DAG.getIntPtrConstant(0, DL));
22343             IntVT = MVT::i32;
22344           }
22345
22346           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT,
22347                                               OnesOrZeroesF);
22348           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
22349                                       DAG.getConstant(1, DL, IntVT));
22350           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8,
22351                                               ANDed);
22352           return OneBitOfTruth;
22353         }
22354       }
22355     }
22356   }
22357   return SDValue();
22358 }
22359
22360 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
22361 /// so it can be folded inside ANDNP.
22362 static bool CanFoldXORWithAllOnes(const SDNode *N) {
22363   EVT VT = N->getValueType(0);
22364
22365   // Match direct AllOnes for 128 and 256-bit vectors
22366   if (ISD::isBuildVectorAllOnes(N))
22367     return true;
22368
22369   // Look through a bit convert.
22370   if (N->getOpcode() == ISD::BITCAST)
22371     N = N->getOperand(0).getNode();
22372
22373   // Sometimes the operand may come from a insert_subvector building a 256-bit
22374   // allones vector
22375   if (VT.is256BitVector() &&
22376       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
22377     SDValue V1 = N->getOperand(0);
22378     SDValue V2 = N->getOperand(1);
22379
22380     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
22381         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
22382         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
22383         ISD::isBuildVectorAllOnes(V2.getNode()))
22384       return true;
22385   }
22386
22387   return false;
22388 }
22389
22390 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
22391 // register. In most cases we actually compare or select YMM-sized registers
22392 // and mixing the two types creates horrible code. This method optimizes
22393 // some of the transition sequences.
22394 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
22395                                  TargetLowering::DAGCombinerInfo &DCI,
22396                                  const X86Subtarget *Subtarget) {
22397   EVT VT = N->getValueType(0);
22398   if (!VT.is256BitVector())
22399     return SDValue();
22400
22401   assert((N->getOpcode() == ISD::ANY_EXTEND ||
22402           N->getOpcode() == ISD::ZERO_EXTEND ||
22403           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
22404
22405   SDValue Narrow = N->getOperand(0);
22406   EVT NarrowVT = Narrow->getValueType(0);
22407   if (!NarrowVT.is128BitVector())
22408     return SDValue();
22409
22410   if (Narrow->getOpcode() != ISD::XOR &&
22411       Narrow->getOpcode() != ISD::AND &&
22412       Narrow->getOpcode() != ISD::OR)
22413     return SDValue();
22414
22415   SDValue N0  = Narrow->getOperand(0);
22416   SDValue N1  = Narrow->getOperand(1);
22417   SDLoc DL(Narrow);
22418
22419   // The Left side has to be a trunc.
22420   if (N0.getOpcode() != ISD::TRUNCATE)
22421     return SDValue();
22422
22423   // The type of the truncated inputs.
22424   EVT WideVT = N0->getOperand(0)->getValueType(0);
22425   if (WideVT != VT)
22426     return SDValue();
22427
22428   // The right side has to be a 'trunc' or a constant vector.
22429   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
22430   ConstantSDNode *RHSConstSplat = nullptr;
22431   if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
22432     RHSConstSplat = RHSBV->getConstantSplatNode();
22433   if (!RHSTrunc && !RHSConstSplat)
22434     return SDValue();
22435
22436   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22437
22438   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
22439     return SDValue();
22440
22441   // Set N0 and N1 to hold the inputs to the new wide operation.
22442   N0 = N0->getOperand(0);
22443   if (RHSConstSplat) {
22444     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
22445                      SDValue(RHSConstSplat, 0));
22446     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
22447     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
22448   } else if (RHSTrunc) {
22449     N1 = N1->getOperand(0);
22450   }
22451
22452   // Generate the wide operation.
22453   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
22454   unsigned Opcode = N->getOpcode();
22455   switch (Opcode) {
22456   case ISD::ANY_EXTEND:
22457     return Op;
22458   case ISD::ZERO_EXTEND: {
22459     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
22460     APInt Mask = APInt::getAllOnesValue(InBits);
22461     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
22462     return DAG.getNode(ISD::AND, DL, VT,
22463                        Op, DAG.getConstant(Mask, DL, VT));
22464   }
22465   case ISD::SIGN_EXTEND:
22466     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
22467                        Op, DAG.getValueType(NarrowVT));
22468   default:
22469     llvm_unreachable("Unexpected opcode");
22470   }
22471 }
22472
22473 static SDValue VectorZextCombine(SDNode *N, SelectionDAG &DAG,
22474                                  TargetLowering::DAGCombinerInfo &DCI,
22475                                  const X86Subtarget *Subtarget) {
22476   SDValue N0 = N->getOperand(0);
22477   SDValue N1 = N->getOperand(1);
22478   SDLoc DL(N);
22479
22480   // A vector zext_in_reg may be represented as a shuffle,
22481   // feeding into a bitcast (this represents anyext) feeding into
22482   // an and with a mask.
22483   // We'd like to try to combine that into a shuffle with zero
22484   // plus a bitcast, removing the and.
22485   if (N0.getOpcode() != ISD::BITCAST ||
22486       N0.getOperand(0).getOpcode() != ISD::VECTOR_SHUFFLE)
22487     return SDValue();
22488
22489   // The other side of the AND should be a splat of 2^C, where C
22490   // is the number of bits in the source type.
22491   if (N1.getOpcode() == ISD::BITCAST)
22492     N1 = N1.getOperand(0);
22493   if (N1.getOpcode() != ISD::BUILD_VECTOR)
22494     return SDValue();
22495   BuildVectorSDNode *Vector = cast<BuildVectorSDNode>(N1);
22496
22497   ShuffleVectorSDNode *Shuffle = cast<ShuffleVectorSDNode>(N0.getOperand(0));
22498   EVT SrcType = Shuffle->getValueType(0);
22499
22500   // We expect a single-source shuffle
22501   if (Shuffle->getOperand(1)->getOpcode() != ISD::UNDEF)
22502     return SDValue();
22503
22504   unsigned SrcSize = SrcType.getScalarSizeInBits();
22505
22506   APInt SplatValue, SplatUndef;
22507   unsigned SplatBitSize;
22508   bool HasAnyUndefs;
22509   if (!Vector->isConstantSplat(SplatValue, SplatUndef,
22510                                 SplatBitSize, HasAnyUndefs))
22511     return SDValue();
22512
22513   unsigned ResSize = N1.getValueType().getScalarSizeInBits();
22514   // Make sure the splat matches the mask we expect
22515   if (SplatBitSize > ResSize ||
22516       (SplatValue + 1).exactLogBase2() != (int)SrcSize)
22517     return SDValue();
22518
22519   // Make sure the input and output size make sense
22520   if (SrcSize >= ResSize || ResSize % SrcSize)
22521     return SDValue();
22522
22523   // We expect a shuffle of the form <0, u, u, u, 1, u, u, u...>
22524   // The number of u's between each two values depends on the ratio between
22525   // the source and dest type.
22526   unsigned ZextRatio = ResSize / SrcSize;
22527   bool IsZext = true;
22528   for (unsigned i = 0; i < SrcType.getVectorNumElements(); ++i) {
22529     if (i % ZextRatio) {
22530       if (Shuffle->getMaskElt(i) > 0) {
22531         // Expected undef
22532         IsZext = false;
22533         break;
22534       }
22535     } else {
22536       if (Shuffle->getMaskElt(i) != (int)(i / ZextRatio)) {
22537         // Expected element number
22538         IsZext = false;
22539         break;
22540       }
22541     }
22542   }
22543
22544   if (!IsZext)
22545     return SDValue();
22546
22547   // Ok, perform the transformation - replace the shuffle with
22548   // a shuffle of the form <0, k, k, k, 1, k, k, k> with zero
22549   // (instead of undef) where the k elements come from the zero vector.
22550   SmallVector<int, 8> Mask;
22551   unsigned NumElems = SrcType.getVectorNumElements();
22552   for (unsigned i = 0; i < NumElems; ++i)
22553     if (i % ZextRatio)
22554       Mask.push_back(NumElems);
22555     else
22556       Mask.push_back(i / ZextRatio);
22557
22558   SDValue NewShuffle = DAG.getVectorShuffle(Shuffle->getValueType(0), DL,
22559     Shuffle->getOperand(0), DAG.getConstant(0, DL, SrcType), Mask);
22560   return DAG.getNode(ISD::BITCAST, DL, N0.getValueType(), NewShuffle);
22561 }
22562
22563 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
22564                                  TargetLowering::DAGCombinerInfo &DCI,
22565                                  const X86Subtarget *Subtarget) {
22566   if (DCI.isBeforeLegalizeOps())
22567     return SDValue();
22568
22569   if (SDValue Zext = VectorZextCombine(N, DAG, DCI, Subtarget))
22570     return Zext;
22571
22572   if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
22573     return R;
22574
22575   EVT VT = N->getValueType(0);
22576   SDValue N0 = N->getOperand(0);
22577   SDValue N1 = N->getOperand(1);
22578   SDLoc DL(N);
22579
22580   // Create BEXTR instructions
22581   // BEXTR is ((X >> imm) & (2**size-1))
22582   if (VT == MVT::i32 || VT == MVT::i64) {
22583     // Check for BEXTR.
22584     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
22585         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
22586       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
22587       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
22588       if (MaskNode && ShiftNode) {
22589         uint64_t Mask = MaskNode->getZExtValue();
22590         uint64_t Shift = ShiftNode->getZExtValue();
22591         if (isMask_64(Mask)) {
22592           uint64_t MaskSize = countPopulation(Mask);
22593           if (Shift + MaskSize <= VT.getSizeInBits())
22594             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
22595                                DAG.getConstant(Shift | (MaskSize << 8), DL,
22596                                                VT));
22597         }
22598       }
22599     } // BEXTR
22600
22601     return SDValue();
22602   }
22603
22604   // Want to form ANDNP nodes:
22605   // 1) In the hopes of then easily combining them with OR and AND nodes
22606   //    to form PBLEND/PSIGN.
22607   // 2) To match ANDN packed intrinsics
22608   if (VT != MVT::v2i64 && VT != MVT::v4i64)
22609     return SDValue();
22610
22611   // Check LHS for vnot
22612   if (N0.getOpcode() == ISD::XOR &&
22613       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
22614       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
22615     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
22616
22617   // Check RHS for vnot
22618   if (N1.getOpcode() == ISD::XOR &&
22619       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
22620       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
22621     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
22622
22623   return SDValue();
22624 }
22625
22626 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
22627                                 TargetLowering::DAGCombinerInfo &DCI,
22628                                 const X86Subtarget *Subtarget) {
22629   if (DCI.isBeforeLegalizeOps())
22630     return SDValue();
22631
22632   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
22633   if (R.getNode())
22634     return R;
22635
22636   SDValue N0 = N->getOperand(0);
22637   SDValue N1 = N->getOperand(1);
22638   EVT VT = N->getValueType(0);
22639
22640   // look for psign/blend
22641   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
22642     if (!Subtarget->hasSSSE3() ||
22643         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
22644       return SDValue();
22645
22646     // Canonicalize pandn to RHS
22647     if (N0.getOpcode() == X86ISD::ANDNP)
22648       std::swap(N0, N1);
22649     // or (and (m, y), (pandn m, x))
22650     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
22651       SDValue Mask = N1.getOperand(0);
22652       SDValue X    = N1.getOperand(1);
22653       SDValue Y;
22654       if (N0.getOperand(0) == Mask)
22655         Y = N0.getOperand(1);
22656       if (N0.getOperand(1) == Mask)
22657         Y = N0.getOperand(0);
22658
22659       // Check to see if the mask appeared in both the AND and ANDNP and
22660       if (!Y.getNode())
22661         return SDValue();
22662
22663       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
22664       // Look through mask bitcast.
22665       if (Mask.getOpcode() == ISD::BITCAST)
22666         Mask = Mask.getOperand(0);
22667       if (X.getOpcode() == ISD::BITCAST)
22668         X = X.getOperand(0);
22669       if (Y.getOpcode() == ISD::BITCAST)
22670         Y = Y.getOperand(0);
22671
22672       EVT MaskVT = Mask.getValueType();
22673
22674       // Validate that the Mask operand is a vector sra node.
22675       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
22676       // there is no psrai.b
22677       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
22678       unsigned SraAmt = ~0;
22679       if (Mask.getOpcode() == ISD::SRA) {
22680         if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
22681           if (auto *AmtConst = AmtBV->getConstantSplatNode())
22682             SraAmt = AmtConst->getZExtValue();
22683       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
22684         SDValue SraC = Mask.getOperand(1);
22685         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
22686       }
22687       if ((SraAmt + 1) != EltBits)
22688         return SDValue();
22689
22690       SDLoc DL(N);
22691
22692       // Now we know we at least have a plendvb with the mask val.  See if
22693       // we can form a psignb/w/d.
22694       // psign = x.type == y.type == mask.type && y = sub(0, x);
22695       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
22696           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
22697           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
22698         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
22699                "Unsupported VT for PSIGN");
22700         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
22701         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
22702       }
22703       // PBLENDVB only available on SSE 4.1
22704       if (!Subtarget->hasSSE41())
22705         return SDValue();
22706
22707       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
22708
22709       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
22710       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
22711       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
22712       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
22713       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
22714     }
22715   }
22716
22717   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
22718     return SDValue();
22719
22720   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
22721   MachineFunction &MF = DAG.getMachineFunction();
22722   bool OptForSize =
22723       MF.getFunction()->hasFnAttribute(Attribute::OptimizeForSize);
22724
22725   // SHLD/SHRD instructions have lower register pressure, but on some
22726   // platforms they have higher latency than the equivalent
22727   // series of shifts/or that would otherwise be generated.
22728   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
22729   // have higher latencies and we are not optimizing for size.
22730   if (!OptForSize && Subtarget->isSHLDSlow())
22731     return SDValue();
22732
22733   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
22734     std::swap(N0, N1);
22735   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
22736     return SDValue();
22737   if (!N0.hasOneUse() || !N1.hasOneUse())
22738     return SDValue();
22739
22740   SDValue ShAmt0 = N0.getOperand(1);
22741   if (ShAmt0.getValueType() != MVT::i8)
22742     return SDValue();
22743   SDValue ShAmt1 = N1.getOperand(1);
22744   if (ShAmt1.getValueType() != MVT::i8)
22745     return SDValue();
22746   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
22747     ShAmt0 = ShAmt0.getOperand(0);
22748   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
22749     ShAmt1 = ShAmt1.getOperand(0);
22750
22751   SDLoc DL(N);
22752   unsigned Opc = X86ISD::SHLD;
22753   SDValue Op0 = N0.getOperand(0);
22754   SDValue Op1 = N1.getOperand(0);
22755   if (ShAmt0.getOpcode() == ISD::SUB) {
22756     Opc = X86ISD::SHRD;
22757     std::swap(Op0, Op1);
22758     std::swap(ShAmt0, ShAmt1);
22759   }
22760
22761   unsigned Bits = VT.getSizeInBits();
22762   if (ShAmt1.getOpcode() == ISD::SUB) {
22763     SDValue Sum = ShAmt1.getOperand(0);
22764     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
22765       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
22766       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
22767         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
22768       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
22769         return DAG.getNode(Opc, DL, VT,
22770                            Op0, Op1,
22771                            DAG.getNode(ISD::TRUNCATE, DL,
22772                                        MVT::i8, ShAmt0));
22773     }
22774   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
22775     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
22776     if (ShAmt0C &&
22777         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
22778       return DAG.getNode(Opc, DL, VT,
22779                          N0.getOperand(0), N1.getOperand(0),
22780                          DAG.getNode(ISD::TRUNCATE, DL,
22781                                        MVT::i8, ShAmt0));
22782   }
22783
22784   return SDValue();
22785 }
22786
22787 // Generate NEG and CMOV for integer abs.
22788 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
22789   EVT VT = N->getValueType(0);
22790
22791   // Since X86 does not have CMOV for 8-bit integer, we don't convert
22792   // 8-bit integer abs to NEG and CMOV.
22793   if (VT.isInteger() && VT.getSizeInBits() == 8)
22794     return SDValue();
22795
22796   SDValue N0 = N->getOperand(0);
22797   SDValue N1 = N->getOperand(1);
22798   SDLoc DL(N);
22799
22800   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
22801   // and change it to SUB and CMOV.
22802   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
22803       N0.getOpcode() == ISD::ADD &&
22804       N0.getOperand(1) == N1 &&
22805       N1.getOpcode() == ISD::SRA &&
22806       N1.getOperand(0) == N0.getOperand(0))
22807     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
22808       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
22809         // Generate SUB & CMOV.
22810         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
22811                                   DAG.getConstant(0, DL, VT), N0.getOperand(0));
22812
22813         SDValue Ops[] = { N0.getOperand(0), Neg,
22814                           DAG.getConstant(X86::COND_GE, DL, MVT::i8),
22815                           SDValue(Neg.getNode(), 1) };
22816         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
22817       }
22818   return SDValue();
22819 }
22820
22821 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
22822 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
22823                                  TargetLowering::DAGCombinerInfo &DCI,
22824                                  const X86Subtarget *Subtarget) {
22825   if (DCI.isBeforeLegalizeOps())
22826     return SDValue();
22827
22828   if (Subtarget->hasCMov()) {
22829     SDValue RV = performIntegerAbsCombine(N, DAG);
22830     if (RV.getNode())
22831       return RV;
22832   }
22833
22834   return SDValue();
22835 }
22836
22837 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
22838 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
22839                                   TargetLowering::DAGCombinerInfo &DCI,
22840                                   const X86Subtarget *Subtarget) {
22841   LoadSDNode *Ld = cast<LoadSDNode>(N);
22842   EVT RegVT = Ld->getValueType(0);
22843   EVT MemVT = Ld->getMemoryVT();
22844   SDLoc dl(Ld);
22845   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22846
22847   // For chips with slow 32-byte unaligned loads, break the 32-byte operation
22848   // into two 16-byte operations.
22849   ISD::LoadExtType Ext = Ld->getExtensionType();
22850   unsigned Alignment = Ld->getAlignment();
22851   bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
22852   if (RegVT.is256BitVector() && Subtarget->isUnalignedMem32Slow() &&
22853       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
22854     unsigned NumElems = RegVT.getVectorNumElements();
22855     if (NumElems < 2)
22856       return SDValue();
22857
22858     SDValue Ptr = Ld->getBasePtr();
22859     SDValue Increment = DAG.getConstant(16, dl, TLI.getPointerTy());
22860
22861     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
22862                                   NumElems/2);
22863     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
22864                                 Ld->getPointerInfo(), Ld->isVolatile(),
22865                                 Ld->isNonTemporal(), Ld->isInvariant(),
22866                                 Alignment);
22867     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
22868     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
22869                                 Ld->getPointerInfo(), Ld->isVolatile(),
22870                                 Ld->isNonTemporal(), Ld->isInvariant(),
22871                                 std::min(16U, Alignment));
22872     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
22873                              Load1.getValue(1),
22874                              Load2.getValue(1));
22875
22876     SDValue NewVec = DAG.getUNDEF(RegVT);
22877     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
22878     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
22879     return DCI.CombineTo(N, NewVec, TF, true);
22880   }
22881
22882   return SDValue();
22883 }
22884
22885 /// PerformMLOADCombine - Resolve extending loads
22886 static SDValue PerformMLOADCombine(SDNode *N, SelectionDAG &DAG,
22887                                    TargetLowering::DAGCombinerInfo &DCI,
22888                                    const X86Subtarget *Subtarget) {
22889   MaskedLoadSDNode *Mld = cast<MaskedLoadSDNode>(N);
22890   if (Mld->getExtensionType() != ISD::SEXTLOAD)
22891     return SDValue();
22892
22893   EVT VT = Mld->getValueType(0);
22894   unsigned NumElems = VT.getVectorNumElements();
22895   EVT LdVT = Mld->getMemoryVT();
22896   SDLoc dl(Mld);
22897
22898   assert(LdVT != VT && "Cannot extend to the same type");
22899   unsigned ToSz = VT.getVectorElementType().getSizeInBits();
22900   unsigned FromSz = LdVT.getVectorElementType().getSizeInBits();
22901   // From, To sizes and ElemCount must be pow of two
22902   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
22903     "Unexpected size for extending masked load");
22904
22905   unsigned SizeRatio  = ToSz / FromSz;
22906   assert(SizeRatio * NumElems * FromSz == VT.getSizeInBits());
22907
22908   // Create a type on which we perform the shuffle
22909   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
22910           LdVT.getScalarType(), NumElems*SizeRatio);
22911   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
22912
22913   // Convert Src0 value
22914   SDValue WideSrc0 = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mld->getSrc0());
22915   if (Mld->getSrc0().getOpcode() != ISD::UNDEF) {
22916     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
22917     for (unsigned i = 0; i != NumElems; ++i)
22918       ShuffleVec[i] = i * SizeRatio;
22919
22920     // Can't shuffle using an illegal type.
22921     assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
22922             && "WideVecVT should be legal");
22923     WideSrc0 = DAG.getVectorShuffle(WideVecVT, dl, WideSrc0,
22924                                     DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
22925   }
22926   // Prepare the new mask
22927   SDValue NewMask;
22928   SDValue Mask = Mld->getMask();
22929   if (Mask.getValueType() == VT) {
22930     // Mask and original value have the same type
22931     NewMask = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mask);
22932     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
22933     for (unsigned i = 0; i != NumElems; ++i)
22934       ShuffleVec[i] = i * SizeRatio;
22935     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
22936       ShuffleVec[i] = NumElems*SizeRatio;
22937     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
22938                                    DAG.getConstant(0, dl, WideVecVT),
22939                                    &ShuffleVec[0]);
22940   }
22941   else {
22942     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
22943     unsigned WidenNumElts = NumElems*SizeRatio;
22944     unsigned MaskNumElts = VT.getVectorNumElements();
22945     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
22946                                      WidenNumElts);
22947
22948     unsigned NumConcat = WidenNumElts / MaskNumElts;
22949     SmallVector<SDValue, 16> Ops(NumConcat);
22950     SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
22951     Ops[0] = Mask;
22952     for (unsigned i = 1; i != NumConcat; ++i)
22953       Ops[i] = ZeroVal;
22954
22955     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
22956   }
22957
22958   SDValue WideLd = DAG.getMaskedLoad(WideVecVT, dl, Mld->getChain(),
22959                                      Mld->getBasePtr(), NewMask, WideSrc0,
22960                                      Mld->getMemoryVT(), Mld->getMemOperand(),
22961                                      ISD::NON_EXTLOAD);
22962   SDValue NewVec = DAG.getNode(X86ISD::VSEXT, dl, VT, WideLd);
22963   return DCI.CombineTo(N, NewVec, WideLd.getValue(1), true);
22964
22965 }
22966 /// PerformMSTORECombine - Resolve truncating stores
22967 static SDValue PerformMSTORECombine(SDNode *N, SelectionDAG &DAG,
22968                                     const X86Subtarget *Subtarget) {
22969   MaskedStoreSDNode *Mst = cast<MaskedStoreSDNode>(N);
22970   if (!Mst->isTruncatingStore())
22971     return SDValue();
22972
22973   EVT VT = Mst->getValue().getValueType();
22974   unsigned NumElems = VT.getVectorNumElements();
22975   EVT StVT = Mst->getMemoryVT();
22976   SDLoc dl(Mst);
22977
22978   assert(StVT != VT && "Cannot truncate to the same type");
22979   unsigned FromSz = VT.getVectorElementType().getSizeInBits();
22980   unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
22981
22982   // From, To sizes and ElemCount must be pow of two
22983   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
22984     "Unexpected size for truncating masked store");
22985   // We are going to use the original vector elt for storing.
22986   // Accumulated smaller vector elements must be a multiple of the store size.
22987   assert (((NumElems * FromSz) % ToSz) == 0 &&
22988           "Unexpected ratio for truncating masked store");
22989
22990   unsigned SizeRatio  = FromSz / ToSz;
22991   assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
22992
22993   // Create a type on which we perform the shuffle
22994   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
22995           StVT.getScalarType(), NumElems*SizeRatio);
22996
22997   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
22998
22999   SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mst->getValue());
23000   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
23001   for (unsigned i = 0; i != NumElems; ++i)
23002     ShuffleVec[i] = i * SizeRatio;
23003
23004   // Can't shuffle using an illegal type.
23005   assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
23006           && "WideVecVT should be legal");
23007
23008   SDValue TruncatedVal = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
23009                                         DAG.getUNDEF(WideVecVT),
23010                                         &ShuffleVec[0]);
23011
23012   SDValue NewMask;
23013   SDValue Mask = Mst->getMask();
23014   if (Mask.getValueType() == VT) {
23015     // Mask and original value have the same type
23016     NewMask = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mask);
23017     for (unsigned i = 0; i != NumElems; ++i)
23018       ShuffleVec[i] = i * SizeRatio;
23019     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
23020       ShuffleVec[i] = NumElems*SizeRatio;
23021     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
23022                                    DAG.getConstant(0, dl, WideVecVT),
23023                                    &ShuffleVec[0]);
23024   }
23025   else {
23026     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
23027     unsigned WidenNumElts = NumElems*SizeRatio;
23028     unsigned MaskNumElts = VT.getVectorNumElements();
23029     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
23030                                      WidenNumElts);
23031
23032     unsigned NumConcat = WidenNumElts / MaskNumElts;
23033     SmallVector<SDValue, 16> Ops(NumConcat);
23034     SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
23035     Ops[0] = Mask;
23036     for (unsigned i = 1; i != NumConcat; ++i)
23037       Ops[i] = ZeroVal;
23038
23039     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
23040   }
23041
23042   return DAG.getMaskedStore(Mst->getChain(), dl, TruncatedVal, Mst->getBasePtr(),
23043                             NewMask, StVT, Mst->getMemOperand(), false);
23044 }
23045 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
23046 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
23047                                    const X86Subtarget *Subtarget) {
23048   StoreSDNode *St = cast<StoreSDNode>(N);
23049   EVT VT = St->getValue().getValueType();
23050   EVT StVT = St->getMemoryVT();
23051   SDLoc dl(St);
23052   SDValue StoredVal = St->getOperand(1);
23053   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23054
23055   // If we are saving a concatenation of two XMM registers and 32-byte stores
23056   // are slow, such as on Sandy Bridge, perform two 16-byte stores.
23057   unsigned Alignment = St->getAlignment();
23058   bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
23059   if (VT.is256BitVector() && Subtarget->isUnalignedMem32Slow() &&
23060       StVT == VT && !IsAligned) {
23061     unsigned NumElems = VT.getVectorNumElements();
23062     if (NumElems < 2)
23063       return SDValue();
23064
23065     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
23066     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
23067
23068     SDValue Stride = DAG.getConstant(16, dl, TLI.getPointerTy());
23069     SDValue Ptr0 = St->getBasePtr();
23070     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
23071
23072     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
23073                                 St->getPointerInfo(), St->isVolatile(),
23074                                 St->isNonTemporal(), Alignment);
23075     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
23076                                 St->getPointerInfo(), St->isVolatile(),
23077                                 St->isNonTemporal(),
23078                                 std::min(16U, Alignment));
23079     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
23080   }
23081
23082   // Optimize trunc store (of multiple scalars) to shuffle and store.
23083   // First, pack all of the elements in one place. Next, store to memory
23084   // in fewer chunks.
23085   if (St->isTruncatingStore() && VT.isVector()) {
23086     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23087     unsigned NumElems = VT.getVectorNumElements();
23088     assert(StVT != VT && "Cannot truncate to the same type");
23089     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
23090     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
23091
23092     // From, To sizes and ElemCount must be pow of two
23093     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
23094     // We are going to use the original vector elt for storing.
23095     // Accumulated smaller vector elements must be a multiple of the store size.
23096     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
23097
23098     unsigned SizeRatio  = FromSz / ToSz;
23099
23100     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
23101
23102     // Create a type on which we perform the shuffle
23103     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
23104             StVT.getScalarType(), NumElems*SizeRatio);
23105
23106     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
23107
23108     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
23109     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
23110     for (unsigned i = 0; i != NumElems; ++i)
23111       ShuffleVec[i] = i * SizeRatio;
23112
23113     // Can't shuffle using an illegal type.
23114     if (!TLI.isTypeLegal(WideVecVT))
23115       return SDValue();
23116
23117     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
23118                                          DAG.getUNDEF(WideVecVT),
23119                                          &ShuffleVec[0]);
23120     // At this point all of the data is stored at the bottom of the
23121     // register. We now need to save it to mem.
23122
23123     // Find the largest store unit
23124     MVT StoreType = MVT::i8;
23125     for (MVT Tp : MVT::integer_valuetypes()) {
23126       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
23127         StoreType = Tp;
23128     }
23129
23130     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
23131     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
23132         (64 <= NumElems * ToSz))
23133       StoreType = MVT::f64;
23134
23135     // Bitcast the original vector into a vector of store-size units
23136     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
23137             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
23138     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
23139     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
23140     SmallVector<SDValue, 8> Chains;
23141     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8, dl,
23142                                         TLI.getPointerTy());
23143     SDValue Ptr = St->getBasePtr();
23144
23145     // Perform one or more big stores into memory.
23146     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
23147       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
23148                                    StoreType, ShuffWide,
23149                                    DAG.getIntPtrConstant(i, dl));
23150       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
23151                                 St->getPointerInfo(), St->isVolatile(),
23152                                 St->isNonTemporal(), St->getAlignment());
23153       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
23154       Chains.push_back(Ch);
23155     }
23156
23157     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
23158   }
23159
23160   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
23161   // the FP state in cases where an emms may be missing.
23162   // A preferable solution to the general problem is to figure out the right
23163   // places to insert EMMS.  This qualifies as a quick hack.
23164
23165   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
23166   if (VT.getSizeInBits() != 64)
23167     return SDValue();
23168
23169   const Function *F = DAG.getMachineFunction().getFunction();
23170   bool NoImplicitFloatOps = F->hasFnAttribute(Attribute::NoImplicitFloat);
23171   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
23172                      && Subtarget->hasSSE2();
23173   if ((VT.isVector() ||
23174        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
23175       isa<LoadSDNode>(St->getValue()) &&
23176       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
23177       St->getChain().hasOneUse() && !St->isVolatile()) {
23178     SDNode* LdVal = St->getValue().getNode();
23179     LoadSDNode *Ld = nullptr;
23180     int TokenFactorIndex = -1;
23181     SmallVector<SDValue, 8> Ops;
23182     SDNode* ChainVal = St->getChain().getNode();
23183     // Must be a store of a load.  We currently handle two cases:  the load
23184     // is a direct child, and it's under an intervening TokenFactor.  It is
23185     // possible to dig deeper under nested TokenFactors.
23186     if (ChainVal == LdVal)
23187       Ld = cast<LoadSDNode>(St->getChain());
23188     else if (St->getValue().hasOneUse() &&
23189              ChainVal->getOpcode() == ISD::TokenFactor) {
23190       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
23191         if (ChainVal->getOperand(i).getNode() == LdVal) {
23192           TokenFactorIndex = i;
23193           Ld = cast<LoadSDNode>(St->getValue());
23194         } else
23195           Ops.push_back(ChainVal->getOperand(i));
23196       }
23197     }
23198
23199     if (!Ld || !ISD::isNormalLoad(Ld))
23200       return SDValue();
23201
23202     // If this is not the MMX case, i.e. we are just turning i64 load/store
23203     // into f64 load/store, avoid the transformation if there are multiple
23204     // uses of the loaded value.
23205     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
23206       return SDValue();
23207
23208     SDLoc LdDL(Ld);
23209     SDLoc StDL(N);
23210     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
23211     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
23212     // pair instead.
23213     if (Subtarget->is64Bit() || F64IsLegal) {
23214       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
23215       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
23216                                   Ld->getPointerInfo(), Ld->isVolatile(),
23217                                   Ld->isNonTemporal(), Ld->isInvariant(),
23218                                   Ld->getAlignment());
23219       SDValue NewChain = NewLd.getValue(1);
23220       if (TokenFactorIndex != -1) {
23221         Ops.push_back(NewChain);
23222         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
23223       }
23224       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
23225                           St->getPointerInfo(),
23226                           St->isVolatile(), St->isNonTemporal(),
23227                           St->getAlignment());
23228     }
23229
23230     // Otherwise, lower to two pairs of 32-bit loads / stores.
23231     SDValue LoAddr = Ld->getBasePtr();
23232     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
23233                                  DAG.getConstant(4, LdDL, MVT::i32));
23234
23235     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
23236                                Ld->getPointerInfo(),
23237                                Ld->isVolatile(), Ld->isNonTemporal(),
23238                                Ld->isInvariant(), Ld->getAlignment());
23239     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
23240                                Ld->getPointerInfo().getWithOffset(4),
23241                                Ld->isVolatile(), Ld->isNonTemporal(),
23242                                Ld->isInvariant(),
23243                                MinAlign(Ld->getAlignment(), 4));
23244
23245     SDValue NewChain = LoLd.getValue(1);
23246     if (TokenFactorIndex != -1) {
23247       Ops.push_back(LoLd);
23248       Ops.push_back(HiLd);
23249       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
23250     }
23251
23252     LoAddr = St->getBasePtr();
23253     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
23254                          DAG.getConstant(4, StDL, MVT::i32));
23255
23256     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
23257                                 St->getPointerInfo(),
23258                                 St->isVolatile(), St->isNonTemporal(),
23259                                 St->getAlignment());
23260     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
23261                                 St->getPointerInfo().getWithOffset(4),
23262                                 St->isVolatile(),
23263                                 St->isNonTemporal(),
23264                                 MinAlign(St->getAlignment(), 4));
23265     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
23266   }
23267
23268   // This is similar to the above case, but here we handle a scalar 64-bit
23269   // integer store that is extracted from a vector on a 32-bit target.
23270   // If we have SSE2, then we can treat it like a floating-point double
23271   // to get past legalization. The execution dependencies fixup pass will
23272   // choose the optimal machine instruction for the store if this really is
23273   // an integer or v2f32 rather than an f64.
23274   if (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit() &&
23275       St->getOperand(1).getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
23276     SDValue OldExtract = St->getOperand(1);
23277     SDValue ExtOp0 = OldExtract.getOperand(0);
23278     unsigned VecSize = ExtOp0.getValueSizeInBits();
23279     MVT VecVT = MVT::getVectorVT(MVT::f64, VecSize / 64);
23280     SDValue BitCast = DAG.getNode(ISD::BITCAST, dl, VecVT, ExtOp0);
23281     SDValue NewExtract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
23282                                      BitCast, OldExtract.getOperand(1));
23283     return DAG.getStore(St->getChain(), dl, NewExtract, St->getBasePtr(),
23284                         St->getPointerInfo(), St->isVolatile(),
23285                         St->isNonTemporal(), St->getAlignment());
23286   }
23287
23288   return SDValue();
23289 }
23290
23291 /// Return 'true' if this vector operation is "horizontal"
23292 /// and return the operands for the horizontal operation in LHS and RHS.  A
23293 /// horizontal operation performs the binary operation on successive elements
23294 /// of its first operand, then on successive elements of its second operand,
23295 /// returning the resulting values in a vector.  For example, if
23296 ///   A = < float a0, float a1, float a2, float a3 >
23297 /// and
23298 ///   B = < float b0, float b1, float b2, float b3 >
23299 /// then the result of doing a horizontal operation on A and B is
23300 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
23301 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
23302 /// A horizontal-op B, for some already available A and B, and if so then LHS is
23303 /// set to A, RHS to B, and the routine returns 'true'.
23304 /// Note that the binary operation should have the property that if one of the
23305 /// operands is UNDEF then the result is UNDEF.
23306 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
23307   // Look for the following pattern: if
23308   //   A = < float a0, float a1, float a2, float a3 >
23309   //   B = < float b0, float b1, float b2, float b3 >
23310   // and
23311   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
23312   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
23313   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
23314   // which is A horizontal-op B.
23315
23316   // At least one of the operands should be a vector shuffle.
23317   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
23318       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
23319     return false;
23320
23321   MVT VT = LHS.getSimpleValueType();
23322
23323   assert((VT.is128BitVector() || VT.is256BitVector()) &&
23324          "Unsupported vector type for horizontal add/sub");
23325
23326   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
23327   // operate independently on 128-bit lanes.
23328   unsigned NumElts = VT.getVectorNumElements();
23329   unsigned NumLanes = VT.getSizeInBits()/128;
23330   unsigned NumLaneElts = NumElts / NumLanes;
23331   assert((NumLaneElts % 2 == 0) &&
23332          "Vector type should have an even number of elements in each lane");
23333   unsigned HalfLaneElts = NumLaneElts/2;
23334
23335   // View LHS in the form
23336   //   LHS = VECTOR_SHUFFLE A, B, LMask
23337   // If LHS is not a shuffle then pretend it is the shuffle
23338   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
23339   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
23340   // type VT.
23341   SDValue A, B;
23342   SmallVector<int, 16> LMask(NumElts);
23343   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
23344     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
23345       A = LHS.getOperand(0);
23346     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
23347       B = LHS.getOperand(1);
23348     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
23349     std::copy(Mask.begin(), Mask.end(), LMask.begin());
23350   } else {
23351     if (LHS.getOpcode() != ISD::UNDEF)
23352       A = LHS;
23353     for (unsigned i = 0; i != NumElts; ++i)
23354       LMask[i] = i;
23355   }
23356
23357   // Likewise, view RHS in the form
23358   //   RHS = VECTOR_SHUFFLE C, D, RMask
23359   SDValue C, D;
23360   SmallVector<int, 16> RMask(NumElts);
23361   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
23362     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
23363       C = RHS.getOperand(0);
23364     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
23365       D = RHS.getOperand(1);
23366     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
23367     std::copy(Mask.begin(), Mask.end(), RMask.begin());
23368   } else {
23369     if (RHS.getOpcode() != ISD::UNDEF)
23370       C = RHS;
23371     for (unsigned i = 0; i != NumElts; ++i)
23372       RMask[i] = i;
23373   }
23374
23375   // Check that the shuffles are both shuffling the same vectors.
23376   if (!(A == C && B == D) && !(A == D && B == C))
23377     return false;
23378
23379   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
23380   if (!A.getNode() && !B.getNode())
23381     return false;
23382
23383   // If A and B occur in reverse order in RHS, then "swap" them (which means
23384   // rewriting the mask).
23385   if (A != C)
23386     ShuffleVectorSDNode::commuteMask(RMask);
23387
23388   // At this point LHS and RHS are equivalent to
23389   //   LHS = VECTOR_SHUFFLE A, B, LMask
23390   //   RHS = VECTOR_SHUFFLE A, B, RMask
23391   // Check that the masks correspond to performing a horizontal operation.
23392   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
23393     for (unsigned i = 0; i != NumLaneElts; ++i) {
23394       int LIdx = LMask[i+l], RIdx = RMask[i+l];
23395
23396       // Ignore any UNDEF components.
23397       if (LIdx < 0 || RIdx < 0 ||
23398           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
23399           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
23400         continue;
23401
23402       // Check that successive elements are being operated on.  If not, this is
23403       // not a horizontal operation.
23404       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
23405       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
23406       if (!(LIdx == Index && RIdx == Index + 1) &&
23407           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
23408         return false;
23409     }
23410   }
23411
23412   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
23413   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
23414   return true;
23415 }
23416
23417 /// Do target-specific dag combines on floating point adds.
23418 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
23419                                   const X86Subtarget *Subtarget) {
23420   EVT VT = N->getValueType(0);
23421   SDValue LHS = N->getOperand(0);
23422   SDValue RHS = N->getOperand(1);
23423
23424   // Try to synthesize horizontal adds from adds of shuffles.
23425   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
23426        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
23427       isHorizontalBinOp(LHS, RHS, true))
23428     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
23429   return SDValue();
23430 }
23431
23432 /// Do target-specific dag combines on floating point subs.
23433 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
23434                                   const X86Subtarget *Subtarget) {
23435   EVT VT = N->getValueType(0);
23436   SDValue LHS = N->getOperand(0);
23437   SDValue RHS = N->getOperand(1);
23438
23439   // Try to synthesize horizontal subs from subs of shuffles.
23440   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
23441        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
23442       isHorizontalBinOp(LHS, RHS, false))
23443     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
23444   return SDValue();
23445 }
23446
23447 /// Do target-specific dag combines on X86ISD::FOR and X86ISD::FXOR nodes.
23448 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
23449   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
23450
23451   // F[X]OR(0.0, x) -> x
23452   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
23453     if (C->getValueAPF().isPosZero())
23454       return N->getOperand(1);
23455
23456   // F[X]OR(x, 0.0) -> x
23457   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
23458     if (C->getValueAPF().isPosZero())
23459       return N->getOperand(0);
23460   return SDValue();
23461 }
23462
23463 /// Do target-specific dag combines on X86ISD::FMIN and X86ISD::FMAX nodes.
23464 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
23465   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
23466
23467   // Only perform optimizations if UnsafeMath is used.
23468   if (!DAG.getTarget().Options.UnsafeFPMath)
23469     return SDValue();
23470
23471   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
23472   // into FMINC and FMAXC, which are Commutative operations.
23473   unsigned NewOp = 0;
23474   switch (N->getOpcode()) {
23475     default: llvm_unreachable("unknown opcode");
23476     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
23477     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
23478   }
23479
23480   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
23481                      N->getOperand(0), N->getOperand(1));
23482 }
23483
23484 /// Do target-specific dag combines on X86ISD::FAND nodes.
23485 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
23486   // FAND(0.0, x) -> 0.0
23487   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
23488     if (C->getValueAPF().isPosZero())
23489       return N->getOperand(0);
23490
23491   // FAND(x, 0.0) -> 0.0
23492   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
23493     if (C->getValueAPF().isPosZero())
23494       return N->getOperand(1);
23495
23496   return SDValue();
23497 }
23498
23499 /// Do target-specific dag combines on X86ISD::FANDN nodes
23500 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
23501   // FANDN(0.0, x) -> x
23502   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
23503     if (C->getValueAPF().isPosZero())
23504       return N->getOperand(1);
23505
23506   // FANDN(x, 0.0) -> 0.0
23507   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
23508     if (C->getValueAPF().isPosZero())
23509       return N->getOperand(1);
23510
23511   return SDValue();
23512 }
23513
23514 static SDValue PerformBTCombine(SDNode *N,
23515                                 SelectionDAG &DAG,
23516                                 TargetLowering::DAGCombinerInfo &DCI) {
23517   // BT ignores high bits in the bit index operand.
23518   SDValue Op1 = N->getOperand(1);
23519   if (Op1.hasOneUse()) {
23520     unsigned BitWidth = Op1.getValueSizeInBits();
23521     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
23522     APInt KnownZero, KnownOne;
23523     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
23524                                           !DCI.isBeforeLegalizeOps());
23525     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23526     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
23527         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
23528       DCI.CommitTargetLoweringOpt(TLO);
23529   }
23530   return SDValue();
23531 }
23532
23533 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
23534   SDValue Op = N->getOperand(0);
23535   if (Op.getOpcode() == ISD::BITCAST)
23536     Op = Op.getOperand(0);
23537   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
23538   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
23539       VT.getVectorElementType().getSizeInBits() ==
23540       OpVT.getVectorElementType().getSizeInBits()) {
23541     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
23542   }
23543   return SDValue();
23544 }
23545
23546 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
23547                                                const X86Subtarget *Subtarget) {
23548   EVT VT = N->getValueType(0);
23549   if (!VT.isVector())
23550     return SDValue();
23551
23552   SDValue N0 = N->getOperand(0);
23553   SDValue N1 = N->getOperand(1);
23554   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
23555   SDLoc dl(N);
23556
23557   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
23558   // both SSE and AVX2 since there is no sign-extended shift right
23559   // operation on a vector with 64-bit elements.
23560   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
23561   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
23562   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
23563       N0.getOpcode() == ISD::SIGN_EXTEND)) {
23564     SDValue N00 = N0.getOperand(0);
23565
23566     // EXTLOAD has a better solution on AVX2,
23567     // it may be replaced with X86ISD::VSEXT node.
23568     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
23569       if (!ISD::isNormalLoad(N00.getNode()))
23570         return SDValue();
23571
23572     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
23573         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
23574                                   N00, N1);
23575       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
23576     }
23577   }
23578   return SDValue();
23579 }
23580
23581 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
23582                                   TargetLowering::DAGCombinerInfo &DCI,
23583                                   const X86Subtarget *Subtarget) {
23584   SDValue N0 = N->getOperand(0);
23585   EVT VT = N->getValueType(0);
23586
23587   // (i8,i32 sext (sdivrem (i8 x, i8 y)) ->
23588   // (i8,i32 (sdivrem_sext_hreg (i8 x, i8 y)
23589   // This exposes the sext to the sdivrem lowering, so that it directly extends
23590   // from AH (which we otherwise need to do contortions to access).
23591   if (N0.getOpcode() == ISD::SDIVREM && N0.getResNo() == 1 &&
23592       N0.getValueType() == MVT::i8 && VT == MVT::i32) {
23593     SDLoc dl(N);
23594     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
23595     SDValue R = DAG.getNode(X86ISD::SDIVREM8_SEXT_HREG, dl, NodeTys,
23596                             N0.getOperand(0), N0.getOperand(1));
23597     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
23598     return R.getValue(1);
23599   }
23600
23601   if (!DCI.isBeforeLegalizeOps())
23602     return SDValue();
23603
23604   if (!Subtarget->hasFp256())
23605     return SDValue();
23606
23607   if (VT.isVector() && VT.getSizeInBits() == 256) {
23608     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
23609     if (R.getNode())
23610       return R;
23611   }
23612
23613   return SDValue();
23614 }
23615
23616 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
23617                                  const X86Subtarget* Subtarget) {
23618   SDLoc dl(N);
23619   EVT VT = N->getValueType(0);
23620
23621   // Let legalize expand this if it isn't a legal type yet.
23622   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
23623     return SDValue();
23624
23625   EVT ScalarVT = VT.getScalarType();
23626   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
23627       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
23628     return SDValue();
23629
23630   SDValue A = N->getOperand(0);
23631   SDValue B = N->getOperand(1);
23632   SDValue C = N->getOperand(2);
23633
23634   bool NegA = (A.getOpcode() == ISD::FNEG);
23635   bool NegB = (B.getOpcode() == ISD::FNEG);
23636   bool NegC = (C.getOpcode() == ISD::FNEG);
23637
23638   // Negative multiplication when NegA xor NegB
23639   bool NegMul = (NegA != NegB);
23640   if (NegA)
23641     A = A.getOperand(0);
23642   if (NegB)
23643     B = B.getOperand(0);
23644   if (NegC)
23645     C = C.getOperand(0);
23646
23647   unsigned Opcode;
23648   if (!NegMul)
23649     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
23650   else
23651     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
23652
23653   return DAG.getNode(Opcode, dl, VT, A, B, C);
23654 }
23655
23656 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
23657                                   TargetLowering::DAGCombinerInfo &DCI,
23658                                   const X86Subtarget *Subtarget) {
23659   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
23660   //           (and (i32 x86isd::setcc_carry), 1)
23661   // This eliminates the zext. This transformation is necessary because
23662   // ISD::SETCC is always legalized to i8.
23663   SDLoc dl(N);
23664   SDValue N0 = N->getOperand(0);
23665   EVT VT = N->getValueType(0);
23666
23667   if (N0.getOpcode() == ISD::AND &&
23668       N0.hasOneUse() &&
23669       N0.getOperand(0).hasOneUse()) {
23670     SDValue N00 = N0.getOperand(0);
23671     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
23672       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
23673       if (!C || C->getZExtValue() != 1)
23674         return SDValue();
23675       return DAG.getNode(ISD::AND, dl, VT,
23676                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
23677                                      N00.getOperand(0), N00.getOperand(1)),
23678                          DAG.getConstant(1, dl, VT));
23679     }
23680   }
23681
23682   if (N0.getOpcode() == ISD::TRUNCATE &&
23683       N0.hasOneUse() &&
23684       N0.getOperand(0).hasOneUse()) {
23685     SDValue N00 = N0.getOperand(0);
23686     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
23687       return DAG.getNode(ISD::AND, dl, VT,
23688                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
23689                                      N00.getOperand(0), N00.getOperand(1)),
23690                          DAG.getConstant(1, dl, VT));
23691     }
23692   }
23693   if (VT.is256BitVector()) {
23694     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
23695     if (R.getNode())
23696       return R;
23697   }
23698
23699   // (i8,i32 zext (udivrem (i8 x, i8 y)) ->
23700   // (i8,i32 (udivrem_zext_hreg (i8 x, i8 y)
23701   // This exposes the zext to the udivrem lowering, so that it directly extends
23702   // from AH (which we otherwise need to do contortions to access).
23703   if (N0.getOpcode() == ISD::UDIVREM &&
23704       N0.getResNo() == 1 && N0.getValueType() == MVT::i8 &&
23705       (VT == MVT::i32 || VT == MVT::i64)) {
23706     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
23707     SDValue R = DAG.getNode(X86ISD::UDIVREM8_ZEXT_HREG, dl, NodeTys,
23708                             N0.getOperand(0), N0.getOperand(1));
23709     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
23710     return R.getValue(1);
23711   }
23712
23713   return SDValue();
23714 }
23715
23716 // Optimize x == -y --> x+y == 0
23717 //          x != -y --> x+y != 0
23718 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
23719                                       const X86Subtarget* Subtarget) {
23720   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
23721   SDValue LHS = N->getOperand(0);
23722   SDValue RHS = N->getOperand(1);
23723   EVT VT = N->getValueType(0);
23724   SDLoc DL(N);
23725
23726   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
23727     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
23728       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
23729         SDValue addV = DAG.getNode(ISD::ADD, DL, LHS.getValueType(), RHS,
23730                                    LHS.getOperand(1));
23731         return DAG.getSetCC(DL, N->getValueType(0), addV,
23732                             DAG.getConstant(0, DL, addV.getValueType()), CC);
23733       }
23734   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
23735     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
23736       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
23737         SDValue addV = DAG.getNode(ISD::ADD, DL, RHS.getValueType(), LHS,
23738                                    RHS.getOperand(1));
23739         return DAG.getSetCC(DL, N->getValueType(0), addV,
23740                             DAG.getConstant(0, DL, addV.getValueType()), CC);
23741       }
23742
23743   if (VT.getScalarType() == MVT::i1 &&
23744       (CC == ISD::SETNE || CC == ISD::SETEQ || ISD::isSignedIntSetCC(CC))) {
23745     bool IsSEXT0 =
23746         (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
23747         (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
23748     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
23749
23750     if (!IsSEXT0 || !IsVZero1) {
23751       // Swap the operands and update the condition code.
23752       std::swap(LHS, RHS);
23753       CC = ISD::getSetCCSwappedOperands(CC);
23754
23755       IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
23756                 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
23757       IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
23758     }
23759
23760     if (IsSEXT0 && IsVZero1) {
23761       assert(VT == LHS.getOperand(0).getValueType() &&
23762              "Uexpected operand type");
23763       if (CC == ISD::SETGT)
23764         return DAG.getConstant(0, DL, VT);
23765       if (CC == ISD::SETLE)
23766         return DAG.getConstant(1, DL, VT);
23767       if (CC == ISD::SETEQ || CC == ISD::SETGE)
23768         return DAG.getNOT(DL, LHS.getOperand(0), VT);
23769
23770       assert((CC == ISD::SETNE || CC == ISD::SETLT) &&
23771              "Unexpected condition code!");
23772       return LHS.getOperand(0);
23773     }
23774   }
23775
23776   return SDValue();
23777 }
23778
23779 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
23780                                          SelectionDAG &DAG) {
23781   SDLoc dl(Load);
23782   MVT VT = Load->getSimpleValueType(0);
23783   MVT EVT = VT.getVectorElementType();
23784   SDValue Addr = Load->getOperand(1);
23785   SDValue NewAddr = DAG.getNode(
23786       ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
23787       DAG.getConstant(Index * EVT.getStoreSize(), dl,
23788                       Addr.getSimpleValueType()));
23789
23790   SDValue NewLoad =
23791       DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
23792                   DAG.getMachineFunction().getMachineMemOperand(
23793                       Load->getMemOperand(), 0, EVT.getStoreSize()));
23794   return NewLoad;
23795 }
23796
23797 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
23798                                       const X86Subtarget *Subtarget) {
23799   SDLoc dl(N);
23800   MVT VT = N->getOperand(1)->getSimpleValueType(0);
23801   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
23802          "X86insertps is only defined for v4x32");
23803
23804   SDValue Ld = N->getOperand(1);
23805   if (MayFoldLoad(Ld)) {
23806     // Extract the countS bits from the immediate so we can get the proper
23807     // address when narrowing the vector load to a specific element.
23808     // When the second source op is a memory address, insertps doesn't use
23809     // countS and just gets an f32 from that address.
23810     unsigned DestIndex =
23811         cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
23812
23813     Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
23814
23815     // Create this as a scalar to vector to match the instruction pattern.
23816     SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
23817     // countS bits are ignored when loading from memory on insertps, which
23818     // means we don't need to explicitly set them to 0.
23819     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
23820                        LoadScalarToVector, N->getOperand(2));
23821   }
23822   return SDValue();
23823 }
23824
23825 static SDValue PerformBLENDICombine(SDNode *N, SelectionDAG &DAG) {
23826   SDValue V0 = N->getOperand(0);
23827   SDValue V1 = N->getOperand(1);
23828   SDLoc DL(N);
23829   EVT VT = N->getValueType(0);
23830
23831   // Canonicalize a v2f64 blend with a mask of 2 by swapping the vector
23832   // operands and changing the mask to 1. This saves us a bunch of
23833   // pattern-matching possibilities related to scalar math ops in SSE/AVX.
23834   // x86InstrInfo knows how to commute this back after instruction selection
23835   // if it would help register allocation.
23836
23837   // TODO: If optimizing for size or a processor that doesn't suffer from
23838   // partial register update stalls, this should be transformed into a MOVSD
23839   // instruction because a MOVSD is 1-2 bytes smaller than a BLENDPD.
23840
23841   if (VT == MVT::v2f64)
23842     if (auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(2)))
23843       if (Mask->getZExtValue() == 2 && !isShuffleFoldableLoad(V0)) {
23844         SDValue NewMask = DAG.getConstant(1, DL, MVT::i8);
23845         return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V0, NewMask);
23846       }
23847
23848   return SDValue();
23849 }
23850
23851 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
23852 // as "sbb reg,reg", since it can be extended without zext and produces
23853 // an all-ones bit which is more useful than 0/1 in some cases.
23854 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
23855                                MVT VT) {
23856   if (VT == MVT::i8)
23857     return DAG.getNode(ISD::AND, DL, VT,
23858                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
23859                                    DAG.getConstant(X86::COND_B, DL, MVT::i8),
23860                                    EFLAGS),
23861                        DAG.getConstant(1, DL, VT));
23862   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
23863   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
23864                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
23865                                  DAG.getConstant(X86::COND_B, DL, MVT::i8),
23866                                  EFLAGS));
23867 }
23868
23869 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
23870 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
23871                                    TargetLowering::DAGCombinerInfo &DCI,
23872                                    const X86Subtarget *Subtarget) {
23873   SDLoc DL(N);
23874   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
23875   SDValue EFLAGS = N->getOperand(1);
23876
23877   if (CC == X86::COND_A) {
23878     // Try to convert COND_A into COND_B in an attempt to facilitate
23879     // materializing "setb reg".
23880     //
23881     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
23882     // cannot take an immediate as its first operand.
23883     //
23884     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
23885         EFLAGS.getValueType().isInteger() &&
23886         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
23887       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
23888                                    EFLAGS.getNode()->getVTList(),
23889                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
23890       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
23891       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
23892     }
23893   }
23894
23895   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
23896   // a zext and produces an all-ones bit which is more useful than 0/1 in some
23897   // cases.
23898   if (CC == X86::COND_B)
23899     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
23900
23901   SDValue Flags;
23902
23903   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
23904   if (Flags.getNode()) {
23905     SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
23906     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
23907   }
23908
23909   return SDValue();
23910 }
23911
23912 // Optimize branch condition evaluation.
23913 //
23914 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
23915                                     TargetLowering::DAGCombinerInfo &DCI,
23916                                     const X86Subtarget *Subtarget) {
23917   SDLoc DL(N);
23918   SDValue Chain = N->getOperand(0);
23919   SDValue Dest = N->getOperand(1);
23920   SDValue EFLAGS = N->getOperand(3);
23921   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
23922
23923   SDValue Flags;
23924
23925   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
23926   if (Flags.getNode()) {
23927     SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
23928     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
23929                        Flags);
23930   }
23931
23932   return SDValue();
23933 }
23934
23935 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
23936                                                          SelectionDAG &DAG) {
23937   // Take advantage of vector comparisons producing 0 or -1 in each lane to
23938   // optimize away operation when it's from a constant.
23939   //
23940   // The general transformation is:
23941   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
23942   //       AND(VECTOR_CMP(x,y), constant2)
23943   //    constant2 = UNARYOP(constant)
23944
23945   // Early exit if this isn't a vector operation, the operand of the
23946   // unary operation isn't a bitwise AND, or if the sizes of the operations
23947   // aren't the same.
23948   EVT VT = N->getValueType(0);
23949   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
23950       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
23951       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
23952     return SDValue();
23953
23954   // Now check that the other operand of the AND is a constant. We could
23955   // make the transformation for non-constant splats as well, but it's unclear
23956   // that would be a benefit as it would not eliminate any operations, just
23957   // perform one more step in scalar code before moving to the vector unit.
23958   if (BuildVectorSDNode *BV =
23959           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
23960     // Bail out if the vector isn't a constant.
23961     if (!BV->isConstant())
23962       return SDValue();
23963
23964     // Everything checks out. Build up the new and improved node.
23965     SDLoc DL(N);
23966     EVT IntVT = BV->getValueType(0);
23967     // Create a new constant of the appropriate type for the transformed
23968     // DAG.
23969     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
23970     // The AND node needs bitcasts to/from an integer vector type around it.
23971     SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
23972     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
23973                                  N->getOperand(0)->getOperand(0), MaskConst);
23974     SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
23975     return Res;
23976   }
23977
23978   return SDValue();
23979 }
23980
23981 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
23982                                         const X86Subtarget *Subtarget) {
23983   // First try to optimize away the conversion entirely when it's
23984   // conditionally from a constant. Vectors only.
23985   SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG);
23986   if (Res != SDValue())
23987     return Res;
23988
23989   // Now move on to more general possibilities.
23990   SDValue Op0 = N->getOperand(0);
23991   EVT InVT = Op0->getValueType(0);
23992
23993   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
23994   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
23995     SDLoc dl(N);
23996     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
23997     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
23998     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
23999   }
24000
24001   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
24002   // a 32-bit target where SSE doesn't support i64->FP operations.
24003   if (Op0.getOpcode() == ISD::LOAD) {
24004     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
24005     EVT VT = Ld->getValueType(0);
24006     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
24007         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
24008         !Subtarget->is64Bit() && VT == MVT::i64) {
24009       SDValue FILDChain = Subtarget->getTargetLowering()->BuildFILD(
24010           SDValue(N, 0), Ld->getValueType(0), Ld->getChain(), Op0, DAG);
24011       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
24012       return FILDChain;
24013     }
24014   }
24015   return SDValue();
24016 }
24017
24018 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
24019 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
24020                                  X86TargetLowering::DAGCombinerInfo &DCI) {
24021   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
24022   // the result is either zero or one (depending on the input carry bit).
24023   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
24024   if (X86::isZeroNode(N->getOperand(0)) &&
24025       X86::isZeroNode(N->getOperand(1)) &&
24026       // We don't have a good way to replace an EFLAGS use, so only do this when
24027       // dead right now.
24028       SDValue(N, 1).use_empty()) {
24029     SDLoc DL(N);
24030     EVT VT = N->getValueType(0);
24031     SDValue CarryOut = DAG.getConstant(0, DL, N->getValueType(1));
24032     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
24033                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
24034                                            DAG.getConstant(X86::COND_B, DL,
24035                                                            MVT::i8),
24036                                            N->getOperand(2)),
24037                                DAG.getConstant(1, DL, VT));
24038     return DCI.CombineTo(N, Res1, CarryOut);
24039   }
24040
24041   return SDValue();
24042 }
24043
24044 // fold (add Y, (sete  X, 0)) -> adc  0, Y
24045 //      (add Y, (setne X, 0)) -> sbb -1, Y
24046 //      (sub (sete  X, 0), Y) -> sbb  0, Y
24047 //      (sub (setne X, 0), Y) -> adc -1, Y
24048 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
24049   SDLoc DL(N);
24050
24051   // Look through ZExts.
24052   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
24053   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
24054     return SDValue();
24055
24056   SDValue SetCC = Ext.getOperand(0);
24057   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
24058     return SDValue();
24059
24060   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
24061   if (CC != X86::COND_E && CC != X86::COND_NE)
24062     return SDValue();
24063
24064   SDValue Cmp = SetCC.getOperand(1);
24065   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
24066       !X86::isZeroNode(Cmp.getOperand(1)) ||
24067       !Cmp.getOperand(0).getValueType().isInteger())
24068     return SDValue();
24069
24070   SDValue CmpOp0 = Cmp.getOperand(0);
24071   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
24072                                DAG.getConstant(1, DL, CmpOp0.getValueType()));
24073
24074   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
24075   if (CC == X86::COND_NE)
24076     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
24077                        DL, OtherVal.getValueType(), OtherVal,
24078                        DAG.getConstant(-1ULL, DL, OtherVal.getValueType()),
24079                        NewCmp);
24080   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
24081                      DL, OtherVal.getValueType(), OtherVal,
24082                      DAG.getConstant(0, DL, OtherVal.getValueType()), NewCmp);
24083 }
24084
24085 /// PerformADDCombine - Do target-specific dag combines on integer adds.
24086 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
24087                                  const X86Subtarget *Subtarget) {
24088   EVT VT = N->getValueType(0);
24089   SDValue Op0 = N->getOperand(0);
24090   SDValue Op1 = N->getOperand(1);
24091
24092   // Try to synthesize horizontal adds from adds of shuffles.
24093   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
24094        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
24095       isHorizontalBinOp(Op0, Op1, true))
24096     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
24097
24098   return OptimizeConditionalInDecrement(N, DAG);
24099 }
24100
24101 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
24102                                  const X86Subtarget *Subtarget) {
24103   SDValue Op0 = N->getOperand(0);
24104   SDValue Op1 = N->getOperand(1);
24105
24106   // X86 can't encode an immediate LHS of a sub. See if we can push the
24107   // negation into a preceding instruction.
24108   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
24109     // If the RHS of the sub is a XOR with one use and a constant, invert the
24110     // immediate. Then add one to the LHS of the sub so we can turn
24111     // X-Y -> X+~Y+1, saving one register.
24112     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
24113         isa<ConstantSDNode>(Op1.getOperand(1))) {
24114       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
24115       EVT VT = Op0.getValueType();
24116       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
24117                                    Op1.getOperand(0),
24118                                    DAG.getConstant(~XorC, SDLoc(Op1), VT));
24119       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
24120                          DAG.getConstant(C->getAPIntValue() + 1, SDLoc(N), VT));
24121     }
24122   }
24123
24124   // Try to synthesize horizontal adds from adds of shuffles.
24125   EVT VT = N->getValueType(0);
24126   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
24127        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
24128       isHorizontalBinOp(Op0, Op1, true))
24129     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
24130
24131   return OptimizeConditionalInDecrement(N, DAG);
24132 }
24133
24134 /// performVZEXTCombine - Performs build vector combines
24135 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
24136                                    TargetLowering::DAGCombinerInfo &DCI,
24137                                    const X86Subtarget *Subtarget) {
24138   SDLoc DL(N);
24139   MVT VT = N->getSimpleValueType(0);
24140   SDValue Op = N->getOperand(0);
24141   MVT OpVT = Op.getSimpleValueType();
24142   MVT OpEltVT = OpVT.getVectorElementType();
24143   unsigned InputBits = OpEltVT.getSizeInBits() * VT.getVectorNumElements();
24144
24145   // (vzext (bitcast (vzext (x)) -> (vzext x)
24146   SDValue V = Op;
24147   while (V.getOpcode() == ISD::BITCAST)
24148     V = V.getOperand(0);
24149
24150   if (V != Op && V.getOpcode() == X86ISD::VZEXT) {
24151     MVT InnerVT = V.getSimpleValueType();
24152     MVT InnerEltVT = InnerVT.getVectorElementType();
24153
24154     // If the element sizes match exactly, we can just do one larger vzext. This
24155     // is always an exact type match as vzext operates on integer types.
24156     if (OpEltVT == InnerEltVT) {
24157       assert(OpVT == InnerVT && "Types must match for vzext!");
24158       return DAG.getNode(X86ISD::VZEXT, DL, VT, V.getOperand(0));
24159     }
24160
24161     // The only other way we can combine them is if only a single element of the
24162     // inner vzext is used in the input to the outer vzext.
24163     if (InnerEltVT.getSizeInBits() < InputBits)
24164       return SDValue();
24165
24166     // In this case, the inner vzext is completely dead because we're going to
24167     // only look at bits inside of the low element. Just do the outer vzext on
24168     // a bitcast of the input to the inner.
24169     return DAG.getNode(X86ISD::VZEXT, DL, VT,
24170                        DAG.getNode(ISD::BITCAST, DL, OpVT, V));
24171   }
24172
24173   // Check if we can bypass extracting and re-inserting an element of an input
24174   // vector. Essentialy:
24175   // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
24176   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR &&
24177       V.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
24178       V.getOperand(0).getSimpleValueType().getSizeInBits() == InputBits) {
24179     SDValue ExtractedV = V.getOperand(0);
24180     SDValue OrigV = ExtractedV.getOperand(0);
24181     if (auto *ExtractIdx = dyn_cast<ConstantSDNode>(ExtractedV.getOperand(1)))
24182       if (ExtractIdx->getZExtValue() == 0) {
24183         MVT OrigVT = OrigV.getSimpleValueType();
24184         // Extract a subvector if necessary...
24185         if (OrigVT.getSizeInBits() > OpVT.getSizeInBits()) {
24186           int Ratio = OrigVT.getSizeInBits() / OpVT.getSizeInBits();
24187           OrigVT = MVT::getVectorVT(OrigVT.getVectorElementType(),
24188                                     OrigVT.getVectorNumElements() / Ratio);
24189           OrigV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigVT, OrigV,
24190                               DAG.getIntPtrConstant(0, DL));
24191         }
24192         Op = DAG.getNode(ISD::BITCAST, DL, OpVT, OrigV);
24193         return DAG.getNode(X86ISD::VZEXT, DL, VT, Op);
24194       }
24195   }
24196
24197   return SDValue();
24198 }
24199
24200 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
24201                                              DAGCombinerInfo &DCI) const {
24202   SelectionDAG &DAG = DCI.DAG;
24203   switch (N->getOpcode()) {
24204   default: break;
24205   case ISD::EXTRACT_VECTOR_ELT:
24206     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
24207   case ISD::VSELECT:
24208   case ISD::SELECT:
24209   case X86ISD::SHRUNKBLEND:
24210     return PerformSELECTCombine(N, DAG, DCI, Subtarget);
24211   case ISD::BITCAST:        return PerformBITCASTCombine(N, DAG);
24212   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
24213   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
24214   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
24215   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
24216   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
24217   case ISD::SHL:
24218   case ISD::SRA:
24219   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
24220   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
24221   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
24222   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
24223   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
24224   case ISD::MLOAD:          return PerformMLOADCombine(N, DAG, DCI, Subtarget);
24225   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
24226   case ISD::MSTORE:         return PerformMSTORECombine(N, DAG, Subtarget);
24227   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, Subtarget);
24228   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
24229   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
24230   case X86ISD::FXOR:
24231   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
24232   case X86ISD::FMIN:
24233   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
24234   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
24235   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
24236   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
24237   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
24238   case ISD::ANY_EXTEND:
24239   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
24240   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
24241   case ISD::SIGN_EXTEND_INREG:
24242     return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
24243   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG,DCI,Subtarget);
24244   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
24245   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
24246   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
24247   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
24248   case X86ISD::SHUFP:       // Handle all target specific shuffles
24249   case X86ISD::PALIGNR:
24250   case X86ISD::UNPCKH:
24251   case X86ISD::UNPCKL:
24252   case X86ISD::MOVHLPS:
24253   case X86ISD::MOVLHPS:
24254   case X86ISD::PSHUFB:
24255   case X86ISD::PSHUFD:
24256   case X86ISD::PSHUFHW:
24257   case X86ISD::PSHUFLW:
24258   case X86ISD::MOVSS:
24259   case X86ISD::MOVSD:
24260   case X86ISD::VPERMILPI:
24261   case X86ISD::VPERM2X128:
24262   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
24263   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
24264   case ISD::INTRINSIC_WO_CHAIN:
24265     return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
24266   case X86ISD::INSERTPS: {
24267     if (getTargetMachine().getOptLevel() > CodeGenOpt::None)
24268       return PerformINSERTPSCombine(N, DAG, Subtarget);
24269     break;
24270   }
24271   case X86ISD::BLENDI:    return PerformBLENDICombine(N, DAG);
24272   }
24273
24274   return SDValue();
24275 }
24276
24277 /// isTypeDesirableForOp - Return true if the target has native support for
24278 /// the specified value type and it is 'desirable' to use the type for the
24279 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
24280 /// instruction encodings are longer and some i16 instructions are slow.
24281 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
24282   if (!isTypeLegal(VT))
24283     return false;
24284   if (VT != MVT::i16)
24285     return true;
24286
24287   switch (Opc) {
24288   default:
24289     return true;
24290   case ISD::LOAD:
24291   case ISD::SIGN_EXTEND:
24292   case ISD::ZERO_EXTEND:
24293   case ISD::ANY_EXTEND:
24294   case ISD::SHL:
24295   case ISD::SRL:
24296   case ISD::SUB:
24297   case ISD::ADD:
24298   case ISD::MUL:
24299   case ISD::AND:
24300   case ISD::OR:
24301   case ISD::XOR:
24302     return false;
24303   }
24304 }
24305
24306 /// IsDesirableToPromoteOp - This method query the target whether it is
24307 /// beneficial for dag combiner to promote the specified node. If true, it
24308 /// should return the desired promotion type by reference.
24309 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
24310   EVT VT = Op.getValueType();
24311   if (VT != MVT::i16)
24312     return false;
24313
24314   bool Promote = false;
24315   bool Commute = false;
24316   switch (Op.getOpcode()) {
24317   default: break;
24318   case ISD::LOAD: {
24319     LoadSDNode *LD = cast<LoadSDNode>(Op);
24320     // If the non-extending load has a single use and it's not live out, then it
24321     // might be folded.
24322     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
24323                                                      Op.hasOneUse()*/) {
24324       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
24325              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
24326         // The only case where we'd want to promote LOAD (rather then it being
24327         // promoted as an operand is when it's only use is liveout.
24328         if (UI->getOpcode() != ISD::CopyToReg)
24329           return false;
24330       }
24331     }
24332     Promote = true;
24333     break;
24334   }
24335   case ISD::SIGN_EXTEND:
24336   case ISD::ZERO_EXTEND:
24337   case ISD::ANY_EXTEND:
24338     Promote = true;
24339     break;
24340   case ISD::SHL:
24341   case ISD::SRL: {
24342     SDValue N0 = Op.getOperand(0);
24343     // Look out for (store (shl (load), x)).
24344     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
24345       return false;
24346     Promote = true;
24347     break;
24348   }
24349   case ISD::ADD:
24350   case ISD::MUL:
24351   case ISD::AND:
24352   case ISD::OR:
24353   case ISD::XOR:
24354     Commute = true;
24355     // fallthrough
24356   case ISD::SUB: {
24357     SDValue N0 = Op.getOperand(0);
24358     SDValue N1 = Op.getOperand(1);
24359     if (!Commute && MayFoldLoad(N1))
24360       return false;
24361     // Avoid disabling potential load folding opportunities.
24362     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
24363       return false;
24364     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
24365       return false;
24366     Promote = true;
24367   }
24368   }
24369
24370   PVT = MVT::i32;
24371   return Promote;
24372 }
24373
24374 //===----------------------------------------------------------------------===//
24375 //                           X86 Inline Assembly Support
24376 //===----------------------------------------------------------------------===//
24377
24378 // Helper to match a string separated by whitespace.
24379 static bool matchAsm(StringRef S, ArrayRef<const char *> Pieces) {
24380   S = S.substr(S.find_first_not_of(" \t")); // Skip leading whitespace.
24381
24382   for (StringRef Piece : Pieces) {
24383     if (!S.startswith(Piece)) // Check if the piece matches.
24384       return false;
24385
24386     S = S.substr(Piece.size());
24387     StringRef::size_type Pos = S.find_first_not_of(" \t");
24388     if (Pos == 0) // We matched a prefix.
24389       return false;
24390
24391     S = S.substr(Pos);
24392   }
24393
24394   return S.empty();
24395 }
24396
24397 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
24398
24399   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
24400     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
24401         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
24402         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
24403
24404       if (AsmPieces.size() == 3)
24405         return true;
24406       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
24407         return true;
24408     }
24409   }
24410   return false;
24411 }
24412
24413 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
24414   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
24415
24416   std::string AsmStr = IA->getAsmString();
24417
24418   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
24419   if (!Ty || Ty->getBitWidth() % 16 != 0)
24420     return false;
24421
24422   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
24423   SmallVector<StringRef, 4> AsmPieces;
24424   SplitString(AsmStr, AsmPieces, ";\n");
24425
24426   switch (AsmPieces.size()) {
24427   default: return false;
24428   case 1:
24429     // FIXME: this should verify that we are targeting a 486 or better.  If not,
24430     // we will turn this bswap into something that will be lowered to logical
24431     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
24432     // lower so don't worry about this.
24433     // bswap $0
24434     if (matchAsm(AsmPieces[0], {"bswap", "$0"}) ||
24435         matchAsm(AsmPieces[0], {"bswapl", "$0"}) ||
24436         matchAsm(AsmPieces[0], {"bswapq", "$0"}) ||
24437         matchAsm(AsmPieces[0], {"bswap", "${0:q}"}) ||
24438         matchAsm(AsmPieces[0], {"bswapl", "${0:q}"}) ||
24439         matchAsm(AsmPieces[0], {"bswapq", "${0:q}"})) {
24440       // No need to check constraints, nothing other than the equivalent of
24441       // "=r,0" would be valid here.
24442       return IntrinsicLowering::LowerToByteSwap(CI);
24443     }
24444
24445     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
24446     if (CI->getType()->isIntegerTy(16) &&
24447         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
24448         (matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) ||
24449          matchAsm(AsmPieces[0], {"rolw", "$$8,", "${0:w}"}))) {
24450       AsmPieces.clear();
24451       const std::string &ConstraintsStr = IA->getConstraintString();
24452       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
24453       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
24454       if (clobbersFlagRegisters(AsmPieces))
24455         return IntrinsicLowering::LowerToByteSwap(CI);
24456     }
24457     break;
24458   case 3:
24459     if (CI->getType()->isIntegerTy(32) &&
24460         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
24461         matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) &&
24462         matchAsm(AsmPieces[1], {"rorl", "$$16,", "$0"}) &&
24463         matchAsm(AsmPieces[2], {"rorw", "$$8,", "${0:w}"})) {
24464       AsmPieces.clear();
24465       const std::string &ConstraintsStr = IA->getConstraintString();
24466       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
24467       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
24468       if (clobbersFlagRegisters(AsmPieces))
24469         return IntrinsicLowering::LowerToByteSwap(CI);
24470     }
24471
24472     if (CI->getType()->isIntegerTy(64)) {
24473       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
24474       if (Constraints.size() >= 2 &&
24475           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
24476           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
24477         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
24478         if (matchAsm(AsmPieces[0], {"bswap", "%eax"}) &&
24479             matchAsm(AsmPieces[1], {"bswap", "%edx"}) &&
24480             matchAsm(AsmPieces[2], {"xchgl", "%eax,", "%edx"}))
24481           return IntrinsicLowering::LowerToByteSwap(CI);
24482       }
24483     }
24484     break;
24485   }
24486   return false;
24487 }
24488
24489 /// getConstraintType - Given a constraint letter, return the type of
24490 /// constraint it is for this target.
24491 X86TargetLowering::ConstraintType
24492 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
24493   if (Constraint.size() == 1) {
24494     switch (Constraint[0]) {
24495     case 'R':
24496     case 'q':
24497     case 'Q':
24498     case 'f':
24499     case 't':
24500     case 'u':
24501     case 'y':
24502     case 'x':
24503     case 'Y':
24504     case 'l':
24505       return C_RegisterClass;
24506     case 'a':
24507     case 'b':
24508     case 'c':
24509     case 'd':
24510     case 'S':
24511     case 'D':
24512     case 'A':
24513       return C_Register;
24514     case 'I':
24515     case 'J':
24516     case 'K':
24517     case 'L':
24518     case 'M':
24519     case 'N':
24520     case 'G':
24521     case 'C':
24522     case 'e':
24523     case 'Z':
24524       return C_Other;
24525     default:
24526       break;
24527     }
24528   }
24529   return TargetLowering::getConstraintType(Constraint);
24530 }
24531
24532 /// Examine constraint type and operand type and determine a weight value.
24533 /// This object must already have been set up with the operand type
24534 /// and the current alternative constraint selected.
24535 TargetLowering::ConstraintWeight
24536   X86TargetLowering::getSingleConstraintMatchWeight(
24537     AsmOperandInfo &info, const char *constraint) const {
24538   ConstraintWeight weight = CW_Invalid;
24539   Value *CallOperandVal = info.CallOperandVal;
24540     // If we don't have a value, we can't do a match,
24541     // but allow it at the lowest weight.
24542   if (!CallOperandVal)
24543     return CW_Default;
24544   Type *type = CallOperandVal->getType();
24545   // Look at the constraint type.
24546   switch (*constraint) {
24547   default:
24548     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
24549   case 'R':
24550   case 'q':
24551   case 'Q':
24552   case 'a':
24553   case 'b':
24554   case 'c':
24555   case 'd':
24556   case 'S':
24557   case 'D':
24558   case 'A':
24559     if (CallOperandVal->getType()->isIntegerTy())
24560       weight = CW_SpecificReg;
24561     break;
24562   case 'f':
24563   case 't':
24564   case 'u':
24565     if (type->isFloatingPointTy())
24566       weight = CW_SpecificReg;
24567     break;
24568   case 'y':
24569     if (type->isX86_MMXTy() && Subtarget->hasMMX())
24570       weight = CW_SpecificReg;
24571     break;
24572   case 'x':
24573   case 'Y':
24574     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
24575         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
24576       weight = CW_Register;
24577     break;
24578   case 'I':
24579     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
24580       if (C->getZExtValue() <= 31)
24581         weight = CW_Constant;
24582     }
24583     break;
24584   case 'J':
24585     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24586       if (C->getZExtValue() <= 63)
24587         weight = CW_Constant;
24588     }
24589     break;
24590   case 'K':
24591     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24592       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
24593         weight = CW_Constant;
24594     }
24595     break;
24596   case 'L':
24597     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24598       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
24599         weight = CW_Constant;
24600     }
24601     break;
24602   case 'M':
24603     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24604       if (C->getZExtValue() <= 3)
24605         weight = CW_Constant;
24606     }
24607     break;
24608   case 'N':
24609     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24610       if (C->getZExtValue() <= 0xff)
24611         weight = CW_Constant;
24612     }
24613     break;
24614   case 'G':
24615   case 'C':
24616     if (isa<ConstantFP>(CallOperandVal)) {
24617       weight = CW_Constant;
24618     }
24619     break;
24620   case 'e':
24621     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24622       if ((C->getSExtValue() >= -0x80000000LL) &&
24623           (C->getSExtValue() <= 0x7fffffffLL))
24624         weight = CW_Constant;
24625     }
24626     break;
24627   case 'Z':
24628     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24629       if (C->getZExtValue() <= 0xffffffff)
24630         weight = CW_Constant;
24631     }
24632     break;
24633   }
24634   return weight;
24635 }
24636
24637 /// LowerXConstraint - try to replace an X constraint, which matches anything,
24638 /// with another that has more specific requirements based on the type of the
24639 /// corresponding operand.
24640 const char *X86TargetLowering::
24641 LowerXConstraint(EVT ConstraintVT) const {
24642   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
24643   // 'f' like normal targets.
24644   if (ConstraintVT.isFloatingPoint()) {
24645     if (Subtarget->hasSSE2())
24646       return "Y";
24647     if (Subtarget->hasSSE1())
24648       return "x";
24649   }
24650
24651   return TargetLowering::LowerXConstraint(ConstraintVT);
24652 }
24653
24654 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
24655 /// vector.  If it is invalid, don't add anything to Ops.
24656 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
24657                                                      std::string &Constraint,
24658                                                      std::vector<SDValue>&Ops,
24659                                                      SelectionDAG &DAG) const {
24660   SDValue Result;
24661
24662   // Only support length 1 constraints for now.
24663   if (Constraint.length() > 1) return;
24664
24665   char ConstraintLetter = Constraint[0];
24666   switch (ConstraintLetter) {
24667   default: break;
24668   case 'I':
24669     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24670       if (C->getZExtValue() <= 31) {
24671         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24672                                        Op.getValueType());
24673         break;
24674       }
24675     }
24676     return;
24677   case 'J':
24678     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24679       if (C->getZExtValue() <= 63) {
24680         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24681                                        Op.getValueType());
24682         break;
24683       }
24684     }
24685     return;
24686   case 'K':
24687     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24688       if (isInt<8>(C->getSExtValue())) {
24689         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24690                                        Op.getValueType());
24691         break;
24692       }
24693     }
24694     return;
24695   case 'L':
24696     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24697       if (C->getZExtValue() == 0xff || C->getZExtValue() == 0xffff ||
24698           (Subtarget->is64Bit() && C->getZExtValue() == 0xffffffff)) {
24699         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op),
24700                                        Op.getValueType());
24701         break;
24702       }
24703     }
24704     return;
24705   case 'M':
24706     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24707       if (C->getZExtValue() <= 3) {
24708         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24709                                        Op.getValueType());
24710         break;
24711       }
24712     }
24713     return;
24714   case 'N':
24715     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24716       if (C->getZExtValue() <= 255) {
24717         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24718                                        Op.getValueType());
24719         break;
24720       }
24721     }
24722     return;
24723   case 'O':
24724     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24725       if (C->getZExtValue() <= 127) {
24726         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24727                                        Op.getValueType());
24728         break;
24729       }
24730     }
24731     return;
24732   case 'e': {
24733     // 32-bit signed value
24734     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24735       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
24736                                            C->getSExtValue())) {
24737         // Widen to 64 bits here to get it sign extended.
24738         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op), MVT::i64);
24739         break;
24740       }
24741     // FIXME gcc accepts some relocatable values here too, but only in certain
24742     // memory models; it's complicated.
24743     }
24744     return;
24745   }
24746   case 'Z': {
24747     // 32-bit unsigned value
24748     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24749       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
24750                                            C->getZExtValue())) {
24751         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24752                                        Op.getValueType());
24753         break;
24754       }
24755     }
24756     // FIXME gcc accepts some relocatable values here too, but only in certain
24757     // memory models; it's complicated.
24758     return;
24759   }
24760   case 'i': {
24761     // Literal immediates are always ok.
24762     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
24763       // Widen to 64 bits here to get it sign extended.
24764       Result = DAG.getTargetConstant(CST->getSExtValue(), SDLoc(Op), MVT::i64);
24765       break;
24766     }
24767
24768     // In any sort of PIC mode addresses need to be computed at runtime by
24769     // adding in a register or some sort of table lookup.  These can't
24770     // be used as immediates.
24771     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
24772       return;
24773
24774     // If we are in non-pic codegen mode, we allow the address of a global (with
24775     // an optional displacement) to be used with 'i'.
24776     GlobalAddressSDNode *GA = nullptr;
24777     int64_t Offset = 0;
24778
24779     // Match either (GA), (GA+C), (GA+C1+C2), etc.
24780     while (1) {
24781       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
24782         Offset += GA->getOffset();
24783         break;
24784       } else if (Op.getOpcode() == ISD::ADD) {
24785         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
24786           Offset += C->getZExtValue();
24787           Op = Op.getOperand(0);
24788           continue;
24789         }
24790       } else if (Op.getOpcode() == ISD::SUB) {
24791         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
24792           Offset += -C->getZExtValue();
24793           Op = Op.getOperand(0);
24794           continue;
24795         }
24796       }
24797
24798       // Otherwise, this isn't something we can handle, reject it.
24799       return;
24800     }
24801
24802     const GlobalValue *GV = GA->getGlobal();
24803     // If we require an extra load to get this address, as in PIC mode, we
24804     // can't accept it.
24805     if (isGlobalStubReference(
24806             Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
24807       return;
24808
24809     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
24810                                         GA->getValueType(0), Offset);
24811     break;
24812   }
24813   }
24814
24815   if (Result.getNode()) {
24816     Ops.push_back(Result);
24817     return;
24818   }
24819   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
24820 }
24821
24822 std::pair<unsigned, const TargetRegisterClass *>
24823 X86TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
24824                                                 const std::string &Constraint,
24825                                                 MVT VT) const {
24826   // First, see if this is a constraint that directly corresponds to an LLVM
24827   // register class.
24828   if (Constraint.size() == 1) {
24829     // GCC Constraint Letters
24830     switch (Constraint[0]) {
24831     default: break;
24832       // TODO: Slight differences here in allocation order and leaving
24833       // RIP in the class. Do they matter any more here than they do
24834       // in the normal allocation?
24835     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
24836       if (Subtarget->is64Bit()) {
24837         if (VT == MVT::i32 || VT == MVT::f32)
24838           return std::make_pair(0U, &X86::GR32RegClass);
24839         if (VT == MVT::i16)
24840           return std::make_pair(0U, &X86::GR16RegClass);
24841         if (VT == MVT::i8 || VT == MVT::i1)
24842           return std::make_pair(0U, &X86::GR8RegClass);
24843         if (VT == MVT::i64 || VT == MVT::f64)
24844           return std::make_pair(0U, &X86::GR64RegClass);
24845         break;
24846       }
24847       // 32-bit fallthrough
24848     case 'Q':   // Q_REGS
24849       if (VT == MVT::i32 || VT == MVT::f32)
24850         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
24851       if (VT == MVT::i16)
24852         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
24853       if (VT == MVT::i8 || VT == MVT::i1)
24854         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
24855       if (VT == MVT::i64)
24856         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
24857       break;
24858     case 'r':   // GENERAL_REGS
24859     case 'l':   // INDEX_REGS
24860       if (VT == MVT::i8 || VT == MVT::i1)
24861         return std::make_pair(0U, &X86::GR8RegClass);
24862       if (VT == MVT::i16)
24863         return std::make_pair(0U, &X86::GR16RegClass);
24864       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
24865         return std::make_pair(0U, &X86::GR32RegClass);
24866       return std::make_pair(0U, &X86::GR64RegClass);
24867     case 'R':   // LEGACY_REGS
24868       if (VT == MVT::i8 || VT == MVT::i1)
24869         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
24870       if (VT == MVT::i16)
24871         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
24872       if (VT == MVT::i32 || !Subtarget->is64Bit())
24873         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
24874       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
24875     case 'f':  // FP Stack registers.
24876       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
24877       // value to the correct fpstack register class.
24878       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
24879         return std::make_pair(0U, &X86::RFP32RegClass);
24880       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
24881         return std::make_pair(0U, &X86::RFP64RegClass);
24882       return std::make_pair(0U, &X86::RFP80RegClass);
24883     case 'y':   // MMX_REGS if MMX allowed.
24884       if (!Subtarget->hasMMX()) break;
24885       return std::make_pair(0U, &X86::VR64RegClass);
24886     case 'Y':   // SSE_REGS if SSE2 allowed
24887       if (!Subtarget->hasSSE2()) break;
24888       // FALL THROUGH.
24889     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
24890       if (!Subtarget->hasSSE1()) break;
24891
24892       switch (VT.SimpleTy) {
24893       default: break;
24894       // Scalar SSE types.
24895       case MVT::f32:
24896       case MVT::i32:
24897         return std::make_pair(0U, &X86::FR32RegClass);
24898       case MVT::f64:
24899       case MVT::i64:
24900         return std::make_pair(0U, &X86::FR64RegClass);
24901       // Vector types.
24902       case MVT::v16i8:
24903       case MVT::v8i16:
24904       case MVT::v4i32:
24905       case MVT::v2i64:
24906       case MVT::v4f32:
24907       case MVT::v2f64:
24908         return std::make_pair(0U, &X86::VR128RegClass);
24909       // AVX types.
24910       case MVT::v32i8:
24911       case MVT::v16i16:
24912       case MVT::v8i32:
24913       case MVT::v4i64:
24914       case MVT::v8f32:
24915       case MVT::v4f64:
24916         return std::make_pair(0U, &X86::VR256RegClass);
24917       case MVT::v8f64:
24918       case MVT::v16f32:
24919       case MVT::v16i32:
24920       case MVT::v8i64:
24921         return std::make_pair(0U, &X86::VR512RegClass);
24922       }
24923       break;
24924     }
24925   }
24926
24927   // Use the default implementation in TargetLowering to convert the register
24928   // constraint into a member of a register class.
24929   std::pair<unsigned, const TargetRegisterClass*> Res;
24930   Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
24931
24932   // Not found as a standard register?
24933   if (!Res.second) {
24934     // Map st(0) -> st(7) -> ST0
24935     if (Constraint.size() == 7 && Constraint[0] == '{' &&
24936         tolower(Constraint[1]) == 's' &&
24937         tolower(Constraint[2]) == 't' &&
24938         Constraint[3] == '(' &&
24939         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
24940         Constraint[5] == ')' &&
24941         Constraint[6] == '}') {
24942
24943       Res.first = X86::FP0+Constraint[4]-'0';
24944       Res.second = &X86::RFP80RegClass;
24945       return Res;
24946     }
24947
24948     // GCC allows "st(0)" to be called just plain "st".
24949     if (StringRef("{st}").equals_lower(Constraint)) {
24950       Res.first = X86::FP0;
24951       Res.second = &X86::RFP80RegClass;
24952       return Res;
24953     }
24954
24955     // flags -> EFLAGS
24956     if (StringRef("{flags}").equals_lower(Constraint)) {
24957       Res.first = X86::EFLAGS;
24958       Res.second = &X86::CCRRegClass;
24959       return Res;
24960     }
24961
24962     // 'A' means EAX + EDX.
24963     if (Constraint == "A") {
24964       Res.first = X86::EAX;
24965       Res.second = &X86::GR32_ADRegClass;
24966       return Res;
24967     }
24968     return Res;
24969   }
24970
24971   // Otherwise, check to see if this is a register class of the wrong value
24972   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
24973   // turn into {ax},{dx}.
24974   if (Res.second->hasType(VT))
24975     return Res;   // Correct type already, nothing to do.
24976
24977   // All of the single-register GCC register classes map their values onto
24978   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
24979   // really want an 8-bit or 32-bit register, map to the appropriate register
24980   // class and return the appropriate register.
24981   if (Res.second == &X86::GR16RegClass) {
24982     if (VT == MVT::i8 || VT == MVT::i1) {
24983       unsigned DestReg = 0;
24984       switch (Res.first) {
24985       default: break;
24986       case X86::AX: DestReg = X86::AL; break;
24987       case X86::DX: DestReg = X86::DL; break;
24988       case X86::CX: DestReg = X86::CL; break;
24989       case X86::BX: DestReg = X86::BL; break;
24990       }
24991       if (DestReg) {
24992         Res.first = DestReg;
24993         Res.second = &X86::GR8RegClass;
24994       }
24995     } else if (VT == MVT::i32 || VT == MVT::f32) {
24996       unsigned DestReg = 0;
24997       switch (Res.first) {
24998       default: break;
24999       case X86::AX: DestReg = X86::EAX; break;
25000       case X86::DX: DestReg = X86::EDX; break;
25001       case X86::CX: DestReg = X86::ECX; break;
25002       case X86::BX: DestReg = X86::EBX; break;
25003       case X86::SI: DestReg = X86::ESI; break;
25004       case X86::DI: DestReg = X86::EDI; break;
25005       case X86::BP: DestReg = X86::EBP; break;
25006       case X86::SP: DestReg = X86::ESP; break;
25007       }
25008       if (DestReg) {
25009         Res.first = DestReg;
25010         Res.second = &X86::GR32RegClass;
25011       }
25012     } else if (VT == MVT::i64 || VT == MVT::f64) {
25013       unsigned DestReg = 0;
25014       switch (Res.first) {
25015       default: break;
25016       case X86::AX: DestReg = X86::RAX; break;
25017       case X86::DX: DestReg = X86::RDX; break;
25018       case X86::CX: DestReg = X86::RCX; break;
25019       case X86::BX: DestReg = X86::RBX; break;
25020       case X86::SI: DestReg = X86::RSI; break;
25021       case X86::DI: DestReg = X86::RDI; break;
25022       case X86::BP: DestReg = X86::RBP; break;
25023       case X86::SP: DestReg = X86::RSP; break;
25024       }
25025       if (DestReg) {
25026         Res.first = DestReg;
25027         Res.second = &X86::GR64RegClass;
25028       }
25029     }
25030   } else if (Res.second == &X86::FR32RegClass ||
25031              Res.second == &X86::FR64RegClass ||
25032              Res.second == &X86::VR128RegClass ||
25033              Res.second == &X86::VR256RegClass ||
25034              Res.second == &X86::FR32XRegClass ||
25035              Res.second == &X86::FR64XRegClass ||
25036              Res.second == &X86::VR128XRegClass ||
25037              Res.second == &X86::VR256XRegClass ||
25038              Res.second == &X86::VR512RegClass) {
25039     // Handle references to XMM physical registers that got mapped into the
25040     // wrong class.  This can happen with constraints like {xmm0} where the
25041     // target independent register mapper will just pick the first match it can
25042     // find, ignoring the required type.
25043
25044     if (VT == MVT::f32 || VT == MVT::i32)
25045       Res.second = &X86::FR32RegClass;
25046     else if (VT == MVT::f64 || VT == MVT::i64)
25047       Res.second = &X86::FR64RegClass;
25048     else if (X86::VR128RegClass.hasType(VT))
25049       Res.second = &X86::VR128RegClass;
25050     else if (X86::VR256RegClass.hasType(VT))
25051       Res.second = &X86::VR256RegClass;
25052     else if (X86::VR512RegClass.hasType(VT))
25053       Res.second = &X86::VR512RegClass;
25054   }
25055
25056   return Res;
25057 }
25058
25059 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
25060                                             Type *Ty) const {
25061   // Scaling factors are not free at all.
25062   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
25063   // will take 2 allocations in the out of order engine instead of 1
25064   // for plain addressing mode, i.e. inst (reg1).
25065   // E.g.,
25066   // vaddps (%rsi,%drx), %ymm0, %ymm1
25067   // Requires two allocations (one for the load, one for the computation)
25068   // whereas:
25069   // vaddps (%rsi), %ymm0, %ymm1
25070   // Requires just 1 allocation, i.e., freeing allocations for other operations
25071   // and having less micro operations to execute.
25072   //
25073   // For some X86 architectures, this is even worse because for instance for
25074   // stores, the complex addressing mode forces the instruction to use the
25075   // "load" ports instead of the dedicated "store" port.
25076   // E.g., on Haswell:
25077   // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
25078   // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
25079   if (isLegalAddressingMode(AM, Ty))
25080     // Scale represents reg2 * scale, thus account for 1
25081     // as soon as we use a second register.
25082     return AM.Scale != 0;
25083   return -1;
25084 }
25085
25086 bool X86TargetLowering::isTargetFTOL() const {
25087   return Subtarget->isTargetKnownWindowsMSVC() && !Subtarget->is64Bit();
25088 }