AVX-512: Extend/Truncate operations for SKX,
[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   if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
517     // f32 and f64 use SSE.
518     // Set up the FP register classes.
519     addRegisterClass(MVT::f32, &X86::FR32RegClass);
520     addRegisterClass(MVT::f64, &X86::FR64RegClass);
521
522     // Use ANDPD to simulate FABS.
523     setOperationAction(ISD::FABS , MVT::f64, Custom);
524     setOperationAction(ISD::FABS , MVT::f32, Custom);
525
526     // Use XORP to simulate FNEG.
527     setOperationAction(ISD::FNEG , MVT::f64, Custom);
528     setOperationAction(ISD::FNEG , MVT::f32, Custom);
529
530     // Use ANDPD and ORPD to simulate FCOPYSIGN.
531     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
532     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
533
534     // Lower this to FGETSIGNx86 plus an AND.
535     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
536     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
537
538     // We don't support sin/cos/fmod
539     setOperationAction(ISD::FSIN   , MVT::f64, Expand);
540     setOperationAction(ISD::FCOS   , MVT::f64, Expand);
541     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
542     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
543     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
544     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
545
546     // Expand FP immediates into loads from the stack, except for the special
547     // cases we handle.
548     addLegalFPImmediate(APFloat(+0.0)); // xorpd
549     addLegalFPImmediate(APFloat(+0.0f)); // xorps
550   } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
551     // Use SSE for f32, x87 for f64.
552     // Set up the FP register classes.
553     addRegisterClass(MVT::f32, &X86::FR32RegClass);
554     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
555
556     // Use ANDPS to simulate FABS.
557     setOperationAction(ISD::FABS , MVT::f32, Custom);
558
559     // Use XORP to simulate FNEG.
560     setOperationAction(ISD::FNEG , MVT::f32, Custom);
561
562     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
563
564     // Use ANDPS and ORPS to simulate FCOPYSIGN.
565     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
566     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
567
568     // We don't support sin/cos/fmod
569     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
570     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
571     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
572
573     // Special cases we handle for FP constants.
574     addLegalFPImmediate(APFloat(+0.0f)); // xorps
575     addLegalFPImmediate(APFloat(+0.0)); // FLD0
576     addLegalFPImmediate(APFloat(+1.0)); // FLD1
577     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
578     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
579
580     if (!TM.Options.UnsafeFPMath) {
581       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
582       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
583       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
584     }
585   } else if (!TM.Options.UseSoftFloat) {
586     // f32 and f64 in x87.
587     // Set up the FP register classes.
588     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
589     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
590
591     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
592     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
593     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
594     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
595
596     if (!TM.Options.UnsafeFPMath) {
597       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
598       setOperationAction(ISD::FSIN   , MVT::f32, Expand);
599       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
600       setOperationAction(ISD::FCOS   , MVT::f32, Expand);
601       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
602       setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
603     }
604     addLegalFPImmediate(APFloat(+0.0)); // FLD0
605     addLegalFPImmediate(APFloat(+1.0)); // FLD1
606     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
607     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
608     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
609     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
610     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
611     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
612   }
613
614   // We don't support FMA.
615   setOperationAction(ISD::FMA, MVT::f64, Expand);
616   setOperationAction(ISD::FMA, MVT::f32, Expand);
617
618   // Long double always uses X87.
619   if (!TM.Options.UseSoftFloat) {
620     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
621     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
622     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
623     {
624       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
625       addLegalFPImmediate(TmpFlt);  // FLD0
626       TmpFlt.changeSign();
627       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
628
629       bool ignored;
630       APFloat TmpFlt2(+1.0);
631       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
632                       &ignored);
633       addLegalFPImmediate(TmpFlt2);  // FLD1
634       TmpFlt2.changeSign();
635       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
636     }
637
638     if (!TM.Options.UnsafeFPMath) {
639       setOperationAction(ISD::FSIN   , MVT::f80, Expand);
640       setOperationAction(ISD::FCOS   , MVT::f80, Expand);
641       setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
642     }
643
644     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
645     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
646     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
647     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
648     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
649     setOperationAction(ISD::FMA, MVT::f80, Expand);
650   }
651
652   // Always use a library call for pow.
653   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
654   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
655   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
656
657   setOperationAction(ISD::FLOG, MVT::f80, Expand);
658   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
659   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
660   setOperationAction(ISD::FEXP, MVT::f80, Expand);
661   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
662   setOperationAction(ISD::FMINNUM, MVT::f80, Expand);
663   setOperationAction(ISD::FMAXNUM, MVT::f80, Expand);
664
665   // First set operation action for all vector types to either promote
666   // (for widening) or expand (for scalarization). Then we will selectively
667   // turn on ones that can be effectively codegen'd.
668   for (MVT VT : MVT::vector_valuetypes()) {
669     setOperationAction(ISD::ADD , VT, Expand);
670     setOperationAction(ISD::SUB , VT, Expand);
671     setOperationAction(ISD::FADD, VT, Expand);
672     setOperationAction(ISD::FNEG, VT, Expand);
673     setOperationAction(ISD::FSUB, VT, Expand);
674     setOperationAction(ISD::MUL , VT, Expand);
675     setOperationAction(ISD::FMUL, VT, Expand);
676     setOperationAction(ISD::SDIV, VT, Expand);
677     setOperationAction(ISD::UDIV, VT, Expand);
678     setOperationAction(ISD::FDIV, VT, Expand);
679     setOperationAction(ISD::SREM, VT, Expand);
680     setOperationAction(ISD::UREM, VT, Expand);
681     setOperationAction(ISD::LOAD, VT, Expand);
682     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
683     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
684     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
685     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
686     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
687     setOperationAction(ISD::FABS, VT, Expand);
688     setOperationAction(ISD::FSIN, VT, Expand);
689     setOperationAction(ISD::FSINCOS, VT, Expand);
690     setOperationAction(ISD::FCOS, VT, Expand);
691     setOperationAction(ISD::FSINCOS, VT, Expand);
692     setOperationAction(ISD::FREM, VT, Expand);
693     setOperationAction(ISD::FMA,  VT, Expand);
694     setOperationAction(ISD::FPOWI, VT, Expand);
695     setOperationAction(ISD::FSQRT, VT, Expand);
696     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
697     setOperationAction(ISD::FFLOOR, VT, Expand);
698     setOperationAction(ISD::FCEIL, VT, Expand);
699     setOperationAction(ISD::FTRUNC, VT, Expand);
700     setOperationAction(ISD::FRINT, VT, Expand);
701     setOperationAction(ISD::FNEARBYINT, VT, Expand);
702     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
703     setOperationAction(ISD::MULHS, VT, Expand);
704     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
705     setOperationAction(ISD::MULHU, VT, Expand);
706     setOperationAction(ISD::SDIVREM, VT, Expand);
707     setOperationAction(ISD::UDIVREM, VT, Expand);
708     setOperationAction(ISD::FPOW, VT, Expand);
709     setOperationAction(ISD::CTPOP, VT, Expand);
710     setOperationAction(ISD::CTTZ, VT, Expand);
711     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
712     setOperationAction(ISD::CTLZ, VT, Expand);
713     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
714     setOperationAction(ISD::SHL, VT, Expand);
715     setOperationAction(ISD::SRA, VT, Expand);
716     setOperationAction(ISD::SRL, VT, Expand);
717     setOperationAction(ISD::ROTL, VT, Expand);
718     setOperationAction(ISD::ROTR, VT, Expand);
719     setOperationAction(ISD::BSWAP, VT, Expand);
720     setOperationAction(ISD::SETCC, VT, Expand);
721     setOperationAction(ISD::FLOG, VT, Expand);
722     setOperationAction(ISD::FLOG2, VT, Expand);
723     setOperationAction(ISD::FLOG10, VT, Expand);
724     setOperationAction(ISD::FEXP, VT, Expand);
725     setOperationAction(ISD::FEXP2, VT, Expand);
726     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
727     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
728     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
729     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
730     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
731     setOperationAction(ISD::TRUNCATE, VT, Expand);
732     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
733     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
734     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
735     setOperationAction(ISD::VSELECT, VT, Expand);
736     setOperationAction(ISD::SELECT_CC, VT, Expand);
737     for (MVT InnerVT : MVT::vector_valuetypes()) {
738       setTruncStoreAction(InnerVT, VT, Expand);
739
740       setLoadExtAction(ISD::SEXTLOAD, InnerVT, VT, Expand);
741       setLoadExtAction(ISD::ZEXTLOAD, InnerVT, VT, Expand);
742
743       // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like
744       // types, we have to deal with them whether we ask for Expansion or not.
745       // Setting Expand causes its own optimisation problems though, so leave
746       // them legal.
747       if (VT.getVectorElementType() == MVT::i1)
748         setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
749     }
750   }
751
752   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
753   // with -msoft-float, disable use of MMX as well.
754   if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
755     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
756     // No operations on x86mmx supported, everything uses intrinsics.
757   }
758
759   // MMX-sized vectors (other than x86mmx) are expected to be expanded
760   // into smaller operations.
761   for (MVT MMXTy : {MVT::v8i8, MVT::v4i16, MVT::v2i32, MVT::v1i64}) {
762     setOperationAction(ISD::MULHS,              MMXTy,      Expand);
763     setOperationAction(ISD::AND,                MMXTy,      Expand);
764     setOperationAction(ISD::OR,                 MMXTy,      Expand);
765     setOperationAction(ISD::XOR,                MMXTy,      Expand);
766     setOperationAction(ISD::SCALAR_TO_VECTOR,   MMXTy,      Expand);
767     setOperationAction(ISD::SELECT,             MMXTy,      Expand);
768     setOperationAction(ISD::BITCAST,            MMXTy,      Expand);
769   }
770   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
771
772   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
773     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
774
775     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
776     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
777     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
778     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
779     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
780     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
781     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
782     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
783     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
784     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
785     setOperationAction(ISD::VSELECT,            MVT::v4f32, Custom);
786     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
787     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
788     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Custom);
789   }
790
791   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
792     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
793
794     // FIXME: Unfortunately, -soft-float and -no-implicit-float mean XMM
795     // registers cannot be used even for integer operations.
796     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
797     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
798     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
799     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
800
801     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
802     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
803     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
804     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
805     setOperationAction(ISD::MUL,                MVT::v16i8, Custom);
806     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
807     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
808     setOperationAction(ISD::UMUL_LOHI,          MVT::v4i32, Custom);
809     setOperationAction(ISD::SMUL_LOHI,          MVT::v4i32, Custom);
810     setOperationAction(ISD::MULHU,              MVT::v8i16, Legal);
811     setOperationAction(ISD::MULHS,              MVT::v8i16, Legal);
812     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
813     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
814     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
815     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
816     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
817     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
818     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
819     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
820     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
821     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
822     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
823     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
824
825     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
826     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
827     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
828     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
829
830     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
831     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
832     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
833     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
834     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
835
836     // Only provide customized ctpop vector bit twiddling for vector types we
837     // know to perform better than using the popcnt instructions on each vector
838     // element. If popcnt isn't supported, always provide the custom version.
839     if (!Subtarget->hasPOPCNT()) {
840       setOperationAction(ISD::CTPOP,            MVT::v4i32, Custom);
841       setOperationAction(ISD::CTPOP,            MVT::v2i64, Custom);
842     }
843
844     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
845     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
846       MVT VT = (MVT::SimpleValueType)i;
847       // Do not attempt to custom lower non-power-of-2 vectors
848       if (!isPowerOf2_32(VT.getVectorNumElements()))
849         continue;
850       // Do not attempt to custom lower non-128-bit vectors
851       if (!VT.is128BitVector())
852         continue;
853       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
854       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
855       setOperationAction(ISD::VSELECT,            VT, Custom);
856       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
857     }
858
859     // We support custom legalizing of sext and anyext loads for specific
860     // memory vector types which we can load as a scalar (or sequence of
861     // scalars) and extend in-register to a legal 128-bit vector type. For sext
862     // loads these must work with a single scalar load.
863     for (MVT VT : MVT::integer_vector_valuetypes()) {
864       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i8, Custom);
865       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i16, Custom);
866       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v8i8, Custom);
867       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i8, Custom);
868       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i16, Custom);
869       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i32, Custom);
870       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i8, Custom);
871       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i16, Custom);
872       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8i8, Custom);
873     }
874
875     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
876     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
877     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
878     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
879     setOperationAction(ISD::VSELECT,            MVT::v2f64, Custom);
880     setOperationAction(ISD::VSELECT,            MVT::v2i64, Custom);
881     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
882     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
883
884     if (Subtarget->is64Bit()) {
885       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
886       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
887     }
888
889     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
890     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
891       MVT VT = (MVT::SimpleValueType)i;
892
893       // Do not attempt to promote non-128-bit vectors
894       if (!VT.is128BitVector())
895         continue;
896
897       setOperationAction(ISD::AND,    VT, Promote);
898       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
899       setOperationAction(ISD::OR,     VT, Promote);
900       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
901       setOperationAction(ISD::XOR,    VT, Promote);
902       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
903       setOperationAction(ISD::LOAD,   VT, Promote);
904       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
905       setOperationAction(ISD::SELECT, VT, Promote);
906       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
907     }
908
909     // Custom lower v2i64 and v2f64 selects.
910     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
911     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
912     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
913     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
914
915     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
916     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
917
918     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
919     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
920     // As there is no 64-bit GPR available, we need build a special custom
921     // sequence to convert from v2i32 to v2f32.
922     if (!Subtarget->is64Bit())
923       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
924
925     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
926     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
927
928     for (MVT VT : MVT::fp_vector_valuetypes())
929       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2f32, Legal);
930
931     setOperationAction(ISD::BITCAST,            MVT::v2i32, Custom);
932     setOperationAction(ISD::BITCAST,            MVT::v4i16, Custom);
933     setOperationAction(ISD::BITCAST,            MVT::v8i8,  Custom);
934   }
935
936   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE41()) {
937     for (MVT RoundedTy : {MVT::f32, MVT::f64, MVT::v4f32, MVT::v2f64}) {
938       setOperationAction(ISD::FFLOOR,           RoundedTy,  Legal);
939       setOperationAction(ISD::FCEIL,            RoundedTy,  Legal);
940       setOperationAction(ISD::FTRUNC,           RoundedTy,  Legal);
941       setOperationAction(ISD::FRINT,            RoundedTy,  Legal);
942       setOperationAction(ISD::FNEARBYINT,       RoundedTy,  Legal);
943     }
944
945     // FIXME: Do we need to handle scalar-to-vector here?
946     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
947
948     // We directly match byte blends in the backend as they match the VSELECT
949     // condition form.
950     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
951
952     // SSE41 brings specific instructions for doing vector sign extend even in
953     // cases where we don't have SRA.
954     for (MVT VT : MVT::integer_vector_valuetypes()) {
955       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i8, Custom);
956       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i16, Custom);
957       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i32, Custom);
958     }
959
960     // SSE41 also has vector sign/zero extending loads, PMOV[SZ]X
961     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i16, MVT::v8i8,  Legal);
962     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i8,  Legal);
963     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i8,  Legal);
964     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
965     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
966     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
967
968     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i16, MVT::v8i8,  Legal);
969     setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i8,  Legal);
970     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i8,  Legal);
971     setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
972     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
973     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
974
975     // i8 and i16 vectors are custom because the source register and source
976     // source memory operand types are not the same width.  f32 vectors are
977     // custom since the immediate controlling the insert encodes additional
978     // information.
979     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
980     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
981     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
982     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
983
984     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
985     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
986     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
987     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
988
989     // FIXME: these should be Legal, but that's only for the case where
990     // the index is constant.  For now custom expand to deal with that.
991     if (Subtarget->is64Bit()) {
992       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
993       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
994     }
995   }
996
997   if (Subtarget->hasSSE2()) {
998     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
999     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1000
1001     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1002     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1003
1004     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1005     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1006
1007     // In the customized shift lowering, the legal cases in AVX2 will be
1008     // recognized.
1009     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1010     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1011
1012     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1013     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1014
1015     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1016   }
1017
1018   if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1019     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1020     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1021     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1022     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1023     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1024     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1025
1026     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1027     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1028     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1029
1030     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1031     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1032     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1033     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1034     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1035     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1036     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1037     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1038     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1039     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1040     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1041     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1042
1043     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1044     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1045     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1046     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1047     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1048     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1049     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1050     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1051     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1052     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1053     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1054     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1055
1056     // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1057     // even though v8i16 is a legal type.
1058     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Promote);
1059     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i16, Promote);
1060     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1061
1062     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1063     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1064     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1065
1066     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1067     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1068
1069     for (MVT VT : MVT::fp_vector_valuetypes())
1070       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4f32, Legal);
1071
1072     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1073     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1074
1075     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1076     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1077
1078     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1079     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1080
1081     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1082     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1083     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1084     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1085
1086     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1087     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1088     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1089
1090     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1091     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1092     setOperationAction(ISD::SIGN_EXTEND,       MVT::v16i16, Custom);
1093     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1094     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1095     setOperationAction(ISD::ZERO_EXTEND,       MVT::v16i16, Custom);
1096     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1097     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1098     setOperationAction(ISD::ANY_EXTEND,        MVT::v16i16, Custom);
1099     setOperationAction(ISD::TRUNCATE,          MVT::v16i8, Custom);
1100     setOperationAction(ISD::TRUNCATE,          MVT::v8i16, Custom);
1101     setOperationAction(ISD::TRUNCATE,          MVT::v4i32, Custom);
1102
1103     if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1104       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1105       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1106       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1107       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1108       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1109       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1110     }
1111
1112     if (Subtarget->hasInt256()) {
1113       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1114       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1115       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1116       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1117
1118       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1119       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1120       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1121       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1122
1123       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1124       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1125       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1126       setOperationAction(ISD::MUL,             MVT::v32i8, Custom);
1127
1128       setOperationAction(ISD::UMUL_LOHI,       MVT::v8i32, Custom);
1129       setOperationAction(ISD::SMUL_LOHI,       MVT::v8i32, Custom);
1130       setOperationAction(ISD::MULHU,           MVT::v16i16, Legal);
1131       setOperationAction(ISD::MULHS,           MVT::v16i16, Legal);
1132
1133       // The custom lowering for UINT_TO_FP for v8i32 becomes interesting
1134       // when we have a 256bit-wide blend with immediate.
1135       setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Custom);
1136
1137       // Only provide customized ctpop vector bit twiddling for vector types we
1138       // know to perform better than using the popcnt instructions on each
1139       // vector element. If popcnt isn't supported, always provide the custom
1140       // version.
1141       if (!Subtarget->hasPOPCNT())
1142         setOperationAction(ISD::CTPOP,           MVT::v4i64, Custom);
1143
1144       // Custom CTPOP always performs better on natively supported v8i32
1145       setOperationAction(ISD::CTPOP,             MVT::v8i32, Custom);
1146
1147       // AVX2 also has wider vector sign/zero extending loads, VPMOV[SZ]X
1148       setLoadExtAction(ISD::SEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1149       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32,  MVT::v8i8,  Legal);
1150       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i8,  Legal);
1151       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32,  MVT::v8i16, Legal);
1152       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i16, Legal);
1153       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i32, Legal);
1154
1155       setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1156       setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32,  MVT::v8i8,  Legal);
1157       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i8,  Legal);
1158       setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32,  MVT::v8i16, Legal);
1159       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i16, Legal);
1160       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i32, Legal);
1161     } else {
1162       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1163       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1164       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1165       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1166
1167       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1168       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1169       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1170       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1171
1172       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1173       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1174       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1175       setOperationAction(ISD::MUL,             MVT::v32i8, Custom);
1176     }
1177
1178     // In the customized shift lowering, the legal cases in AVX2 will be
1179     // recognized.
1180     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1181     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1182
1183     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1184     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1185
1186     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1187
1188     // Custom lower several nodes for 256-bit types.
1189     for (MVT VT : MVT::vector_valuetypes()) {
1190       if (VT.getScalarSizeInBits() >= 32) {
1191         setOperationAction(ISD::MLOAD,  VT, Legal);
1192         setOperationAction(ISD::MSTORE, VT, Legal);
1193       }
1194       // Extract subvector is special because the value type
1195       // (result) is 128-bit but the source is 256-bit wide.
1196       if (VT.is128BitVector()) {
1197         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1198       }
1199       // Do not attempt to custom lower other non-256-bit vectors
1200       if (!VT.is256BitVector())
1201         continue;
1202
1203       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1204       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1205       setOperationAction(ISD::VSELECT,            VT, Custom);
1206       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1207       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1208       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1209       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1210       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1211     }
1212
1213     if (Subtarget->hasInt256())
1214       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1215
1216
1217     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1218     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1219       MVT VT = (MVT::SimpleValueType)i;
1220
1221       // Do not attempt to promote non-256-bit vectors
1222       if (!VT.is256BitVector())
1223         continue;
1224
1225       setOperationAction(ISD::AND,    VT, Promote);
1226       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1227       setOperationAction(ISD::OR,     VT, Promote);
1228       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1229       setOperationAction(ISD::XOR,    VT, Promote);
1230       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1231       setOperationAction(ISD::LOAD,   VT, Promote);
1232       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1233       setOperationAction(ISD::SELECT, VT, Promote);
1234       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1235     }
1236   }
1237
1238   if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512()) {
1239     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1240     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1241     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1242     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1243
1244     addRegisterClass(MVT::i1,     &X86::VK1RegClass);
1245     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1246     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1247
1248     for (MVT VT : MVT::fp_vector_valuetypes())
1249       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8f32, Legal);
1250
1251     setOperationAction(ISD::BR_CC,              MVT::i1,    Expand);
1252     setOperationAction(ISD::SETCC,              MVT::i1,    Custom);
1253     setOperationAction(ISD::XOR,                MVT::i1,    Legal);
1254     setOperationAction(ISD::OR,                 MVT::i1,    Legal);
1255     setOperationAction(ISD::AND,                MVT::i1,    Legal);
1256     setOperationAction(ISD::LOAD,               MVT::v16f32, Legal);
1257     setOperationAction(ISD::LOAD,               MVT::v8f64, Legal);
1258     setOperationAction(ISD::LOAD,               MVT::v8i64, Legal);
1259     setOperationAction(ISD::LOAD,               MVT::v16i32, Legal);
1260     setOperationAction(ISD::LOAD,               MVT::v16i1, Legal);
1261
1262     setOperationAction(ISD::FADD,               MVT::v16f32, Legal);
1263     setOperationAction(ISD::FSUB,               MVT::v16f32, Legal);
1264     setOperationAction(ISD::FMUL,               MVT::v16f32, Legal);
1265     setOperationAction(ISD::FDIV,               MVT::v16f32, Legal);
1266     setOperationAction(ISD::FSQRT,              MVT::v16f32, Legal);
1267     setOperationAction(ISD::FNEG,               MVT::v16f32, Custom);
1268
1269     setOperationAction(ISD::FADD,               MVT::v8f64, Legal);
1270     setOperationAction(ISD::FSUB,               MVT::v8f64, Legal);
1271     setOperationAction(ISD::FMUL,               MVT::v8f64, Legal);
1272     setOperationAction(ISD::FDIV,               MVT::v8f64, Legal);
1273     setOperationAction(ISD::FSQRT,              MVT::v8f64, Legal);
1274     setOperationAction(ISD::FNEG,               MVT::v8f64, Custom);
1275     setOperationAction(ISD::FMA,                MVT::v8f64, Legal);
1276     setOperationAction(ISD::FMA,                MVT::v16f32, Legal);
1277
1278     setOperationAction(ISD::FP_TO_SINT,         MVT::i32, Legal);
1279     setOperationAction(ISD::FP_TO_UINT,         MVT::i32, Legal);
1280     setOperationAction(ISD::SINT_TO_FP,         MVT::i32, Legal);
1281     setOperationAction(ISD::UINT_TO_FP,         MVT::i32, Legal);
1282     if (Subtarget->is64Bit()) {
1283       setOperationAction(ISD::FP_TO_UINT,       MVT::i64, Legal);
1284       setOperationAction(ISD::FP_TO_SINT,       MVT::i64, Legal);
1285       setOperationAction(ISD::SINT_TO_FP,       MVT::i64, Legal);
1286       setOperationAction(ISD::UINT_TO_FP,       MVT::i64, Legal);
1287     }
1288     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1289     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1290     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1291     setOperationAction(ISD::FP_TO_UINT,         MVT::v4i32, Legal);
1292     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1293     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i1,   Custom);
1294     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i1,  Custom);
1295     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i8,  Promote);
1296     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i16, Promote);
1297     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1298     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1299     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Legal);
1300     setOperationAction(ISD::FP_ROUND,           MVT::v8f32, Legal);
1301     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Legal);
1302
1303     setOperationAction(ISD::TRUNCATE,           MVT::i1, Custom);
1304     setOperationAction(ISD::TRUNCATE,           MVT::v16i8, Custom);
1305     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1306     if (Subtarget->hasDQI()) {
1307       setOperationAction(ISD::TRUNCATE,           MVT::v2i1, Custom);
1308       setOperationAction(ISD::TRUNCATE,           MVT::v4i1, Custom);
1309     }
1310     setOperationAction(ISD::TRUNCATE,           MVT::v8i1, Custom);
1311     setOperationAction(ISD::TRUNCATE,           MVT::v16i1, Custom);
1312     setOperationAction(ISD::TRUNCATE,           MVT::v16i16, Custom);
1313     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1314     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1315     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1316     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1317     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i8, Custom);
1318     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i16, Custom);
1319     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i16, Custom);
1320     if (Subtarget->hasDQI()) {
1321       setOperationAction(ISD::SIGN_EXTEND,        MVT::v4i32, Custom);
1322       setOperationAction(ISD::SIGN_EXTEND,        MVT::v2i64, Custom);
1323     }
1324     setOperationAction(ISD::FFLOOR,             MVT::v16f32, Legal);
1325     setOperationAction(ISD::FFLOOR,             MVT::v8f64, Legal);
1326     setOperationAction(ISD::FCEIL,              MVT::v16f32, Legal);
1327     setOperationAction(ISD::FCEIL,              MVT::v8f64, Legal);
1328     setOperationAction(ISD::FTRUNC,             MVT::v16f32, Legal);
1329     setOperationAction(ISD::FTRUNC,             MVT::v8f64, Legal);
1330     setOperationAction(ISD::FRINT,              MVT::v16f32, Legal);
1331     setOperationAction(ISD::FRINT,              MVT::v8f64, Legal);
1332     setOperationAction(ISD::FNEARBYINT,         MVT::v16f32, Legal);
1333     setOperationAction(ISD::FNEARBYINT,         MVT::v8f64, Legal);
1334
1335     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1336     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1337     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1338     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1339     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i1, Legal);
1340
1341     setOperationAction(ISD::SETCC,              MVT::v16i1, Custom);
1342     setOperationAction(ISD::SETCC,              MVT::v8i1, Custom);
1343
1344     setOperationAction(ISD::MUL,              MVT::v8i64, Custom);
1345
1346     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1,  Custom);
1347     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1348     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i1, Custom);
1349     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i1, Custom);
1350     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i1, Custom);
1351     setOperationAction(ISD::BUILD_VECTOR,       MVT::v16i1, Custom);
1352     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1353     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1354     setOperationAction(ISD::SELECT,             MVT::v16f32, Custom);
1355
1356     setOperationAction(ISD::ADD,                MVT::v8i64, Legal);
1357     setOperationAction(ISD::ADD,                MVT::v16i32, Legal);
1358
1359     setOperationAction(ISD::SUB,                MVT::v8i64, Legal);
1360     setOperationAction(ISD::SUB,                MVT::v16i32, Legal);
1361
1362     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1363
1364     setOperationAction(ISD::SRL,                MVT::v8i64, Custom);
1365     setOperationAction(ISD::SRL,                MVT::v16i32, Custom);
1366
1367     setOperationAction(ISD::SHL,                MVT::v8i64, Custom);
1368     setOperationAction(ISD::SHL,                MVT::v16i32, Custom);
1369
1370     setOperationAction(ISD::SRA,                MVT::v8i64, Custom);
1371     setOperationAction(ISD::SRA,                MVT::v16i32, Custom);
1372
1373     setOperationAction(ISD::AND,                MVT::v8i64, Legal);
1374     setOperationAction(ISD::OR,                 MVT::v8i64, Legal);
1375     setOperationAction(ISD::XOR,                MVT::v8i64, Legal);
1376     setOperationAction(ISD::AND,                MVT::v16i32, Legal);
1377     setOperationAction(ISD::OR,                 MVT::v16i32, Legal);
1378     setOperationAction(ISD::XOR,                MVT::v16i32, Legal);
1379
1380     if (Subtarget->hasCDI()) {
1381       setOperationAction(ISD::CTLZ,             MVT::v8i64, Legal);
1382       setOperationAction(ISD::CTLZ,             MVT::v16i32, Legal);
1383     }
1384     if (Subtarget->hasDQI()) {
1385       setOperationAction(ISD::MUL,             MVT::v2i64, Legal);
1386       setOperationAction(ISD::MUL,             MVT::v4i64, Legal);
1387       setOperationAction(ISD::MUL,             MVT::v8i64, Legal);
1388     }
1389     // Custom lower several nodes.
1390     for (MVT VT : MVT::vector_valuetypes()) {
1391       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1392       // Extract subvector is special because the value type
1393       // (result) is 256/128-bit but the source is 512-bit wide.
1394       if (VT.is128BitVector() || VT.is256BitVector()) {
1395         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1396       }
1397       if (VT.getVectorElementType() == MVT::i1)
1398         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1399
1400       // Do not attempt to custom lower other non-512-bit vectors
1401       if (!VT.is512BitVector())
1402         continue;
1403
1404       if ( EltSize >= 32) {
1405         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1406         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1407         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1408         setOperationAction(ISD::VSELECT,             VT, Legal);
1409         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1410         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1411         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1412         setOperationAction(ISD::MLOAD,               VT, Legal);
1413         setOperationAction(ISD::MSTORE,              VT, Legal);
1414       }
1415     }
1416     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1417       MVT VT = (MVT::SimpleValueType)i;
1418
1419       // Do not attempt to promote non-512-bit vectors.
1420       if (!VT.is512BitVector())
1421         continue;
1422
1423       setOperationAction(ISD::SELECT, VT, Promote);
1424       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1425     }
1426   }// has  AVX-512
1427
1428   if (!TM.Options.UseSoftFloat && Subtarget->hasBWI()) {
1429     addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1430     addRegisterClass(MVT::v64i8,  &X86::VR512RegClass);
1431
1432     addRegisterClass(MVT::v32i1,  &X86::VK32RegClass);
1433     addRegisterClass(MVT::v64i1,  &X86::VK64RegClass);
1434
1435     setOperationAction(ISD::LOAD,               MVT::v32i16, Legal);
1436     setOperationAction(ISD::LOAD,               MVT::v64i8, Legal);
1437     setOperationAction(ISD::SETCC,              MVT::v32i1, Custom);
1438     setOperationAction(ISD::SETCC,              MVT::v64i1, Custom);
1439     setOperationAction(ISD::ADD,                MVT::v32i16, Legal);
1440     setOperationAction(ISD::ADD,                MVT::v64i8, Legal);
1441     setOperationAction(ISD::SUB,                MVT::v32i16, Legal);
1442     setOperationAction(ISD::SUB,                MVT::v64i8, Legal);
1443     setOperationAction(ISD::MUL,                MVT::v32i16, Legal);
1444     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v32i1, Custom);
1445     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v64i1, Custom);
1446     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v32i1, Custom);
1447     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v64i1, Custom);
1448
1449     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1450       const MVT VT = (MVT::SimpleValueType)i;
1451
1452       const unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1453
1454       // Do not attempt to promote non-512-bit vectors.
1455       if (!VT.is512BitVector())
1456         continue;
1457
1458       if (EltSize < 32) {
1459         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1460         setOperationAction(ISD::VSELECT,             VT, Legal);
1461       }
1462     }
1463   }
1464
1465   if (!TM.Options.UseSoftFloat && Subtarget->hasVLX()) {
1466     addRegisterClass(MVT::v4i1,   &X86::VK4RegClass);
1467     addRegisterClass(MVT::v2i1,   &X86::VK2RegClass);
1468
1469     setOperationAction(ISD::SETCC,              MVT::v4i1, Custom);
1470     setOperationAction(ISD::SETCC,              MVT::v2i1, Custom);
1471     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i1, Custom);
1472     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1, Custom);
1473     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v8i1, Custom);
1474     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v4i1, Custom);
1475
1476     setOperationAction(ISD::AND,                MVT::v8i32, Legal);
1477     setOperationAction(ISD::OR,                 MVT::v8i32, Legal);
1478     setOperationAction(ISD::XOR,                MVT::v8i32, Legal);
1479     setOperationAction(ISD::AND,                MVT::v4i32, Legal);
1480     setOperationAction(ISD::OR,                 MVT::v4i32, Legal);
1481     setOperationAction(ISD::XOR,                MVT::v4i32, Legal);
1482   }
1483
1484   // We want to custom lower some of our intrinsics.
1485   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1486   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1487   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1488   if (!Subtarget->is64Bit())
1489     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1490
1491   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1492   // handle type legalization for these operations here.
1493   //
1494   // FIXME: We really should do custom legalization for addition and
1495   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1496   // than generic legalization for 64-bit multiplication-with-overflow, though.
1497   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1498     // Add/Sub/Mul with overflow operations are custom lowered.
1499     MVT VT = IntVTs[i];
1500     setOperationAction(ISD::SADDO, VT, Custom);
1501     setOperationAction(ISD::UADDO, VT, Custom);
1502     setOperationAction(ISD::SSUBO, VT, Custom);
1503     setOperationAction(ISD::USUBO, VT, Custom);
1504     setOperationAction(ISD::SMULO, VT, Custom);
1505     setOperationAction(ISD::UMULO, VT, Custom);
1506   }
1507
1508
1509   if (!Subtarget->is64Bit()) {
1510     // These libcalls are not available in 32-bit.
1511     setLibcallName(RTLIB::SHL_I128, nullptr);
1512     setLibcallName(RTLIB::SRL_I128, nullptr);
1513     setLibcallName(RTLIB::SRA_I128, nullptr);
1514   }
1515
1516   // Combine sin / cos into one node or libcall if possible.
1517   if (Subtarget->hasSinCos()) {
1518     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1519     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1520     if (Subtarget->isTargetDarwin()) {
1521       // For MacOSX, we don't want the normal expansion of a libcall to sincos.
1522       // We want to issue a libcall to __sincos_stret to avoid memory traffic.
1523       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1524       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1525     }
1526   }
1527
1528   if (Subtarget->isTargetWin64()) {
1529     setOperationAction(ISD::SDIV, MVT::i128, Custom);
1530     setOperationAction(ISD::UDIV, MVT::i128, Custom);
1531     setOperationAction(ISD::SREM, MVT::i128, Custom);
1532     setOperationAction(ISD::UREM, MVT::i128, Custom);
1533     setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1534     setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1535   }
1536
1537   // We have target-specific dag combine patterns for the following nodes:
1538   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1539   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1540   setTargetDAGCombine(ISD::BITCAST);
1541   setTargetDAGCombine(ISD::VSELECT);
1542   setTargetDAGCombine(ISD::SELECT);
1543   setTargetDAGCombine(ISD::SHL);
1544   setTargetDAGCombine(ISD::SRA);
1545   setTargetDAGCombine(ISD::SRL);
1546   setTargetDAGCombine(ISD::OR);
1547   setTargetDAGCombine(ISD::AND);
1548   setTargetDAGCombine(ISD::ADD);
1549   setTargetDAGCombine(ISD::FADD);
1550   setTargetDAGCombine(ISD::FSUB);
1551   setTargetDAGCombine(ISD::FMA);
1552   setTargetDAGCombine(ISD::SUB);
1553   setTargetDAGCombine(ISD::LOAD);
1554   setTargetDAGCombine(ISD::MLOAD);
1555   setTargetDAGCombine(ISD::STORE);
1556   setTargetDAGCombine(ISD::MSTORE);
1557   setTargetDAGCombine(ISD::ZERO_EXTEND);
1558   setTargetDAGCombine(ISD::ANY_EXTEND);
1559   setTargetDAGCombine(ISD::SIGN_EXTEND);
1560   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1561   setTargetDAGCombine(ISD::TRUNCATE);
1562   setTargetDAGCombine(ISD::SINT_TO_FP);
1563   setTargetDAGCombine(ISD::SETCC);
1564   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1565   setTargetDAGCombine(ISD::BUILD_VECTOR);
1566   setTargetDAGCombine(ISD::MUL);
1567   setTargetDAGCombine(ISD::XOR);
1568
1569   computeRegisterProperties(Subtarget->getRegisterInfo());
1570
1571   // On Darwin, -Os means optimize for size without hurting performance,
1572   // do not reduce the limit.
1573   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1574   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1575   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1576   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1577   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1578   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1579   setPrefLoopAlignment(4); // 2^4 bytes.
1580
1581   // Predictable cmov don't hurt on atom because it's in-order.
1582   PredictableSelectIsExpensive = !Subtarget->isAtom();
1583   EnableExtLdPromotion = true;
1584   setPrefFunctionAlignment(4); // 2^4 bytes.
1585
1586   verifyIntrinsicTables();
1587 }
1588
1589 // This has so far only been implemented for 64-bit MachO.
1590 bool X86TargetLowering::useLoadStackGuardNode() const {
1591   return Subtarget->isTargetMachO() && Subtarget->is64Bit();
1592 }
1593
1594 TargetLoweringBase::LegalizeTypeAction
1595 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1596   if (ExperimentalVectorWideningLegalization &&
1597       VT.getVectorNumElements() != 1 &&
1598       VT.getVectorElementType().getSimpleVT() != MVT::i1)
1599     return TypeWidenVector;
1600
1601   return TargetLoweringBase::getPreferredVectorAction(VT);
1602 }
1603
1604 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1605   if (!VT.isVector())
1606     return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1607
1608   const unsigned NumElts = VT.getVectorNumElements();
1609   const EVT EltVT = VT.getVectorElementType();
1610   if (VT.is512BitVector()) {
1611     if (Subtarget->hasAVX512())
1612       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1613           EltVT == MVT::f32 || EltVT == MVT::f64)
1614         switch(NumElts) {
1615         case  8: return MVT::v8i1;
1616         case 16: return MVT::v16i1;
1617       }
1618     if (Subtarget->hasBWI())
1619       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1620         switch(NumElts) {
1621         case 32: return MVT::v32i1;
1622         case 64: return MVT::v64i1;
1623       }
1624   }
1625
1626   if (VT.is256BitVector() || VT.is128BitVector()) {
1627     if (Subtarget->hasVLX())
1628       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1629           EltVT == MVT::f32 || EltVT == MVT::f64)
1630         switch(NumElts) {
1631         case 2: return MVT::v2i1;
1632         case 4: return MVT::v4i1;
1633         case 8: return MVT::v8i1;
1634       }
1635     if (Subtarget->hasBWI() && Subtarget->hasVLX())
1636       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1637         switch(NumElts) {
1638         case  8: return MVT::v8i1;
1639         case 16: return MVT::v16i1;
1640         case 32: return MVT::v32i1;
1641       }
1642   }
1643
1644   return VT.changeVectorElementTypeToInteger();
1645 }
1646
1647 /// Helper for getByValTypeAlignment to determine
1648 /// the desired ByVal argument alignment.
1649 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1650   if (MaxAlign == 16)
1651     return;
1652   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1653     if (VTy->getBitWidth() == 128)
1654       MaxAlign = 16;
1655   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1656     unsigned EltAlign = 0;
1657     getMaxByValAlign(ATy->getElementType(), EltAlign);
1658     if (EltAlign > MaxAlign)
1659       MaxAlign = EltAlign;
1660   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1661     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1662       unsigned EltAlign = 0;
1663       getMaxByValAlign(STy->getElementType(i), EltAlign);
1664       if (EltAlign > MaxAlign)
1665         MaxAlign = EltAlign;
1666       if (MaxAlign == 16)
1667         break;
1668     }
1669   }
1670 }
1671
1672 /// Return the desired alignment for ByVal aggregate
1673 /// function arguments in the caller parameter area. For X86, aggregates
1674 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1675 /// are at 4-byte boundaries.
1676 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1677   if (Subtarget->is64Bit()) {
1678     // Max of 8 and alignment of type.
1679     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1680     if (TyAlign > 8)
1681       return TyAlign;
1682     return 8;
1683   }
1684
1685   unsigned Align = 4;
1686   if (Subtarget->hasSSE1())
1687     getMaxByValAlign(Ty, Align);
1688   return Align;
1689 }
1690
1691 /// Returns the target specific optimal type for load
1692 /// and store operations as a result of memset, memcpy, and memmove
1693 /// lowering. If DstAlign is zero that means it's safe to destination
1694 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1695 /// means there isn't a need to check it against alignment requirement,
1696 /// probably because the source does not need to be loaded. If 'IsMemset' is
1697 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1698 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1699 /// source is constant so it does not need to be loaded.
1700 /// It returns EVT::Other if the type should be determined using generic
1701 /// target-independent logic.
1702 EVT
1703 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1704                                        unsigned DstAlign, unsigned SrcAlign,
1705                                        bool IsMemset, bool ZeroMemset,
1706                                        bool MemcpyStrSrc,
1707                                        MachineFunction &MF) const {
1708   const Function *F = MF.getFunction();
1709   if ((!IsMemset || ZeroMemset) &&
1710       !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1711     if (Size >= 16 &&
1712         (Subtarget->isUnalignedMemAccessFast() ||
1713          ((DstAlign == 0 || DstAlign >= 16) &&
1714           (SrcAlign == 0 || SrcAlign >= 16)))) {
1715       if (Size >= 32) {
1716         if (Subtarget->hasInt256())
1717           return MVT::v8i32;
1718         if (Subtarget->hasFp256())
1719           return MVT::v8f32;
1720       }
1721       if (Subtarget->hasSSE2())
1722         return MVT::v4i32;
1723       if (Subtarget->hasSSE1())
1724         return MVT::v4f32;
1725     } else if (!MemcpyStrSrc && Size >= 8 &&
1726                !Subtarget->is64Bit() &&
1727                Subtarget->hasSSE2()) {
1728       // Do not use f64 to lower memcpy if source is string constant. It's
1729       // better to use i32 to avoid the loads.
1730       return MVT::f64;
1731     }
1732   }
1733   if (Subtarget->is64Bit() && Size >= 8)
1734     return MVT::i64;
1735   return MVT::i32;
1736 }
1737
1738 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1739   if (VT == MVT::f32)
1740     return X86ScalarSSEf32;
1741   else if (VT == MVT::f64)
1742     return X86ScalarSSEf64;
1743   return true;
1744 }
1745
1746 bool
1747 X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1748                                                   unsigned,
1749                                                   unsigned,
1750                                                   bool *Fast) const {
1751   if (Fast)
1752     *Fast = Subtarget->isUnalignedMemAccessFast();
1753   return true;
1754 }
1755
1756 /// Return the entry encoding for a jump table in the
1757 /// current function.  The returned value is a member of the
1758 /// MachineJumpTableInfo::JTEntryKind enum.
1759 unsigned X86TargetLowering::getJumpTableEncoding() const {
1760   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1761   // symbol.
1762   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1763       Subtarget->isPICStyleGOT())
1764     return MachineJumpTableInfo::EK_Custom32;
1765
1766   // Otherwise, use the normal jump table encoding heuristics.
1767   return TargetLowering::getJumpTableEncoding();
1768 }
1769
1770 const MCExpr *
1771 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1772                                              const MachineBasicBlock *MBB,
1773                                              unsigned uid,MCContext &Ctx) const{
1774   assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
1775          Subtarget->isPICStyleGOT());
1776   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1777   // entries.
1778   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1779                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1780 }
1781
1782 /// Returns relocation base for the given PIC jumptable.
1783 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1784                                                     SelectionDAG &DAG) const {
1785   if (!Subtarget->is64Bit())
1786     // This doesn't have SDLoc associated with it, but is not really the
1787     // same as a Register.
1788     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1789   return Table;
1790 }
1791
1792 /// This returns the relocation base for the given PIC jumptable,
1793 /// the same as getPICJumpTableRelocBase, but as an MCExpr.
1794 const MCExpr *X86TargetLowering::
1795 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1796                              MCContext &Ctx) const {
1797   // X86-64 uses RIP relative addressing based on the jump table label.
1798   if (Subtarget->isPICStyleRIPRel())
1799     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1800
1801   // Otherwise, the reference is relative to the PIC base.
1802   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1803 }
1804
1805 std::pair<const TargetRegisterClass *, uint8_t>
1806 X86TargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1807                                            MVT VT) const {
1808   const TargetRegisterClass *RRC = nullptr;
1809   uint8_t Cost = 1;
1810   switch (VT.SimpleTy) {
1811   default:
1812     return TargetLowering::findRepresentativeClass(TRI, VT);
1813   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1814     RRC = Subtarget->is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
1815     break;
1816   case MVT::x86mmx:
1817     RRC = &X86::VR64RegClass;
1818     break;
1819   case MVT::f32: case MVT::f64:
1820   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1821   case MVT::v4f32: case MVT::v2f64:
1822   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1823   case MVT::v4f64:
1824     RRC = &X86::VR128RegClass;
1825     break;
1826   }
1827   return std::make_pair(RRC, Cost);
1828 }
1829
1830 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1831                                                unsigned &Offset) const {
1832   if (!Subtarget->isTargetLinux())
1833     return false;
1834
1835   if (Subtarget->is64Bit()) {
1836     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1837     Offset = 0x28;
1838     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1839       AddressSpace = 256;
1840     else
1841       AddressSpace = 257;
1842   } else {
1843     // %gs:0x14 on i386
1844     Offset = 0x14;
1845     AddressSpace = 256;
1846   }
1847   return true;
1848 }
1849
1850 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1851                                             unsigned DestAS) const {
1852   assert(SrcAS != DestAS && "Expected different address spaces!");
1853
1854   return SrcAS < 256 && DestAS < 256;
1855 }
1856
1857 //===----------------------------------------------------------------------===//
1858 //               Return Value Calling Convention Implementation
1859 //===----------------------------------------------------------------------===//
1860
1861 #include "X86GenCallingConv.inc"
1862
1863 bool
1864 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1865                                   MachineFunction &MF, bool isVarArg,
1866                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1867                         LLVMContext &Context) const {
1868   SmallVector<CCValAssign, 16> RVLocs;
1869   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
1870   return CCInfo.CheckReturn(Outs, RetCC_X86);
1871 }
1872
1873 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1874   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1875   return ScratchRegs;
1876 }
1877
1878 SDValue
1879 X86TargetLowering::LowerReturn(SDValue Chain,
1880                                CallingConv::ID CallConv, bool isVarArg,
1881                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1882                                const SmallVectorImpl<SDValue> &OutVals,
1883                                SDLoc dl, SelectionDAG &DAG) const {
1884   MachineFunction &MF = DAG.getMachineFunction();
1885   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1886
1887   SmallVector<CCValAssign, 16> RVLocs;
1888   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
1889   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1890
1891   SDValue Flag;
1892   SmallVector<SDValue, 6> RetOps;
1893   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1894   // Operand #1 = Bytes To Pop
1895   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1896                    MVT::i16));
1897
1898   // Copy the result values into the output registers.
1899   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1900     CCValAssign &VA = RVLocs[i];
1901     assert(VA.isRegLoc() && "Can only return in registers!");
1902     SDValue ValToCopy = OutVals[i];
1903     EVT ValVT = ValToCopy.getValueType();
1904
1905     // Promote values to the appropriate types.
1906     if (VA.getLocInfo() == CCValAssign::SExt)
1907       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1908     else if (VA.getLocInfo() == CCValAssign::ZExt)
1909       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1910     else if (VA.getLocInfo() == CCValAssign::AExt)
1911       ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1912     else if (VA.getLocInfo() == CCValAssign::BCvt)
1913       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1914
1915     assert(VA.getLocInfo() != CCValAssign::FPExt &&
1916            "Unexpected FP-extend for return value.");
1917
1918     // If this is x86-64, and we disabled SSE, we can't return FP values,
1919     // or SSE or MMX vectors.
1920     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1921          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1922           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1923       report_fatal_error("SSE register return with SSE disabled");
1924     }
1925     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1926     // llvm-gcc has never done it right and no one has noticed, so this
1927     // should be OK for now.
1928     if (ValVT == MVT::f64 &&
1929         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1930       report_fatal_error("SSE2 register return with SSE2 disabled");
1931
1932     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1933     // the RET instruction and handled by the FP Stackifier.
1934     if (VA.getLocReg() == X86::FP0 ||
1935         VA.getLocReg() == X86::FP1) {
1936       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1937       // change the value to the FP stack register class.
1938       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1939         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1940       RetOps.push_back(ValToCopy);
1941       // Don't emit a copytoreg.
1942       continue;
1943     }
1944
1945     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1946     // which is returned in RAX / RDX.
1947     if (Subtarget->is64Bit()) {
1948       if (ValVT == MVT::x86mmx) {
1949         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1950           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1951           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1952                                   ValToCopy);
1953           // If we don't have SSE2 available, convert to v4f32 so the generated
1954           // register is legal.
1955           if (!Subtarget->hasSSE2())
1956             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1957         }
1958       }
1959     }
1960
1961     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1962     Flag = Chain.getValue(1);
1963     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1964   }
1965
1966   // The x86-64 ABIs require that for returning structs by value we copy
1967   // the sret argument into %rax/%eax (depending on ABI) for the return.
1968   // Win32 requires us to put the sret argument to %eax as well.
1969   // We saved the argument into a virtual register in the entry block,
1970   // so now we copy the value out and into %rax/%eax.
1971   //
1972   // Checking Function.hasStructRetAttr() here is insufficient because the IR
1973   // may not have an explicit sret argument. If FuncInfo.CanLowerReturn is
1974   // false, then an sret argument may be implicitly inserted in the SelDAG. In
1975   // either case FuncInfo->setSRetReturnReg() will have been called.
1976   if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
1977     assert((Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC()) &&
1978            "No need for an sret register");
1979     SDValue Val = DAG.getCopyFromReg(Chain, dl, SRetReg, getPointerTy());
1980
1981     unsigned RetValReg
1982         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
1983           X86::RAX : X86::EAX;
1984     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
1985     Flag = Chain.getValue(1);
1986
1987     // RAX/EAX now acts like a return value.
1988     RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
1989   }
1990
1991   RetOps[0] = Chain;  // Update chain.
1992
1993   // Add the flag if we have it.
1994   if (Flag.getNode())
1995     RetOps.push_back(Flag);
1996
1997   return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
1998 }
1999
2000 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2001   if (N->getNumValues() != 1)
2002     return false;
2003   if (!N->hasNUsesOfValue(1, 0))
2004     return false;
2005
2006   SDValue TCChain = Chain;
2007   SDNode *Copy = *N->use_begin();
2008   if (Copy->getOpcode() == ISD::CopyToReg) {
2009     // If the copy has a glue operand, we conservatively assume it isn't safe to
2010     // perform a tail call.
2011     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2012       return false;
2013     TCChain = Copy->getOperand(0);
2014   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2015     return false;
2016
2017   bool HasRet = false;
2018   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2019        UI != UE; ++UI) {
2020     if (UI->getOpcode() != X86ISD::RET_FLAG)
2021       return false;
2022     // If we are returning more than one value, we can definitely
2023     // not make a tail call see PR19530
2024     if (UI->getNumOperands() > 4)
2025       return false;
2026     if (UI->getNumOperands() == 4 &&
2027         UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2028       return false;
2029     HasRet = true;
2030   }
2031
2032   if (!HasRet)
2033     return false;
2034
2035   Chain = TCChain;
2036   return true;
2037 }
2038
2039 EVT
2040 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
2041                                             ISD::NodeType ExtendKind) const {
2042   MVT ReturnMVT;
2043   // TODO: Is this also valid on 32-bit?
2044   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2045     ReturnMVT = MVT::i8;
2046   else
2047     ReturnMVT = MVT::i32;
2048
2049   EVT MinVT = getRegisterType(Context, ReturnMVT);
2050   return VT.bitsLT(MinVT) ? MinVT : VT;
2051 }
2052
2053 /// Lower the result values of a call into the
2054 /// appropriate copies out of appropriate physical registers.
2055 ///
2056 SDValue
2057 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2058                                    CallingConv::ID CallConv, bool isVarArg,
2059                                    const SmallVectorImpl<ISD::InputArg> &Ins,
2060                                    SDLoc dl, SelectionDAG &DAG,
2061                                    SmallVectorImpl<SDValue> &InVals) const {
2062
2063   // Assign locations to each value returned by this call.
2064   SmallVector<CCValAssign, 16> RVLocs;
2065   bool Is64Bit = Subtarget->is64Bit();
2066   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2067                  *DAG.getContext());
2068   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2069
2070   // Copy all of the result registers out of their specified physreg.
2071   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2072     CCValAssign &VA = RVLocs[i];
2073     EVT CopyVT = VA.getValVT();
2074
2075     // If this is x86-64, and we disabled SSE, we can't return FP values
2076     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2077         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2078       report_fatal_error("SSE register return with SSE disabled");
2079     }
2080
2081     // If we prefer to use the value in xmm registers, copy it out as f80 and
2082     // use a truncate to move it from fp stack reg to xmm reg.
2083     if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2084         isScalarFPTypeInSSEReg(VA.getValVT()))
2085       CopyVT = MVT::f80;
2086
2087     Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2088                                CopyVT, InFlag).getValue(1);
2089     SDValue Val = Chain.getValue(0);
2090
2091     if (CopyVT != VA.getValVT())
2092       Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2093                         // This truncation won't change the value.
2094                         DAG.getIntPtrConstant(1));
2095
2096     InFlag = Chain.getValue(2);
2097     InVals.push_back(Val);
2098   }
2099
2100   return Chain;
2101 }
2102
2103 //===----------------------------------------------------------------------===//
2104 //                C & StdCall & Fast Calling Convention implementation
2105 //===----------------------------------------------------------------------===//
2106 //  StdCall calling convention seems to be standard for many Windows' API
2107 //  routines and around. It differs from C calling convention just a little:
2108 //  callee should clean up the stack, not caller. Symbols should be also
2109 //  decorated in some fancy way :) It doesn't support any vector arguments.
2110 //  For info on fast calling convention see Fast Calling Convention (tail call)
2111 //  implementation LowerX86_32FastCCCallTo.
2112
2113 /// CallIsStructReturn - Determines whether a call uses struct return
2114 /// semantics.
2115 enum StructReturnType {
2116   NotStructReturn,
2117   RegStructReturn,
2118   StackStructReturn
2119 };
2120 static StructReturnType
2121 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2122   if (Outs.empty())
2123     return NotStructReturn;
2124
2125   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2126   if (!Flags.isSRet())
2127     return NotStructReturn;
2128   if (Flags.isInReg())
2129     return RegStructReturn;
2130   return StackStructReturn;
2131 }
2132
2133 /// Determines whether a function uses struct return semantics.
2134 static StructReturnType
2135 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2136   if (Ins.empty())
2137     return NotStructReturn;
2138
2139   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2140   if (!Flags.isSRet())
2141     return NotStructReturn;
2142   if (Flags.isInReg())
2143     return RegStructReturn;
2144   return StackStructReturn;
2145 }
2146
2147 /// Make a copy of an aggregate at address specified by "Src" to address
2148 /// "Dst" with size and alignment information specified by the specific
2149 /// parameter attribute. The copy will be passed as a byval function parameter.
2150 static SDValue
2151 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2152                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2153                           SDLoc dl) {
2154   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2155
2156   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2157                        /*isVolatile*/false, /*AlwaysInline=*/true,
2158                        /*isTailCall*/false,
2159                        MachinePointerInfo(), MachinePointerInfo());
2160 }
2161
2162 /// Return true if the calling convention is one that
2163 /// supports tail call optimization.
2164 static bool IsTailCallConvention(CallingConv::ID CC) {
2165   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2166           CC == CallingConv::HiPE);
2167 }
2168
2169 /// \brief Return true if the calling convention is a C calling convention.
2170 static bool IsCCallConvention(CallingConv::ID CC) {
2171   return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2172           CC == CallingConv::X86_64_SysV);
2173 }
2174
2175 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2176   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2177     return false;
2178
2179   CallSite CS(CI);
2180   CallingConv::ID CalleeCC = CS.getCallingConv();
2181   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2182     return false;
2183
2184   return true;
2185 }
2186
2187 /// Return true if the function is being made into
2188 /// a tailcall target by changing its ABI.
2189 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2190                                    bool GuaranteedTailCallOpt) {
2191   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2192 }
2193
2194 SDValue
2195 X86TargetLowering::LowerMemArgument(SDValue Chain,
2196                                     CallingConv::ID CallConv,
2197                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2198                                     SDLoc dl, SelectionDAG &DAG,
2199                                     const CCValAssign &VA,
2200                                     MachineFrameInfo *MFI,
2201                                     unsigned i) const {
2202   // Create the nodes corresponding to a load from this parameter slot.
2203   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2204   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2205       CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2206   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2207   EVT ValVT;
2208
2209   // If value is passed by pointer we have address passed instead of the value
2210   // itself.
2211   if (VA.getLocInfo() == CCValAssign::Indirect)
2212     ValVT = VA.getLocVT();
2213   else
2214     ValVT = VA.getValVT();
2215
2216   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2217   // changed with more analysis.
2218   // In case of tail call optimization mark all arguments mutable. Since they
2219   // could be overwritten by lowering of arguments in case of a tail call.
2220   if (Flags.isByVal()) {
2221     unsigned Bytes = Flags.getByValSize();
2222     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2223     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2224     return DAG.getFrameIndex(FI, getPointerTy());
2225   } else {
2226     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2227                                     VA.getLocMemOffset(), isImmutable);
2228     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2229     return DAG.getLoad(ValVT, dl, Chain, FIN,
2230                        MachinePointerInfo::getFixedStack(FI),
2231                        false, false, false, 0);
2232   }
2233 }
2234
2235 // FIXME: Get this from tablegen.
2236 static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
2237                                                 const X86Subtarget *Subtarget) {
2238   assert(Subtarget->is64Bit());
2239
2240   if (Subtarget->isCallingConvWin64(CallConv)) {
2241     static const MCPhysReg GPR64ArgRegsWin64[] = {
2242       X86::RCX, X86::RDX, X86::R8,  X86::R9
2243     };
2244     return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
2245   }
2246
2247   static const MCPhysReg GPR64ArgRegs64Bit[] = {
2248     X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2249   };
2250   return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
2251 }
2252
2253 // FIXME: Get this from tablegen.
2254 static ArrayRef<MCPhysReg> get64BitArgumentXMMs(MachineFunction &MF,
2255                                                 CallingConv::ID CallConv,
2256                                                 const X86Subtarget *Subtarget) {
2257   assert(Subtarget->is64Bit());
2258   if (Subtarget->isCallingConvWin64(CallConv)) {
2259     // The XMM registers which might contain var arg parameters are shadowed
2260     // in their paired GPR.  So we only need to save the GPR to their home
2261     // slots.
2262     // TODO: __vectorcall will change this.
2263     return None;
2264   }
2265
2266   const Function *Fn = MF.getFunction();
2267   bool NoImplicitFloatOps = Fn->hasFnAttribute(Attribute::NoImplicitFloat);
2268   assert(!(MF.getTarget().Options.UseSoftFloat && NoImplicitFloatOps) &&
2269          "SSE register cannot be used when SSE is disabled!");
2270   if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2271       !Subtarget->hasSSE1())
2272     // Kernel mode asks for SSE to be disabled, so there are no XMM argument
2273     // registers.
2274     return None;
2275
2276   static const MCPhysReg XMMArgRegs64Bit[] = {
2277     X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2278     X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2279   };
2280   return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
2281 }
2282
2283 SDValue
2284 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2285                                         CallingConv::ID CallConv,
2286                                         bool isVarArg,
2287                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2288                                         SDLoc dl,
2289                                         SelectionDAG &DAG,
2290                                         SmallVectorImpl<SDValue> &InVals)
2291                                           const {
2292   MachineFunction &MF = DAG.getMachineFunction();
2293   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2294   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
2295
2296   const Function* Fn = MF.getFunction();
2297   if (Fn->hasExternalLinkage() &&
2298       Subtarget->isTargetCygMing() &&
2299       Fn->getName() == "main")
2300     FuncInfo->setForceFramePointer(true);
2301
2302   MachineFrameInfo *MFI = MF.getFrameInfo();
2303   bool Is64Bit = Subtarget->is64Bit();
2304   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2305
2306   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2307          "Var args not supported with calling convention fastcc, ghc or hipe");
2308
2309   // Assign locations to all of the incoming arguments.
2310   SmallVector<CCValAssign, 16> ArgLocs;
2311   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2312
2313   // Allocate shadow area for Win64
2314   if (IsWin64)
2315     CCInfo.AllocateStack(32, 8);
2316
2317   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2318
2319   unsigned LastVal = ~0U;
2320   SDValue ArgValue;
2321   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2322     CCValAssign &VA = ArgLocs[i];
2323     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2324     // places.
2325     assert(VA.getValNo() != LastVal &&
2326            "Don't support value assigned to multiple locs yet");
2327     (void)LastVal;
2328     LastVal = VA.getValNo();
2329
2330     if (VA.isRegLoc()) {
2331       EVT RegVT = VA.getLocVT();
2332       const TargetRegisterClass *RC;
2333       if (RegVT == MVT::i32)
2334         RC = &X86::GR32RegClass;
2335       else if (Is64Bit && RegVT == MVT::i64)
2336         RC = &X86::GR64RegClass;
2337       else if (RegVT == MVT::f32)
2338         RC = &X86::FR32RegClass;
2339       else if (RegVT == MVT::f64)
2340         RC = &X86::FR64RegClass;
2341       else if (RegVT.is512BitVector())
2342         RC = &X86::VR512RegClass;
2343       else if (RegVT.is256BitVector())
2344         RC = &X86::VR256RegClass;
2345       else if (RegVT.is128BitVector())
2346         RC = &X86::VR128RegClass;
2347       else if (RegVT == MVT::x86mmx)
2348         RC = &X86::VR64RegClass;
2349       else if (RegVT == MVT::i1)
2350         RC = &X86::VK1RegClass;
2351       else if (RegVT == MVT::v8i1)
2352         RC = &X86::VK8RegClass;
2353       else if (RegVT == MVT::v16i1)
2354         RC = &X86::VK16RegClass;
2355       else if (RegVT == MVT::v32i1)
2356         RC = &X86::VK32RegClass;
2357       else if (RegVT == MVT::v64i1)
2358         RC = &X86::VK64RegClass;
2359       else
2360         llvm_unreachable("Unknown argument type!");
2361
2362       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2363       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2364
2365       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2366       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2367       // right size.
2368       if (VA.getLocInfo() == CCValAssign::SExt)
2369         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2370                                DAG.getValueType(VA.getValVT()));
2371       else if (VA.getLocInfo() == CCValAssign::ZExt)
2372         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2373                                DAG.getValueType(VA.getValVT()));
2374       else if (VA.getLocInfo() == CCValAssign::BCvt)
2375         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2376
2377       if (VA.isExtInLoc()) {
2378         // Handle MMX values passed in XMM regs.
2379         if (RegVT.isVector())
2380           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2381         else
2382           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2383       }
2384     } else {
2385       assert(VA.isMemLoc());
2386       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2387     }
2388
2389     // If value is passed via pointer - do a load.
2390     if (VA.getLocInfo() == CCValAssign::Indirect)
2391       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2392                              MachinePointerInfo(), false, false, false, 0);
2393
2394     InVals.push_back(ArgValue);
2395   }
2396
2397   if (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC()) {
2398     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2399       // The x86-64 ABIs require that for returning structs by value we copy
2400       // the sret argument into %rax/%eax (depending on ABI) for the return.
2401       // Win32 requires us to put the sret argument to %eax as well.
2402       // Save the argument into a virtual register so that we can access it
2403       // from the return points.
2404       if (Ins[i].Flags.isSRet()) {
2405         unsigned Reg = FuncInfo->getSRetReturnReg();
2406         if (!Reg) {
2407           MVT PtrTy = getPointerTy();
2408           Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2409           FuncInfo->setSRetReturnReg(Reg);
2410         }
2411         SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2412         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2413         break;
2414       }
2415     }
2416   }
2417
2418   unsigned StackSize = CCInfo.getNextStackOffset();
2419   // Align stack specially for tail calls.
2420   if (FuncIsMadeTailCallSafe(CallConv,
2421                              MF.getTarget().Options.GuaranteedTailCallOpt))
2422     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2423
2424   // If the function takes variable number of arguments, make a frame index for
2425   // the start of the first vararg value... for expansion of llvm.va_start. We
2426   // can skip this if there are no va_start calls.
2427   if (MFI->hasVAStart() &&
2428       (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2429                    CallConv != CallingConv::X86_ThisCall))) {
2430     FuncInfo->setVarArgsFrameIndex(
2431         MFI->CreateFixedObject(1, StackSize, true));
2432   }
2433
2434   MachineModuleInfo &MMI = MF.getMMI();
2435   const Function *WinEHParent = nullptr;
2436   if (IsWin64 && MMI.hasWinEHFuncInfo(Fn))
2437     WinEHParent = MMI.getWinEHParent(Fn);
2438   bool IsWinEHOutlined = WinEHParent && WinEHParent != Fn;
2439   bool IsWinEHParent = WinEHParent && WinEHParent == Fn;
2440
2441   // Figure out if XMM registers are in use.
2442   assert(!(MF.getTarget().Options.UseSoftFloat &&
2443            Fn->hasFnAttribute(Attribute::NoImplicitFloat)) &&
2444          "SSE register cannot be used when SSE is disabled!");
2445
2446   // 64-bit calling conventions support varargs and register parameters, so we
2447   // have to do extra work to spill them in the prologue.
2448   if (Is64Bit && isVarArg && MFI->hasVAStart()) {
2449     // Find the first unallocated argument registers.
2450     ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
2451     ArrayRef<MCPhysReg> ArgXMMs = get64BitArgumentXMMs(MF, CallConv, Subtarget);
2452     unsigned NumIntRegs = CCInfo.getFirstUnallocated(ArgGPRs);
2453     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(ArgXMMs);
2454     assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2455            "SSE register cannot be used when SSE is disabled!");
2456
2457     // Gather all the live in physical registers.
2458     SmallVector<SDValue, 6> LiveGPRs;
2459     SmallVector<SDValue, 8> LiveXMMRegs;
2460     SDValue ALVal;
2461     for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
2462       unsigned GPR = MF.addLiveIn(Reg, &X86::GR64RegClass);
2463       LiveGPRs.push_back(
2464           DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64));
2465     }
2466     if (!ArgXMMs.empty()) {
2467       unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2468       ALVal = DAG.getCopyFromReg(Chain, dl, AL, MVT::i8);
2469       for (MCPhysReg Reg : ArgXMMs.slice(NumXMMRegs)) {
2470         unsigned XMMReg = MF.addLiveIn(Reg, &X86::VR128RegClass);
2471         LiveXMMRegs.push_back(
2472             DAG.getCopyFromReg(Chain, dl, XMMReg, MVT::v4f32));
2473       }
2474     }
2475
2476     if (IsWin64) {
2477       // Get to the caller-allocated home save location.  Add 8 to account
2478       // for the return address.
2479       int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2480       FuncInfo->setRegSaveFrameIndex(
2481           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2482       // Fixup to set vararg frame on shadow area (4 x i64).
2483       if (NumIntRegs < 4)
2484         FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2485     } else {
2486       // For X86-64, if there are vararg parameters that are passed via
2487       // registers, then we must store them to their spots on the stack so
2488       // they may be loaded by deferencing the result of va_next.
2489       FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2490       FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
2491       FuncInfo->setRegSaveFrameIndex(MFI->CreateStackObject(
2492           ArgGPRs.size() * 8 + ArgXMMs.size() * 16, 16, false));
2493     }
2494
2495     // Store the integer parameter registers.
2496     SmallVector<SDValue, 8> MemOps;
2497     SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2498                                       getPointerTy());
2499     unsigned Offset = FuncInfo->getVarArgsGPOffset();
2500     for (SDValue Val : LiveGPRs) {
2501       SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2502                                 DAG.getIntPtrConstant(Offset));
2503       SDValue Store =
2504         DAG.getStore(Val.getValue(1), dl, Val, FIN,
2505                      MachinePointerInfo::getFixedStack(
2506                        FuncInfo->getRegSaveFrameIndex(), Offset),
2507                      false, false, 0);
2508       MemOps.push_back(Store);
2509       Offset += 8;
2510     }
2511
2512     if (!ArgXMMs.empty() && NumXMMRegs != ArgXMMs.size()) {
2513       // Now store the XMM (fp + vector) parameter registers.
2514       SmallVector<SDValue, 12> SaveXMMOps;
2515       SaveXMMOps.push_back(Chain);
2516       SaveXMMOps.push_back(ALVal);
2517       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2518                              FuncInfo->getRegSaveFrameIndex()));
2519       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2520                              FuncInfo->getVarArgsFPOffset()));
2521       SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
2522                         LiveXMMRegs.end());
2523       MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2524                                    MVT::Other, SaveXMMOps));
2525     }
2526
2527     if (!MemOps.empty())
2528       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2529   } else if (IsWinEHOutlined) {
2530     // Get to the caller-allocated home save location.  Add 8 to account
2531     // for the return address.
2532     int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2533     FuncInfo->setRegSaveFrameIndex(MFI->CreateFixedObject(
2534         /*Size=*/1, /*SPOffset=*/HomeOffset + 8, /*Immutable=*/false));
2535
2536     MMI.getWinEHFuncInfo(Fn)
2537         .CatchHandlerParentFrameObjIdx[const_cast<Function *>(Fn)] =
2538         FuncInfo->getRegSaveFrameIndex();
2539
2540     // Store the second integer parameter (rdx) into rsp+16 relative to the
2541     // stack pointer at the entry of the function.
2542     SDValue RSFIN =
2543         DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), getPointerTy());
2544     unsigned GPR = MF.addLiveIn(X86::RDX, &X86::GR64RegClass);
2545     SDValue Val = DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64);
2546     Chain = DAG.getStore(
2547         Val.getValue(1), dl, Val, RSFIN,
2548         MachinePointerInfo::getFixedStack(FuncInfo->getRegSaveFrameIndex()),
2549         /*isVolatile=*/true, /*isNonTemporal=*/false, /*Alignment=*/0);
2550   }
2551
2552   if (isVarArg && MFI->hasMustTailInVarArgFunc()) {
2553     // Find the largest legal vector type.
2554     MVT VecVT = MVT::Other;
2555     // FIXME: Only some x86_32 calling conventions support AVX512.
2556     if (Subtarget->hasAVX512() &&
2557         (Is64Bit || (CallConv == CallingConv::X86_VectorCall ||
2558                      CallConv == CallingConv::Intel_OCL_BI)))
2559       VecVT = MVT::v16f32;
2560     else if (Subtarget->hasAVX())
2561       VecVT = MVT::v8f32;
2562     else if (Subtarget->hasSSE2())
2563       VecVT = MVT::v4f32;
2564
2565     // We forward some GPRs and some vector types.
2566     SmallVector<MVT, 2> RegParmTypes;
2567     MVT IntVT = Is64Bit ? MVT::i64 : MVT::i32;
2568     RegParmTypes.push_back(IntVT);
2569     if (VecVT != MVT::Other)
2570       RegParmTypes.push_back(VecVT);
2571
2572     // Compute the set of forwarded registers. The rest are scratch.
2573     SmallVectorImpl<ForwardedRegister> &Forwards =
2574         FuncInfo->getForwardedMustTailRegParms();
2575     CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, CC_X86);
2576
2577     // Conservatively forward AL on x86_64, since it might be used for varargs.
2578     if (Is64Bit && !CCInfo.isAllocated(X86::AL)) {
2579       unsigned ALVReg = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2580       Forwards.push_back(ForwardedRegister(ALVReg, X86::AL, MVT::i8));
2581     }
2582
2583     // Copy all forwards from physical to virtual registers.
2584     for (ForwardedRegister &F : Forwards) {
2585       // FIXME: Can we use a less constrained schedule?
2586       SDValue RegVal = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2587       F.VReg = MF.getRegInfo().createVirtualRegister(getRegClassFor(F.VT));
2588       Chain = DAG.getCopyToReg(Chain, dl, F.VReg, RegVal);
2589     }
2590   }
2591
2592   // Some CCs need callee pop.
2593   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2594                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2595     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2596   } else {
2597     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2598     // If this is an sret function, the return should pop the hidden pointer.
2599     if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2600         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2601         argsAreStructReturn(Ins) == StackStructReturn)
2602       FuncInfo->setBytesToPopOnReturn(4);
2603   }
2604
2605   if (!Is64Bit) {
2606     // RegSaveFrameIndex is X86-64 only.
2607     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2608     if (CallConv == CallingConv::X86_FastCall ||
2609         CallConv == CallingConv::X86_ThisCall)
2610       // fastcc functions can't have varargs.
2611       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2612   }
2613
2614   FuncInfo->setArgumentStackSize(StackSize);
2615
2616   if (IsWinEHParent) {
2617     int UnwindHelpFI = MFI->CreateStackObject(8, 8, /*isSS=*/false);
2618     SDValue StackSlot = DAG.getFrameIndex(UnwindHelpFI, MVT::i64);
2619     MMI.getWinEHFuncInfo(MF.getFunction()).UnwindHelpFrameIdx = UnwindHelpFI;
2620     SDValue Neg2 = DAG.getConstant(-2, MVT::i64);
2621     Chain = DAG.getStore(Chain, dl, Neg2, StackSlot,
2622                          MachinePointerInfo::getFixedStack(UnwindHelpFI),
2623                          /*isVolatile=*/true,
2624                          /*isNonTemporal=*/false, /*Alignment=*/0);
2625   }
2626
2627   return Chain;
2628 }
2629
2630 SDValue
2631 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2632                                     SDValue StackPtr, SDValue Arg,
2633                                     SDLoc dl, SelectionDAG &DAG,
2634                                     const CCValAssign &VA,
2635                                     ISD::ArgFlagsTy Flags) const {
2636   unsigned LocMemOffset = VA.getLocMemOffset();
2637   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2638   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2639   if (Flags.isByVal())
2640     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2641
2642   return DAG.getStore(Chain, dl, Arg, PtrOff,
2643                       MachinePointerInfo::getStack(LocMemOffset),
2644                       false, false, 0);
2645 }
2646
2647 /// Emit a load of return address if tail call
2648 /// optimization is performed and it is required.
2649 SDValue
2650 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2651                                            SDValue &OutRetAddr, SDValue Chain,
2652                                            bool IsTailCall, bool Is64Bit,
2653                                            int FPDiff, SDLoc dl) const {
2654   // Adjust the Return address stack slot.
2655   EVT VT = getPointerTy();
2656   OutRetAddr = getReturnAddressFrameIndex(DAG);
2657
2658   // Load the "old" Return address.
2659   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2660                            false, false, false, 0);
2661   return SDValue(OutRetAddr.getNode(), 1);
2662 }
2663
2664 /// Emit a store of the return address if tail call
2665 /// optimization is performed and it is required (FPDiff!=0).
2666 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2667                                         SDValue Chain, SDValue RetAddrFrIdx,
2668                                         EVT PtrVT, unsigned SlotSize,
2669                                         int FPDiff, SDLoc dl) {
2670   // Store the return address to the appropriate stack slot.
2671   if (!FPDiff) return Chain;
2672   // Calculate the new stack slot for the return address.
2673   int NewReturnAddrFI =
2674     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2675                                          false);
2676   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2677   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2678                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2679                        false, false, 0);
2680   return Chain;
2681 }
2682
2683 SDValue
2684 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2685                              SmallVectorImpl<SDValue> &InVals) const {
2686   SelectionDAG &DAG                     = CLI.DAG;
2687   SDLoc &dl                             = CLI.DL;
2688   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2689   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2690   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2691   SDValue Chain                         = CLI.Chain;
2692   SDValue Callee                        = CLI.Callee;
2693   CallingConv::ID CallConv              = CLI.CallConv;
2694   bool &isTailCall                      = CLI.IsTailCall;
2695   bool isVarArg                         = CLI.IsVarArg;
2696
2697   MachineFunction &MF = DAG.getMachineFunction();
2698   bool Is64Bit        = Subtarget->is64Bit();
2699   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2700   StructReturnType SR = callIsStructReturn(Outs);
2701   bool IsSibcall      = false;
2702   X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2703
2704   if (MF.getTarget().Options.DisableTailCalls)
2705     isTailCall = false;
2706
2707   bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2708   if (IsMustTail) {
2709     // Force this to be a tail call.  The verifier rules are enough to ensure
2710     // that we can lower this successfully without moving the return address
2711     // around.
2712     isTailCall = true;
2713   } else if (isTailCall) {
2714     // Check if it's really possible to do a tail call.
2715     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2716                     isVarArg, SR != NotStructReturn,
2717                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2718                     Outs, OutVals, Ins, DAG);
2719
2720     // Sibcalls are automatically detected tailcalls which do not require
2721     // ABI changes.
2722     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2723       IsSibcall = true;
2724
2725     if (isTailCall)
2726       ++NumTailCalls;
2727   }
2728
2729   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2730          "Var args not supported with calling convention fastcc, ghc or hipe");
2731
2732   // Analyze operands of the call, assigning locations to each operand.
2733   SmallVector<CCValAssign, 16> ArgLocs;
2734   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2735
2736   // Allocate shadow area for Win64
2737   if (IsWin64)
2738     CCInfo.AllocateStack(32, 8);
2739
2740   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2741
2742   // Get a count of how many bytes are to be pushed on the stack.
2743   unsigned NumBytes = CCInfo.getNextStackOffset();
2744   if (IsSibcall)
2745     // This is a sibcall. The memory operands are available in caller's
2746     // own caller's stack.
2747     NumBytes = 0;
2748   else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
2749            IsTailCallConvention(CallConv))
2750     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2751
2752   int FPDiff = 0;
2753   if (isTailCall && !IsSibcall && !IsMustTail) {
2754     // Lower arguments at fp - stackoffset + fpdiff.
2755     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2756
2757     FPDiff = NumBytesCallerPushed - NumBytes;
2758
2759     // Set the delta of movement of the returnaddr stackslot.
2760     // But only set if delta is greater than previous delta.
2761     if (FPDiff < X86Info->getTCReturnAddrDelta())
2762       X86Info->setTCReturnAddrDelta(FPDiff);
2763   }
2764
2765   unsigned NumBytesToPush = NumBytes;
2766   unsigned NumBytesToPop = NumBytes;
2767
2768   // If we have an inalloca argument, all stack space has already been allocated
2769   // for us and be right at the top of the stack.  We don't support multiple
2770   // arguments passed in memory when using inalloca.
2771   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2772     NumBytesToPush = 0;
2773     if (!ArgLocs.back().isMemLoc())
2774       report_fatal_error("cannot use inalloca attribute on a register "
2775                          "parameter");
2776     if (ArgLocs.back().getLocMemOffset() != 0)
2777       report_fatal_error("any parameter with the inalloca attribute must be "
2778                          "the only memory argument");
2779   }
2780
2781   if (!IsSibcall)
2782     Chain = DAG.getCALLSEQ_START(
2783         Chain, DAG.getIntPtrConstant(NumBytesToPush, true), dl);
2784
2785   SDValue RetAddrFrIdx;
2786   // Load return address for tail calls.
2787   if (isTailCall && FPDiff)
2788     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2789                                     Is64Bit, FPDiff, dl);
2790
2791   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2792   SmallVector<SDValue, 8> MemOpChains;
2793   SDValue StackPtr;
2794
2795   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2796   // of tail call optimization arguments are handle later.
2797   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
2798   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2799     // Skip inalloca arguments, they have already been written.
2800     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2801     if (Flags.isInAlloca())
2802       continue;
2803
2804     CCValAssign &VA = ArgLocs[i];
2805     EVT RegVT = VA.getLocVT();
2806     SDValue Arg = OutVals[i];
2807     bool isByVal = Flags.isByVal();
2808
2809     // Promote the value if needed.
2810     switch (VA.getLocInfo()) {
2811     default: llvm_unreachable("Unknown loc info!");
2812     case CCValAssign::Full: break;
2813     case CCValAssign::SExt:
2814       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2815       break;
2816     case CCValAssign::ZExt:
2817       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2818       break;
2819     case CCValAssign::AExt:
2820       if (RegVT.is128BitVector()) {
2821         // Special case: passing MMX values in XMM registers.
2822         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2823         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2824         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2825       } else
2826         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2827       break;
2828     case CCValAssign::BCvt:
2829       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2830       break;
2831     case CCValAssign::Indirect: {
2832       // Store the argument.
2833       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2834       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2835       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2836                            MachinePointerInfo::getFixedStack(FI),
2837                            false, false, 0);
2838       Arg = SpillSlot;
2839       break;
2840     }
2841     }
2842
2843     if (VA.isRegLoc()) {
2844       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2845       if (isVarArg && IsWin64) {
2846         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2847         // shadow reg if callee is a varargs function.
2848         unsigned ShadowReg = 0;
2849         switch (VA.getLocReg()) {
2850         case X86::XMM0: ShadowReg = X86::RCX; break;
2851         case X86::XMM1: ShadowReg = X86::RDX; break;
2852         case X86::XMM2: ShadowReg = X86::R8; break;
2853         case X86::XMM3: ShadowReg = X86::R9; break;
2854         }
2855         if (ShadowReg)
2856           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2857       }
2858     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2859       assert(VA.isMemLoc());
2860       if (!StackPtr.getNode())
2861         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2862                                       getPointerTy());
2863       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2864                                              dl, DAG, VA, Flags));
2865     }
2866   }
2867
2868   if (!MemOpChains.empty())
2869     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2870
2871   if (Subtarget->isPICStyleGOT()) {
2872     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2873     // GOT pointer.
2874     if (!isTailCall) {
2875       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2876                DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2877     } else {
2878       // If we are tail calling and generating PIC/GOT style code load the
2879       // address of the callee into ECX. The value in ecx is used as target of
2880       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2881       // for tail calls on PIC/GOT architectures. Normally we would just put the
2882       // address of GOT into ebx and then call target@PLT. But for tail calls
2883       // ebx would be restored (since ebx is callee saved) before jumping to the
2884       // target@PLT.
2885
2886       // Note: The actual moving to ECX is done further down.
2887       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2888       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2889           !G->getGlobal()->hasProtectedVisibility())
2890         Callee = LowerGlobalAddress(Callee, DAG);
2891       else if (isa<ExternalSymbolSDNode>(Callee))
2892         Callee = LowerExternalSymbol(Callee, DAG);
2893     }
2894   }
2895
2896   if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail) {
2897     // From AMD64 ABI document:
2898     // For calls that may call functions that use varargs or stdargs
2899     // (prototype-less calls or calls to functions containing ellipsis (...) in
2900     // the declaration) %al is used as hidden argument to specify the number
2901     // of SSE registers used. The contents of %al do not need to match exactly
2902     // the number of registers, but must be an ubound on the number of SSE
2903     // registers used and is in the range 0 - 8 inclusive.
2904
2905     // Count the number of XMM registers allocated.
2906     static const MCPhysReg XMMArgRegs[] = {
2907       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2908       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2909     };
2910     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
2911     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2912            && "SSE registers cannot be used when SSE is disabled");
2913
2914     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2915                                         DAG.getConstant(NumXMMRegs, MVT::i8)));
2916   }
2917
2918   if (isVarArg && IsMustTail) {
2919     const auto &Forwards = X86Info->getForwardedMustTailRegParms();
2920     for (const auto &F : Forwards) {
2921       SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2922       RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
2923     }
2924   }
2925
2926   // For tail calls lower the arguments to the 'real' stack slots.  Sibcalls
2927   // don't need this because the eligibility check rejects calls that require
2928   // shuffling arguments passed in memory.
2929   if (!IsSibcall && isTailCall) {
2930     // Force all the incoming stack arguments to be loaded from the stack
2931     // before any new outgoing arguments are stored to the stack, because the
2932     // outgoing stack slots may alias the incoming argument stack slots, and
2933     // the alias isn't otherwise explicit. This is slightly more conservative
2934     // than necessary, because it means that each store effectively depends
2935     // on every argument instead of just those arguments it would clobber.
2936     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2937
2938     SmallVector<SDValue, 8> MemOpChains2;
2939     SDValue FIN;
2940     int FI = 0;
2941     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2942       CCValAssign &VA = ArgLocs[i];
2943       if (VA.isRegLoc())
2944         continue;
2945       assert(VA.isMemLoc());
2946       SDValue Arg = OutVals[i];
2947       ISD::ArgFlagsTy Flags = Outs[i].Flags;
2948       // Skip inalloca arguments.  They don't require any work.
2949       if (Flags.isInAlloca())
2950         continue;
2951       // Create frame index.
2952       int32_t Offset = VA.getLocMemOffset()+FPDiff;
2953       uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2954       FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2955       FIN = DAG.getFrameIndex(FI, getPointerTy());
2956
2957       if (Flags.isByVal()) {
2958         // Copy relative to framepointer.
2959         SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2960         if (!StackPtr.getNode())
2961           StackPtr = DAG.getCopyFromReg(Chain, dl,
2962                                         RegInfo->getStackRegister(),
2963                                         getPointerTy());
2964         Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2965
2966         MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2967                                                          ArgChain,
2968                                                          Flags, DAG, dl));
2969       } else {
2970         // Store relative to framepointer.
2971         MemOpChains2.push_back(
2972           DAG.getStore(ArgChain, dl, Arg, FIN,
2973                        MachinePointerInfo::getFixedStack(FI),
2974                        false, false, 0));
2975       }
2976     }
2977
2978     if (!MemOpChains2.empty())
2979       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
2980
2981     // Store the return address to the appropriate stack slot.
2982     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2983                                      getPointerTy(), RegInfo->getSlotSize(),
2984                                      FPDiff, dl);
2985   }
2986
2987   // Build a sequence of copy-to-reg nodes chained together with token chain
2988   // and flag operands which copy the outgoing args into registers.
2989   SDValue InFlag;
2990   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2991     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2992                              RegsToPass[i].second, InFlag);
2993     InFlag = Chain.getValue(1);
2994   }
2995
2996   if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
2997     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2998     // In the 64-bit large code model, we have to make all calls
2999     // through a register, since the call instruction's 32-bit
3000     // pc-relative offset may not be large enough to hold the whole
3001     // address.
3002   } else if (Callee->getOpcode() == ISD::GlobalAddress) {
3003     // If the callee is a GlobalAddress node (quite common, every direct call
3004     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
3005     // it.
3006     GlobalAddressSDNode* G = cast<GlobalAddressSDNode>(Callee);
3007
3008     // We should use extra load for direct calls to dllimported functions in
3009     // non-JIT mode.
3010     const GlobalValue *GV = G->getGlobal();
3011     if (!GV->hasDLLImportStorageClass()) {
3012       unsigned char OpFlags = 0;
3013       bool ExtraLoad = false;
3014       unsigned WrapperKind = ISD::DELETED_NODE;
3015
3016       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
3017       // external symbols most go through the PLT in PIC mode.  If the symbol
3018       // has hidden or protected visibility, or if it is static or local, then
3019       // we don't need to use the PLT - we can directly call it.
3020       if (Subtarget->isTargetELF() &&
3021           DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
3022           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
3023         OpFlags = X86II::MO_PLT;
3024       } else if (Subtarget->isPICStyleStubAny() &&
3025                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
3026                  (!Subtarget->getTargetTriple().isMacOSX() ||
3027                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3028         // PC-relative references to external symbols should go through $stub,
3029         // unless we're building with the leopard linker or later, which
3030         // automatically synthesizes these stubs.
3031         OpFlags = X86II::MO_DARWIN_STUB;
3032       } else if (Subtarget->isPICStyleRIPRel() && isa<Function>(GV) &&
3033                  cast<Function>(GV)->hasFnAttribute(Attribute::NonLazyBind)) {
3034         // If the function is marked as non-lazy, generate an indirect call
3035         // which loads from the GOT directly. This avoids runtime overhead
3036         // at the cost of eager binding (and one extra byte of encoding).
3037         OpFlags = X86II::MO_GOTPCREL;
3038         WrapperKind = X86ISD::WrapperRIP;
3039         ExtraLoad = true;
3040       }
3041
3042       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
3043                                           G->getOffset(), OpFlags);
3044
3045       // Add a wrapper if needed.
3046       if (WrapperKind != ISD::DELETED_NODE)
3047         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
3048       // Add extra indirection if needed.
3049       if (ExtraLoad)
3050         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
3051                              MachinePointerInfo::getGOT(),
3052                              false, false, false, 0);
3053     }
3054   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3055     unsigned char OpFlags = 0;
3056
3057     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
3058     // external symbols should go through the PLT.
3059     if (Subtarget->isTargetELF() &&
3060         DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
3061       OpFlags = X86II::MO_PLT;
3062     } else if (Subtarget->isPICStyleStubAny() &&
3063                (!Subtarget->getTargetTriple().isMacOSX() ||
3064                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3065       // PC-relative references to external symbols should go through $stub,
3066       // unless we're building with the leopard linker or later, which
3067       // automatically synthesizes these stubs.
3068       OpFlags = X86II::MO_DARWIN_STUB;
3069     }
3070
3071     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
3072                                          OpFlags);
3073   } else if (Subtarget->isTarget64BitILP32() &&
3074              Callee->getValueType(0) == MVT::i32) {
3075     // Zero-extend the 32-bit Callee address into a 64-bit according to x32 ABI
3076     Callee = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Callee);
3077   }
3078
3079   // Returns a chain & a flag for retval copy to use.
3080   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3081   SmallVector<SDValue, 8> Ops;
3082
3083   if (!IsSibcall && isTailCall) {
3084     Chain = DAG.getCALLSEQ_END(Chain,
3085                                DAG.getIntPtrConstant(NumBytesToPop, true),
3086                                DAG.getIntPtrConstant(0, true), InFlag, dl);
3087     InFlag = Chain.getValue(1);
3088   }
3089
3090   Ops.push_back(Chain);
3091   Ops.push_back(Callee);
3092
3093   if (isTailCall)
3094     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
3095
3096   // Add argument registers to the end of the list so that they are known live
3097   // into the call.
3098   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3099     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3100                                   RegsToPass[i].second.getValueType()));
3101
3102   // Add a register mask operand representing the call-preserved registers.
3103   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
3104   const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
3105   assert(Mask && "Missing call preserved mask for calling convention");
3106   Ops.push_back(DAG.getRegisterMask(Mask));
3107
3108   if (InFlag.getNode())
3109     Ops.push_back(InFlag);
3110
3111   if (isTailCall) {
3112     // We used to do:
3113     //// If this is the first return lowered for this function, add the regs
3114     //// to the liveout set for the function.
3115     // This isn't right, although it's probably harmless on x86; liveouts
3116     // should be computed from returns not tail calls.  Consider a void
3117     // function making a tail call to a function returning int.
3118     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3119   }
3120
3121   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3122   InFlag = Chain.getValue(1);
3123
3124   // Create the CALLSEQ_END node.
3125   unsigned NumBytesForCalleeToPop;
3126   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3127                        DAG.getTarget().Options.GuaranteedTailCallOpt))
3128     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
3129   else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
3130            !Subtarget->getTargetTriple().isOSMSVCRT() &&
3131            SR == StackStructReturn)
3132     // If this is a call to a struct-return function, the callee
3133     // pops the hidden struct pointer, so we have to push it back.
3134     // This is common for Darwin/X86, Linux & Mingw32 targets.
3135     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3136     NumBytesForCalleeToPop = 4;
3137   else
3138     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
3139
3140   // Returns a flag for retval copy to use.
3141   if (!IsSibcall) {
3142     Chain = DAG.getCALLSEQ_END(Chain,
3143                                DAG.getIntPtrConstant(NumBytesToPop, true),
3144                                DAG.getIntPtrConstant(NumBytesForCalleeToPop,
3145                                                      true),
3146                                InFlag, dl);
3147     InFlag = Chain.getValue(1);
3148   }
3149
3150   // Handle result values, copying them out of physregs into vregs that we
3151   // return.
3152   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3153                          Ins, dl, DAG, InVals);
3154 }
3155
3156 //===----------------------------------------------------------------------===//
3157 //                Fast Calling Convention (tail call) implementation
3158 //===----------------------------------------------------------------------===//
3159
3160 //  Like std call, callee cleans arguments, convention except that ECX is
3161 //  reserved for storing the tail called function address. Only 2 registers are
3162 //  free for argument passing (inreg). Tail call optimization is performed
3163 //  provided:
3164 //                * tailcallopt is enabled
3165 //                * caller/callee are fastcc
3166 //  On X86_64 architecture with GOT-style position independent code only local
3167 //  (within module) calls are supported at the moment.
3168 //  To keep the stack aligned according to platform abi the function
3169 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
3170 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3171 //  If a tail called function callee has more arguments than the caller the
3172 //  caller needs to make sure that there is room to move the RETADDR to. This is
3173 //  achieved by reserving an area the size of the argument delta right after the
3174 //  original RETADDR, but before the saved framepointer or the spilled registers
3175 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3176 //  stack layout:
3177 //    arg1
3178 //    arg2
3179 //    RETADDR
3180 //    [ new RETADDR
3181 //      move area ]
3182 //    (possible EBP)
3183 //    ESI
3184 //    EDI
3185 //    local1 ..
3186
3187 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3188 /// for a 16 byte align requirement.
3189 unsigned
3190 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3191                                                SelectionDAG& DAG) const {
3192   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3193   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
3194   unsigned StackAlignment = TFI.getStackAlignment();
3195   uint64_t AlignMask = StackAlignment - 1;
3196   int64_t Offset = StackSize;
3197   unsigned SlotSize = RegInfo->getSlotSize();
3198   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3199     // Number smaller than 12 so just add the difference.
3200     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3201   } else {
3202     // Mask out lower bits, add stackalignment once plus the 12 bytes.
3203     Offset = ((~AlignMask) & Offset) + StackAlignment +
3204       (StackAlignment-SlotSize);
3205   }
3206   return Offset;
3207 }
3208
3209 /// MatchingStackOffset - Return true if the given stack call argument is
3210 /// already available in the same position (relatively) of the caller's
3211 /// incoming argument stack.
3212 static
3213 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3214                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3215                          const X86InstrInfo *TII) {
3216   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3217   int FI = INT_MAX;
3218   if (Arg.getOpcode() == ISD::CopyFromReg) {
3219     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3220     if (!TargetRegisterInfo::isVirtualRegister(VR))
3221       return false;
3222     MachineInstr *Def = MRI->getVRegDef(VR);
3223     if (!Def)
3224       return false;
3225     if (!Flags.isByVal()) {
3226       if (!TII->isLoadFromStackSlot(Def, FI))
3227         return false;
3228     } else {
3229       unsigned Opcode = Def->getOpcode();
3230       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r ||
3231            Opcode == X86::LEA64_32r) &&
3232           Def->getOperand(1).isFI()) {
3233         FI = Def->getOperand(1).getIndex();
3234         Bytes = Flags.getByValSize();
3235       } else
3236         return false;
3237     }
3238   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3239     if (Flags.isByVal())
3240       // ByVal argument is passed in as a pointer but it's now being
3241       // dereferenced. e.g.
3242       // define @foo(%struct.X* %A) {
3243       //   tail call @bar(%struct.X* byval %A)
3244       // }
3245       return false;
3246     SDValue Ptr = Ld->getBasePtr();
3247     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3248     if (!FINode)
3249       return false;
3250     FI = FINode->getIndex();
3251   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3252     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3253     FI = FINode->getIndex();
3254     Bytes = Flags.getByValSize();
3255   } else
3256     return false;
3257
3258   assert(FI != INT_MAX);
3259   if (!MFI->isFixedObjectIndex(FI))
3260     return false;
3261   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3262 }
3263
3264 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3265 /// for tail call optimization. Targets which want to do tail call
3266 /// optimization should implement this function.
3267 bool
3268 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3269                                                      CallingConv::ID CalleeCC,
3270                                                      bool isVarArg,
3271                                                      bool isCalleeStructRet,
3272                                                      bool isCallerStructRet,
3273                                                      Type *RetTy,
3274                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3275                                     const SmallVectorImpl<SDValue> &OutVals,
3276                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3277                                                      SelectionDAG &DAG) const {
3278   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3279     return false;
3280
3281   // If -tailcallopt is specified, make fastcc functions tail-callable.
3282   const MachineFunction &MF = DAG.getMachineFunction();
3283   const Function *CallerF = MF.getFunction();
3284
3285   // If the function return type is x86_fp80 and the callee return type is not,
3286   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3287   // perform a tailcall optimization here.
3288   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3289     return false;
3290
3291   CallingConv::ID CallerCC = CallerF->getCallingConv();
3292   bool CCMatch = CallerCC == CalleeCC;
3293   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3294   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3295
3296   // Win64 functions have extra shadow space for argument homing. Don't do the
3297   // sibcall if the caller and callee have mismatched expectations for this
3298   // space.
3299   if (IsCalleeWin64 != IsCallerWin64)
3300     return false;
3301
3302   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3303     if (IsTailCallConvention(CalleeCC) && CCMatch)
3304       return true;
3305     return false;
3306   }
3307
3308   // Look for obvious safe cases to perform tail call optimization that do not
3309   // require ABI changes. This is what gcc calls sibcall.
3310
3311   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3312   // emit a special epilogue.
3313   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3314   if (RegInfo->needsStackRealignment(MF))
3315     return false;
3316
3317   // Also avoid sibcall optimization if either caller or callee uses struct
3318   // return semantics.
3319   if (isCalleeStructRet || isCallerStructRet)
3320     return false;
3321
3322   // An stdcall/thiscall caller is expected to clean up its arguments; the
3323   // callee isn't going to do that.
3324   // FIXME: this is more restrictive than needed. We could produce a tailcall
3325   // when the stack adjustment matches. For example, with a thiscall that takes
3326   // only one argument.
3327   if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3328                    CallerCC == CallingConv::X86_ThisCall))
3329     return false;
3330
3331   // Do not sibcall optimize vararg calls unless all arguments are passed via
3332   // registers.
3333   if (isVarArg && !Outs.empty()) {
3334
3335     // Optimizing for varargs on Win64 is unlikely to be safe without
3336     // additional testing.
3337     if (IsCalleeWin64 || IsCallerWin64)
3338       return false;
3339
3340     SmallVector<CCValAssign, 16> ArgLocs;
3341     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3342                    *DAG.getContext());
3343
3344     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3345     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3346       if (!ArgLocs[i].isRegLoc())
3347         return false;
3348   }
3349
3350   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3351   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3352   // this into a sibcall.
3353   bool Unused = false;
3354   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3355     if (!Ins[i].Used) {
3356       Unused = true;
3357       break;
3358     }
3359   }
3360   if (Unused) {
3361     SmallVector<CCValAssign, 16> RVLocs;
3362     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), RVLocs,
3363                    *DAG.getContext());
3364     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3365     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3366       CCValAssign &VA = RVLocs[i];
3367       if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3368         return false;
3369     }
3370   }
3371
3372   // If the calling conventions do not match, then we'd better make sure the
3373   // results are returned in the same way as what the caller expects.
3374   if (!CCMatch) {
3375     SmallVector<CCValAssign, 16> RVLocs1;
3376     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
3377                     *DAG.getContext());
3378     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3379
3380     SmallVector<CCValAssign, 16> RVLocs2;
3381     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
3382                     *DAG.getContext());
3383     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3384
3385     if (RVLocs1.size() != RVLocs2.size())
3386       return false;
3387     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3388       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3389         return false;
3390       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3391         return false;
3392       if (RVLocs1[i].isRegLoc()) {
3393         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3394           return false;
3395       } else {
3396         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3397           return false;
3398       }
3399     }
3400   }
3401
3402   // If the callee takes no arguments then go on to check the results of the
3403   // call.
3404   if (!Outs.empty()) {
3405     // Check if stack adjustment is needed. For now, do not do this if any
3406     // argument is passed on the stack.
3407     SmallVector<CCValAssign, 16> ArgLocs;
3408     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3409                    *DAG.getContext());
3410
3411     // Allocate shadow area for Win64
3412     if (IsCalleeWin64)
3413       CCInfo.AllocateStack(32, 8);
3414
3415     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3416     if (CCInfo.getNextStackOffset()) {
3417       MachineFunction &MF = DAG.getMachineFunction();
3418       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3419         return false;
3420
3421       // Check if the arguments are already laid out in the right way as
3422       // the caller's fixed stack objects.
3423       MachineFrameInfo *MFI = MF.getFrameInfo();
3424       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3425       const X86InstrInfo *TII = Subtarget->getInstrInfo();
3426       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3427         CCValAssign &VA = ArgLocs[i];
3428         SDValue Arg = OutVals[i];
3429         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3430         if (VA.getLocInfo() == CCValAssign::Indirect)
3431           return false;
3432         if (!VA.isRegLoc()) {
3433           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3434                                    MFI, MRI, TII))
3435             return false;
3436         }
3437       }
3438     }
3439
3440     // If the tailcall address may be in a register, then make sure it's
3441     // possible to register allocate for it. In 32-bit, the call address can
3442     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3443     // callee-saved registers are restored. These happen to be the same
3444     // registers used to pass 'inreg' arguments so watch out for those.
3445     if (!Subtarget->is64Bit() &&
3446         ((!isa<GlobalAddressSDNode>(Callee) &&
3447           !isa<ExternalSymbolSDNode>(Callee)) ||
3448          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3449       unsigned NumInRegs = 0;
3450       // In PIC we need an extra register to formulate the address computation
3451       // for the callee.
3452       unsigned MaxInRegs =
3453         (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3454
3455       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3456         CCValAssign &VA = ArgLocs[i];
3457         if (!VA.isRegLoc())
3458           continue;
3459         unsigned Reg = VA.getLocReg();
3460         switch (Reg) {
3461         default: break;
3462         case X86::EAX: case X86::EDX: case X86::ECX:
3463           if (++NumInRegs == MaxInRegs)
3464             return false;
3465           break;
3466         }
3467       }
3468     }
3469   }
3470
3471   return true;
3472 }
3473
3474 FastISel *
3475 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3476                                   const TargetLibraryInfo *libInfo) const {
3477   return X86::createFastISel(funcInfo, libInfo);
3478 }
3479
3480 //===----------------------------------------------------------------------===//
3481 //                           Other Lowering Hooks
3482 //===----------------------------------------------------------------------===//
3483
3484 static bool MayFoldLoad(SDValue Op) {
3485   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3486 }
3487
3488 static bool MayFoldIntoStore(SDValue Op) {
3489   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3490 }
3491
3492 static bool isTargetShuffle(unsigned Opcode) {
3493   switch(Opcode) {
3494   default: return false;
3495   case X86ISD::BLENDI:
3496   case X86ISD::PSHUFB:
3497   case X86ISD::PSHUFD:
3498   case X86ISD::PSHUFHW:
3499   case X86ISD::PSHUFLW:
3500   case X86ISD::SHUFP:
3501   case X86ISD::PALIGNR:
3502   case X86ISD::MOVLHPS:
3503   case X86ISD::MOVLHPD:
3504   case X86ISD::MOVHLPS:
3505   case X86ISD::MOVLPS:
3506   case X86ISD::MOVLPD:
3507   case X86ISD::MOVSHDUP:
3508   case X86ISD::MOVSLDUP:
3509   case X86ISD::MOVDDUP:
3510   case X86ISD::MOVSS:
3511   case X86ISD::MOVSD:
3512   case X86ISD::UNPCKL:
3513   case X86ISD::UNPCKH:
3514   case X86ISD::VPERMILPI:
3515   case X86ISD::VPERM2X128:
3516   case X86ISD::VPERMI:
3517     return true;
3518   }
3519 }
3520
3521 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3522                                     SDValue V1, unsigned TargetMask,
3523                                     SelectionDAG &DAG) {
3524   switch(Opc) {
3525   default: llvm_unreachable("Unknown x86 shuffle node");
3526   case X86ISD::PSHUFD:
3527   case X86ISD::PSHUFHW:
3528   case X86ISD::PSHUFLW:
3529   case X86ISD::VPERMILPI:
3530   case X86ISD::VPERMI:
3531     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3532   }
3533 }
3534
3535 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3536                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3537   switch(Opc) {
3538   default: llvm_unreachable("Unknown x86 shuffle node");
3539   case X86ISD::MOVLHPS:
3540   case X86ISD::MOVLHPD:
3541   case X86ISD::MOVHLPS:
3542   case X86ISD::MOVLPS:
3543   case X86ISD::MOVLPD:
3544   case X86ISD::MOVSS:
3545   case X86ISD::MOVSD:
3546   case X86ISD::UNPCKL:
3547   case X86ISD::UNPCKH:
3548     return DAG.getNode(Opc, dl, VT, V1, V2);
3549   }
3550 }
3551
3552 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3553   MachineFunction &MF = DAG.getMachineFunction();
3554   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3555   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3556   int ReturnAddrIndex = FuncInfo->getRAIndex();
3557
3558   if (ReturnAddrIndex == 0) {
3559     // Set up a frame object for the return address.
3560     unsigned SlotSize = RegInfo->getSlotSize();
3561     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3562                                                            -(int64_t)SlotSize,
3563                                                            false);
3564     FuncInfo->setRAIndex(ReturnAddrIndex);
3565   }
3566
3567   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3568 }
3569
3570 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3571                                        bool hasSymbolicDisplacement) {
3572   // Offset should fit into 32 bit immediate field.
3573   if (!isInt<32>(Offset))
3574     return false;
3575
3576   // If we don't have a symbolic displacement - we don't have any extra
3577   // restrictions.
3578   if (!hasSymbolicDisplacement)
3579     return true;
3580
3581   // FIXME: Some tweaks might be needed for medium code model.
3582   if (M != CodeModel::Small && M != CodeModel::Kernel)
3583     return false;
3584
3585   // For small code model we assume that latest object is 16MB before end of 31
3586   // bits boundary. We may also accept pretty large negative constants knowing
3587   // that all objects are in the positive half of address space.
3588   if (M == CodeModel::Small && Offset < 16*1024*1024)
3589     return true;
3590
3591   // For kernel code model we know that all object resist in the negative half
3592   // of 32bits address space. We may not accept negative offsets, since they may
3593   // be just off and we may accept pretty large positive ones.
3594   if (M == CodeModel::Kernel && Offset >= 0)
3595     return true;
3596
3597   return false;
3598 }
3599
3600 /// isCalleePop - Determines whether the callee is required to pop its
3601 /// own arguments. Callee pop is necessary to support tail calls.
3602 bool X86::isCalleePop(CallingConv::ID CallingConv,
3603                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3604   switch (CallingConv) {
3605   default:
3606     return false;
3607   case CallingConv::X86_StdCall:
3608   case CallingConv::X86_FastCall:
3609   case CallingConv::X86_ThisCall:
3610     return !is64Bit;
3611   case CallingConv::Fast:
3612   case CallingConv::GHC:
3613   case CallingConv::HiPE:
3614     if (IsVarArg)
3615       return false;
3616     return TailCallOpt;
3617   }
3618 }
3619
3620 /// \brief Return true if the condition is an unsigned comparison operation.
3621 static bool isX86CCUnsigned(unsigned X86CC) {
3622   switch (X86CC) {
3623   default: llvm_unreachable("Invalid integer condition!");
3624   case X86::COND_E:     return true;
3625   case X86::COND_G:     return false;
3626   case X86::COND_GE:    return false;
3627   case X86::COND_L:     return false;
3628   case X86::COND_LE:    return false;
3629   case X86::COND_NE:    return true;
3630   case X86::COND_B:     return true;
3631   case X86::COND_A:     return true;
3632   case X86::COND_BE:    return true;
3633   case X86::COND_AE:    return true;
3634   }
3635   llvm_unreachable("covered switch fell through?!");
3636 }
3637
3638 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3639 /// specific condition code, returning the condition code and the LHS/RHS of the
3640 /// comparison to make.
3641 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3642                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3643   if (!isFP) {
3644     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3645       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3646         // X > -1   -> X == 0, jump !sign.
3647         RHS = DAG.getConstant(0, RHS.getValueType());
3648         return X86::COND_NS;
3649       }
3650       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3651         // X < 0   -> X == 0, jump on sign.
3652         return X86::COND_S;
3653       }
3654       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3655         // X < 1   -> X <= 0
3656         RHS = DAG.getConstant(0, RHS.getValueType());
3657         return X86::COND_LE;
3658       }
3659     }
3660
3661     switch (SetCCOpcode) {
3662     default: llvm_unreachable("Invalid integer condition!");
3663     case ISD::SETEQ:  return X86::COND_E;
3664     case ISD::SETGT:  return X86::COND_G;
3665     case ISD::SETGE:  return X86::COND_GE;
3666     case ISD::SETLT:  return X86::COND_L;
3667     case ISD::SETLE:  return X86::COND_LE;
3668     case ISD::SETNE:  return X86::COND_NE;
3669     case ISD::SETULT: return X86::COND_B;
3670     case ISD::SETUGT: return X86::COND_A;
3671     case ISD::SETULE: return X86::COND_BE;
3672     case ISD::SETUGE: return X86::COND_AE;
3673     }
3674   }
3675
3676   // First determine if it is required or is profitable to flip the operands.
3677
3678   // If LHS is a foldable load, but RHS is not, flip the condition.
3679   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3680       !ISD::isNON_EXTLoad(RHS.getNode())) {
3681     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3682     std::swap(LHS, RHS);
3683   }
3684
3685   switch (SetCCOpcode) {
3686   default: break;
3687   case ISD::SETOLT:
3688   case ISD::SETOLE:
3689   case ISD::SETUGT:
3690   case ISD::SETUGE:
3691     std::swap(LHS, RHS);
3692     break;
3693   }
3694
3695   // On a floating point condition, the flags are set as follows:
3696   // ZF  PF  CF   op
3697   //  0 | 0 | 0 | X > Y
3698   //  0 | 0 | 1 | X < Y
3699   //  1 | 0 | 0 | X == Y
3700   //  1 | 1 | 1 | unordered
3701   switch (SetCCOpcode) {
3702   default: llvm_unreachable("Condcode should be pre-legalized away");
3703   case ISD::SETUEQ:
3704   case ISD::SETEQ:   return X86::COND_E;
3705   case ISD::SETOLT:              // flipped
3706   case ISD::SETOGT:
3707   case ISD::SETGT:   return X86::COND_A;
3708   case ISD::SETOLE:              // flipped
3709   case ISD::SETOGE:
3710   case ISD::SETGE:   return X86::COND_AE;
3711   case ISD::SETUGT:              // flipped
3712   case ISD::SETULT:
3713   case ISD::SETLT:   return X86::COND_B;
3714   case ISD::SETUGE:              // flipped
3715   case ISD::SETULE:
3716   case ISD::SETLE:   return X86::COND_BE;
3717   case ISD::SETONE:
3718   case ISD::SETNE:   return X86::COND_NE;
3719   case ISD::SETUO:   return X86::COND_P;
3720   case ISD::SETO:    return X86::COND_NP;
3721   case ISD::SETOEQ:
3722   case ISD::SETUNE:  return X86::COND_INVALID;
3723   }
3724 }
3725
3726 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3727 /// code. Current x86 isa includes the following FP cmov instructions:
3728 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3729 static bool hasFPCMov(unsigned X86CC) {
3730   switch (X86CC) {
3731   default:
3732     return false;
3733   case X86::COND_B:
3734   case X86::COND_BE:
3735   case X86::COND_E:
3736   case X86::COND_P:
3737   case X86::COND_A:
3738   case X86::COND_AE:
3739   case X86::COND_NE:
3740   case X86::COND_NP:
3741     return true;
3742   }
3743 }
3744
3745 /// isFPImmLegal - Returns true if the target can instruction select the
3746 /// specified FP immediate natively. If false, the legalizer will
3747 /// materialize the FP immediate as a load from a constant pool.
3748 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3749   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3750     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3751       return true;
3752   }
3753   return false;
3754 }
3755
3756 bool X86TargetLowering::shouldReduceLoadWidth(SDNode *Load,
3757                                               ISD::LoadExtType ExtTy,
3758                                               EVT NewVT) const {
3759   // "ELF Handling for Thread-Local Storage" specifies that R_X86_64_GOTTPOFF
3760   // relocation target a movq or addq instruction: don't let the load shrink.
3761   SDValue BasePtr = cast<LoadSDNode>(Load)->getBasePtr();
3762   if (BasePtr.getOpcode() == X86ISD::WrapperRIP)
3763     if (const auto *GA = dyn_cast<GlobalAddressSDNode>(BasePtr.getOperand(0)))
3764       return GA->getTargetFlags() != X86II::MO_GOTTPOFF;
3765   return true;
3766 }
3767
3768 /// \brief Returns true if it is beneficial to convert a load of a constant
3769 /// to just the constant itself.
3770 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3771                                                           Type *Ty) const {
3772   assert(Ty->isIntegerTy());
3773
3774   unsigned BitSize = Ty->getPrimitiveSizeInBits();
3775   if (BitSize == 0 || BitSize > 64)
3776     return false;
3777   return true;
3778 }
3779
3780 bool X86TargetLowering::isExtractSubvectorCheap(EVT ResVT,
3781                                                 unsigned Index) const {
3782   if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
3783     return false;
3784
3785   return (Index == 0 || Index == ResVT.getVectorNumElements());
3786 }
3787
3788 bool X86TargetLowering::isCheapToSpeculateCttz() const {
3789   // Speculate cttz only if we can directly use TZCNT.
3790   return Subtarget->hasBMI();
3791 }
3792
3793 bool X86TargetLowering::isCheapToSpeculateCtlz() const {
3794   // Speculate ctlz only if we can directly use LZCNT.
3795   return Subtarget->hasLZCNT();
3796 }
3797
3798 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3799 /// the specified range (L, H].
3800 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3801   return (Val < 0) || (Val >= Low && Val < Hi);
3802 }
3803
3804 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3805 /// specified value.
3806 static bool isUndefOrEqual(int Val, int CmpVal) {
3807   return (Val < 0 || Val == CmpVal);
3808 }
3809
3810 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3811 /// from position Pos and ending in Pos+Size, falls within the specified
3812 /// sequential range (Low, Low+Size]. or is undef.
3813 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3814                                        unsigned Pos, unsigned Size, int Low) {
3815   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3816     if (!isUndefOrEqual(Mask[i], Low))
3817       return false;
3818   return true;
3819 }
3820
3821 /// isVEXTRACTIndex - Return true if the specified
3822 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3823 /// suitable for instruction that extract 128 or 256 bit vectors
3824 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
3825   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
3826   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3827     return false;
3828
3829   // The index should be aligned on a vecWidth-bit boundary.
3830   uint64_t Index =
3831     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3832
3833   MVT VT = N->getSimpleValueType(0);
3834   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
3835   bool Result = (Index * ElSize) % vecWidth == 0;
3836
3837   return Result;
3838 }
3839
3840 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
3841 /// operand specifies a subvector insert that is suitable for input to
3842 /// insertion of 128 or 256-bit subvectors
3843 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
3844   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
3845   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3846     return false;
3847   // The index should be aligned on a vecWidth-bit boundary.
3848   uint64_t Index =
3849     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3850
3851   MVT VT = N->getSimpleValueType(0);
3852   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
3853   bool Result = (Index * ElSize) % vecWidth == 0;
3854
3855   return Result;
3856 }
3857
3858 bool X86::isVINSERT128Index(SDNode *N) {
3859   return isVINSERTIndex(N, 128);
3860 }
3861
3862 bool X86::isVINSERT256Index(SDNode *N) {
3863   return isVINSERTIndex(N, 256);
3864 }
3865
3866 bool X86::isVEXTRACT128Index(SDNode *N) {
3867   return isVEXTRACTIndex(N, 128);
3868 }
3869
3870 bool X86::isVEXTRACT256Index(SDNode *N) {
3871   return isVEXTRACTIndex(N, 256);
3872 }
3873
3874 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
3875   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
3876   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3877     llvm_unreachable("Illegal extract subvector for VEXTRACT");
3878
3879   uint64_t Index =
3880     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3881
3882   MVT VecVT = N->getOperand(0).getSimpleValueType();
3883   MVT ElVT = VecVT.getVectorElementType();
3884
3885   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
3886   return Index / NumElemsPerChunk;
3887 }
3888
3889 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
3890   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
3891   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3892     llvm_unreachable("Illegal insert subvector for VINSERT");
3893
3894   uint64_t Index =
3895     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3896
3897   MVT VecVT = N->getSimpleValueType(0);
3898   MVT ElVT = VecVT.getVectorElementType();
3899
3900   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
3901   return Index / NumElemsPerChunk;
3902 }
3903
3904 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
3905 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
3906 /// and VINSERTI128 instructions.
3907 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
3908   return getExtractVEXTRACTImmediate(N, 128);
3909 }
3910
3911 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
3912 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
3913 /// and VINSERTI64x4 instructions.
3914 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
3915   return getExtractVEXTRACTImmediate(N, 256);
3916 }
3917
3918 /// getInsertVINSERT128Immediate - Return the appropriate immediate
3919 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
3920 /// and VINSERTI128 instructions.
3921 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
3922   return getInsertVINSERTImmediate(N, 128);
3923 }
3924
3925 /// getInsertVINSERT256Immediate - Return the appropriate immediate
3926 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
3927 /// and VINSERTI64x4 instructions.
3928 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
3929   return getInsertVINSERTImmediate(N, 256);
3930 }
3931
3932 /// isZero - Returns true if Elt is a constant integer zero
3933 static bool isZero(SDValue V) {
3934   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
3935   return C && C->isNullValue();
3936 }
3937
3938 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
3939 /// constant +0.0.
3940 bool X86::isZeroNode(SDValue Elt) {
3941   if (isZero(Elt))
3942     return true;
3943   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
3944     return CFP->getValueAPF().isPosZero();
3945   return false;
3946 }
3947
3948 /// getZeroVector - Returns a vector of specified type with all zero elements.
3949 ///
3950 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
3951                              SelectionDAG &DAG, SDLoc dl) {
3952   assert(VT.isVector() && "Expected a vector type");
3953
3954   // Always build SSE zero vectors as <4 x i32> bitcasted
3955   // to their dest type. This ensures they get CSE'd.
3956   SDValue Vec;
3957   if (VT.is128BitVector()) {  // SSE
3958     if (Subtarget->hasSSE2()) {  // SSE2
3959       SDValue Cst = DAG.getConstant(0, MVT::i32);
3960       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3961     } else { // SSE1
3962       SDValue Cst = DAG.getConstantFP(+0.0, MVT::f32);
3963       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
3964     }
3965   } else if (VT.is256BitVector()) { // AVX
3966     if (Subtarget->hasInt256()) { // AVX2
3967       SDValue Cst = DAG.getConstant(0, MVT::i32);
3968       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
3969       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
3970     } else {
3971       // 256-bit logic and arithmetic instructions in AVX are all
3972       // floating-point, no support for integer ops. Emit fp zeroed vectors.
3973       SDValue Cst = DAG.getConstantFP(+0.0, MVT::f32);
3974       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
3975       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
3976     }
3977   } else if (VT.is512BitVector()) { // AVX-512
3978       SDValue Cst = DAG.getConstant(0, MVT::i32);
3979       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
3980                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
3981       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
3982   } else if (VT.getScalarType() == MVT::i1) {
3983
3984     assert((Subtarget->hasBWI() || VT.getVectorNumElements() <= 16)
3985             && "Unexpected vector type");
3986     assert((Subtarget->hasVLX() || VT.getVectorNumElements() >= 8)
3987             && "Unexpected vector type");
3988     SDValue Cst = DAG.getConstant(0, MVT::i1);
3989     SmallVector<SDValue, 64> Ops(VT.getVectorNumElements(), Cst);
3990     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
3991   } else
3992     llvm_unreachable("Unexpected vector type");
3993
3994   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
3995 }
3996
3997 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
3998                                 SelectionDAG &DAG, SDLoc dl,
3999                                 unsigned vectorWidth) {
4000   assert((vectorWidth == 128 || vectorWidth == 256) &&
4001          "Unsupported vector width");
4002   EVT VT = Vec.getValueType();
4003   EVT ElVT = VT.getVectorElementType();
4004   unsigned Factor = VT.getSizeInBits()/vectorWidth;
4005   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
4006                                   VT.getVectorNumElements()/Factor);
4007
4008   // Extract from UNDEF is UNDEF.
4009   if (Vec.getOpcode() == ISD::UNDEF)
4010     return DAG.getUNDEF(ResultVT);
4011
4012   // Extract the relevant vectorWidth bits.  Generate an EXTRACT_SUBVECTOR
4013   unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
4014
4015   // This is the index of the first element of the vectorWidth-bit chunk
4016   // we want.
4017   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
4018                                * ElemsPerChunk);
4019
4020   // If the input is a buildvector just emit a smaller one.
4021   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
4022     return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
4023                        makeArrayRef(Vec->op_begin() + NormalizedIdxVal,
4024                                     ElemsPerChunk));
4025
4026   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
4027   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec, VecIdx);
4028 }
4029
4030 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
4031 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
4032 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
4033 /// instructions or a simple subregister reference. Idx is an index in the
4034 /// 128 bits we want.  It need not be aligned to a 128-bit boundary.  That makes
4035 /// lowering EXTRACT_VECTOR_ELT operations easier.
4036 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
4037                                    SelectionDAG &DAG, SDLoc dl) {
4038   assert((Vec.getValueType().is256BitVector() ||
4039           Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
4040   return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
4041 }
4042
4043 /// Generate a DAG to grab 256-bits from a 512-bit vector.
4044 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
4045                                    SelectionDAG &DAG, SDLoc dl) {
4046   assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
4047   return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
4048 }
4049
4050 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
4051                                unsigned IdxVal, SelectionDAG &DAG,
4052                                SDLoc dl, unsigned vectorWidth) {
4053   assert((vectorWidth == 128 || vectorWidth == 256) &&
4054          "Unsupported vector width");
4055   // Inserting UNDEF is Result
4056   if (Vec.getOpcode() == ISD::UNDEF)
4057     return Result;
4058   EVT VT = Vec.getValueType();
4059   EVT ElVT = VT.getVectorElementType();
4060   EVT ResultVT = Result.getValueType();
4061
4062   // Insert the relevant vectorWidth bits.
4063   unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
4064
4065   // This is the index of the first element of the vectorWidth-bit chunk
4066   // we want.
4067   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
4068                                * ElemsPerChunk);
4069
4070   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
4071   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec, VecIdx);
4072 }
4073
4074 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
4075 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
4076 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
4077 /// simple superregister reference.  Idx is an index in the 128 bits
4078 /// we want.  It need not be aligned to a 128-bit boundary.  That makes
4079 /// lowering INSERT_VECTOR_ELT operations easier.
4080 static SDValue Insert128BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4081                                   SelectionDAG &DAG, SDLoc dl) {
4082   assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
4083
4084   // For insertion into the zero index (low half) of a 256-bit vector, it is
4085   // more efficient to generate a blend with immediate instead of an insert*128.
4086   // We are still creating an INSERT_SUBVECTOR below with an undef node to
4087   // extend the subvector to the size of the result vector. Make sure that
4088   // we are not recursing on that node by checking for undef here.
4089   if (IdxVal == 0 && Result.getValueType().is256BitVector() &&
4090       Result.getOpcode() != ISD::UNDEF) {
4091     EVT ResultVT = Result.getValueType();
4092     SDValue ZeroIndex = DAG.getIntPtrConstant(0);
4093     SDValue Undef = DAG.getUNDEF(ResultVT);
4094     SDValue Vec256 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Undef,
4095                                  Vec, ZeroIndex);
4096
4097     // The blend instruction, and therefore its mask, depend on the data type.
4098     MVT ScalarType = ResultVT.getScalarType().getSimpleVT();
4099     if (ScalarType.isFloatingPoint()) {
4100       // Choose either vblendps (float) or vblendpd (double).
4101       unsigned ScalarSize = ScalarType.getSizeInBits();
4102       assert((ScalarSize == 64 || ScalarSize == 32) && "Unknown float type");
4103       unsigned MaskVal = (ScalarSize == 64) ? 0x03 : 0x0f;
4104       SDValue Mask = DAG.getConstant(MaskVal, MVT::i8);
4105       return DAG.getNode(X86ISD::BLENDI, dl, ResultVT, Result, Vec256, Mask);
4106     }
4107
4108     const X86Subtarget &Subtarget =
4109     static_cast<const X86Subtarget &>(DAG.getSubtarget());
4110
4111     // AVX2 is needed for 256-bit integer blend support.
4112     // Integers must be cast to 32-bit because there is only vpblendd;
4113     // vpblendw can't be used for this because it has a handicapped mask.
4114
4115     // If we don't have AVX2, then cast to float. Using a wrong domain blend
4116     // is still more efficient than using the wrong domain vinsertf128 that
4117     // will be created by InsertSubVector().
4118     MVT CastVT = Subtarget.hasAVX2() ? MVT::v8i32 : MVT::v8f32;
4119
4120     SDValue Mask = DAG.getConstant(0x0f, MVT::i8);
4121     Vec256 = DAG.getNode(ISD::BITCAST, dl, CastVT, Vec256);
4122     Vec256 = DAG.getNode(X86ISD::BLENDI, dl, CastVT, Result, Vec256, Mask);
4123     return DAG.getNode(ISD::BITCAST, dl, ResultVT, Vec256);
4124   }
4125
4126   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
4127 }
4128
4129 static SDValue Insert256BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4130                                   SelectionDAG &DAG, SDLoc dl) {
4131   assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
4132   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
4133 }
4134
4135 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
4136 /// instructions. This is used because creating CONCAT_VECTOR nodes of
4137 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
4138 /// large BUILD_VECTORS.
4139 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
4140                                    unsigned NumElems, SelectionDAG &DAG,
4141                                    SDLoc dl) {
4142   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4143   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
4144 }
4145
4146 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
4147                                    unsigned NumElems, SelectionDAG &DAG,
4148                                    SDLoc dl) {
4149   SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4150   return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
4151 }
4152
4153 /// getOnesVector - Returns a vector of specified type with all bits set.
4154 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4155 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4156 /// Then bitcast to their original type, ensuring they get CSE'd.
4157 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4158                              SDLoc dl) {
4159   assert(VT.isVector() && "Expected a vector type");
4160
4161   SDValue Cst = DAG.getConstant(~0U, MVT::i32);
4162   SDValue Vec;
4163   if (VT.is256BitVector()) {
4164     if (HasInt256) { // AVX2
4165       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4166       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4167     } else { // AVX
4168       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4169       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4170     }
4171   } else if (VT.is128BitVector()) {
4172     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4173   } else
4174     llvm_unreachable("Unexpected vector type");
4175
4176   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4177 }
4178
4179 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4180 /// operation of specified width.
4181 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4182                        SDValue V2) {
4183   unsigned NumElems = VT.getVectorNumElements();
4184   SmallVector<int, 8> Mask;
4185   Mask.push_back(NumElems);
4186   for (unsigned i = 1; i != NumElems; ++i)
4187     Mask.push_back(i);
4188   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4189 }
4190
4191 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4192 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4193                           SDValue V2) {
4194   unsigned NumElems = VT.getVectorNumElements();
4195   SmallVector<int, 8> Mask;
4196   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4197     Mask.push_back(i);
4198     Mask.push_back(i + NumElems);
4199   }
4200   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4201 }
4202
4203 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4204 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4205                           SDValue V2) {
4206   unsigned NumElems = VT.getVectorNumElements();
4207   SmallVector<int, 8> Mask;
4208   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4209     Mask.push_back(i + Half);
4210     Mask.push_back(i + NumElems + Half);
4211   }
4212   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4213 }
4214
4215 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4216 /// vector of zero or undef vector.  This produces a shuffle where the low
4217 /// element of V2 is swizzled into the zero/undef vector, landing at element
4218 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4219 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4220                                            bool IsZero,
4221                                            const X86Subtarget *Subtarget,
4222                                            SelectionDAG &DAG) {
4223   MVT VT = V2.getSimpleValueType();
4224   SDValue V1 = IsZero
4225     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
4226   unsigned NumElems = VT.getVectorNumElements();
4227   SmallVector<int, 16> MaskVec;
4228   for (unsigned i = 0; i != NumElems; ++i)
4229     // If this is the insertion idx, put the low elt of V2 here.
4230     MaskVec.push_back(i == Idx ? NumElems : i);
4231   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
4232 }
4233
4234 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4235 /// target specific opcode. Returns true if the Mask could be calculated. Sets
4236 /// IsUnary to true if only uses one source. Note that this will set IsUnary for
4237 /// shuffles which use a single input multiple times, and in those cases it will
4238 /// adjust the mask to only have indices within that single input.
4239 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4240                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
4241   unsigned NumElems = VT.getVectorNumElements();
4242   SDValue ImmN;
4243
4244   IsUnary = false;
4245   bool IsFakeUnary = false;
4246   switch(N->getOpcode()) {
4247   case X86ISD::BLENDI:
4248     ImmN = N->getOperand(N->getNumOperands()-1);
4249     DecodeBLENDMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4250     break;
4251   case X86ISD::SHUFP:
4252     ImmN = N->getOperand(N->getNumOperands()-1);
4253     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4254     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4255     break;
4256   case X86ISD::UNPCKH:
4257     DecodeUNPCKHMask(VT, Mask);
4258     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4259     break;
4260   case X86ISD::UNPCKL:
4261     DecodeUNPCKLMask(VT, Mask);
4262     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4263     break;
4264   case X86ISD::MOVHLPS:
4265     DecodeMOVHLPSMask(NumElems, Mask);
4266     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4267     break;
4268   case X86ISD::MOVLHPS:
4269     DecodeMOVLHPSMask(NumElems, Mask);
4270     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4271     break;
4272   case X86ISD::PALIGNR:
4273     ImmN = N->getOperand(N->getNumOperands()-1);
4274     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4275     break;
4276   case X86ISD::PSHUFD:
4277   case X86ISD::VPERMILPI:
4278     ImmN = N->getOperand(N->getNumOperands()-1);
4279     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4280     IsUnary = true;
4281     break;
4282   case X86ISD::PSHUFHW:
4283     ImmN = N->getOperand(N->getNumOperands()-1);
4284     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4285     IsUnary = true;
4286     break;
4287   case X86ISD::PSHUFLW:
4288     ImmN = N->getOperand(N->getNumOperands()-1);
4289     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4290     IsUnary = true;
4291     break;
4292   case X86ISD::PSHUFB: {
4293     IsUnary = true;
4294     SDValue MaskNode = N->getOperand(1);
4295     while (MaskNode->getOpcode() == ISD::BITCAST)
4296       MaskNode = MaskNode->getOperand(0);
4297
4298     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4299       // If we have a build-vector, then things are easy.
4300       EVT VT = MaskNode.getValueType();
4301       assert(VT.isVector() &&
4302              "Can't produce a non-vector with a build_vector!");
4303       if (!VT.isInteger())
4304         return false;
4305
4306       int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
4307
4308       SmallVector<uint64_t, 32> RawMask;
4309       for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
4310         SDValue Op = MaskNode->getOperand(i);
4311         if (Op->getOpcode() == ISD::UNDEF) {
4312           RawMask.push_back((uint64_t)SM_SentinelUndef);
4313           continue;
4314         }
4315         auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4316         if (!CN)
4317           return false;
4318         APInt MaskElement = CN->getAPIntValue();
4319
4320         // We now have to decode the element which could be any integer size and
4321         // extract each byte of it.
4322         for (int j = 0; j < NumBytesPerElement; ++j) {
4323           // Note that this is x86 and so always little endian: the low byte is
4324           // the first byte of the mask.
4325           RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
4326           MaskElement = MaskElement.lshr(8);
4327         }
4328       }
4329       DecodePSHUFBMask(RawMask, Mask);
4330       break;
4331     }
4332
4333     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4334     if (!MaskLoad)
4335       return false;
4336
4337     SDValue Ptr = MaskLoad->getBasePtr();
4338     if (Ptr->getOpcode() == X86ISD::Wrapper)
4339       Ptr = Ptr->getOperand(0);
4340
4341     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4342     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4343       return false;
4344
4345     if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
4346       DecodePSHUFBMask(C, Mask);
4347       if (Mask.empty())
4348         return false;
4349       break;
4350     }
4351
4352     return false;
4353   }
4354   case X86ISD::VPERMI:
4355     ImmN = N->getOperand(N->getNumOperands()-1);
4356     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4357     IsUnary = true;
4358     break;
4359   case X86ISD::MOVSS:
4360   case X86ISD::MOVSD:
4361     DecodeScalarMoveMask(VT, /* IsLoad */ false, Mask);
4362     break;
4363   case X86ISD::VPERM2X128:
4364     ImmN = N->getOperand(N->getNumOperands()-1);
4365     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4366     if (Mask.empty()) return false;
4367     break;
4368   case X86ISD::MOVSLDUP:
4369     DecodeMOVSLDUPMask(VT, Mask);
4370     IsUnary = true;
4371     break;
4372   case X86ISD::MOVSHDUP:
4373     DecodeMOVSHDUPMask(VT, Mask);
4374     IsUnary = true;
4375     break;
4376   case X86ISD::MOVDDUP:
4377     DecodeMOVDDUPMask(VT, Mask);
4378     IsUnary = true;
4379     break;
4380   case X86ISD::MOVLHPD:
4381   case X86ISD::MOVLPD:
4382   case X86ISD::MOVLPS:
4383     // Not yet implemented
4384     return false;
4385   default: llvm_unreachable("unknown target shuffle node");
4386   }
4387
4388   // If we have a fake unary shuffle, the shuffle mask is spread across two
4389   // inputs that are actually the same node. Re-map the mask to always point
4390   // into the first input.
4391   if (IsFakeUnary)
4392     for (int &M : Mask)
4393       if (M >= (int)Mask.size())
4394         M -= Mask.size();
4395
4396   return true;
4397 }
4398
4399 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4400 /// element of the result of the vector shuffle.
4401 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4402                                    unsigned Depth) {
4403   if (Depth == 6)
4404     return SDValue();  // Limit search depth.
4405
4406   SDValue V = SDValue(N, 0);
4407   EVT VT = V.getValueType();
4408   unsigned Opcode = V.getOpcode();
4409
4410   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4411   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4412     int Elt = SV->getMaskElt(Index);
4413
4414     if (Elt < 0)
4415       return DAG.getUNDEF(VT.getVectorElementType());
4416
4417     unsigned NumElems = VT.getVectorNumElements();
4418     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4419                                          : SV->getOperand(1);
4420     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4421   }
4422
4423   // Recurse into target specific vector shuffles to find scalars.
4424   if (isTargetShuffle(Opcode)) {
4425     MVT ShufVT = V.getSimpleValueType();
4426     unsigned NumElems = ShufVT.getVectorNumElements();
4427     SmallVector<int, 16> ShuffleMask;
4428     bool IsUnary;
4429
4430     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4431       return SDValue();
4432
4433     int Elt = ShuffleMask[Index];
4434     if (Elt < 0)
4435       return DAG.getUNDEF(ShufVT.getVectorElementType());
4436
4437     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4438                                          : N->getOperand(1);
4439     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4440                                Depth+1);
4441   }
4442
4443   // Actual nodes that may contain scalar elements
4444   if (Opcode == ISD::BITCAST) {
4445     V = V.getOperand(0);
4446     EVT SrcVT = V.getValueType();
4447     unsigned NumElems = VT.getVectorNumElements();
4448
4449     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4450       return SDValue();
4451   }
4452
4453   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4454     return (Index == 0) ? V.getOperand(0)
4455                         : DAG.getUNDEF(VT.getVectorElementType());
4456
4457   if (V.getOpcode() == ISD::BUILD_VECTOR)
4458     return V.getOperand(Index);
4459
4460   return SDValue();
4461 }
4462
4463 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4464 ///
4465 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4466                                        unsigned NumNonZero, unsigned NumZero,
4467                                        SelectionDAG &DAG,
4468                                        const X86Subtarget* Subtarget,
4469                                        const TargetLowering &TLI) {
4470   if (NumNonZero > 8)
4471     return SDValue();
4472
4473   SDLoc dl(Op);
4474   SDValue V;
4475   bool First = true;
4476
4477   // SSE4.1 - use PINSRB to insert each byte directly.
4478   if (Subtarget->hasSSE41()) {
4479     for (unsigned i = 0; i < 16; ++i) {
4480       bool isNonZero = (NonZeros & (1 << i)) != 0;
4481       if (isNonZero) {
4482         if (First) {
4483           if (NumZero)
4484             V = getZeroVector(MVT::v16i8, Subtarget, DAG, dl);
4485           else
4486             V = DAG.getUNDEF(MVT::v16i8);
4487           First = false;
4488         }
4489         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4490                         MVT::v16i8, V, Op.getOperand(i),
4491                         DAG.getIntPtrConstant(i));
4492       }
4493     }
4494
4495     return V;
4496   }
4497
4498   // Pre-SSE4.1 - merge byte pairs and insert with PINSRW.
4499   for (unsigned i = 0; i < 16; ++i) {
4500     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4501     if (ThisIsNonZero && First) {
4502       if (NumZero)
4503         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4504       else
4505         V = DAG.getUNDEF(MVT::v8i16);
4506       First = false;
4507     }
4508
4509     if ((i & 1) != 0) {
4510       SDValue ThisElt, LastElt;
4511       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4512       if (LastIsNonZero) {
4513         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4514                               MVT::i16, Op.getOperand(i-1));
4515       }
4516       if (ThisIsNonZero) {
4517         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4518         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4519                               ThisElt, DAG.getConstant(8, MVT::i8));
4520         if (LastIsNonZero)
4521           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4522       } else
4523         ThisElt = LastElt;
4524
4525       if (ThisElt.getNode())
4526         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4527                         DAG.getIntPtrConstant(i/2));
4528     }
4529   }
4530
4531   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4532 }
4533
4534 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4535 ///
4536 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4537                                      unsigned NumNonZero, unsigned NumZero,
4538                                      SelectionDAG &DAG,
4539                                      const X86Subtarget* Subtarget,
4540                                      const TargetLowering &TLI) {
4541   if (NumNonZero > 4)
4542     return SDValue();
4543
4544   SDLoc dl(Op);
4545   SDValue V;
4546   bool First = true;
4547   for (unsigned i = 0; i < 8; ++i) {
4548     bool isNonZero = (NonZeros & (1 << i)) != 0;
4549     if (isNonZero) {
4550       if (First) {
4551         if (NumZero)
4552           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4553         else
4554           V = DAG.getUNDEF(MVT::v8i16);
4555         First = false;
4556       }
4557       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4558                       MVT::v8i16, V, Op.getOperand(i),
4559                       DAG.getIntPtrConstant(i));
4560     }
4561   }
4562
4563   return V;
4564 }
4565
4566 /// LowerBuildVectorv4x32 - Custom lower build_vector of v4i32 or v4f32.
4567 static SDValue LowerBuildVectorv4x32(SDValue Op, SelectionDAG &DAG,
4568                                      const X86Subtarget *Subtarget,
4569                                      const TargetLowering &TLI) {
4570   // Find all zeroable elements.
4571   std::bitset<4> Zeroable;
4572   for (int i=0; i < 4; ++i) {
4573     SDValue Elt = Op->getOperand(i);
4574     Zeroable[i] = (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt));
4575   }
4576   assert(Zeroable.size() - Zeroable.count() > 1 &&
4577          "We expect at least two non-zero elements!");
4578
4579   // We only know how to deal with build_vector nodes where elements are either
4580   // zeroable or extract_vector_elt with constant index.
4581   SDValue FirstNonZero;
4582   unsigned FirstNonZeroIdx;
4583   for (unsigned i=0; i < 4; ++i) {
4584     if (Zeroable[i])
4585       continue;
4586     SDValue Elt = Op->getOperand(i);
4587     if (Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4588         !isa<ConstantSDNode>(Elt.getOperand(1)))
4589       return SDValue();
4590     // Make sure that this node is extracting from a 128-bit vector.
4591     MVT VT = Elt.getOperand(0).getSimpleValueType();
4592     if (!VT.is128BitVector())
4593       return SDValue();
4594     if (!FirstNonZero.getNode()) {
4595       FirstNonZero = Elt;
4596       FirstNonZeroIdx = i;
4597     }
4598   }
4599
4600   assert(FirstNonZero.getNode() && "Unexpected build vector of all zeros!");
4601   SDValue V1 = FirstNonZero.getOperand(0);
4602   MVT VT = V1.getSimpleValueType();
4603
4604   // See if this build_vector can be lowered as a blend with zero.
4605   SDValue Elt;
4606   unsigned EltMaskIdx, EltIdx;
4607   int Mask[4];
4608   for (EltIdx = 0; EltIdx < 4; ++EltIdx) {
4609     if (Zeroable[EltIdx]) {
4610       // The zero vector will be on the right hand side.
4611       Mask[EltIdx] = EltIdx+4;
4612       continue;
4613     }
4614
4615     Elt = Op->getOperand(EltIdx);
4616     // By construction, Elt is a EXTRACT_VECTOR_ELT with constant index.
4617     EltMaskIdx = cast<ConstantSDNode>(Elt.getOperand(1))->getZExtValue();
4618     if (Elt.getOperand(0) != V1 || EltMaskIdx != EltIdx)
4619       break;
4620     Mask[EltIdx] = EltIdx;
4621   }
4622
4623   if (EltIdx == 4) {
4624     // Let the shuffle legalizer deal with blend operations.
4625     SDValue VZero = getZeroVector(VT, Subtarget, DAG, SDLoc(Op));
4626     if (V1.getSimpleValueType() != VT)
4627       V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), VT, V1);
4628     return DAG.getVectorShuffle(VT, SDLoc(V1), V1, VZero, &Mask[0]);
4629   }
4630
4631   // See if we can lower this build_vector to a INSERTPS.
4632   if (!Subtarget->hasSSE41())
4633     return SDValue();
4634
4635   SDValue V2 = Elt.getOperand(0);
4636   if (Elt == FirstNonZero && EltIdx == FirstNonZeroIdx)
4637     V1 = SDValue();
4638
4639   bool CanFold = true;
4640   for (unsigned i = EltIdx + 1; i < 4 && CanFold; ++i) {
4641     if (Zeroable[i])
4642       continue;
4643
4644     SDValue Current = Op->getOperand(i);
4645     SDValue SrcVector = Current->getOperand(0);
4646     if (!V1.getNode())
4647       V1 = SrcVector;
4648     CanFold = SrcVector == V1 &&
4649       cast<ConstantSDNode>(Current.getOperand(1))->getZExtValue() == i;
4650   }
4651
4652   if (!CanFold)
4653     return SDValue();
4654
4655   assert(V1.getNode() && "Expected at least two non-zero elements!");
4656   if (V1.getSimpleValueType() != MVT::v4f32)
4657     V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), MVT::v4f32, V1);
4658   if (V2.getSimpleValueType() != MVT::v4f32)
4659     V2 = DAG.getNode(ISD::BITCAST, SDLoc(V2), MVT::v4f32, V2);
4660
4661   // Ok, we can emit an INSERTPS instruction.
4662   unsigned ZMask = Zeroable.to_ulong();
4663
4664   unsigned InsertPSMask = EltMaskIdx << 6 | EltIdx << 4 | ZMask;
4665   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
4666   SDValue Result = DAG.getNode(X86ISD::INSERTPS, SDLoc(Op), MVT::v4f32, V1, V2,
4667                                DAG.getIntPtrConstant(InsertPSMask));
4668   return DAG.getNode(ISD::BITCAST, SDLoc(Op), VT, Result);
4669 }
4670
4671 /// Return a vector logical shift node.
4672 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4673                          unsigned NumBits, SelectionDAG &DAG,
4674                          const TargetLowering &TLI, SDLoc dl) {
4675   assert(VT.is128BitVector() && "Unknown type for VShift");
4676   MVT ShVT = MVT::v2i64;
4677   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4678   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4679   MVT ScalarShiftTy = TLI.getScalarShiftAmountTy(SrcOp.getValueType());
4680   assert(NumBits % 8 == 0 && "Only support byte sized shifts");
4681   SDValue ShiftVal = DAG.getConstant(NumBits/8, ScalarShiftTy);
4682   return DAG.getNode(ISD::BITCAST, dl, VT,
4683                      DAG.getNode(Opc, dl, ShVT, SrcOp, ShiftVal));
4684 }
4685
4686 static SDValue
4687 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
4688
4689   // Check if the scalar load can be widened into a vector load. And if
4690   // the address is "base + cst" see if the cst can be "absorbed" into
4691   // the shuffle mask.
4692   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4693     SDValue Ptr = LD->getBasePtr();
4694     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4695       return SDValue();
4696     EVT PVT = LD->getValueType(0);
4697     if (PVT != MVT::i32 && PVT != MVT::f32)
4698       return SDValue();
4699
4700     int FI = -1;
4701     int64_t Offset = 0;
4702     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4703       FI = FINode->getIndex();
4704       Offset = 0;
4705     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4706                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4707       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4708       Offset = Ptr.getConstantOperandVal(1);
4709       Ptr = Ptr.getOperand(0);
4710     } else {
4711       return SDValue();
4712     }
4713
4714     // FIXME: 256-bit vector instructions don't require a strict alignment,
4715     // improve this code to support it better.
4716     unsigned RequiredAlign = VT.getSizeInBits()/8;
4717     SDValue Chain = LD->getChain();
4718     // Make sure the stack object alignment is at least 16 or 32.
4719     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4720     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4721       if (MFI->isFixedObjectIndex(FI)) {
4722         // Can't change the alignment. FIXME: It's possible to compute
4723         // the exact stack offset and reference FI + adjust offset instead.
4724         // If someone *really* cares about this. That's the way to implement it.
4725         return SDValue();
4726       } else {
4727         MFI->setObjectAlignment(FI, RequiredAlign);
4728       }
4729     }
4730
4731     // (Offset % 16 or 32) must be multiple of 4. Then address is then
4732     // Ptr + (Offset & ~15).
4733     if (Offset < 0)
4734       return SDValue();
4735     if ((Offset % RequiredAlign) & 3)
4736       return SDValue();
4737     int64_t StartOffset = Offset & ~(RequiredAlign-1);
4738     if (StartOffset)
4739       Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
4740                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4741
4742     int EltNo = (Offset - StartOffset) >> 2;
4743     unsigned NumElems = VT.getVectorNumElements();
4744
4745     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4746     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4747                              LD->getPointerInfo().getWithOffset(StartOffset),
4748                              false, false, false, 0);
4749
4750     SmallVector<int, 8> Mask(NumElems, EltNo);
4751
4752     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
4753   }
4754
4755   return SDValue();
4756 }
4757
4758 /// Given the initializing elements 'Elts' of a vector of type 'VT', see if the
4759 /// elements can be replaced by a single large load which has the same value as
4760 /// a build_vector or insert_subvector whose loaded operands are 'Elts'.
4761 ///
4762 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4763 ///
4764 /// FIXME: we'd also like to handle the case where the last elements are zero
4765 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4766 /// There's even a handy isZeroNode for that purpose.
4767 static SDValue EltsFromConsecutiveLoads(EVT VT, ArrayRef<SDValue> Elts,
4768                                         SDLoc &DL, SelectionDAG &DAG,
4769                                         bool isAfterLegalize) {
4770   unsigned NumElems = Elts.size();
4771
4772   LoadSDNode *LDBase = nullptr;
4773   unsigned LastLoadedElt = -1U;
4774
4775   // For each element in the initializer, see if we've found a load or an undef.
4776   // If we don't find an initial load element, or later load elements are
4777   // non-consecutive, bail out.
4778   for (unsigned i = 0; i < NumElems; ++i) {
4779     SDValue Elt = Elts[i];
4780     // Look through a bitcast.
4781     if (Elt.getNode() && Elt.getOpcode() == ISD::BITCAST)
4782       Elt = Elt.getOperand(0);
4783     if (!Elt.getNode() ||
4784         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4785       return SDValue();
4786     if (!LDBase) {
4787       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4788         return SDValue();
4789       LDBase = cast<LoadSDNode>(Elt.getNode());
4790       LastLoadedElt = i;
4791       continue;
4792     }
4793     if (Elt.getOpcode() == ISD::UNDEF)
4794       continue;
4795
4796     LoadSDNode *LD = cast<LoadSDNode>(Elt);
4797     EVT LdVT = Elt.getValueType();
4798     // Each loaded element must be the correct fractional portion of the
4799     // requested vector load.
4800     if (LdVT.getSizeInBits() != VT.getSizeInBits() / NumElems)
4801       return SDValue();
4802     if (!DAG.isConsecutiveLoad(LD, LDBase, LdVT.getSizeInBits() / 8, i))
4803       return SDValue();
4804     LastLoadedElt = i;
4805   }
4806
4807   // If we have found an entire vector of loads and undefs, then return a large
4808   // load of the entire vector width starting at the base pointer.  If we found
4809   // consecutive loads for the low half, generate a vzext_load node.
4810   if (LastLoadedElt == NumElems - 1) {
4811     assert(LDBase && "Did not find base load for merging consecutive loads");
4812     EVT EltVT = LDBase->getValueType(0);
4813     // Ensure that the input vector size for the merged loads matches the
4814     // cumulative size of the input elements.
4815     if (VT.getSizeInBits() != EltVT.getSizeInBits() * NumElems)
4816       return SDValue();
4817
4818     if (isAfterLegalize &&
4819         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
4820       return SDValue();
4821
4822     SDValue NewLd = SDValue();
4823
4824     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4825                         LDBase->getPointerInfo(), LDBase->isVolatile(),
4826                         LDBase->isNonTemporal(), LDBase->isInvariant(),
4827                         LDBase->getAlignment());
4828
4829     if (LDBase->hasAnyUseOfValue(1)) {
4830       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
4831                                      SDValue(LDBase, 1),
4832                                      SDValue(NewLd.getNode(), 1));
4833       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
4834       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
4835                              SDValue(NewLd.getNode(), 1));
4836     }
4837
4838     return NewLd;
4839   }
4840
4841   //TODO: The code below fires only for for loading the low v2i32 / v2f32
4842   //of a v4i32 / v4f32. It's probably worth generalizing.
4843   EVT EltVT = VT.getVectorElementType();
4844   if (NumElems == 4 && LastLoadedElt == 1 && (EltVT.getSizeInBits() == 32) &&
4845       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
4846     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4847     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4848     SDValue ResNode =
4849         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
4850                                 LDBase->getPointerInfo(),
4851                                 LDBase->getAlignment(),
4852                                 false/*isVolatile*/, true/*ReadMem*/,
4853                                 false/*WriteMem*/);
4854
4855     // Make sure the newly-created LOAD is in the same position as LDBase in
4856     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
4857     // update uses of LDBase's output chain to use the TokenFactor.
4858     if (LDBase->hasAnyUseOfValue(1)) {
4859       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
4860                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
4861       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
4862       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
4863                              SDValue(ResNode.getNode(), 1));
4864     }
4865
4866     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
4867   }
4868   return SDValue();
4869 }
4870
4871 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
4872 /// to generate a splat value for the following cases:
4873 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
4874 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
4875 /// a scalar load, or a constant.
4876 /// The VBROADCAST node is returned when a pattern is found,
4877 /// or SDValue() otherwise.
4878 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
4879                                     SelectionDAG &DAG) {
4880   // VBROADCAST requires AVX.
4881   // TODO: Splats could be generated for non-AVX CPUs using SSE
4882   // instructions, but there's less potential gain for only 128-bit vectors.
4883   if (!Subtarget->hasAVX())
4884     return SDValue();
4885
4886   MVT VT = Op.getSimpleValueType();
4887   SDLoc dl(Op);
4888
4889   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
4890          "Unsupported vector type for broadcast.");
4891
4892   SDValue Ld;
4893   bool ConstSplatVal;
4894
4895   switch (Op.getOpcode()) {
4896     default:
4897       // Unknown pattern found.
4898       return SDValue();
4899
4900     case ISD::BUILD_VECTOR: {
4901       auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
4902       BitVector UndefElements;
4903       SDValue Splat = BVOp->getSplatValue(&UndefElements);
4904
4905       // We need a splat of a single value to use broadcast, and it doesn't
4906       // make any sense if the value is only in one element of the vector.
4907       if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
4908         return SDValue();
4909
4910       Ld = Splat;
4911       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
4912                        Ld.getOpcode() == ISD::ConstantFP);
4913
4914       // Make sure that all of the users of a non-constant load are from the
4915       // BUILD_VECTOR node.
4916       if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
4917         return SDValue();
4918       break;
4919     }
4920
4921     case ISD::VECTOR_SHUFFLE: {
4922       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4923
4924       // Shuffles must have a splat mask where the first element is
4925       // broadcasted.
4926       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
4927         return SDValue();
4928
4929       SDValue Sc = Op.getOperand(0);
4930       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
4931           Sc.getOpcode() != ISD::BUILD_VECTOR) {
4932
4933         if (!Subtarget->hasInt256())
4934           return SDValue();
4935
4936         // Use the register form of the broadcast instruction available on AVX2.
4937         if (VT.getSizeInBits() >= 256)
4938           Sc = Extract128BitVector(Sc, 0, DAG, dl);
4939         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
4940       }
4941
4942       Ld = Sc.getOperand(0);
4943       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
4944                        Ld.getOpcode() == ISD::ConstantFP);
4945
4946       // The scalar_to_vector node and the suspected
4947       // load node must have exactly one user.
4948       // Constants may have multiple users.
4949
4950       // AVX-512 has register version of the broadcast
4951       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
4952         Ld.getValueType().getSizeInBits() >= 32;
4953       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
4954           !hasRegVer))
4955         return SDValue();
4956       break;
4957     }
4958   }
4959
4960   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
4961   bool IsGE256 = (VT.getSizeInBits() >= 256);
4962
4963   // When optimizing for size, generate up to 5 extra bytes for a broadcast
4964   // instruction to save 8 or more bytes of constant pool data.
4965   // TODO: If multiple splats are generated to load the same constant,
4966   // it may be detrimental to overall size. There needs to be a way to detect
4967   // that condition to know if this is truly a size win.
4968   const Function *F = DAG.getMachineFunction().getFunction();
4969   bool OptForSize = F->hasFnAttribute(Attribute::OptimizeForSize);
4970
4971   // Handle broadcasting a single constant scalar from the constant pool
4972   // into a vector.
4973   // On Sandybridge (no AVX2), it is still better to load a constant vector
4974   // from the constant pool and not to broadcast it from a scalar.
4975   // But override that restriction when optimizing for size.
4976   // TODO: Check if splatting is recommended for other AVX-capable CPUs.
4977   if (ConstSplatVal && (Subtarget->hasAVX2() || OptForSize)) {
4978     EVT CVT = Ld.getValueType();
4979     assert(!CVT.isVector() && "Must not broadcast a vector type");
4980
4981     // Splat f32, i32, v4f64, v4i64 in all cases with AVX2.
4982     // For size optimization, also splat v2f64 and v2i64, and for size opt
4983     // with AVX2, also splat i8 and i16.
4984     // With pattern matching, the VBROADCAST node may become a VMOVDDUP.
4985     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
4986         (OptForSize && (ScalarSize == 64 || Subtarget->hasAVX2()))) {
4987       const Constant *C = nullptr;
4988       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
4989         C = CI->getConstantIntValue();
4990       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
4991         C = CF->getConstantFPValue();
4992
4993       assert(C && "Invalid constant type");
4994
4995       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4996       SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
4997       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
4998       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
4999                        MachinePointerInfo::getConstantPool(),
5000                        false, false, false, Alignment);
5001
5002       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5003     }
5004   }
5005
5006   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5007
5008   // Handle AVX2 in-register broadcasts.
5009   if (!IsLoad && Subtarget->hasInt256() &&
5010       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5011     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5012
5013   // The scalar source must be a normal load.
5014   if (!IsLoad)
5015     return SDValue();
5016
5017   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5018       (Subtarget->hasVLX() && ScalarSize == 64))
5019     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5020
5021   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5022   // double since there is no vbroadcastsd xmm
5023   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5024     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5025       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5026   }
5027
5028   // Unsupported broadcast.
5029   return SDValue();
5030 }
5031
5032 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5033 /// underlying vector and index.
5034 ///
5035 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5036 /// index.
5037 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5038                                          SDValue ExtIdx) {
5039   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5040   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5041     return Idx;
5042
5043   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5044   // lowered this:
5045   //   (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5046   // to:
5047   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
5048   //                           (extract_subvector (v8f32 %vreg0), Constant<4>),
5049   //                           undef)
5050   //                       Constant<0>)
5051   // In this case the vector is the extract_subvector expression and the index
5052   // is 2, as specified by the shuffle.
5053   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5054   SDValue ShuffleVec = SVOp->getOperand(0);
5055   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5056   assert(ShuffleVecVT.getVectorElementType() ==
5057          ExtractedFromVec.getSimpleValueType().getVectorElementType());
5058
5059   int ShuffleIdx = SVOp->getMaskElt(Idx);
5060   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5061     ExtractedFromVec = ShuffleVec;
5062     return ShuffleIdx;
5063   }
5064   return Idx;
5065 }
5066
5067 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5068   MVT VT = Op.getSimpleValueType();
5069
5070   // Skip if insert_vec_elt is not supported.
5071   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5072   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5073     return SDValue();
5074
5075   SDLoc DL(Op);
5076   unsigned NumElems = Op.getNumOperands();
5077
5078   SDValue VecIn1;
5079   SDValue VecIn2;
5080   SmallVector<unsigned, 4> InsertIndices;
5081   SmallVector<int, 8> Mask(NumElems, -1);
5082
5083   for (unsigned i = 0; i != NumElems; ++i) {
5084     unsigned Opc = Op.getOperand(i).getOpcode();
5085
5086     if (Opc == ISD::UNDEF)
5087       continue;
5088
5089     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5090       // Quit if more than 1 elements need inserting.
5091       if (InsertIndices.size() > 1)
5092         return SDValue();
5093
5094       InsertIndices.push_back(i);
5095       continue;
5096     }
5097
5098     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5099     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5100     // Quit if non-constant index.
5101     if (!isa<ConstantSDNode>(ExtIdx))
5102       return SDValue();
5103     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5104
5105     // Quit if extracted from vector of different type.
5106     if (ExtractedFromVec.getValueType() != VT)
5107       return SDValue();
5108
5109     if (!VecIn1.getNode())
5110       VecIn1 = ExtractedFromVec;
5111     else if (VecIn1 != ExtractedFromVec) {
5112       if (!VecIn2.getNode())
5113         VecIn2 = ExtractedFromVec;
5114       else if (VecIn2 != ExtractedFromVec)
5115         // Quit if more than 2 vectors to shuffle
5116         return SDValue();
5117     }
5118
5119     if (ExtractedFromVec == VecIn1)
5120       Mask[i] = Idx;
5121     else if (ExtractedFromVec == VecIn2)
5122       Mask[i] = Idx + NumElems;
5123   }
5124
5125   if (!VecIn1.getNode())
5126     return SDValue();
5127
5128   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5129   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5130   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5131     unsigned Idx = InsertIndices[i];
5132     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5133                      DAG.getIntPtrConstant(Idx));
5134   }
5135
5136   return NV;
5137 }
5138
5139 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5140 SDValue
5141 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5142
5143   MVT VT = Op.getSimpleValueType();
5144   assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
5145          "Unexpected type in LowerBUILD_VECTORvXi1!");
5146
5147   SDLoc dl(Op);
5148   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5149     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
5150     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5151     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5152   }
5153
5154   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5155     SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
5156     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5157     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5158   }
5159
5160   bool AllContants = true;
5161   uint64_t Immediate = 0;
5162   int NonConstIdx = -1;
5163   bool IsSplat = true;
5164   unsigned NumNonConsts = 0;
5165   unsigned NumConsts = 0;
5166   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5167     SDValue In = Op.getOperand(idx);
5168     if (In.getOpcode() == ISD::UNDEF)
5169       continue;
5170     if (!isa<ConstantSDNode>(In)) {
5171       AllContants = false;
5172       NonConstIdx = idx;
5173       NumNonConsts++;
5174     } else {
5175       NumConsts++;
5176       if (cast<ConstantSDNode>(In)->getZExtValue())
5177       Immediate |= (1ULL << idx);
5178     }
5179     if (In != Op.getOperand(0))
5180       IsSplat = false;
5181   }
5182
5183   if (AllContants) {
5184     SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
5185       DAG.getConstant(Immediate, MVT::i16));
5186     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
5187                        DAG.getIntPtrConstant(0));
5188   }
5189
5190   if (NumNonConsts == 1 && NonConstIdx != 0) {
5191     SDValue DstVec;
5192     if (NumConsts) {
5193       SDValue VecAsImm = DAG.getConstant(Immediate,
5194                                          MVT::getIntegerVT(VT.getSizeInBits()));
5195       DstVec = DAG.getNode(ISD::BITCAST, dl, VT, VecAsImm);
5196     }
5197     else
5198       DstVec = DAG.getUNDEF(VT);
5199     return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5200                        Op.getOperand(NonConstIdx),
5201                        DAG.getIntPtrConstant(NonConstIdx));
5202   }
5203   if (!IsSplat && (NonConstIdx != 0))
5204     llvm_unreachable("Unsupported BUILD_VECTOR operation");
5205   MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
5206   SDValue Select;
5207   if (IsSplat)
5208     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
5209                           DAG.getConstant(-1, SelectVT),
5210                           DAG.getConstant(0, SelectVT));
5211   else
5212     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
5213                          DAG.getConstant((Immediate | 1), SelectVT),
5214                          DAG.getConstant(Immediate, SelectVT));
5215   return DAG.getNode(ISD::BITCAST, dl, VT, Select);
5216 }
5217
5218 /// \brief Return true if \p N implements a horizontal binop and return the
5219 /// operands for the horizontal binop into V0 and V1.
5220 ///
5221 /// This is a helper function of LowerToHorizontalOp().
5222 /// This function checks that the build_vector \p N in input implements a
5223 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
5224 /// operation to match.
5225 /// For example, if \p Opcode is equal to ISD::ADD, then this function
5226 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
5227 /// is equal to ISD::SUB, then this function checks if this is a horizontal
5228 /// arithmetic sub.
5229 ///
5230 /// This function only analyzes elements of \p N whose indices are
5231 /// in range [BaseIdx, LastIdx).
5232 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
5233                               SelectionDAG &DAG,
5234                               unsigned BaseIdx, unsigned LastIdx,
5235                               SDValue &V0, SDValue &V1) {
5236   EVT VT = N->getValueType(0);
5237
5238   assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
5239   assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
5240          "Invalid Vector in input!");
5241
5242   bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
5243   bool CanFold = true;
5244   unsigned ExpectedVExtractIdx = BaseIdx;
5245   unsigned NumElts = LastIdx - BaseIdx;
5246   V0 = DAG.getUNDEF(VT);
5247   V1 = DAG.getUNDEF(VT);
5248
5249   // Check if N implements a horizontal binop.
5250   for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
5251     SDValue Op = N->getOperand(i + BaseIdx);
5252
5253     // Skip UNDEFs.
5254     if (Op->getOpcode() == ISD::UNDEF) {
5255       // Update the expected vector extract index.
5256       if (i * 2 == NumElts)
5257         ExpectedVExtractIdx = BaseIdx;
5258       ExpectedVExtractIdx += 2;
5259       continue;
5260     }
5261
5262     CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
5263
5264     if (!CanFold)
5265       break;
5266
5267     SDValue Op0 = Op.getOperand(0);
5268     SDValue Op1 = Op.getOperand(1);
5269
5270     // Try to match the following pattern:
5271     // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
5272     CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5273         Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5274         Op0.getOperand(0) == Op1.getOperand(0) &&
5275         isa<ConstantSDNode>(Op0.getOperand(1)) &&
5276         isa<ConstantSDNode>(Op1.getOperand(1)));
5277     if (!CanFold)
5278       break;
5279
5280     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5281     unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
5282
5283     if (i * 2 < NumElts) {
5284       if (V0.getOpcode() == ISD::UNDEF) {
5285         V0 = Op0.getOperand(0);
5286         if (V0.getValueType() != VT)
5287           return false;
5288       }
5289     } else {
5290       if (V1.getOpcode() == ISD::UNDEF) {
5291         V1 = Op0.getOperand(0);
5292         if (V1.getValueType() != VT)
5293           return false;
5294       }
5295       if (i * 2 == NumElts)
5296         ExpectedVExtractIdx = BaseIdx;
5297     }
5298
5299     SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
5300     if (I0 == ExpectedVExtractIdx)
5301       CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
5302     else if (IsCommutable && I1 == ExpectedVExtractIdx) {
5303       // Try to match the following dag sequence:
5304       // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
5305       CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
5306     } else
5307       CanFold = false;
5308
5309     ExpectedVExtractIdx += 2;
5310   }
5311
5312   return CanFold;
5313 }
5314
5315 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
5316 /// a concat_vector.
5317 ///
5318 /// This is a helper function of LowerToHorizontalOp().
5319 /// This function expects two 256-bit vectors called V0 and V1.
5320 /// At first, each vector is split into two separate 128-bit vectors.
5321 /// Then, the resulting 128-bit vectors are used to implement two
5322 /// horizontal binary operations.
5323 ///
5324 /// The kind of horizontal binary operation is defined by \p X86Opcode.
5325 ///
5326 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
5327 /// the two new horizontal binop.
5328 /// When Mode is set, the first horizontal binop dag node would take as input
5329 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
5330 /// horizontal binop dag node would take as input the lower 128-bit of V1
5331 /// and the upper 128-bit of V1.
5332 ///   Example:
5333 ///     HADD V0_LO, V0_HI
5334 ///     HADD V1_LO, V1_HI
5335 ///
5336 /// Otherwise, the first horizontal binop dag node takes as input the lower
5337 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
5338 /// dag node takes the the upper 128-bit of V0 and the upper 128-bit of V1.
5339 ///   Example:
5340 ///     HADD V0_LO, V1_LO
5341 ///     HADD V0_HI, V1_HI
5342 ///
5343 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
5344 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
5345 /// the upper 128-bits of the result.
5346 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
5347                                      SDLoc DL, SelectionDAG &DAG,
5348                                      unsigned X86Opcode, bool Mode,
5349                                      bool isUndefLO, bool isUndefHI) {
5350   EVT VT = V0.getValueType();
5351   assert(VT.is256BitVector() && VT == V1.getValueType() &&
5352          "Invalid nodes in input!");
5353
5354   unsigned NumElts = VT.getVectorNumElements();
5355   SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
5356   SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
5357   SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
5358   SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
5359   EVT NewVT = V0_LO.getValueType();
5360
5361   SDValue LO = DAG.getUNDEF(NewVT);
5362   SDValue HI = DAG.getUNDEF(NewVT);
5363
5364   if (Mode) {
5365     // Don't emit a horizontal binop if the result is expected to be UNDEF.
5366     if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
5367       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
5368     if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
5369       HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
5370   } else {
5371     // Don't emit a horizontal binop if the result is expected to be UNDEF.
5372     if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
5373                        V1_LO->getOpcode() != ISD::UNDEF))
5374       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
5375
5376     if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
5377                        V1_HI->getOpcode() != ISD::UNDEF))
5378       HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
5379   }
5380
5381   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
5382 }
5383
5384 /// Try to fold a build_vector that performs an 'addsub' to an X86ISD::ADDSUB
5385 /// node.
5386 static SDValue LowerToAddSub(const BuildVectorSDNode *BV,
5387                              const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5388   EVT VT = BV->getValueType(0);
5389   if ((!Subtarget->hasSSE3() || (VT != MVT::v4f32 && VT != MVT::v2f64)) &&
5390       (!Subtarget->hasAVX() || (VT != MVT::v8f32 && VT != MVT::v4f64)))
5391     return SDValue();
5392
5393   SDLoc DL(BV);
5394   unsigned NumElts = VT.getVectorNumElements();
5395   SDValue InVec0 = DAG.getUNDEF(VT);
5396   SDValue InVec1 = DAG.getUNDEF(VT);
5397
5398   assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
5399           VT == MVT::v2f64) && "build_vector with an invalid type found!");
5400
5401   // Odd-numbered elements in the input build vector are obtained from
5402   // adding two integer/float elements.
5403   // Even-numbered elements in the input build vector are obtained from
5404   // subtracting two integer/float elements.
5405   unsigned ExpectedOpcode = ISD::FSUB;
5406   unsigned NextExpectedOpcode = ISD::FADD;
5407   bool AddFound = false;
5408   bool SubFound = false;
5409
5410   for (unsigned i = 0, e = NumElts; i != e; ++i) {
5411     SDValue Op = BV->getOperand(i);
5412
5413     // Skip 'undef' values.
5414     unsigned Opcode = Op.getOpcode();
5415     if (Opcode == ISD::UNDEF) {
5416       std::swap(ExpectedOpcode, NextExpectedOpcode);
5417       continue;
5418     }
5419
5420     // Early exit if we found an unexpected opcode.
5421     if (Opcode != ExpectedOpcode)
5422       return SDValue();
5423
5424     SDValue Op0 = Op.getOperand(0);
5425     SDValue Op1 = Op.getOperand(1);
5426
5427     // Try to match the following pattern:
5428     // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
5429     // Early exit if we cannot match that sequence.
5430     if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5431         Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5432         !isa<ConstantSDNode>(Op0.getOperand(1)) ||
5433         !isa<ConstantSDNode>(Op1.getOperand(1)) ||
5434         Op0.getOperand(1) != Op1.getOperand(1))
5435       return SDValue();
5436
5437     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5438     if (I0 != i)
5439       return SDValue();
5440
5441     // We found a valid add/sub node. Update the information accordingly.
5442     if (i & 1)
5443       AddFound = true;
5444     else
5445       SubFound = true;
5446
5447     // Update InVec0 and InVec1.
5448     if (InVec0.getOpcode() == ISD::UNDEF) {
5449       InVec0 = Op0.getOperand(0);
5450       if (InVec0.getValueType() != VT)
5451         return SDValue();
5452     }
5453     if (InVec1.getOpcode() == ISD::UNDEF) {
5454       InVec1 = Op1.getOperand(0);
5455       if (InVec1.getValueType() != VT)
5456         return SDValue();
5457     }
5458
5459     // Make sure that operands in input to each add/sub node always
5460     // come from a same pair of vectors.
5461     if (InVec0 != Op0.getOperand(0)) {
5462       if (ExpectedOpcode == ISD::FSUB)
5463         return SDValue();
5464
5465       // FADD is commutable. Try to commute the operands
5466       // and then test again.
5467       std::swap(Op0, Op1);
5468       if (InVec0 != Op0.getOperand(0))
5469         return SDValue();
5470     }
5471
5472     if (InVec1 != Op1.getOperand(0))
5473       return SDValue();
5474
5475     // Update the pair of expected opcodes.
5476     std::swap(ExpectedOpcode, NextExpectedOpcode);
5477   }
5478
5479   // Don't try to fold this build_vector into an ADDSUB if the inputs are undef.
5480   if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
5481       InVec1.getOpcode() != ISD::UNDEF)
5482     return DAG.getNode(X86ISD::ADDSUB, DL, VT, InVec0, InVec1);
5483
5484   return SDValue();
5485 }
5486
5487 /// Lower BUILD_VECTOR to a horizontal add/sub operation if possible.
5488 static SDValue LowerToHorizontalOp(const BuildVectorSDNode *BV,
5489                                    const X86Subtarget *Subtarget,
5490                                    SelectionDAG &DAG) {
5491   EVT VT = BV->getValueType(0);
5492   unsigned NumElts = VT.getVectorNumElements();
5493   unsigned NumUndefsLO = 0;
5494   unsigned NumUndefsHI = 0;
5495   unsigned Half = NumElts/2;
5496
5497   // Count the number of UNDEF operands in the build_vector in input.
5498   for (unsigned i = 0, e = Half; i != e; ++i)
5499     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5500       NumUndefsLO++;
5501
5502   for (unsigned i = Half, e = NumElts; i != e; ++i)
5503     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5504       NumUndefsHI++;
5505
5506   // Early exit if this is either a build_vector of all UNDEFs or all the
5507   // operands but one are UNDEF.
5508   if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
5509     return SDValue();
5510
5511   SDLoc DL(BV);
5512   SDValue InVec0, InVec1;
5513   if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
5514     // Try to match an SSE3 float HADD/HSUB.
5515     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5516       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5517
5518     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5519       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5520   } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
5521     // Try to match an SSSE3 integer HADD/HSUB.
5522     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5523       return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
5524
5525     if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5526       return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
5527   }
5528
5529   if (!Subtarget->hasAVX())
5530     return SDValue();
5531
5532   if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
5533     // Try to match an AVX horizontal add/sub of packed single/double
5534     // precision floating point values from 256-bit vectors.
5535     SDValue InVec2, InVec3;
5536     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
5537         isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
5538         ((InVec0.getOpcode() == ISD::UNDEF ||
5539           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5540         ((InVec1.getOpcode() == ISD::UNDEF ||
5541           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5542       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5543
5544     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
5545         isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
5546         ((InVec0.getOpcode() == ISD::UNDEF ||
5547           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5548         ((InVec1.getOpcode() == ISD::UNDEF ||
5549           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5550       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5551   } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
5552     // Try to match an AVX2 horizontal add/sub of signed integers.
5553     SDValue InVec2, InVec3;
5554     unsigned X86Opcode;
5555     bool CanFold = true;
5556
5557     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
5558         isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
5559         ((InVec0.getOpcode() == ISD::UNDEF ||
5560           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5561         ((InVec1.getOpcode() == ISD::UNDEF ||
5562           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5563       X86Opcode = X86ISD::HADD;
5564     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
5565         isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
5566         ((InVec0.getOpcode() == ISD::UNDEF ||
5567           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5568         ((InVec1.getOpcode() == ISD::UNDEF ||
5569           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5570       X86Opcode = X86ISD::HSUB;
5571     else
5572       CanFold = false;
5573
5574     if (CanFold) {
5575       // Fold this build_vector into a single horizontal add/sub.
5576       // Do this only if the target has AVX2.
5577       if (Subtarget->hasAVX2())
5578         return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
5579
5580       // Do not try to expand this build_vector into a pair of horizontal
5581       // add/sub if we can emit a pair of scalar add/sub.
5582       if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5583         return SDValue();
5584
5585       // Convert this build_vector into a pair of horizontal binop followed by
5586       // a concat vector.
5587       bool isUndefLO = NumUndefsLO == Half;
5588       bool isUndefHI = NumUndefsHI == Half;
5589       return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
5590                                    isUndefLO, isUndefHI);
5591     }
5592   }
5593
5594   if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
5595        VT == MVT::v16i16) && Subtarget->hasAVX()) {
5596     unsigned X86Opcode;
5597     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5598       X86Opcode = X86ISD::HADD;
5599     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5600       X86Opcode = X86ISD::HSUB;
5601     else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5602       X86Opcode = X86ISD::FHADD;
5603     else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5604       X86Opcode = X86ISD::FHSUB;
5605     else
5606       return SDValue();
5607
5608     // Don't try to expand this build_vector into a pair of horizontal add/sub
5609     // if we can simply emit a pair of scalar add/sub.
5610     if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5611       return SDValue();
5612
5613     // Convert this build_vector into two horizontal add/sub followed by
5614     // a concat vector.
5615     bool isUndefLO = NumUndefsLO == Half;
5616     bool isUndefHI = NumUndefsHI == Half;
5617     return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
5618                                  isUndefLO, isUndefHI);
5619   }
5620
5621   return SDValue();
5622 }
5623
5624 SDValue
5625 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5626   SDLoc dl(Op);
5627
5628   MVT VT = Op.getSimpleValueType();
5629   MVT ExtVT = VT.getVectorElementType();
5630   unsigned NumElems = Op.getNumOperands();
5631
5632   // Generate vectors for predicate vectors.
5633   if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
5634     return LowerBUILD_VECTORvXi1(Op, DAG);
5635
5636   // Vectors containing all zeros can be matched by pxor and xorps later
5637   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5638     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5639     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5640     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
5641       return Op;
5642
5643     return getZeroVector(VT, Subtarget, DAG, dl);
5644   }
5645
5646   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5647   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5648   // vpcmpeqd on 256-bit vectors.
5649   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5650     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5651       return Op;
5652
5653     if (!VT.is512BitVector())
5654       return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5655   }
5656
5657   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(Op.getNode());
5658   if (SDValue AddSub = LowerToAddSub(BV, Subtarget, DAG))
5659     return AddSub;
5660   if (SDValue HorizontalOp = LowerToHorizontalOp(BV, Subtarget, DAG))
5661     return HorizontalOp;
5662   if (SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG))
5663     return Broadcast;
5664
5665   unsigned EVTBits = ExtVT.getSizeInBits();
5666
5667   unsigned NumZero  = 0;
5668   unsigned NumNonZero = 0;
5669   unsigned NonZeros = 0;
5670   bool IsAllConstants = true;
5671   SmallSet<SDValue, 8> Values;
5672   for (unsigned i = 0; i < NumElems; ++i) {
5673     SDValue Elt = Op.getOperand(i);
5674     if (Elt.getOpcode() == ISD::UNDEF)
5675       continue;
5676     Values.insert(Elt);
5677     if (Elt.getOpcode() != ISD::Constant &&
5678         Elt.getOpcode() != ISD::ConstantFP)
5679       IsAllConstants = false;
5680     if (X86::isZeroNode(Elt))
5681       NumZero++;
5682     else {
5683       NonZeros |= (1 << i);
5684       NumNonZero++;
5685     }
5686   }
5687
5688   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5689   if (NumNonZero == 0)
5690     return DAG.getUNDEF(VT);
5691
5692   // Special case for single non-zero, non-undef, element.
5693   if (NumNonZero == 1) {
5694     unsigned Idx = countTrailingZeros(NonZeros);
5695     SDValue Item = Op.getOperand(Idx);
5696
5697     // If this is an insertion of an i64 value on x86-32, and if the top bits of
5698     // the value are obviously zero, truncate the value to i32 and do the
5699     // insertion that way.  Only do this if the value is non-constant or if the
5700     // value is a constant being inserted into element 0.  It is cheaper to do
5701     // a constant pool load than it is to do a movd + shuffle.
5702     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5703         (!IsAllConstants || Idx == 0)) {
5704       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5705         // Handle SSE only.
5706         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5707         EVT VecVT = MVT::v4i32;
5708
5709         // Truncate the value (which may itself be a constant) to i32, and
5710         // convert it to a vector with movd (S2V+shuffle to zero extend).
5711         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5712         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5713         return DAG.getNode(
5714             ISD::BITCAST, dl, VT,
5715             getShuffleVectorZeroOrUndef(Item, Idx * 2, true, Subtarget, DAG));
5716       }
5717     }
5718
5719     // If we have a constant or non-constant insertion into the low element of
5720     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5721     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5722     // depending on what the source datatype is.
5723     if (Idx == 0) {
5724       if (NumZero == 0)
5725         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5726
5727       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5728           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5729         if (VT.is512BitVector()) {
5730           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5731           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5732                              Item, DAG.getIntPtrConstant(0));
5733         }
5734         assert((VT.is128BitVector() || VT.is256BitVector()) &&
5735                "Expected an SSE value type!");
5736         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5737         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5738         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5739       }
5740
5741       // We can't directly insert an i8 or i16 into a vector, so zero extend
5742       // it to i32 first.
5743       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5744         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5745         if (VT.is256BitVector()) {
5746           if (Subtarget->hasAVX()) {
5747             Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v8i32, Item);
5748             Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5749           } else {
5750             // Without AVX, we need to extend to a 128-bit vector and then
5751             // insert into the 256-bit vector.
5752             Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5753             SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5754             Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5755           }
5756         } else {
5757           assert(VT.is128BitVector() && "Expected an SSE value type!");
5758           Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5759           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5760         }
5761         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5762       }
5763     }
5764
5765     // Is it a vector logical left shift?
5766     if (NumElems == 2 && Idx == 1 &&
5767         X86::isZeroNode(Op.getOperand(0)) &&
5768         !X86::isZeroNode(Op.getOperand(1))) {
5769       unsigned NumBits = VT.getSizeInBits();
5770       return getVShift(true, VT,
5771                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5772                                    VT, Op.getOperand(1)),
5773                        NumBits/2, DAG, *this, dl);
5774     }
5775
5776     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5777       return SDValue();
5778
5779     // Otherwise, if this is a vector with i32 or f32 elements, and the element
5780     // is a non-constant being inserted into an element other than the low one,
5781     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
5782     // movd/movss) to move this into the low element, then shuffle it into
5783     // place.
5784     if (EVTBits == 32) {
5785       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5786       return getShuffleVectorZeroOrUndef(Item, Idx, NumZero > 0, Subtarget, DAG);
5787     }
5788   }
5789
5790   // Splat is obviously ok. Let legalizer expand it to a shuffle.
5791   if (Values.size() == 1) {
5792     if (EVTBits == 32) {
5793       // Instead of a shuffle like this:
5794       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5795       // Check if it's possible to issue this instead.
5796       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5797       unsigned Idx = countTrailingZeros(NonZeros);
5798       SDValue Item = Op.getOperand(Idx);
5799       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5800         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5801     }
5802     return SDValue();
5803   }
5804
5805   // A vector full of immediates; various special cases are already
5806   // handled, so this is best done with a single constant-pool load.
5807   if (IsAllConstants)
5808     return SDValue();
5809
5810   // For AVX-length vectors, see if we can use a vector load to get all of the
5811   // elements, otherwise build the individual 128-bit pieces and use
5812   // shuffles to put them in place.
5813   if (VT.is256BitVector() || VT.is512BitVector()) {
5814     SmallVector<SDValue, 64> V(Op->op_begin(), Op->op_begin() + NumElems);
5815
5816     // Check for a build vector of consecutive loads.
5817     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
5818       return LD;
5819
5820     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5821
5822     // Build both the lower and upper subvector.
5823     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
5824                                 makeArrayRef(&V[0], NumElems/2));
5825     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
5826                                 makeArrayRef(&V[NumElems / 2], NumElems/2));
5827
5828     // Recreate the wider vector with the lower and upper part.
5829     if (VT.is256BitVector())
5830       return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5831     return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5832   }
5833
5834   // Let legalizer expand 2-wide build_vectors.
5835   if (EVTBits == 64) {
5836     if (NumNonZero == 1) {
5837       // One half is zero or undef.
5838       unsigned Idx = countTrailingZeros(NonZeros);
5839       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5840                                  Op.getOperand(Idx));
5841       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
5842     }
5843     return SDValue();
5844   }
5845
5846   // If element VT is < 32 bits, convert it to inserts into a zero vector.
5847   if (EVTBits == 8 && NumElems == 16)
5848     if (SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5849                                         Subtarget, *this))
5850       return V;
5851
5852   if (EVTBits == 16 && NumElems == 8)
5853     if (SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5854                                       Subtarget, *this))
5855       return V;
5856
5857   // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
5858   if (EVTBits == 32 && NumElems == 4)
5859     if (SDValue V = LowerBuildVectorv4x32(Op, DAG, Subtarget, *this))
5860       return V;
5861
5862   // If element VT is == 32 bits, turn it into a number of shuffles.
5863   SmallVector<SDValue, 8> V(NumElems);
5864   if (NumElems == 4 && NumZero > 0) {
5865     for (unsigned i = 0; i < 4; ++i) {
5866       bool isZero = !(NonZeros & (1 << i));
5867       if (isZero)
5868         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
5869       else
5870         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5871     }
5872
5873     for (unsigned i = 0; i < 2; ++i) {
5874       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5875         default: break;
5876         case 0:
5877           V[i] = V[i*2];  // Must be a zero vector.
5878           break;
5879         case 1:
5880           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5881           break;
5882         case 2:
5883           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5884           break;
5885         case 3:
5886           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5887           break;
5888       }
5889     }
5890
5891     bool Reverse1 = (NonZeros & 0x3) == 2;
5892     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5893     int MaskVec[] = {
5894       Reverse1 ? 1 : 0,
5895       Reverse1 ? 0 : 1,
5896       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
5897       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
5898     };
5899     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5900   }
5901
5902   if (Values.size() > 1 && VT.is128BitVector()) {
5903     // Check for a build vector of consecutive loads.
5904     for (unsigned i = 0; i < NumElems; ++i)
5905       V[i] = Op.getOperand(i);
5906
5907     // Check for elements which are consecutive loads.
5908     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
5909       return LD;
5910
5911     // Check for a build vector from mostly shuffle plus few inserting.
5912     if (SDValue Sh = buildFromShuffleMostly(Op, DAG))
5913       return Sh;
5914
5915     // For SSE 4.1, use insertps to put the high elements into the low element.
5916     if (Subtarget->hasSSE41()) {
5917       SDValue Result;
5918       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5919         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5920       else
5921         Result = DAG.getUNDEF(VT);
5922
5923       for (unsigned i = 1; i < NumElems; ++i) {
5924         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5925         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5926                              Op.getOperand(i), DAG.getIntPtrConstant(i));
5927       }
5928       return Result;
5929     }
5930
5931     // Otherwise, expand into a number of unpckl*, start by extending each of
5932     // our (non-undef) elements to the full vector width with the element in the
5933     // bottom slot of the vector (which generates no code for SSE).
5934     for (unsigned i = 0; i < NumElems; ++i) {
5935       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5936         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5937       else
5938         V[i] = DAG.getUNDEF(VT);
5939     }
5940
5941     // Next, we iteratively mix elements, e.g. for v4f32:
5942     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5943     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5944     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
5945     unsigned EltStride = NumElems >> 1;
5946     while (EltStride != 0) {
5947       for (unsigned i = 0; i < EltStride; ++i) {
5948         // If V[i+EltStride] is undef and this is the first round of mixing,
5949         // then it is safe to just drop this shuffle: V[i] is already in the
5950         // right place, the one element (since it's the first round) being
5951         // inserted as undef can be dropped.  This isn't safe for successive
5952         // rounds because they will permute elements within both vectors.
5953         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5954             EltStride == NumElems/2)
5955           continue;
5956
5957         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5958       }
5959       EltStride >>= 1;
5960     }
5961     return V[0];
5962   }
5963   return SDValue();
5964 }
5965
5966 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5967 // to create 256-bit vectors from two other 128-bit ones.
5968 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5969   SDLoc dl(Op);
5970   MVT ResVT = Op.getSimpleValueType();
5971
5972   assert((ResVT.is256BitVector() ||
5973           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
5974
5975   SDValue V1 = Op.getOperand(0);
5976   SDValue V2 = Op.getOperand(1);
5977   unsigned NumElems = ResVT.getVectorNumElements();
5978   if (ResVT.is256BitVector())
5979     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
5980
5981   if (Op.getNumOperands() == 4) {
5982     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
5983                                 ResVT.getVectorNumElements()/2);
5984     SDValue V3 = Op.getOperand(2);
5985     SDValue V4 = Op.getOperand(3);
5986     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
5987       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
5988   }
5989   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
5990 }
5991
5992 static SDValue LowerCONCAT_VECTORSvXi1(SDValue Op,
5993                                        const X86Subtarget *Subtarget,
5994                                        SelectionDAG & DAG) {
5995   SDLoc dl(Op);
5996   MVT ResVT = Op.getSimpleValueType();
5997   unsigned NumOfOperands = Op.getNumOperands();
5998
5999   assert(isPowerOf2_32(NumOfOperands) &&
6000          "Unexpected number of operands in CONCAT_VECTORS");
6001
6002   if (NumOfOperands > 2) {
6003     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6004                                   ResVT.getVectorNumElements()/2);
6005     SmallVector<SDValue, 2> Ops;
6006     for (unsigned i = 0; i < NumOfOperands/2; i++)
6007       Ops.push_back(Op.getOperand(i));
6008     SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6009     Ops.clear();
6010     for (unsigned i = NumOfOperands/2; i < NumOfOperands; i++)
6011       Ops.push_back(Op.getOperand(i));
6012     SDValue Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6013     return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Lo, Hi);
6014   }
6015
6016   SDValue V1 = Op.getOperand(0);
6017   SDValue V2 = Op.getOperand(1);
6018   bool IsZeroV1 = ISD::isBuildVectorAllZeros(V1.getNode());
6019   bool IsZeroV2 = ISD::isBuildVectorAllZeros(V2.getNode());
6020
6021   if (IsZeroV1 && IsZeroV2)
6022     return getZeroVector(ResVT, Subtarget, DAG, dl);
6023
6024   SDValue ZeroIdx = DAG.getIntPtrConstant(0);
6025   SDValue Undef = DAG.getUNDEF(ResVT);
6026   unsigned NumElems = ResVT.getVectorNumElements();
6027   SDValue ShiftBits = DAG.getConstant(NumElems/2, MVT::i8);
6028
6029   V2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V2, ZeroIdx);
6030   V2 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V2, ShiftBits);
6031   if (IsZeroV1)
6032     return V2;
6033
6034   V1 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V1, ZeroIdx);
6035   // Zero the upper bits of V1
6036   V1 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V1, ShiftBits);
6037   V1 = DAG.getNode(X86ISD::VSRLI, dl, ResVT, V1, ShiftBits);
6038   if (IsZeroV2)
6039     return V1;
6040   return DAG.getNode(ISD::OR, dl, ResVT, V1, V2);
6041 }
6042
6043 static SDValue LowerCONCAT_VECTORS(SDValue Op,
6044                                    const X86Subtarget *Subtarget,
6045                                    SelectionDAG &DAG) {
6046   MVT VT = Op.getSimpleValueType();
6047   if (VT.getVectorElementType() == MVT::i1)
6048     return LowerCONCAT_VECTORSvXi1(Op, Subtarget, DAG);
6049
6050   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6051          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6052           Op.getNumOperands() == 4)));
6053
6054   // AVX can use the vinsertf128 instruction to create 256-bit vectors
6055   // from two other 128-bit ones.
6056
6057   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6058   return LowerAVXCONCAT_VECTORS(Op, DAG);
6059 }
6060
6061
6062 //===----------------------------------------------------------------------===//
6063 // Vector shuffle lowering
6064 //
6065 // This is an experimental code path for lowering vector shuffles on x86. It is
6066 // designed to handle arbitrary vector shuffles and blends, gracefully
6067 // degrading performance as necessary. It works hard to recognize idiomatic
6068 // shuffles and lower them to optimal instruction patterns without leaving
6069 // a framework that allows reasonably efficient handling of all vector shuffle
6070 // patterns.
6071 //===----------------------------------------------------------------------===//
6072
6073 /// \brief Tiny helper function to identify a no-op mask.
6074 ///
6075 /// This is a somewhat boring predicate function. It checks whether the mask
6076 /// array input, which is assumed to be a single-input shuffle mask of the kind
6077 /// used by the X86 shuffle instructions (not a fully general
6078 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
6079 /// in-place shuffle are 'no-op's.
6080 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
6081   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6082     if (Mask[i] != -1 && Mask[i] != i)
6083       return false;
6084   return true;
6085 }
6086
6087 /// \brief Helper function to classify a mask as a single-input mask.
6088 ///
6089 /// This isn't a generic single-input test because in the vector shuffle
6090 /// lowering we canonicalize single inputs to be the first input operand. This
6091 /// means we can more quickly test for a single input by only checking whether
6092 /// an input from the second operand exists. We also assume that the size of
6093 /// mask corresponds to the size of the input vectors which isn't true in the
6094 /// fully general case.
6095 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
6096   for (int M : Mask)
6097     if (M >= (int)Mask.size())
6098       return false;
6099   return true;
6100 }
6101
6102 /// \brief Test whether there are elements crossing 128-bit lanes in this
6103 /// shuffle mask.
6104 ///
6105 /// X86 divides up its shuffles into in-lane and cross-lane shuffle operations
6106 /// and we routinely test for these.
6107 static bool is128BitLaneCrossingShuffleMask(MVT VT, ArrayRef<int> Mask) {
6108   int LaneSize = 128 / VT.getScalarSizeInBits();
6109   int Size = Mask.size();
6110   for (int i = 0; i < Size; ++i)
6111     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
6112       return true;
6113   return false;
6114 }
6115
6116 /// \brief Test whether a shuffle mask is equivalent within each 128-bit lane.
6117 ///
6118 /// This checks a shuffle mask to see if it is performing the same
6119 /// 128-bit lane-relative shuffle in each 128-bit lane. This trivially implies
6120 /// that it is also not lane-crossing. It may however involve a blend from the
6121 /// same lane of a second vector.
6122 ///
6123 /// The specific repeated shuffle mask is populated in \p RepeatedMask, as it is
6124 /// non-trivial to compute in the face of undef lanes. The representation is
6125 /// *not* suitable for use with existing 128-bit shuffles as it will contain
6126 /// entries from both V1 and V2 inputs to the wider mask.
6127 static bool
6128 is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
6129                                 SmallVectorImpl<int> &RepeatedMask) {
6130   int LaneSize = 128 / VT.getScalarSizeInBits();
6131   RepeatedMask.resize(LaneSize, -1);
6132   int Size = Mask.size();
6133   for (int i = 0; i < Size; ++i) {
6134     if (Mask[i] < 0)
6135       continue;
6136     if ((Mask[i] % Size) / LaneSize != i / LaneSize)
6137       // This entry crosses lanes, so there is no way to model this shuffle.
6138       return false;
6139
6140     // Ok, handle the in-lane shuffles by detecting if and when they repeat.
6141     if (RepeatedMask[i % LaneSize] == -1)
6142       // This is the first non-undef entry in this slot of a 128-bit lane.
6143       RepeatedMask[i % LaneSize] =
6144           Mask[i] < Size ? Mask[i] % LaneSize : Mask[i] % LaneSize + Size;
6145     else if (RepeatedMask[i % LaneSize] + (i / LaneSize) * LaneSize != Mask[i])
6146       // Found a mismatch with the repeated mask.
6147       return false;
6148   }
6149   return true;
6150 }
6151
6152 /// \brief Checks whether a shuffle mask is equivalent to an explicit list of
6153 /// arguments.
6154 ///
6155 /// This is a fast way to test a shuffle mask against a fixed pattern:
6156 ///
6157 ///   if (isShuffleEquivalent(Mask, 3, 2, {1, 0})) { ... }
6158 ///
6159 /// It returns true if the mask is exactly as wide as the argument list, and
6160 /// each element of the mask is either -1 (signifying undef) or the value given
6161 /// in the argument.
6162 static bool isShuffleEquivalent(SDValue V1, SDValue V2, ArrayRef<int> Mask,
6163                                 ArrayRef<int> ExpectedMask) {
6164   if (Mask.size() != ExpectedMask.size())
6165     return false;
6166
6167   int Size = Mask.size();
6168
6169   // If the values are build vectors, we can look through them to find
6170   // equivalent inputs that make the shuffles equivalent.
6171   auto *BV1 = dyn_cast<BuildVectorSDNode>(V1);
6172   auto *BV2 = dyn_cast<BuildVectorSDNode>(V2);
6173
6174   for (int i = 0; i < Size; ++i)
6175     if (Mask[i] != -1 && Mask[i] != ExpectedMask[i]) {
6176       auto *MaskBV = Mask[i] < Size ? BV1 : BV2;
6177       auto *ExpectedBV = ExpectedMask[i] < Size ? BV1 : BV2;
6178       if (!MaskBV || !ExpectedBV ||
6179           MaskBV->getOperand(Mask[i] % Size) !=
6180               ExpectedBV->getOperand(ExpectedMask[i] % Size))
6181         return false;
6182     }
6183
6184   return true;
6185 }
6186
6187 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
6188 ///
6189 /// This helper function produces an 8-bit shuffle immediate corresponding to
6190 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
6191 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
6192 /// example.
6193 ///
6194 /// NB: We rely heavily on "undef" masks preserving the input lane.
6195 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask,
6196                                           SelectionDAG &DAG) {
6197   assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
6198   assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
6199   assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
6200   assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
6201   assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
6202
6203   unsigned Imm = 0;
6204   Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
6205   Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
6206   Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
6207   Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
6208   return DAG.getConstant(Imm, MVT::i8);
6209 }
6210
6211 /// \brief Try to emit a blend instruction for a shuffle using bit math.
6212 ///
6213 /// This is used as a fallback approach when first class blend instructions are
6214 /// unavailable. Currently it is only suitable for integer vectors, but could
6215 /// be generalized for floating point vectors if desirable.
6216 static SDValue lowerVectorShuffleAsBitBlend(SDLoc DL, MVT VT, SDValue V1,
6217                                             SDValue V2, ArrayRef<int> Mask,
6218                                             SelectionDAG &DAG) {
6219   assert(VT.isInteger() && "Only supports integer vector types!");
6220   MVT EltVT = VT.getScalarType();
6221   int NumEltBits = EltVT.getSizeInBits();
6222   SDValue Zero = DAG.getConstant(0, EltVT);
6223   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), EltVT);
6224   SmallVector<SDValue, 16> MaskOps;
6225   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6226     if (Mask[i] != -1 && Mask[i] != i && Mask[i] != i + Size)
6227       return SDValue(); // Shuffled input!
6228     MaskOps.push_back(Mask[i] < Size ? AllOnes : Zero);
6229   }
6230
6231   SDValue V1Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, MaskOps);
6232   V1 = DAG.getNode(ISD::AND, DL, VT, V1, V1Mask);
6233   // We have to cast V2 around.
6234   MVT MaskVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
6235   V2 = DAG.getNode(ISD::BITCAST, DL, VT,
6236                    DAG.getNode(X86ISD::ANDNP, DL, MaskVT,
6237                                DAG.getNode(ISD::BITCAST, DL, MaskVT, V1Mask),
6238                                DAG.getNode(ISD::BITCAST, DL, MaskVT, V2)));
6239   return DAG.getNode(ISD::OR, DL, VT, V1, V2);
6240 }
6241
6242 /// \brief Try to emit a blend instruction for a shuffle.
6243 ///
6244 /// This doesn't do any checks for the availability of instructions for blending
6245 /// these values. It relies on the availability of the X86ISD::BLENDI pattern to
6246 /// be matched in the backend with the type given. What it does check for is
6247 /// that the shuffle mask is in fact a blend.
6248 static SDValue lowerVectorShuffleAsBlend(SDLoc DL, MVT VT, SDValue V1,
6249                                          SDValue V2, ArrayRef<int> Mask,
6250                                          const X86Subtarget *Subtarget,
6251                                          SelectionDAG &DAG) {
6252   unsigned BlendMask = 0;
6253   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6254     if (Mask[i] >= Size) {
6255       if (Mask[i] != i + Size)
6256         return SDValue(); // Shuffled V2 input!
6257       BlendMask |= 1u << i;
6258       continue;
6259     }
6260     if (Mask[i] >= 0 && Mask[i] != i)
6261       return SDValue(); // Shuffled V1 input!
6262   }
6263   switch (VT.SimpleTy) {
6264   case MVT::v2f64:
6265   case MVT::v4f32:
6266   case MVT::v4f64:
6267   case MVT::v8f32:
6268     return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V2,
6269                        DAG.getConstant(BlendMask, MVT::i8));
6270
6271   case MVT::v4i64:
6272   case MVT::v8i32:
6273     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6274     // FALLTHROUGH
6275   case MVT::v2i64:
6276   case MVT::v4i32:
6277     // If we have AVX2 it is faster to use VPBLENDD when the shuffle fits into
6278     // that instruction.
6279     if (Subtarget->hasAVX2()) {
6280       // Scale the blend by the number of 32-bit dwords per element.
6281       int Scale =  VT.getScalarSizeInBits() / 32;
6282       BlendMask = 0;
6283       for (int i = 0, Size = Mask.size(); i < Size; ++i)
6284         if (Mask[i] >= Size)
6285           for (int j = 0; j < Scale; ++j)
6286             BlendMask |= 1u << (i * Scale + j);
6287
6288       MVT BlendVT = VT.getSizeInBits() > 128 ? MVT::v8i32 : MVT::v4i32;
6289       V1 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V1);
6290       V2 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V2);
6291       return DAG.getNode(ISD::BITCAST, DL, VT,
6292                          DAG.getNode(X86ISD::BLENDI, DL, BlendVT, V1, V2,
6293                                      DAG.getConstant(BlendMask, MVT::i8)));
6294     }
6295     // FALLTHROUGH
6296   case MVT::v8i16: {
6297     // For integer shuffles we need to expand the mask and cast the inputs to
6298     // v8i16s prior to blending.
6299     int Scale = 8 / VT.getVectorNumElements();
6300     BlendMask = 0;
6301     for (int i = 0, Size = Mask.size(); i < Size; ++i)
6302       if (Mask[i] >= Size)
6303         for (int j = 0; j < Scale; ++j)
6304           BlendMask |= 1u << (i * Scale + j);
6305
6306     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1);
6307     V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V2);
6308     return DAG.getNode(ISD::BITCAST, DL, VT,
6309                        DAG.getNode(X86ISD::BLENDI, DL, MVT::v8i16, V1, V2,
6310                                    DAG.getConstant(BlendMask, MVT::i8)));
6311   }
6312
6313   case MVT::v16i16: {
6314     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6315     SmallVector<int, 8> RepeatedMask;
6316     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
6317       // We can lower these with PBLENDW which is mirrored across 128-bit lanes.
6318       assert(RepeatedMask.size() == 8 && "Repeated mask size doesn't match!");
6319       BlendMask = 0;
6320       for (int i = 0; i < 8; ++i)
6321         if (RepeatedMask[i] >= 16)
6322           BlendMask |= 1u << i;
6323       return DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
6324                          DAG.getConstant(BlendMask, MVT::i8));
6325     }
6326   }
6327     // FALLTHROUGH
6328   case MVT::v16i8:
6329   case MVT::v32i8: {
6330     assert((VT.getSizeInBits() == 128 || Subtarget->hasAVX2()) &&
6331            "256-bit byte-blends require AVX2 support!");
6332
6333     // Scale the blend by the number of bytes per element.
6334     int Scale = VT.getScalarSizeInBits() / 8;
6335
6336     // This form of blend is always done on bytes. Compute the byte vector
6337     // type.
6338     MVT BlendVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
6339
6340     // Compute the VSELECT mask. Note that VSELECT is really confusing in the
6341     // mix of LLVM's code generator and the x86 backend. We tell the code
6342     // generator that boolean values in the elements of an x86 vector register
6343     // are -1 for true and 0 for false. We then use the LLVM semantics of 'true'
6344     // mapping a select to operand #1, and 'false' mapping to operand #2. The
6345     // reality in x86 is that vector masks (pre-AVX-512) use only the high bit
6346     // of the element (the remaining are ignored) and 0 in that high bit would
6347     // mean operand #1 while 1 in the high bit would mean operand #2. So while
6348     // the LLVM model for boolean values in vector elements gets the relevant
6349     // bit set, it is set backwards and over constrained relative to x86's
6350     // actual model.
6351     SmallVector<SDValue, 32> VSELECTMask;
6352     for (int i = 0, Size = Mask.size(); i < Size; ++i)
6353       for (int j = 0; j < Scale; ++j)
6354         VSELECTMask.push_back(
6355             Mask[i] < 0 ? DAG.getUNDEF(MVT::i8)
6356                         : DAG.getConstant(Mask[i] < Size ? -1 : 0, MVT::i8));
6357
6358     V1 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V1);
6359     V2 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V2);
6360     return DAG.getNode(
6361         ISD::BITCAST, DL, VT,
6362         DAG.getNode(ISD::VSELECT, DL, BlendVT,
6363                     DAG.getNode(ISD::BUILD_VECTOR, DL, BlendVT, VSELECTMask),
6364                     V1, V2));
6365   }
6366
6367   default:
6368     llvm_unreachable("Not a supported integer vector type!");
6369   }
6370 }
6371
6372 /// \brief Try to lower as a blend of elements from two inputs followed by
6373 /// a single-input permutation.
6374 ///
6375 /// This matches the pattern where we can blend elements from two inputs and
6376 /// then reduce the shuffle to a single-input permutation.
6377 static SDValue lowerVectorShuffleAsBlendAndPermute(SDLoc DL, MVT VT, SDValue V1,
6378                                                    SDValue V2,
6379                                                    ArrayRef<int> Mask,
6380                                                    SelectionDAG &DAG) {
6381   // We build up the blend mask while checking whether a blend is a viable way
6382   // to reduce the shuffle.
6383   SmallVector<int, 32> BlendMask(Mask.size(), -1);
6384   SmallVector<int, 32> PermuteMask(Mask.size(), -1);
6385
6386   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6387     if (Mask[i] < 0)
6388       continue;
6389
6390     assert(Mask[i] < Size * 2 && "Shuffle input is out of bounds.");
6391
6392     if (BlendMask[Mask[i] % Size] == -1)
6393       BlendMask[Mask[i] % Size] = Mask[i];
6394     else if (BlendMask[Mask[i] % Size] != Mask[i])
6395       return SDValue(); // Can't blend in the needed input!
6396
6397     PermuteMask[i] = Mask[i] % Size;
6398   }
6399
6400   SDValue V = DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6401   return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), PermuteMask);
6402 }
6403
6404 /// \brief Generic routine to decompose a shuffle and blend into indepndent
6405 /// blends and permutes.
6406 ///
6407 /// This matches the extremely common pattern for handling combined
6408 /// shuffle+blend operations on newer X86 ISAs where we have very fast blend
6409 /// operations. It will try to pick the best arrangement of shuffles and
6410 /// blends.
6411 static SDValue lowerVectorShuffleAsDecomposedShuffleBlend(SDLoc DL, MVT VT,
6412                                                           SDValue V1,
6413                                                           SDValue V2,
6414                                                           ArrayRef<int> Mask,
6415                                                           SelectionDAG &DAG) {
6416   // Shuffle the input elements into the desired positions in V1 and V2 and
6417   // blend them together.
6418   SmallVector<int, 32> V1Mask(Mask.size(), -1);
6419   SmallVector<int, 32> V2Mask(Mask.size(), -1);
6420   SmallVector<int, 32> BlendMask(Mask.size(), -1);
6421   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6422     if (Mask[i] >= 0 && Mask[i] < Size) {
6423       V1Mask[i] = Mask[i];
6424       BlendMask[i] = i;
6425     } else if (Mask[i] >= Size) {
6426       V2Mask[i] = Mask[i] - Size;
6427       BlendMask[i] = i + Size;
6428     }
6429
6430   // Try to lower with the simpler initial blend strategy unless one of the
6431   // input shuffles would be a no-op. We prefer to shuffle inputs as the
6432   // shuffle may be able to fold with a load or other benefit. However, when
6433   // we'll have to do 2x as many shuffles in order to achieve this, blending
6434   // first is a better strategy.
6435   if (!isNoopShuffleMask(V1Mask) && !isNoopShuffleMask(V2Mask))
6436     if (SDValue BlendPerm =
6437             lowerVectorShuffleAsBlendAndPermute(DL, VT, V1, V2, Mask, DAG))
6438       return BlendPerm;
6439
6440   V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
6441   V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
6442   return DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6443 }
6444
6445 /// \brief Try to lower a vector shuffle as a byte rotation.
6446 ///
6447 /// SSSE3 has a generic PALIGNR instruction in x86 that will do an arbitrary
6448 /// byte-rotation of the concatenation of two vectors; pre-SSSE3 can use
6449 /// a PSRLDQ/PSLLDQ/POR pattern to get a similar effect. This routine will
6450 /// try to generically lower a vector shuffle through such an pattern. It
6451 /// does not check for the profitability of lowering either as PALIGNR or
6452 /// PSRLDQ/PSLLDQ/POR, only whether the mask is valid to lower in that form.
6453 /// This matches shuffle vectors that look like:
6454 ///
6455 ///   v8i16 [11, 12, 13, 14, 15, 0, 1, 2]
6456 ///
6457 /// Essentially it concatenates V1 and V2, shifts right by some number of
6458 /// elements, and takes the low elements as the result. Note that while this is
6459 /// specified as a *right shift* because x86 is little-endian, it is a *left
6460 /// rotate* of the vector lanes.
6461 static SDValue lowerVectorShuffleAsByteRotate(SDLoc DL, MVT VT, SDValue V1,
6462                                               SDValue V2,
6463                                               ArrayRef<int> Mask,
6464                                               const X86Subtarget *Subtarget,
6465                                               SelectionDAG &DAG) {
6466   assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
6467
6468   int NumElts = Mask.size();
6469   int NumLanes = VT.getSizeInBits() / 128;
6470   int NumLaneElts = NumElts / NumLanes;
6471
6472   // We need to detect various ways of spelling a rotation:
6473   //   [11, 12, 13, 14, 15,  0,  1,  2]
6474   //   [-1, 12, 13, 14, -1, -1,  1, -1]
6475   //   [-1, -1, -1, -1, -1, -1,  1,  2]
6476   //   [ 3,  4,  5,  6,  7,  8,  9, 10]
6477   //   [-1,  4,  5,  6, -1, -1,  9, -1]
6478   //   [-1,  4,  5,  6, -1, -1, -1, -1]
6479   int Rotation = 0;
6480   SDValue Lo, Hi;
6481   for (int l = 0; l < NumElts; l += NumLaneElts) {
6482     for (int i = 0; i < NumLaneElts; ++i) {
6483       if (Mask[l + i] == -1)
6484         continue;
6485       assert(Mask[l + i] >= 0 && "Only -1 is a valid negative mask element!");
6486
6487       // Get the mod-Size index and lane correct it.
6488       int LaneIdx = (Mask[l + i] % NumElts) - l;
6489       // Make sure it was in this lane.
6490       if (LaneIdx < 0 || LaneIdx >= NumLaneElts)
6491         return SDValue();
6492
6493       // Determine where a rotated vector would have started.
6494       int StartIdx = i - LaneIdx;
6495       if (StartIdx == 0)
6496         // The identity rotation isn't interesting, stop.
6497         return SDValue();
6498
6499       // If we found the tail of a vector the rotation must be the missing
6500       // front. If we found the head of a vector, it must be how much of the
6501       // head.
6502       int CandidateRotation = StartIdx < 0 ? -StartIdx : NumLaneElts - StartIdx;
6503
6504       if (Rotation == 0)
6505         Rotation = CandidateRotation;
6506       else if (Rotation != CandidateRotation)
6507         // The rotations don't match, so we can't match this mask.
6508         return SDValue();
6509
6510       // Compute which value this mask is pointing at.
6511       SDValue MaskV = Mask[l + i] < NumElts ? V1 : V2;
6512
6513       // Compute which of the two target values this index should be assigned
6514       // to. This reflects whether the high elements are remaining or the low
6515       // elements are remaining.
6516       SDValue &TargetV = StartIdx < 0 ? Hi : Lo;
6517
6518       // Either set up this value if we've not encountered it before, or check
6519       // that it remains consistent.
6520       if (!TargetV)
6521         TargetV = MaskV;
6522       else if (TargetV != MaskV)
6523         // This may be a rotation, but it pulls from the inputs in some
6524         // unsupported interleaving.
6525         return SDValue();
6526     }
6527   }
6528
6529   // Check that we successfully analyzed the mask, and normalize the results.
6530   assert(Rotation != 0 && "Failed to locate a viable rotation!");
6531   assert((Lo || Hi) && "Failed to find a rotated input vector!");
6532   if (!Lo)
6533     Lo = Hi;
6534   else if (!Hi)
6535     Hi = Lo;
6536
6537   // The actual rotate instruction rotates bytes, so we need to scale the
6538   // rotation based on how many bytes are in the vector lane.
6539   int Scale = 16 / NumLaneElts;
6540
6541   // SSSE3 targets can use the palignr instruction.
6542   if (Subtarget->hasSSSE3()) {
6543     // Cast the inputs to i8 vector of correct length to match PALIGNR.
6544     MVT AlignVT = MVT::getVectorVT(MVT::i8, 16 * NumLanes);
6545     Lo = DAG.getNode(ISD::BITCAST, DL, AlignVT, Lo);
6546     Hi = DAG.getNode(ISD::BITCAST, DL, AlignVT, Hi);
6547
6548     return DAG.getNode(ISD::BITCAST, DL, VT,
6549                        DAG.getNode(X86ISD::PALIGNR, DL, AlignVT, Hi, Lo,
6550                                    DAG.getConstant(Rotation * Scale, MVT::i8)));
6551   }
6552
6553   assert(VT.getSizeInBits() == 128 &&
6554          "Rotate-based lowering only supports 128-bit lowering!");
6555   assert(Mask.size() <= 16 &&
6556          "Can shuffle at most 16 bytes in a 128-bit vector!");
6557
6558   // Default SSE2 implementation
6559   int LoByteShift = 16 - Rotation * Scale;
6560   int HiByteShift = Rotation * Scale;
6561
6562   // Cast the inputs to v2i64 to match PSLLDQ/PSRLDQ.
6563   Lo = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Lo);
6564   Hi = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Hi);
6565
6566   SDValue LoShift = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v2i64, Lo,
6567                                 DAG.getConstant(LoByteShift, MVT::i8));
6568   SDValue HiShift = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v2i64, Hi,
6569                                 DAG.getConstant(HiByteShift, MVT::i8));
6570   return DAG.getNode(ISD::BITCAST, DL, VT,
6571                      DAG.getNode(ISD::OR, DL, MVT::v2i64, LoShift, HiShift));
6572 }
6573
6574 /// \brief Compute whether each element of a shuffle is zeroable.
6575 ///
6576 /// A "zeroable" vector shuffle element is one which can be lowered to zero.
6577 /// Either it is an undef element in the shuffle mask, the element of the input
6578 /// referenced is undef, or the element of the input referenced is known to be
6579 /// zero. Many x86 shuffles can zero lanes cheaply and we often want to handle
6580 /// as many lanes with this technique as possible to simplify the remaining
6581 /// shuffle.
6582 static SmallBitVector computeZeroableShuffleElements(ArrayRef<int> Mask,
6583                                                      SDValue V1, SDValue V2) {
6584   SmallBitVector Zeroable(Mask.size(), false);
6585
6586   while (V1.getOpcode() == ISD::BITCAST)
6587     V1 = V1->getOperand(0);
6588   while (V2.getOpcode() == ISD::BITCAST)
6589     V2 = V2->getOperand(0);
6590
6591   bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
6592   bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
6593
6594   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6595     int M = Mask[i];
6596     // Handle the easy cases.
6597     if (M < 0 || (M >= 0 && M < Size && V1IsZero) || (M >= Size && V2IsZero)) {
6598       Zeroable[i] = true;
6599       continue;
6600     }
6601
6602     // If this is an index into a build_vector node (which has the same number
6603     // of elements), dig out the input value and use it.
6604     SDValue V = M < Size ? V1 : V2;
6605     if (V.getOpcode() != ISD::BUILD_VECTOR || Size != (int)V.getNumOperands())
6606       continue;
6607
6608     SDValue Input = V.getOperand(M % Size);
6609     // The UNDEF opcode check really should be dead code here, but not quite
6610     // worth asserting on (it isn't invalid, just unexpected).
6611     if (Input.getOpcode() == ISD::UNDEF || X86::isZeroNode(Input))
6612       Zeroable[i] = true;
6613   }
6614
6615   return Zeroable;
6616 }
6617
6618 /// \brief Try to emit a bitmask instruction for a shuffle.
6619 ///
6620 /// This handles cases where we can model a blend exactly as a bitmask due to
6621 /// one of the inputs being zeroable.
6622 static SDValue lowerVectorShuffleAsBitMask(SDLoc DL, MVT VT, SDValue V1,
6623                                            SDValue V2, ArrayRef<int> Mask,
6624                                            SelectionDAG &DAG) {
6625   MVT EltVT = VT.getScalarType();
6626   int NumEltBits = EltVT.getSizeInBits();
6627   MVT IntEltVT = MVT::getIntegerVT(NumEltBits);
6628   SDValue Zero = DAG.getConstant(0, IntEltVT);
6629   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), IntEltVT);
6630   if (EltVT.isFloatingPoint()) {
6631     Zero = DAG.getNode(ISD::BITCAST, DL, EltVT, Zero);
6632     AllOnes = DAG.getNode(ISD::BITCAST, DL, EltVT, AllOnes);
6633   }
6634   SmallVector<SDValue, 16> VMaskOps(Mask.size(), Zero);
6635   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6636   SDValue V;
6637   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6638     if (Zeroable[i])
6639       continue;
6640     if (Mask[i] % Size != i)
6641       return SDValue(); // Not a blend.
6642     if (!V)
6643       V = Mask[i] < Size ? V1 : V2;
6644     else if (V != (Mask[i] < Size ? V1 : V2))
6645       return SDValue(); // Can only let one input through the mask.
6646
6647     VMaskOps[i] = AllOnes;
6648   }
6649   if (!V)
6650     return SDValue(); // No non-zeroable elements!
6651
6652   SDValue VMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, VMaskOps);
6653   V = DAG.getNode(VT.isFloatingPoint()
6654                   ? (unsigned) X86ISD::FAND : (unsigned) ISD::AND,
6655                   DL, VT, V, VMask);
6656   return V;
6657 }
6658
6659 /// \brief Try to lower a vector shuffle as a bit shift (shifts in zeros).
6660 ///
6661 /// Attempts to match a shuffle mask against the PSLL(W/D/Q/DQ) and
6662 /// PSRL(W/D/Q/DQ) SSE2 and AVX2 logical bit-shift instructions. The function
6663 /// matches elements from one of the input vectors shuffled to the left or
6664 /// right with zeroable elements 'shifted in'. It handles both the strictly
6665 /// bit-wise element shifts and the byte shift across an entire 128-bit double
6666 /// quad word lane.
6667 ///
6668 /// PSHL : (little-endian) left bit shift.
6669 /// [ zz, 0, zz,  2 ]
6670 /// [ -1, 4, zz, -1 ]
6671 /// PSRL : (little-endian) right bit shift.
6672 /// [  1, zz,  3, zz]
6673 /// [ -1, -1,  7, zz]
6674 /// PSLLDQ : (little-endian) left byte shift
6675 /// [ zz,  0,  1,  2,  3,  4,  5,  6]
6676 /// [ zz, zz, -1, -1,  2,  3,  4, -1]
6677 /// [ zz, zz, zz, zz, zz, zz, -1,  1]
6678 /// PSRLDQ : (little-endian) right byte shift
6679 /// [  5, 6,  7, zz, zz, zz, zz, zz]
6680 /// [ -1, 5,  6,  7, zz, zz, zz, zz]
6681 /// [  1, 2, -1, -1, -1, -1, zz, zz]
6682 static SDValue lowerVectorShuffleAsShift(SDLoc DL, MVT VT, SDValue V1,
6683                                          SDValue V2, ArrayRef<int> Mask,
6684                                          SelectionDAG &DAG) {
6685   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6686
6687   int Size = Mask.size();
6688   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
6689
6690   auto CheckZeros = [&](int Shift, int Scale, bool Left) {
6691     for (int i = 0; i < Size; i += Scale)
6692       for (int j = 0; j < Shift; ++j)
6693         if (!Zeroable[i + j + (Left ? 0 : (Scale - Shift))])
6694           return false;
6695
6696     return true;
6697   };
6698
6699   auto MatchShift = [&](int Shift, int Scale, bool Left, SDValue V) {
6700     for (int i = 0; i != Size; i += Scale) {
6701       unsigned Pos = Left ? i + Shift : i;
6702       unsigned Low = Left ? i : i + Shift;
6703       unsigned Len = Scale - Shift;
6704       if (!isSequentialOrUndefInRange(Mask, Pos, Len,
6705                                       Low + (V == V1 ? 0 : Size)))
6706         return SDValue();
6707     }
6708
6709     int ShiftEltBits = VT.getScalarSizeInBits() * Scale;
6710     bool ByteShift = ShiftEltBits > 64;
6711     unsigned OpCode = Left ? (ByteShift ? X86ISD::VSHLDQ : X86ISD::VSHLI)
6712                            : (ByteShift ? X86ISD::VSRLDQ : X86ISD::VSRLI);
6713     int ShiftAmt = Shift * VT.getScalarSizeInBits() / (ByteShift ? 8 : 1);
6714
6715     // Normalize the scale for byte shifts to still produce an i64 element
6716     // type.
6717     Scale = ByteShift ? Scale / 2 : Scale;
6718
6719     // We need to round trip through the appropriate type for the shift.
6720     MVT ShiftSVT = MVT::getIntegerVT(VT.getScalarSizeInBits() * Scale);
6721     MVT ShiftVT = MVT::getVectorVT(ShiftSVT, Size / Scale);
6722     assert(DAG.getTargetLoweringInfo().isTypeLegal(ShiftVT) &&
6723            "Illegal integer vector type");
6724     V = DAG.getNode(ISD::BITCAST, DL, ShiftVT, V);
6725
6726     V = DAG.getNode(OpCode, DL, ShiftVT, V, DAG.getConstant(ShiftAmt, MVT::i8));
6727     return DAG.getNode(ISD::BITCAST, DL, VT, V);
6728   };
6729
6730   // SSE/AVX supports logical shifts up to 64-bit integers - so we can just
6731   // keep doubling the size of the integer elements up to that. We can
6732   // then shift the elements of the integer vector by whole multiples of
6733   // their width within the elements of the larger integer vector. Test each
6734   // multiple to see if we can find a match with the moved element indices
6735   // and that the shifted in elements are all zeroable.
6736   for (int Scale = 2; Scale * VT.getScalarSizeInBits() <= 128; Scale *= 2)
6737     for (int Shift = 1; Shift != Scale; ++Shift)
6738       for (bool Left : {true, false})
6739         if (CheckZeros(Shift, Scale, Left))
6740           for (SDValue V : {V1, V2})
6741             if (SDValue Match = MatchShift(Shift, Scale, Left, V))
6742               return Match;
6743
6744   // no match
6745   return SDValue();
6746 }
6747
6748 /// \brief Lower a vector shuffle as a zero or any extension.
6749 ///
6750 /// Given a specific number of elements, element bit width, and extension
6751 /// stride, produce either a zero or any extension based on the available
6752 /// features of the subtarget.
6753 static SDValue lowerVectorShuffleAsSpecificZeroOrAnyExtend(
6754     SDLoc DL, MVT VT, int Scale, bool AnyExt, SDValue InputV,
6755     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6756   assert(Scale > 1 && "Need a scale to extend.");
6757   int NumElements = VT.getVectorNumElements();
6758   int EltBits = VT.getScalarSizeInBits();
6759   assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
6760          "Only 8, 16, and 32 bit elements can be extended.");
6761   assert(Scale * EltBits <= 64 && "Cannot zero extend past 64 bits.");
6762
6763   // Found a valid zext mask! Try various lowering strategies based on the
6764   // input type and available ISA extensions.
6765   if (Subtarget->hasSSE41()) {
6766     MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits * Scale),
6767                                  NumElements / Scale);
6768     return DAG.getNode(ISD::BITCAST, DL, VT,
6769                        DAG.getNode(X86ISD::VZEXT, DL, ExtVT, InputV));
6770   }
6771
6772   // For any extends we can cheat for larger element sizes and use shuffle
6773   // instructions that can fold with a load and/or copy.
6774   if (AnyExt && EltBits == 32) {
6775     int PSHUFDMask[4] = {0, -1, 1, -1};
6776     return DAG.getNode(
6777         ISD::BITCAST, DL, VT,
6778         DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
6779                     DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, InputV),
6780                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
6781   }
6782   if (AnyExt && EltBits == 16 && Scale > 2) {
6783     int PSHUFDMask[4] = {0, -1, 0, -1};
6784     InputV = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
6785                          DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, InputV),
6786                          getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG));
6787     int PSHUFHWMask[4] = {1, -1, -1, -1};
6788     return DAG.getNode(
6789         ISD::BITCAST, DL, VT,
6790         DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16,
6791                     DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, InputV),
6792                     getV4X86ShuffleImm8ForMask(PSHUFHWMask, DAG)));
6793   }
6794
6795   // If this would require more than 2 unpack instructions to expand, use
6796   // pshufb when available. We can only use more than 2 unpack instructions
6797   // when zero extending i8 elements which also makes it easier to use pshufb.
6798   if (Scale > 4 && EltBits == 8 && Subtarget->hasSSSE3()) {
6799     assert(NumElements == 16 && "Unexpected byte vector width!");
6800     SDValue PSHUFBMask[16];
6801     for (int i = 0; i < 16; ++i)
6802       PSHUFBMask[i] =
6803           DAG.getConstant((i % Scale == 0) ? i / Scale : 0x80, MVT::i8);
6804     InputV = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, InputV);
6805     return DAG.getNode(ISD::BITCAST, DL, VT,
6806                        DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, InputV,
6807                                    DAG.getNode(ISD::BUILD_VECTOR, DL,
6808                                                MVT::v16i8, PSHUFBMask)));
6809   }
6810
6811   // Otherwise emit a sequence of unpacks.
6812   do {
6813     MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
6814     SDValue Ext = AnyExt ? DAG.getUNDEF(InputVT)
6815                          : getZeroVector(InputVT, Subtarget, DAG, DL);
6816     InputV = DAG.getNode(ISD::BITCAST, DL, InputVT, InputV);
6817     InputV = DAG.getNode(X86ISD::UNPCKL, DL, InputVT, InputV, Ext);
6818     Scale /= 2;
6819     EltBits *= 2;
6820     NumElements /= 2;
6821   } while (Scale > 1);
6822   return DAG.getNode(ISD::BITCAST, DL, VT, InputV);
6823 }
6824
6825 /// \brief Try to lower a vector shuffle as a zero extension on any microarch.
6826 ///
6827 /// This routine will try to do everything in its power to cleverly lower
6828 /// a shuffle which happens to match the pattern of a zero extend. It doesn't
6829 /// check for the profitability of this lowering,  it tries to aggressively
6830 /// match this pattern. It will use all of the micro-architectural details it
6831 /// can to emit an efficient lowering. It handles both blends with all-zero
6832 /// inputs to explicitly zero-extend and undef-lanes (sometimes undef due to
6833 /// masking out later).
6834 ///
6835 /// The reason we have dedicated lowering for zext-style shuffles is that they
6836 /// are both incredibly common and often quite performance sensitive.
6837 static SDValue lowerVectorShuffleAsZeroOrAnyExtend(
6838     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
6839     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6840   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6841
6842   int Bits = VT.getSizeInBits();
6843   int NumElements = VT.getVectorNumElements();
6844   assert(VT.getScalarSizeInBits() <= 32 &&
6845          "Exceeds 32-bit integer zero extension limit");
6846   assert((int)Mask.size() == NumElements && "Unexpected shuffle mask size");
6847
6848   // Define a helper function to check a particular ext-scale and lower to it if
6849   // valid.
6850   auto Lower = [&](int Scale) -> SDValue {
6851     SDValue InputV;
6852     bool AnyExt = true;
6853     for (int i = 0; i < NumElements; ++i) {
6854       if (Mask[i] == -1)
6855         continue; // Valid anywhere but doesn't tell us anything.
6856       if (i % Scale != 0) {
6857         // Each of the extended elements need to be zeroable.
6858         if (!Zeroable[i])
6859           return SDValue();
6860
6861         // We no longer are in the anyext case.
6862         AnyExt = false;
6863         continue;
6864       }
6865
6866       // Each of the base elements needs to be consecutive indices into the
6867       // same input vector.
6868       SDValue V = Mask[i] < NumElements ? V1 : V2;
6869       if (!InputV)
6870         InputV = V;
6871       else if (InputV != V)
6872         return SDValue(); // Flip-flopping inputs.
6873
6874       if (Mask[i] % NumElements != i / Scale)
6875         return SDValue(); // Non-consecutive strided elements.
6876     }
6877
6878     // If we fail to find an input, we have a zero-shuffle which should always
6879     // have already been handled.
6880     // FIXME: Maybe handle this here in case during blending we end up with one?
6881     if (!InputV)
6882       return SDValue();
6883
6884     return lowerVectorShuffleAsSpecificZeroOrAnyExtend(
6885         DL, VT, Scale, AnyExt, InputV, Subtarget, DAG);
6886   };
6887
6888   // The widest scale possible for extending is to a 64-bit integer.
6889   assert(Bits % 64 == 0 &&
6890          "The number of bits in a vector must be divisible by 64 on x86!");
6891   int NumExtElements = Bits / 64;
6892
6893   // Each iteration, try extending the elements half as much, but into twice as
6894   // many elements.
6895   for (; NumExtElements < NumElements; NumExtElements *= 2) {
6896     assert(NumElements % NumExtElements == 0 &&
6897            "The input vector size must be divisible by the extended size.");
6898     if (SDValue V = Lower(NumElements / NumExtElements))
6899       return V;
6900   }
6901
6902   // General extends failed, but 128-bit vectors may be able to use MOVQ.
6903   if (Bits != 128)
6904     return SDValue();
6905
6906   // Returns one of the source operands if the shuffle can be reduced to a
6907   // MOVQ, copying the lower 64-bits and zero-extending to the upper 64-bits.
6908   auto CanZExtLowHalf = [&]() {
6909     for (int i = NumElements / 2; i != NumElements; ++i)
6910       if (!Zeroable[i])
6911         return SDValue();
6912     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, 0))
6913       return V1;
6914     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, NumElements))
6915       return V2;
6916     return SDValue();
6917   };
6918
6919   if (SDValue V = CanZExtLowHalf()) {
6920     V = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, V);
6921     V = DAG.getNode(X86ISD::VZEXT_MOVL, DL, MVT::v2i64, V);
6922     return DAG.getNode(ISD::BITCAST, DL, VT, V);
6923   }
6924
6925   // No viable ext lowering found.
6926   return SDValue();
6927 }
6928
6929 /// \brief Try to get a scalar value for a specific element of a vector.
6930 ///
6931 /// Looks through BUILD_VECTOR and SCALAR_TO_VECTOR nodes to find a scalar.
6932 static SDValue getScalarValueForVectorElement(SDValue V, int Idx,
6933                                               SelectionDAG &DAG) {
6934   MVT VT = V.getSimpleValueType();
6935   MVT EltVT = VT.getVectorElementType();
6936   while (V.getOpcode() == ISD::BITCAST)
6937     V = V.getOperand(0);
6938   // If the bitcasts shift the element size, we can't extract an equivalent
6939   // element from it.
6940   MVT NewVT = V.getSimpleValueType();
6941   if (!NewVT.isVector() || NewVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
6942     return SDValue();
6943
6944   if (V.getOpcode() == ISD::BUILD_VECTOR ||
6945       (Idx == 0 && V.getOpcode() == ISD::SCALAR_TO_VECTOR)) {
6946     // Ensure the scalar operand is the same size as the destination.
6947     // FIXME: Add support for scalar truncation where possible.
6948     SDValue S = V.getOperand(Idx);
6949     if (EltVT.getSizeInBits() == S.getSimpleValueType().getSizeInBits())
6950       return DAG.getNode(ISD::BITCAST, SDLoc(V), EltVT, S);
6951   }
6952
6953   return SDValue();
6954 }
6955
6956 /// \brief Helper to test for a load that can be folded with x86 shuffles.
6957 ///
6958 /// This is particularly important because the set of instructions varies
6959 /// significantly based on whether the operand is a load or not.
6960 static bool isShuffleFoldableLoad(SDValue V) {
6961   while (V.getOpcode() == ISD::BITCAST)
6962     V = V.getOperand(0);
6963
6964   return ISD::isNON_EXTLoad(V.getNode());
6965 }
6966
6967 /// \brief Try to lower insertion of a single element into a zero vector.
6968 ///
6969 /// This is a common pattern that we have especially efficient patterns to lower
6970 /// across all subtarget feature sets.
6971 static SDValue lowerVectorShuffleAsElementInsertion(
6972     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
6973     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6974   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6975   MVT ExtVT = VT;
6976   MVT EltVT = VT.getVectorElementType();
6977
6978   int V2Index = std::find_if(Mask.begin(), Mask.end(),
6979                              [&Mask](int M) { return M >= (int)Mask.size(); }) -
6980                 Mask.begin();
6981   bool IsV1Zeroable = true;
6982   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6983     if (i != V2Index && !Zeroable[i]) {
6984       IsV1Zeroable = false;
6985       break;
6986     }
6987
6988   // Check for a single input from a SCALAR_TO_VECTOR node.
6989   // FIXME: All of this should be canonicalized into INSERT_VECTOR_ELT and
6990   // all the smarts here sunk into that routine. However, the current
6991   // lowering of BUILD_VECTOR makes that nearly impossible until the old
6992   // vector shuffle lowering is dead.
6993   if (SDValue V2S = getScalarValueForVectorElement(
6994           V2, Mask[V2Index] - Mask.size(), DAG)) {
6995     // We need to zext the scalar if it is smaller than an i32.
6996     V2S = DAG.getNode(ISD::BITCAST, DL, EltVT, V2S);
6997     if (EltVT == MVT::i8 || EltVT == MVT::i16) {
6998       // Using zext to expand a narrow element won't work for non-zero
6999       // insertions.
7000       if (!IsV1Zeroable)
7001         return SDValue();
7002
7003       // Zero-extend directly to i32.
7004       ExtVT = MVT::v4i32;
7005       V2S = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, V2S);
7006     }
7007     V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
7008   } else if (Mask[V2Index] != (int)Mask.size() || EltVT == MVT::i8 ||
7009              EltVT == MVT::i16) {
7010     // Either not inserting from the low element of the input or the input
7011     // element size is too small to use VZEXT_MOVL to clear the high bits.
7012     return SDValue();
7013   }
7014
7015   if (!IsV1Zeroable) {
7016     // If V1 can't be treated as a zero vector we have fewer options to lower
7017     // this. We can't support integer vectors or non-zero targets cheaply, and
7018     // the V1 elements can't be permuted in any way.
7019     assert(VT == ExtVT && "Cannot change extended type when non-zeroable!");
7020     if (!VT.isFloatingPoint() || V2Index != 0)
7021       return SDValue();
7022     SmallVector<int, 8> V1Mask(Mask.begin(), Mask.end());
7023     V1Mask[V2Index] = -1;
7024     if (!isNoopShuffleMask(V1Mask))
7025       return SDValue();
7026     // This is essentially a special case blend operation, but if we have
7027     // general purpose blend operations, they are always faster. Bail and let
7028     // the rest of the lowering handle these as blends.
7029     if (Subtarget->hasSSE41())
7030       return SDValue();
7031
7032     // Otherwise, use MOVSD or MOVSS.
7033     assert((EltVT == MVT::f32 || EltVT == MVT::f64) &&
7034            "Only two types of floating point element types to handle!");
7035     return DAG.getNode(EltVT == MVT::f32 ? X86ISD::MOVSS : X86ISD::MOVSD, DL,
7036                        ExtVT, V1, V2);
7037   }
7038
7039   // This lowering only works for the low element with floating point vectors.
7040   if (VT.isFloatingPoint() && V2Index != 0)
7041     return SDValue();
7042
7043   V2 = DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2);
7044   if (ExtVT != VT)
7045     V2 = DAG.getNode(ISD::BITCAST, DL, VT, V2);
7046
7047   if (V2Index != 0) {
7048     // If we have 4 or fewer lanes we can cheaply shuffle the element into
7049     // the desired position. Otherwise it is more efficient to do a vector
7050     // shift left. We know that we can do a vector shift left because all
7051     // the inputs are zero.
7052     if (VT.isFloatingPoint() || VT.getVectorNumElements() <= 4) {
7053       SmallVector<int, 4> V2Shuffle(Mask.size(), 1);
7054       V2Shuffle[V2Index] = 0;
7055       V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Shuffle);
7056     } else {
7057       V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, V2);
7058       V2 = DAG.getNode(
7059           X86ISD::VSHLDQ, DL, MVT::v2i64, V2,
7060           DAG.getConstant(
7061               V2Index * EltVT.getSizeInBits()/8,
7062               DAG.getTargetLoweringInfo().getScalarShiftAmountTy(MVT::v2i64)));
7063       V2 = DAG.getNode(ISD::BITCAST, DL, VT, V2);
7064     }
7065   }
7066   return V2;
7067 }
7068
7069 /// \brief Try to lower broadcast of a single element.
7070 ///
7071 /// For convenience, this code also bundles all of the subtarget feature set
7072 /// filtering. While a little annoying to re-dispatch on type here, there isn't
7073 /// a convenient way to factor it out.
7074 static SDValue lowerVectorShuffleAsBroadcast(SDLoc DL, MVT VT, SDValue V,
7075                                              ArrayRef<int> Mask,
7076                                              const X86Subtarget *Subtarget,
7077                                              SelectionDAG &DAG) {
7078   if (!Subtarget->hasAVX())
7079     return SDValue();
7080   if (VT.isInteger() && !Subtarget->hasAVX2())
7081     return SDValue();
7082
7083   // Check that the mask is a broadcast.
7084   int BroadcastIdx = -1;
7085   for (int M : Mask)
7086     if (M >= 0 && BroadcastIdx == -1)
7087       BroadcastIdx = M;
7088     else if (M >= 0 && M != BroadcastIdx)
7089       return SDValue();
7090
7091   assert(BroadcastIdx < (int)Mask.size() && "We only expect to be called with "
7092                                             "a sorted mask where the broadcast "
7093                                             "comes from V1.");
7094
7095   // Go up the chain of (vector) values to find a scalar load that we can
7096   // combine with the broadcast.
7097   for (;;) {
7098     switch (V.getOpcode()) {
7099     case ISD::CONCAT_VECTORS: {
7100       int OperandSize = Mask.size() / V.getNumOperands();
7101       V = V.getOperand(BroadcastIdx / OperandSize);
7102       BroadcastIdx %= OperandSize;
7103       continue;
7104     }
7105
7106     case ISD::INSERT_SUBVECTOR: {
7107       SDValue VOuter = V.getOperand(0), VInner = V.getOperand(1);
7108       auto ConstantIdx = dyn_cast<ConstantSDNode>(V.getOperand(2));
7109       if (!ConstantIdx)
7110         break;
7111
7112       int BeginIdx = (int)ConstantIdx->getZExtValue();
7113       int EndIdx =
7114           BeginIdx + (int)VInner.getValueType().getVectorNumElements();
7115       if (BroadcastIdx >= BeginIdx && BroadcastIdx < EndIdx) {
7116         BroadcastIdx -= BeginIdx;
7117         V = VInner;
7118       } else {
7119         V = VOuter;
7120       }
7121       continue;
7122     }
7123     }
7124     break;
7125   }
7126
7127   // Check if this is a broadcast of a scalar. We special case lowering
7128   // for scalars so that we can more effectively fold with loads.
7129   if (V.getOpcode() == ISD::BUILD_VECTOR ||
7130       (V.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)) {
7131     V = V.getOperand(BroadcastIdx);
7132
7133     // If the scalar isn't a load, we can't broadcast from it in AVX1.
7134     // Only AVX2 has register broadcasts.
7135     if (!Subtarget->hasAVX2() && !isShuffleFoldableLoad(V))
7136       return SDValue();
7137   } else if (BroadcastIdx != 0 || !Subtarget->hasAVX2()) {
7138     // We can't broadcast from a vector register without AVX2, and we can only
7139     // broadcast from the zero-element of a vector register.
7140     return SDValue();
7141   }
7142
7143   return DAG.getNode(X86ISD::VBROADCAST, DL, VT, V);
7144 }
7145
7146 // Check for whether we can use INSERTPS to perform the shuffle. We only use
7147 // INSERTPS when the V1 elements are already in the correct locations
7148 // because otherwise we can just always use two SHUFPS instructions which
7149 // are much smaller to encode than a SHUFPS and an INSERTPS. We can also
7150 // perform INSERTPS if a single V1 element is out of place and all V2
7151 // elements are zeroable.
7152 static SDValue lowerVectorShuffleAsInsertPS(SDValue Op, SDValue V1, SDValue V2,
7153                                             ArrayRef<int> Mask,
7154                                             SelectionDAG &DAG) {
7155   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7156   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7157   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7158   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7159
7160   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7161
7162   unsigned ZMask = 0;
7163   int V1DstIndex = -1;
7164   int V2DstIndex = -1;
7165   bool V1UsedInPlace = false;
7166
7167   for (int i = 0; i < 4; ++i) {
7168     // Synthesize a zero mask from the zeroable elements (includes undefs).
7169     if (Zeroable[i]) {
7170       ZMask |= 1 << i;
7171       continue;
7172     }
7173
7174     // Flag if we use any V1 inputs in place.
7175     if (i == Mask[i]) {
7176       V1UsedInPlace = true;
7177       continue;
7178     }
7179
7180     // We can only insert a single non-zeroable element.
7181     if (V1DstIndex != -1 || V2DstIndex != -1)
7182       return SDValue();
7183
7184     if (Mask[i] < 4) {
7185       // V1 input out of place for insertion.
7186       V1DstIndex = i;
7187     } else {
7188       // V2 input for insertion.
7189       V2DstIndex = i;
7190     }
7191   }
7192
7193   // Don't bother if we have no (non-zeroable) element for insertion.
7194   if (V1DstIndex == -1 && V2DstIndex == -1)
7195     return SDValue();
7196
7197   // Determine element insertion src/dst indices. The src index is from the
7198   // start of the inserted vector, not the start of the concatenated vector.
7199   unsigned V2SrcIndex = 0;
7200   if (V1DstIndex != -1) {
7201     // If we have a V1 input out of place, we use V1 as the V2 element insertion
7202     // and don't use the original V2 at all.
7203     V2SrcIndex = Mask[V1DstIndex];
7204     V2DstIndex = V1DstIndex;
7205     V2 = V1;
7206   } else {
7207     V2SrcIndex = Mask[V2DstIndex] - 4;
7208   }
7209
7210   // If no V1 inputs are used in place, then the result is created only from
7211   // the zero mask and the V2 insertion - so remove V1 dependency.
7212   if (!V1UsedInPlace)
7213     V1 = DAG.getUNDEF(MVT::v4f32);
7214
7215   unsigned InsertPSMask = V2SrcIndex << 6 | V2DstIndex << 4 | ZMask;
7216   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
7217
7218   // Insert the V2 element into the desired position.
7219   SDLoc DL(Op);
7220   return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
7221                      DAG.getConstant(InsertPSMask, MVT::i8));
7222 }
7223
7224 /// \brief Try to lower a shuffle as a permute of the inputs followed by an
7225 /// UNPCK instruction.
7226 ///
7227 /// This specifically targets cases where we end up with alternating between
7228 /// the two inputs, and so can permute them into something that feeds a single
7229 /// UNPCK instruction. Note that this routine only targets integer vectors
7230 /// because for floating point vectors we have a generalized SHUFPS lowering
7231 /// strategy that handles everything that doesn't *exactly* match an unpack,
7232 /// making this clever lowering unnecessary.
7233 static SDValue lowerVectorShuffleAsUnpack(SDLoc DL, MVT VT, SDValue V1,
7234                                           SDValue V2, ArrayRef<int> Mask,
7235                                           SelectionDAG &DAG) {
7236   assert(!VT.isFloatingPoint() &&
7237          "This routine only supports integer vectors.");
7238   assert(!isSingleInputShuffleMask(Mask) &&
7239          "This routine should only be used when blending two inputs.");
7240   assert(Mask.size() >= 2 && "Single element masks are invalid.");
7241
7242   int Size = Mask.size();
7243
7244   int NumLoInputs = std::count_if(Mask.begin(), Mask.end(), [Size](int M) {
7245     return M >= 0 && M % Size < Size / 2;
7246   });
7247   int NumHiInputs = std::count_if(
7248       Mask.begin(), Mask.end(), [Size](int M) { return M % Size >= Size / 2; });
7249
7250   bool UnpackLo = NumLoInputs >= NumHiInputs;
7251
7252   auto TryUnpack = [&](MVT UnpackVT, int Scale) {
7253     SmallVector<int, 32> V1Mask(Mask.size(), -1);
7254     SmallVector<int, 32> V2Mask(Mask.size(), -1);
7255
7256     for (int i = 0; i < Size; ++i) {
7257       if (Mask[i] < 0)
7258         continue;
7259
7260       // Each element of the unpack contains Scale elements from this mask.
7261       int UnpackIdx = i / Scale;
7262
7263       // We only handle the case where V1 feeds the first slots of the unpack.
7264       // We rely on canonicalization to ensure this is the case.
7265       if ((UnpackIdx % 2 == 0) != (Mask[i] < Size))
7266         return SDValue();
7267
7268       // Setup the mask for this input. The indexing is tricky as we have to
7269       // handle the unpack stride.
7270       SmallVectorImpl<int> &VMask = (UnpackIdx % 2 == 0) ? V1Mask : V2Mask;
7271       VMask[(UnpackIdx / 2) * Scale + i % Scale + (UnpackLo ? 0 : Size / 2)] =
7272           Mask[i] % Size;
7273     }
7274
7275     // If we will have to shuffle both inputs to use the unpack, check whether
7276     // we can just unpack first and shuffle the result. If so, skip this unpack.
7277     if ((NumLoInputs == 0 || NumHiInputs == 0) && !isNoopShuffleMask(V1Mask) &&
7278         !isNoopShuffleMask(V2Mask))
7279       return SDValue();
7280
7281     // Shuffle the inputs into place.
7282     V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
7283     V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
7284
7285     // Cast the inputs to the type we will use to unpack them.
7286     V1 = DAG.getNode(ISD::BITCAST, DL, UnpackVT, V1);
7287     V2 = DAG.getNode(ISD::BITCAST, DL, UnpackVT, V2);
7288
7289     // Unpack the inputs and cast the result back to the desired type.
7290     return DAG.getNode(ISD::BITCAST, DL, VT,
7291                        DAG.getNode(UnpackLo ? X86ISD::UNPCKL : X86ISD::UNPCKH,
7292                                    DL, UnpackVT, V1, V2));
7293   };
7294
7295   // We try each unpack from the largest to the smallest to try and find one
7296   // that fits this mask.
7297   int OrigNumElements = VT.getVectorNumElements();
7298   int OrigScalarSize = VT.getScalarSizeInBits();
7299   for (int ScalarSize = 64; ScalarSize >= OrigScalarSize; ScalarSize /= 2) {
7300     int Scale = ScalarSize / OrigScalarSize;
7301     int NumElements = OrigNumElements / Scale;
7302     MVT UnpackVT = MVT::getVectorVT(MVT::getIntegerVT(ScalarSize), NumElements);
7303     if (SDValue Unpack = TryUnpack(UnpackVT, Scale))
7304       return Unpack;
7305   }
7306
7307   // If none of the unpack-rooted lowerings worked (or were profitable) try an
7308   // initial unpack.
7309   if (NumLoInputs == 0 || NumHiInputs == 0) {
7310     assert((NumLoInputs > 0 || NumHiInputs > 0) &&
7311            "We have to have *some* inputs!");
7312     int HalfOffset = NumLoInputs == 0 ? Size / 2 : 0;
7313
7314     // FIXME: We could consider the total complexity of the permute of each
7315     // possible unpacking. Or at the least we should consider how many
7316     // half-crossings are created.
7317     // FIXME: We could consider commuting the unpacks.
7318
7319     SmallVector<int, 32> PermMask;
7320     PermMask.assign(Size, -1);
7321     for (int i = 0; i < Size; ++i) {
7322       if (Mask[i] < 0)
7323         continue;
7324
7325       assert(Mask[i] % Size >= HalfOffset && "Found input from wrong half!");
7326
7327       PermMask[i] =
7328           2 * ((Mask[i] % Size) - HalfOffset) + (Mask[i] < Size ? 0 : 1);
7329     }
7330     return DAG.getVectorShuffle(
7331         VT, DL, DAG.getNode(NumLoInputs == 0 ? X86ISD::UNPCKH : X86ISD::UNPCKL,
7332                             DL, VT, V1, V2),
7333         DAG.getUNDEF(VT), PermMask);
7334   }
7335
7336   return SDValue();
7337 }
7338
7339 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
7340 ///
7341 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
7342 /// support for floating point shuffles but not integer shuffles. These
7343 /// instructions will incur a domain crossing penalty on some chips though so
7344 /// it is better to avoid lowering through this for integer vectors where
7345 /// possible.
7346 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7347                                        const X86Subtarget *Subtarget,
7348                                        SelectionDAG &DAG) {
7349   SDLoc DL(Op);
7350   assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
7351   assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7352   assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7353   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7354   ArrayRef<int> Mask = SVOp->getMask();
7355   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7356
7357   if (isSingleInputShuffleMask(Mask)) {
7358     // Use low duplicate instructions for masks that match their pattern.
7359     if (Subtarget->hasSSE3())
7360       if (isShuffleEquivalent(V1, V2, Mask, {0, 0}))
7361         return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v2f64, V1);
7362
7363     // Straight shuffle of a single input vector. Simulate this by using the
7364     // single input as both of the "inputs" to this instruction..
7365     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
7366
7367     if (Subtarget->hasAVX()) {
7368       // If we have AVX, we can use VPERMILPS which will allow folding a load
7369       // into the shuffle.
7370       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v2f64, V1,
7371                          DAG.getConstant(SHUFPDMask, MVT::i8));
7372     }
7373
7374     return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V1,
7375                        DAG.getConstant(SHUFPDMask, MVT::i8));
7376   }
7377   assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
7378   assert(Mask[1] >= 2 && "Non-canonicalized blend!");
7379
7380   // If we have a single input, insert that into V1 if we can do so cheaply.
7381   if ((Mask[0] >= 2) + (Mask[1] >= 2) == 1) {
7382     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7383             DL, MVT::v2f64, V1, V2, Mask, Subtarget, DAG))
7384       return Insertion;
7385     // Try inverting the insertion since for v2 masks it is easy to do and we
7386     // can't reliably sort the mask one way or the other.
7387     int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
7388                           Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
7389     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7390             DL, MVT::v2f64, V2, V1, InverseMask, Subtarget, DAG))
7391       return Insertion;
7392   }
7393
7394   // Try to use one of the special instruction patterns to handle two common
7395   // blend patterns if a zero-blend above didn't work.
7396   if (isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
7397       isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7398     if (SDValue V1S = getScalarValueForVectorElement(V1, Mask[0], DAG))
7399       // We can either use a special instruction to load over the low double or
7400       // to move just the low double.
7401       return DAG.getNode(
7402           isShuffleFoldableLoad(V1S) ? X86ISD::MOVLPD : X86ISD::MOVSD,
7403           DL, MVT::v2f64, V2,
7404           DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V1S));
7405
7406   if (Subtarget->hasSSE41())
7407     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2f64, V1, V2, Mask,
7408                                                   Subtarget, DAG))
7409       return Blend;
7410
7411   // Use dedicated unpack instructions for masks that match their pattern.
7412   if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7413     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2f64, V1, V2);
7414   if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7415     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2f64, V1, V2);
7416
7417   unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
7418   return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V2,
7419                      DAG.getConstant(SHUFPDMask, MVT::i8));
7420 }
7421
7422 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
7423 ///
7424 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
7425 /// the integer unit to minimize domain crossing penalties. However, for blends
7426 /// it falls back to the floating point shuffle operation with appropriate bit
7427 /// casting.
7428 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7429                                        const X86Subtarget *Subtarget,
7430                                        SelectionDAG &DAG) {
7431   SDLoc DL(Op);
7432   assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
7433   assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7434   assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7435   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7436   ArrayRef<int> Mask = SVOp->getMask();
7437   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7438
7439   if (isSingleInputShuffleMask(Mask)) {
7440     // Check for being able to broadcast a single element.
7441     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v2i64, V1,
7442                                                           Mask, Subtarget, DAG))
7443       return Broadcast;
7444
7445     // Straight shuffle of a single input vector. For everything from SSE2
7446     // onward this has a single fast instruction with no scary immediates.
7447     // We have to map the mask as it is actually a v4i32 shuffle instruction.
7448     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V1);
7449     int WidenedMask[4] = {
7450         std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
7451         std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
7452     return DAG.getNode(
7453         ISD::BITCAST, DL, MVT::v2i64,
7454         DAG.getNode(X86ISD::PSHUFD, SDLoc(Op), MVT::v4i32, V1,
7455                     getV4X86ShuffleImm8ForMask(WidenedMask, DAG)));
7456   }
7457   assert(Mask[0] != -1 && "No undef lanes in multi-input v2 shuffles!");
7458   assert(Mask[1] != -1 && "No undef lanes in multi-input v2 shuffles!");
7459   assert(Mask[0] < 2 && "We sort V1 to be the first input.");
7460   assert(Mask[1] >= 2 && "We sort V2 to be the second input.");
7461
7462   // If we have a blend of two PACKUS operations an the blend aligns with the
7463   // low and half halves, we can just merge the PACKUS operations. This is
7464   // particularly important as it lets us merge shuffles that this routine itself
7465   // creates.
7466   auto GetPackNode = [](SDValue V) {
7467     while (V.getOpcode() == ISD::BITCAST)
7468       V = V.getOperand(0);
7469
7470     return V.getOpcode() == X86ISD::PACKUS ? V : SDValue();
7471   };
7472   if (SDValue V1Pack = GetPackNode(V1))
7473     if (SDValue V2Pack = GetPackNode(V2))
7474       return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7475                          DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8,
7476                                      Mask[0] == 0 ? V1Pack.getOperand(0)
7477                                                   : V1Pack.getOperand(1),
7478                                      Mask[1] == 2 ? V2Pack.getOperand(0)
7479                                                   : V2Pack.getOperand(1)));
7480
7481   // Try to use shift instructions.
7482   if (SDValue Shift =
7483           lowerVectorShuffleAsShift(DL, MVT::v2i64, V1, V2, Mask, DAG))
7484     return Shift;
7485
7486   // When loading a scalar and then shuffling it into a vector we can often do
7487   // the insertion cheaply.
7488   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7489           DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
7490     return Insertion;
7491   // Try inverting the insertion since for v2 masks it is easy to do and we
7492   // can't reliably sort the mask one way or the other.
7493   int InverseMask[2] = {Mask[0] ^ 2, Mask[1] ^ 2};
7494   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7495           DL, MVT::v2i64, V2, V1, InverseMask, Subtarget, DAG))
7496     return Insertion;
7497
7498   // We have different paths for blend lowering, but they all must use the
7499   // *exact* same predicate.
7500   bool IsBlendSupported = Subtarget->hasSSE41();
7501   if (IsBlendSupported)
7502     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2i64, V1, V2, Mask,
7503                                                   Subtarget, DAG))
7504       return Blend;
7505
7506   // Use dedicated unpack instructions for masks that match their pattern.
7507   if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7508     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, V1, V2);
7509   if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7510     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2i64, V1, V2);
7511
7512   // Try to use byte rotation instructions.
7513   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
7514   if (Subtarget->hasSSSE3())
7515     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
7516             DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
7517       return Rotate;
7518
7519   // If we have direct support for blends, we should lower by decomposing into
7520   // a permute. That will be faster than the domain cross.
7521   if (IsBlendSupported)
7522     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v2i64, V1, V2,
7523                                                       Mask, DAG);
7524
7525   // We implement this with SHUFPD which is pretty lame because it will likely
7526   // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
7527   // However, all the alternatives are still more cycles and newer chips don't
7528   // have this problem. It would be really nice if x86 had better shuffles here.
7529   V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V1);
7530   V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V2);
7531   return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7532                      DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
7533 }
7534
7535 /// \brief Test whether this can be lowered with a single SHUFPS instruction.
7536 ///
7537 /// This is used to disable more specialized lowerings when the shufps lowering
7538 /// will happen to be efficient.
7539 static bool isSingleSHUFPSMask(ArrayRef<int> Mask) {
7540   // This routine only handles 128-bit shufps.
7541   assert(Mask.size() == 4 && "Unsupported mask size!");
7542
7543   // To lower with a single SHUFPS we need to have the low half and high half
7544   // each requiring a single input.
7545   if (Mask[0] != -1 && Mask[1] != -1 && (Mask[0] < 4) != (Mask[1] < 4))
7546     return false;
7547   if (Mask[2] != -1 && Mask[3] != -1 && (Mask[2] < 4) != (Mask[3] < 4))
7548     return false;
7549
7550   return true;
7551 }
7552
7553 /// \brief Lower a vector shuffle using the SHUFPS instruction.
7554 ///
7555 /// This is a helper routine dedicated to lowering vector shuffles using SHUFPS.
7556 /// It makes no assumptions about whether this is the *best* lowering, it simply
7557 /// uses it.
7558 static SDValue lowerVectorShuffleWithSHUFPS(SDLoc DL, MVT VT,
7559                                             ArrayRef<int> Mask, SDValue V1,
7560                                             SDValue V2, SelectionDAG &DAG) {
7561   SDValue LowV = V1, HighV = V2;
7562   int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
7563
7564   int NumV2Elements =
7565       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7566
7567   if (NumV2Elements == 1) {
7568     int V2Index =
7569         std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
7570         Mask.begin();
7571
7572     // Compute the index adjacent to V2Index and in the same half by toggling
7573     // the low bit.
7574     int V2AdjIndex = V2Index ^ 1;
7575
7576     if (Mask[V2AdjIndex] == -1) {
7577       // Handles all the cases where we have a single V2 element and an undef.
7578       // This will only ever happen in the high lanes because we commute the
7579       // vector otherwise.
7580       if (V2Index < 2)
7581         std::swap(LowV, HighV);
7582       NewMask[V2Index] -= 4;
7583     } else {
7584       // Handle the case where the V2 element ends up adjacent to a V1 element.
7585       // To make this work, blend them together as the first step.
7586       int V1Index = V2AdjIndex;
7587       int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
7588       V2 = DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
7589                        getV4X86ShuffleImm8ForMask(BlendMask, DAG));
7590
7591       // Now proceed to reconstruct the final blend as we have the necessary
7592       // high or low half formed.
7593       if (V2Index < 2) {
7594         LowV = V2;
7595         HighV = V1;
7596       } else {
7597         HighV = V2;
7598       }
7599       NewMask[V1Index] = 2; // We put the V1 element in V2[2].
7600       NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
7601     }
7602   } else if (NumV2Elements == 2) {
7603     if (Mask[0] < 4 && Mask[1] < 4) {
7604       // Handle the easy case where we have V1 in the low lanes and V2 in the
7605       // high lanes.
7606       NewMask[2] -= 4;
7607       NewMask[3] -= 4;
7608     } else if (Mask[2] < 4 && Mask[3] < 4) {
7609       // We also handle the reversed case because this utility may get called
7610       // when we detect a SHUFPS pattern but can't easily commute the shuffle to
7611       // arrange things in the right direction.
7612       NewMask[0] -= 4;
7613       NewMask[1] -= 4;
7614       HighV = V1;
7615       LowV = V2;
7616     } else {
7617       // We have a mixture of V1 and V2 in both low and high lanes. Rather than
7618       // trying to place elements directly, just blend them and set up the final
7619       // shuffle to place them.
7620
7621       // The first two blend mask elements are for V1, the second two are for
7622       // V2.
7623       int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
7624                           Mask[2] < 4 ? Mask[2] : Mask[3],
7625                           (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
7626                           (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
7627       V1 = DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
7628                        getV4X86ShuffleImm8ForMask(BlendMask, DAG));
7629
7630       // Now we do a normal shuffle of V1 by giving V1 as both operands to
7631       // a blend.
7632       LowV = HighV = V1;
7633       NewMask[0] = Mask[0] < 4 ? 0 : 2;
7634       NewMask[1] = Mask[0] < 4 ? 2 : 0;
7635       NewMask[2] = Mask[2] < 4 ? 1 : 3;
7636       NewMask[3] = Mask[2] < 4 ? 3 : 1;
7637     }
7638   }
7639   return DAG.getNode(X86ISD::SHUFP, DL, VT, LowV, HighV,
7640                      getV4X86ShuffleImm8ForMask(NewMask, DAG));
7641 }
7642
7643 /// \brief Lower 4-lane 32-bit floating point shuffles.
7644 ///
7645 /// Uses instructions exclusively from the floating point unit to minimize
7646 /// domain crossing penalties, as these are sufficient to implement all v4f32
7647 /// shuffles.
7648 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7649                                        const X86Subtarget *Subtarget,
7650                                        SelectionDAG &DAG) {
7651   SDLoc DL(Op);
7652   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7653   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7654   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7655   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7656   ArrayRef<int> Mask = SVOp->getMask();
7657   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7658
7659   int NumV2Elements =
7660       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7661
7662   if (NumV2Elements == 0) {
7663     // Check for being able to broadcast a single element.
7664     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f32, V1,
7665                                                           Mask, Subtarget, DAG))
7666       return Broadcast;
7667
7668     // Use even/odd duplicate instructions for masks that match their pattern.
7669     if (Subtarget->hasSSE3()) {
7670       if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
7671         return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v4f32, V1);
7672       if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3}))
7673         return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v4f32, V1);
7674     }
7675
7676     if (Subtarget->hasAVX()) {
7677       // If we have AVX, we can use VPERMILPS which will allow folding a load
7678       // into the shuffle.
7679       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f32, V1,
7680                          getV4X86ShuffleImm8ForMask(Mask, DAG));
7681     }
7682
7683     // Otherwise, use a straight shuffle of a single input vector. We pass the
7684     // input vector to both operands to simulate this with a SHUFPS.
7685     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
7686                        getV4X86ShuffleImm8ForMask(Mask, DAG));
7687   }
7688
7689   // There are special ways we can lower some single-element blends. However, we
7690   // have custom ways we can lower more complex single-element blends below that
7691   // we defer to if both this and BLENDPS fail to match, so restrict this to
7692   // when the V2 input is targeting element 0 of the mask -- that is the fast
7693   // case here.
7694   if (NumV2Elements == 1 && Mask[0] >= 4)
7695     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4f32, V1, V2,
7696                                                          Mask, Subtarget, DAG))
7697       return V;
7698
7699   if (Subtarget->hasSSE41()) {
7700     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f32, V1, V2, Mask,
7701                                                   Subtarget, DAG))
7702       return Blend;
7703
7704     // Use INSERTPS if we can complete the shuffle efficiently.
7705     if (SDValue V = lowerVectorShuffleAsInsertPS(Op, V1, V2, Mask, DAG))
7706       return V;
7707
7708     if (!isSingleSHUFPSMask(Mask))
7709       if (SDValue BlendPerm = lowerVectorShuffleAsBlendAndPermute(
7710               DL, MVT::v4f32, V1, V2, Mask, DAG))
7711         return BlendPerm;
7712   }
7713
7714   // Use dedicated unpack instructions for masks that match their pattern.
7715   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
7716     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V1, V2);
7717   if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
7718     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V1, V2);
7719   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
7720     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V2, V1);
7721   if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
7722     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V2, V1);
7723
7724   // Otherwise fall back to a SHUFPS lowering strategy.
7725   return lowerVectorShuffleWithSHUFPS(DL, MVT::v4f32, Mask, V1, V2, DAG);
7726 }
7727
7728 /// \brief Lower 4-lane i32 vector shuffles.
7729 ///
7730 /// We try to handle these with integer-domain shuffles where we can, but for
7731 /// blends we use the floating point domain blend instructions.
7732 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7733                                        const X86Subtarget *Subtarget,
7734                                        SelectionDAG &DAG) {
7735   SDLoc DL(Op);
7736   assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
7737   assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7738   assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7739   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7740   ArrayRef<int> Mask = SVOp->getMask();
7741   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7742
7743   // Whenever we can lower this as a zext, that instruction is strictly faster
7744   // than any alternative. It also allows us to fold memory operands into the
7745   // shuffle in many cases.
7746   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v4i32, V1, V2,
7747                                                          Mask, Subtarget, DAG))
7748     return ZExt;
7749
7750   int NumV2Elements =
7751       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7752
7753   if (NumV2Elements == 0) {
7754     // Check for being able to broadcast a single element.
7755     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i32, V1,
7756                                                           Mask, Subtarget, DAG))
7757       return Broadcast;
7758
7759     // Straight shuffle of a single input vector. For everything from SSE2
7760     // onward this has a single fast instruction with no scary immediates.
7761     // We coerce the shuffle pattern to be compatible with UNPCK instructions
7762     // but we aren't actually going to use the UNPCK instruction because doing
7763     // so prevents folding a load into this instruction or making a copy.
7764     const int UnpackLoMask[] = {0, 0, 1, 1};
7765     const int UnpackHiMask[] = {2, 2, 3, 3};
7766     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 1, 1}))
7767       Mask = UnpackLoMask;
7768     else if (isShuffleEquivalent(V1, V2, Mask, {2, 2, 3, 3}))
7769       Mask = UnpackHiMask;
7770
7771     return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
7772                        getV4X86ShuffleImm8ForMask(Mask, DAG));
7773   }
7774
7775   // Try to use shift instructions.
7776   if (SDValue Shift =
7777           lowerVectorShuffleAsShift(DL, MVT::v4i32, V1, V2, Mask, DAG))
7778     return Shift;
7779
7780   // There are special ways we can lower some single-element blends.
7781   if (NumV2Elements == 1)
7782     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4i32, V1, V2,
7783                                                          Mask, Subtarget, DAG))
7784       return V;
7785
7786   // We have different paths for blend lowering, but they all must use the
7787   // *exact* same predicate.
7788   bool IsBlendSupported = Subtarget->hasSSE41();
7789   if (IsBlendSupported)
7790     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i32, V1, V2, Mask,
7791                                                   Subtarget, DAG))
7792       return Blend;
7793
7794   if (SDValue Masked =
7795           lowerVectorShuffleAsBitMask(DL, MVT::v4i32, V1, V2, Mask, DAG))
7796     return Masked;
7797
7798   // Use dedicated unpack instructions for masks that match their pattern.
7799   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
7800     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V1, V2);
7801   if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
7802     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V1, V2);
7803   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
7804     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V2, V1);
7805   if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
7806     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V2, V1);
7807
7808   // Try to use byte rotation instructions.
7809   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
7810   if (Subtarget->hasSSSE3())
7811     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
7812             DL, MVT::v4i32, V1, V2, Mask, Subtarget, DAG))
7813       return Rotate;
7814
7815   // If we have direct support for blends, we should lower by decomposing into
7816   // a permute. That will be faster than the domain cross.
7817   if (IsBlendSupported)
7818     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i32, V1, V2,
7819                                                       Mask, DAG);
7820
7821   // Try to lower by permuting the inputs into an unpack instruction.
7822   if (SDValue Unpack =
7823           lowerVectorShuffleAsUnpack(DL, MVT::v4i32, V1, V2, Mask, DAG))
7824     return Unpack;
7825
7826   // We implement this with SHUFPS because it can blend from two vectors.
7827   // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
7828   // up the inputs, bypassing domain shift penalties that we would encur if we
7829   // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
7830   // relevant.
7831   return DAG.getNode(ISD::BITCAST, DL, MVT::v4i32,
7832                      DAG.getVectorShuffle(
7833                          MVT::v4f32, DL,
7834                          DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V1),
7835                          DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V2), Mask));
7836 }
7837
7838 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
7839 /// shuffle lowering, and the most complex part.
7840 ///
7841 /// The lowering strategy is to try to form pairs of input lanes which are
7842 /// targeted at the same half of the final vector, and then use a dword shuffle
7843 /// to place them onto the right half, and finally unpack the paired lanes into
7844 /// their final position.
7845 ///
7846 /// The exact breakdown of how to form these dword pairs and align them on the
7847 /// correct sides is really tricky. See the comments within the function for
7848 /// more of the details.
7849 ///
7850 /// This code also handles repeated 128-bit lanes of v8i16 shuffles, but each
7851 /// lane must shuffle the *exact* same way. In fact, you must pass a v8 Mask to
7852 /// this routine for it to work correctly. To shuffle a 256-bit or 512-bit i16
7853 /// vector, form the analogous 128-bit 8-element Mask.
7854 static SDValue lowerV8I16GeneralSingleInputVectorShuffle(
7855     SDLoc DL, MVT VT, SDValue V, MutableArrayRef<int> Mask,
7856     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7857   assert(VT.getScalarType() == MVT::i16 && "Bad input type!");
7858   MVT PSHUFDVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
7859
7860   assert(Mask.size() == 8 && "Shuffle mask length doen't match!");
7861   MutableArrayRef<int> LoMask = Mask.slice(0, 4);
7862   MutableArrayRef<int> HiMask = Mask.slice(4, 4);
7863
7864   SmallVector<int, 4> LoInputs;
7865   std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
7866                [](int M) { return M >= 0; });
7867   std::sort(LoInputs.begin(), LoInputs.end());
7868   LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
7869   SmallVector<int, 4> HiInputs;
7870   std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
7871                [](int M) { return M >= 0; });
7872   std::sort(HiInputs.begin(), HiInputs.end());
7873   HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
7874   int NumLToL =
7875       std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
7876   int NumHToL = LoInputs.size() - NumLToL;
7877   int NumLToH =
7878       std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
7879   int NumHToH = HiInputs.size() - NumLToH;
7880   MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
7881   MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
7882   MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
7883   MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
7884
7885   // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
7886   // such inputs we can swap two of the dwords across the half mark and end up
7887   // with <=2 inputs to each half in each half. Once there, we can fall through
7888   // to the generic code below. For example:
7889   //
7890   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
7891   // Mask:  [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
7892   //
7893   // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
7894   // and an existing 2-into-2 on the other half. In this case we may have to
7895   // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
7896   // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
7897   // Fortunately, we don't have to handle anything but a 2-into-2 pattern
7898   // because any other situation (including a 3-into-1 or 1-into-3 in the other
7899   // half than the one we target for fixing) will be fixed when we re-enter this
7900   // path. We will also combine away any sequence of PSHUFD instructions that
7901   // result into a single instruction. Here is an example of the tricky case:
7902   //
7903   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
7904   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
7905   //
7906   // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
7907   //
7908   // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
7909   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
7910   //
7911   // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
7912   // Mask:  [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
7913   //
7914   // The result is fine to be handled by the generic logic.
7915   auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
7916                           ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
7917                           int AOffset, int BOffset) {
7918     assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
7919            "Must call this with A having 3 or 1 inputs from the A half.");
7920     assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
7921            "Must call this with B having 1 or 3 inputs from the B half.");
7922     assert(AToAInputs.size() + BToAInputs.size() == 4 &&
7923            "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
7924
7925     // Compute the index of dword with only one word among the three inputs in
7926     // a half by taking the sum of the half with three inputs and subtracting
7927     // the sum of the actual three inputs. The difference is the remaining
7928     // slot.
7929     int ADWord, BDWord;
7930     int &TripleDWord = AToAInputs.size() == 3 ? ADWord : BDWord;
7931     int &OneInputDWord = AToAInputs.size() == 3 ? BDWord : ADWord;
7932     int TripleInputOffset = AToAInputs.size() == 3 ? AOffset : BOffset;
7933     ArrayRef<int> TripleInputs = AToAInputs.size() == 3 ? AToAInputs : BToAInputs;
7934     int OneInput = AToAInputs.size() == 3 ? BToAInputs[0] : AToAInputs[0];
7935     int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
7936     int TripleNonInputIdx =
7937         TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
7938     TripleDWord = TripleNonInputIdx / 2;
7939
7940     // We use xor with one to compute the adjacent DWord to whichever one the
7941     // OneInput is in.
7942     OneInputDWord = (OneInput / 2) ^ 1;
7943
7944     // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
7945     // and BToA inputs. If there is also such a problem with the BToB and AToB
7946     // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
7947     // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
7948     // is essential that we don't *create* a 3<-1 as then we might oscillate.
7949     if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
7950       // Compute how many inputs will be flipped by swapping these DWords. We
7951       // need
7952       // to balance this to ensure we don't form a 3-1 shuffle in the other
7953       // half.
7954       int NumFlippedAToBInputs =
7955           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
7956           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
7957       int NumFlippedBToBInputs =
7958           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
7959           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
7960       if ((NumFlippedAToBInputs == 1 &&
7961            (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
7962           (NumFlippedBToBInputs == 1 &&
7963            (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
7964         // We choose whether to fix the A half or B half based on whether that
7965         // half has zero flipped inputs. At zero, we may not be able to fix it
7966         // with that half. We also bias towards fixing the B half because that
7967         // will more commonly be the high half, and we have to bias one way.
7968         auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
7969                                                        ArrayRef<int> Inputs) {
7970           int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
7971           bool IsFixIdxInput = std::find(Inputs.begin(), Inputs.end(),
7972                                          PinnedIdx ^ 1) != Inputs.end();
7973           // Determine whether the free index is in the flipped dword or the
7974           // unflipped dword based on where the pinned index is. We use this bit
7975           // in an xor to conditionally select the adjacent dword.
7976           int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
7977           bool IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
7978                                              FixFreeIdx) != Inputs.end();
7979           if (IsFixIdxInput == IsFixFreeIdxInput)
7980             FixFreeIdx += 1;
7981           IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
7982                                         FixFreeIdx) != Inputs.end();
7983           assert(IsFixIdxInput != IsFixFreeIdxInput &&
7984                  "We need to be changing the number of flipped inputs!");
7985           int PSHUFHalfMask[] = {0, 1, 2, 3};
7986           std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
7987           V = DAG.getNode(FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
7988                           MVT::v8i16, V,
7989                           getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DAG));
7990
7991           for (int &M : Mask)
7992             if (M != -1 && M == FixIdx)
7993               M = FixFreeIdx;
7994             else if (M != -1 && M == FixFreeIdx)
7995               M = FixIdx;
7996         };
7997         if (NumFlippedBToBInputs != 0) {
7998           int BPinnedIdx =
7999               BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8000           FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
8001         } else {
8002           assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
8003           int APinnedIdx =
8004               AToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8005           FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
8006         }
8007       }
8008     }
8009
8010     int PSHUFDMask[] = {0, 1, 2, 3};
8011     PSHUFDMask[ADWord] = BDWord;
8012     PSHUFDMask[BDWord] = ADWord;
8013     V = DAG.getNode(ISD::BITCAST, DL, VT,
8014                     DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT,
8015                                 DAG.getNode(ISD::BITCAST, DL, PSHUFDVT, V),
8016                                 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
8017
8018     // Adjust the mask to match the new locations of A and B.
8019     for (int &M : Mask)
8020       if (M != -1 && M/2 == ADWord)
8021         M = 2 * BDWord + M % 2;
8022       else if (M != -1 && M/2 == BDWord)
8023         M = 2 * ADWord + M % 2;
8024
8025     // Recurse back into this routine to re-compute state now that this isn't
8026     // a 3 and 1 problem.
8027     return lowerV8I16GeneralSingleInputVectorShuffle(DL, VT, V, Mask, Subtarget,
8028                                                      DAG);
8029   };
8030   if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
8031     return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
8032   else if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
8033     return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
8034
8035   // At this point there are at most two inputs to the low and high halves from
8036   // each half. That means the inputs can always be grouped into dwords and
8037   // those dwords can then be moved to the correct half with a dword shuffle.
8038   // We use at most one low and one high word shuffle to collect these paired
8039   // inputs into dwords, and finally a dword shuffle to place them.
8040   int PSHUFLMask[4] = {-1, -1, -1, -1};
8041   int PSHUFHMask[4] = {-1, -1, -1, -1};
8042   int PSHUFDMask[4] = {-1, -1, -1, -1};
8043
8044   // First fix the masks for all the inputs that are staying in their
8045   // original halves. This will then dictate the targets of the cross-half
8046   // shuffles.
8047   auto fixInPlaceInputs =
8048       [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
8049                     MutableArrayRef<int> SourceHalfMask,
8050                     MutableArrayRef<int> HalfMask, int HalfOffset) {
8051     if (InPlaceInputs.empty())
8052       return;
8053     if (InPlaceInputs.size() == 1) {
8054       SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8055           InPlaceInputs[0] - HalfOffset;
8056       PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
8057       return;
8058     }
8059     if (IncomingInputs.empty()) {
8060       // Just fix all of the in place inputs.
8061       for (int Input : InPlaceInputs) {
8062         SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
8063         PSHUFDMask[Input / 2] = Input / 2;
8064       }
8065       return;
8066     }
8067
8068     assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
8069     SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8070         InPlaceInputs[0] - HalfOffset;
8071     // Put the second input next to the first so that they are packed into
8072     // a dword. We find the adjacent index by toggling the low bit.
8073     int AdjIndex = InPlaceInputs[0] ^ 1;
8074     SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
8075     std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
8076     PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
8077   };
8078   fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
8079   fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
8080
8081   // Now gather the cross-half inputs and place them into a free dword of
8082   // their target half.
8083   // FIXME: This operation could almost certainly be simplified dramatically to
8084   // look more like the 3-1 fixing operation.
8085   auto moveInputsToRightHalf = [&PSHUFDMask](
8086       MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
8087       MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
8088       MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
8089       int DestOffset) {
8090     auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
8091       return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
8092     };
8093     auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
8094                                                int Word) {
8095       int LowWord = Word & ~1;
8096       int HighWord = Word | 1;
8097       return isWordClobbered(SourceHalfMask, LowWord) ||
8098              isWordClobbered(SourceHalfMask, HighWord);
8099     };
8100
8101     if (IncomingInputs.empty())
8102       return;
8103
8104     if (ExistingInputs.empty()) {
8105       // Map any dwords with inputs from them into the right half.
8106       for (int Input : IncomingInputs) {
8107         // If the source half mask maps over the inputs, turn those into
8108         // swaps and use the swapped lane.
8109         if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
8110           if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
8111             SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
8112                 Input - SourceOffset;
8113             // We have to swap the uses in our half mask in one sweep.
8114             for (int &M : HalfMask)
8115               if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
8116                 M = Input;
8117               else if (M == Input)
8118                 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8119           } else {
8120             assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
8121                        Input - SourceOffset &&
8122                    "Previous placement doesn't match!");
8123           }
8124           // Note that this correctly re-maps both when we do a swap and when
8125           // we observe the other side of the swap above. We rely on that to
8126           // avoid swapping the members of the input list directly.
8127           Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8128         }
8129
8130         // Map the input's dword into the correct half.
8131         if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
8132           PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
8133         else
8134           assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
8135                      Input / 2 &&
8136                  "Previous placement doesn't match!");
8137       }
8138
8139       // And just directly shift any other-half mask elements to be same-half
8140       // as we will have mirrored the dword containing the element into the
8141       // same position within that half.
8142       for (int &M : HalfMask)
8143         if (M >= SourceOffset && M < SourceOffset + 4) {
8144           M = M - SourceOffset + DestOffset;
8145           assert(M >= 0 && "This should never wrap below zero!");
8146         }
8147       return;
8148     }
8149
8150     // Ensure we have the input in a viable dword of its current half. This
8151     // is particularly tricky because the original position may be clobbered
8152     // by inputs being moved and *staying* in that half.
8153     if (IncomingInputs.size() == 1) {
8154       if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8155         int InputFixed = std::find(std::begin(SourceHalfMask),
8156                                    std::end(SourceHalfMask), -1) -
8157                          std::begin(SourceHalfMask) + SourceOffset;
8158         SourceHalfMask[InputFixed - SourceOffset] =
8159             IncomingInputs[0] - SourceOffset;
8160         std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
8161                      InputFixed);
8162         IncomingInputs[0] = InputFixed;
8163       }
8164     } else if (IncomingInputs.size() == 2) {
8165       if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
8166           isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8167         // We have two non-adjacent or clobbered inputs we need to extract from
8168         // the source half. To do this, we need to map them into some adjacent
8169         // dword slot in the source mask.
8170         int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
8171                               IncomingInputs[1] - SourceOffset};
8172
8173         // If there is a free slot in the source half mask adjacent to one of
8174         // the inputs, place the other input in it. We use (Index XOR 1) to
8175         // compute an adjacent index.
8176         if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
8177             SourceHalfMask[InputsFixed[0] ^ 1] == -1) {
8178           SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
8179           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8180           InputsFixed[1] = InputsFixed[0] ^ 1;
8181         } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
8182                    SourceHalfMask[InputsFixed[1] ^ 1] == -1) {
8183           SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
8184           SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
8185           InputsFixed[0] = InputsFixed[1] ^ 1;
8186         } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] == -1 &&
8187                    SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] == -1) {
8188           // The two inputs are in the same DWord but it is clobbered and the
8189           // adjacent DWord isn't used at all. Move both inputs to the free
8190           // slot.
8191           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
8192           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
8193           InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
8194           InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
8195         } else {
8196           // The only way we hit this point is if there is no clobbering
8197           // (because there are no off-half inputs to this half) and there is no
8198           // free slot adjacent to one of the inputs. In this case, we have to
8199           // swap an input with a non-input.
8200           for (int i = 0; i < 4; ++i)
8201             assert((SourceHalfMask[i] == -1 || SourceHalfMask[i] == i) &&
8202                    "We can't handle any clobbers here!");
8203           assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
8204                  "Cannot have adjacent inputs here!");
8205
8206           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8207           SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
8208
8209           // We also have to update the final source mask in this case because
8210           // it may need to undo the above swap.
8211           for (int &M : FinalSourceHalfMask)
8212             if (M == (InputsFixed[0] ^ 1) + SourceOffset)
8213               M = InputsFixed[1] + SourceOffset;
8214             else if (M == InputsFixed[1] + SourceOffset)
8215               M = (InputsFixed[0] ^ 1) + SourceOffset;
8216
8217           InputsFixed[1] = InputsFixed[0] ^ 1;
8218         }
8219
8220         // Point everything at the fixed inputs.
8221         for (int &M : HalfMask)
8222           if (M == IncomingInputs[0])
8223             M = InputsFixed[0] + SourceOffset;
8224           else if (M == IncomingInputs[1])
8225             M = InputsFixed[1] + SourceOffset;
8226
8227         IncomingInputs[0] = InputsFixed[0] + SourceOffset;
8228         IncomingInputs[1] = InputsFixed[1] + SourceOffset;
8229       }
8230     } else {
8231       llvm_unreachable("Unhandled input size!");
8232     }
8233
8234     // Now hoist the DWord down to the right half.
8235     int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
8236     assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
8237     PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
8238     for (int &M : HalfMask)
8239       for (int Input : IncomingInputs)
8240         if (M == Input)
8241           M = FreeDWord * 2 + Input % 2;
8242   };
8243   moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
8244                         /*SourceOffset*/ 4, /*DestOffset*/ 0);
8245   moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
8246                         /*SourceOffset*/ 0, /*DestOffset*/ 4);
8247
8248   // Now enact all the shuffles we've computed to move the inputs into their
8249   // target half.
8250   if (!isNoopShuffleMask(PSHUFLMask))
8251     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8252                     getV4X86ShuffleImm8ForMask(PSHUFLMask, DAG));
8253   if (!isNoopShuffleMask(PSHUFHMask))
8254     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8255                     getV4X86ShuffleImm8ForMask(PSHUFHMask, DAG));
8256   if (!isNoopShuffleMask(PSHUFDMask))
8257     V = DAG.getNode(ISD::BITCAST, DL, VT,
8258                     DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT,
8259                                 DAG.getNode(ISD::BITCAST, DL, PSHUFDVT, V),
8260                                 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
8261
8262   // At this point, each half should contain all its inputs, and we can then
8263   // just shuffle them into their final position.
8264   assert(std::count_if(LoMask.begin(), LoMask.end(),
8265                        [](int M) { return M >= 4; }) == 0 &&
8266          "Failed to lift all the high half inputs to the low mask!");
8267   assert(std::count_if(HiMask.begin(), HiMask.end(),
8268                        [](int M) { return M >= 0 && M < 4; }) == 0 &&
8269          "Failed to lift all the low half inputs to the high mask!");
8270
8271   // Do a half shuffle for the low mask.
8272   if (!isNoopShuffleMask(LoMask))
8273     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8274                     getV4X86ShuffleImm8ForMask(LoMask, DAG));
8275
8276   // Do a half shuffle with the high mask after shifting its values down.
8277   for (int &M : HiMask)
8278     if (M >= 0)
8279       M -= 4;
8280   if (!isNoopShuffleMask(HiMask))
8281     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8282                     getV4X86ShuffleImm8ForMask(HiMask, DAG));
8283
8284   return V;
8285 }
8286
8287 /// \brief Helper to form a PSHUFB-based shuffle+blend.
8288 static SDValue lowerVectorShuffleAsPSHUFB(SDLoc DL, MVT VT, SDValue V1,
8289                                           SDValue V2, ArrayRef<int> Mask,
8290                                           SelectionDAG &DAG, bool &V1InUse,
8291                                           bool &V2InUse) {
8292   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
8293   SDValue V1Mask[16];
8294   SDValue V2Mask[16];
8295   V1InUse = false;
8296   V2InUse = false;
8297
8298   int Size = Mask.size();
8299   int Scale = 16 / Size;
8300   for (int i = 0; i < 16; ++i) {
8301     if (Mask[i / Scale] == -1) {
8302       V1Mask[i] = V2Mask[i] = DAG.getUNDEF(MVT::i8);
8303     } else {
8304       const int ZeroMask = 0x80;
8305       int V1Idx = Mask[i / Scale] < Size ? Mask[i / Scale] * Scale + i % Scale
8306                                           : ZeroMask;
8307       int V2Idx = Mask[i / Scale] < Size
8308                       ? ZeroMask
8309                       : (Mask[i / Scale] - Size) * Scale + i % Scale;
8310       if (Zeroable[i / Scale])
8311         V1Idx = V2Idx = ZeroMask;
8312       V1Mask[i] = DAG.getConstant(V1Idx, MVT::i8);
8313       V2Mask[i] = DAG.getConstant(V2Idx, MVT::i8);
8314       V1InUse |= (ZeroMask != V1Idx);
8315       V2InUse |= (ZeroMask != V2Idx);
8316     }
8317   }
8318
8319   if (V1InUse)
8320     V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8321                      DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, V1),
8322                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
8323   if (V2InUse)
8324     V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8325                      DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, V2),
8326                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
8327
8328   // If we need shuffled inputs from both, blend the two.
8329   SDValue V;
8330   if (V1InUse && V2InUse)
8331     V = DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
8332   else
8333     V = V1InUse ? V1 : V2;
8334
8335   // Cast the result back to the correct type.
8336   return DAG.getNode(ISD::BITCAST, DL, VT, V);
8337 }
8338
8339 /// \brief Generic lowering of 8-lane i16 shuffles.
8340 ///
8341 /// This handles both single-input shuffles and combined shuffle/blends with
8342 /// two inputs. The single input shuffles are immediately delegated to
8343 /// a dedicated lowering routine.
8344 ///
8345 /// The blends are lowered in one of three fundamental ways. If there are few
8346 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
8347 /// of the input is significantly cheaper when lowered as an interleaving of
8348 /// the two inputs, try to interleave them. Otherwise, blend the low and high
8349 /// halves of the inputs separately (making them have relatively few inputs)
8350 /// and then concatenate them.
8351 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8352                                        const X86Subtarget *Subtarget,
8353                                        SelectionDAG &DAG) {
8354   SDLoc DL(Op);
8355   assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
8356   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8357   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8358   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8359   ArrayRef<int> OrigMask = SVOp->getMask();
8360   int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
8361                         OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
8362   MutableArrayRef<int> Mask(MaskStorage);
8363
8364   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
8365
8366   // Whenever we can lower this as a zext, that instruction is strictly faster
8367   // than any alternative.
8368   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
8369           DL, MVT::v8i16, V1, V2, OrigMask, Subtarget, DAG))
8370     return ZExt;
8371
8372   auto isV1 = [](int M) { return M >= 0 && M < 8; };
8373   (void)isV1;
8374   auto isV2 = [](int M) { return M >= 8; };
8375
8376   int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
8377
8378   if (NumV2Inputs == 0) {
8379     // Check for being able to broadcast a single element.
8380     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i16, V1,
8381                                                           Mask, Subtarget, DAG))
8382       return Broadcast;
8383
8384     // Try to use shift instructions.
8385     if (SDValue Shift =
8386             lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V1, Mask, DAG))
8387       return Shift;
8388
8389     // Use dedicated unpack instructions for masks that match their pattern.
8390     if (isShuffleEquivalent(V1, V1, Mask, {0, 0, 1, 1, 2, 2, 3, 3}))
8391       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V1);
8392     if (isShuffleEquivalent(V1, V1, Mask, {4, 4, 5, 5, 6, 6, 7, 7}))
8393       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V1);
8394
8395     // Try to use byte rotation instructions.
8396     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(DL, MVT::v8i16, V1, V1,
8397                                                         Mask, Subtarget, DAG))
8398       return Rotate;
8399
8400     return lowerV8I16GeneralSingleInputVectorShuffle(DL, MVT::v8i16, V1, Mask,
8401                                                      Subtarget, DAG);
8402   }
8403
8404   assert(std::any_of(Mask.begin(), Mask.end(), isV1) &&
8405          "All single-input shuffles should be canonicalized to be V1-input "
8406          "shuffles.");
8407
8408   // Try to use shift instructions.
8409   if (SDValue Shift =
8410           lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V2, Mask, DAG))
8411     return Shift;
8412
8413   // There are special ways we can lower some single-element blends.
8414   if (NumV2Inputs == 1)
8415     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v8i16, V1, V2,
8416                                                          Mask, Subtarget, DAG))
8417       return V;
8418
8419   // We have different paths for blend lowering, but they all must use the
8420   // *exact* same predicate.
8421   bool IsBlendSupported = Subtarget->hasSSE41();
8422   if (IsBlendSupported)
8423     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i16, V1, V2, Mask,
8424                                                   Subtarget, DAG))
8425       return Blend;
8426
8427   if (SDValue Masked =
8428           lowerVectorShuffleAsBitMask(DL, MVT::v8i16, V1, V2, Mask, DAG))
8429     return Masked;
8430
8431   // Use dedicated unpack instructions for masks that match their pattern.
8432   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 2, 10, 3, 11}))
8433     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V2);
8434   if (isShuffleEquivalent(V1, V2, Mask, {4, 12, 5, 13, 6, 14, 7, 15}))
8435     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V2);
8436
8437   // Try to use byte rotation instructions.
8438   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8439           DL, MVT::v8i16, V1, V2, Mask, Subtarget, DAG))
8440     return Rotate;
8441
8442   if (SDValue BitBlend =
8443           lowerVectorShuffleAsBitBlend(DL, MVT::v8i16, V1, V2, Mask, DAG))
8444     return BitBlend;
8445
8446   if (SDValue Unpack =
8447           lowerVectorShuffleAsUnpack(DL, MVT::v8i16, V1, V2, Mask, DAG))
8448     return Unpack;
8449
8450   // If we can't directly blend but can use PSHUFB, that will be better as it
8451   // can both shuffle and set up the inefficient blend.
8452   if (!IsBlendSupported && Subtarget->hasSSSE3()) {
8453     bool V1InUse, V2InUse;
8454     return lowerVectorShuffleAsPSHUFB(DL, MVT::v8i16, V1, V2, Mask, DAG,
8455                                       V1InUse, V2InUse);
8456   }
8457
8458   // We can always bit-blend if we have to so the fallback strategy is to
8459   // decompose into single-input permutes and blends.
8460   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i16, V1, V2,
8461                                                       Mask, DAG);
8462 }
8463
8464 /// \brief Check whether a compaction lowering can be done by dropping even
8465 /// elements and compute how many times even elements must be dropped.
8466 ///
8467 /// This handles shuffles which take every Nth element where N is a power of
8468 /// two. Example shuffle masks:
8469 ///
8470 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14,  0,  2,  4,  6,  8, 10, 12, 14
8471 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
8472 ///  N = 2:  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12
8473 ///  N = 2:  0,  4,  8, 12, 16, 20, 24, 28,  0,  4,  8, 12, 16, 20, 24, 28
8474 ///  N = 3:  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8
8475 ///  N = 3:  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24
8476 ///
8477 /// Any of these lanes can of course be undef.
8478 ///
8479 /// This routine only supports N <= 3.
8480 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
8481 /// for larger N.
8482 ///
8483 /// \returns N above, or the number of times even elements must be dropped if
8484 /// there is such a number. Otherwise returns zero.
8485 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
8486   // Figure out whether we're looping over two inputs or just one.
8487   bool IsSingleInput = isSingleInputShuffleMask(Mask);
8488
8489   // The modulus for the shuffle vector entries is based on whether this is
8490   // a single input or not.
8491   int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
8492   assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
8493          "We should only be called with masks with a power-of-2 size!");
8494
8495   uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
8496
8497   // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
8498   // and 2^3 simultaneously. This is because we may have ambiguity with
8499   // partially undef inputs.
8500   bool ViableForN[3] = {true, true, true};
8501
8502   for (int i = 0, e = Mask.size(); i < e; ++i) {
8503     // Ignore undef lanes, we'll optimistically collapse them to the pattern we
8504     // want.
8505     if (Mask[i] == -1)
8506       continue;
8507
8508     bool IsAnyViable = false;
8509     for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8510       if (ViableForN[j]) {
8511         uint64_t N = j + 1;
8512
8513         // The shuffle mask must be equal to (i * 2^N) % M.
8514         if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
8515           IsAnyViable = true;
8516         else
8517           ViableForN[j] = false;
8518       }
8519     // Early exit if we exhaust the possible powers of two.
8520     if (!IsAnyViable)
8521       break;
8522   }
8523
8524   for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8525     if (ViableForN[j])
8526       return j + 1;
8527
8528   // Return 0 as there is no viable power of two.
8529   return 0;
8530 }
8531
8532 /// \brief Generic lowering of v16i8 shuffles.
8533 ///
8534 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
8535 /// detect any complexity reducing interleaving. If that doesn't help, it uses
8536 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
8537 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
8538 /// back together.
8539 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8540                                        const X86Subtarget *Subtarget,
8541                                        SelectionDAG &DAG) {
8542   SDLoc DL(Op);
8543   assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
8544   assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8545   assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8546   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8547   ArrayRef<int> Mask = SVOp->getMask();
8548   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
8549
8550   // Try to use shift instructions.
8551   if (SDValue Shift =
8552           lowerVectorShuffleAsShift(DL, MVT::v16i8, V1, V2, Mask, DAG))
8553     return Shift;
8554
8555   // Try to use byte rotation instructions.
8556   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8557           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
8558     return Rotate;
8559
8560   // Try to use a zext lowering.
8561   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
8562           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
8563     return ZExt;
8564
8565   int NumV2Elements =
8566       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 16; });
8567
8568   // For single-input shuffles, there are some nicer lowering tricks we can use.
8569   if (NumV2Elements == 0) {
8570     // Check for being able to broadcast a single element.
8571     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i8, V1,
8572                                                           Mask, Subtarget, DAG))
8573       return Broadcast;
8574
8575     // Check whether we can widen this to an i16 shuffle by duplicating bytes.
8576     // Notably, this handles splat and partial-splat shuffles more efficiently.
8577     // However, it only makes sense if the pre-duplication shuffle simplifies
8578     // things significantly. Currently, this means we need to be able to
8579     // express the pre-duplication shuffle as an i16 shuffle.
8580     //
8581     // FIXME: We should check for other patterns which can be widened into an
8582     // i16 shuffle as well.
8583     auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
8584       for (int i = 0; i < 16; i += 2)
8585         if (Mask[i] != -1 && Mask[i + 1] != -1 && Mask[i] != Mask[i + 1])
8586           return false;
8587
8588       return true;
8589     };
8590     auto tryToWidenViaDuplication = [&]() -> SDValue {
8591       if (!canWidenViaDuplication(Mask))
8592         return SDValue();
8593       SmallVector<int, 4> LoInputs;
8594       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
8595                    [](int M) { return M >= 0 && M < 8; });
8596       std::sort(LoInputs.begin(), LoInputs.end());
8597       LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
8598                      LoInputs.end());
8599       SmallVector<int, 4> HiInputs;
8600       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
8601                    [](int M) { return M >= 8; });
8602       std::sort(HiInputs.begin(), HiInputs.end());
8603       HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
8604                      HiInputs.end());
8605
8606       bool TargetLo = LoInputs.size() >= HiInputs.size();
8607       ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
8608       ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
8609
8610       int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
8611       SmallDenseMap<int, int, 8> LaneMap;
8612       for (int I : InPlaceInputs) {
8613         PreDupI16Shuffle[I/2] = I/2;
8614         LaneMap[I] = I;
8615       }
8616       int j = TargetLo ? 0 : 4, je = j + 4;
8617       for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
8618         // Check if j is already a shuffle of this input. This happens when
8619         // there are two adjacent bytes after we move the low one.
8620         if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
8621           // If we haven't yet mapped the input, search for a slot into which
8622           // we can map it.
8623           while (j < je && PreDupI16Shuffle[j] != -1)
8624             ++j;
8625
8626           if (j == je)
8627             // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
8628             return SDValue();
8629
8630           // Map this input with the i16 shuffle.
8631           PreDupI16Shuffle[j] = MovingInputs[i] / 2;
8632         }
8633
8634         // Update the lane map based on the mapping we ended up with.
8635         LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
8636       }
8637       V1 = DAG.getNode(
8638           ISD::BITCAST, DL, MVT::v16i8,
8639           DAG.getVectorShuffle(MVT::v8i16, DL,
8640                                DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
8641                                DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
8642
8643       // Unpack the bytes to form the i16s that will be shuffled into place.
8644       V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
8645                        MVT::v16i8, V1, V1);
8646
8647       int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8648       for (int i = 0; i < 16; ++i)
8649         if (Mask[i] != -1) {
8650           int MappedMask = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
8651           assert(MappedMask < 8 && "Invalid v8 shuffle mask!");
8652           if (PostDupI16Shuffle[i / 2] == -1)
8653             PostDupI16Shuffle[i / 2] = MappedMask;
8654           else
8655             assert(PostDupI16Shuffle[i / 2] == MappedMask &&
8656                    "Conflicting entrties in the original shuffle!");
8657         }
8658       return DAG.getNode(
8659           ISD::BITCAST, DL, MVT::v16i8,
8660           DAG.getVectorShuffle(MVT::v8i16, DL,
8661                                DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
8662                                DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
8663     };
8664     if (SDValue V = tryToWidenViaDuplication())
8665       return V;
8666   }
8667
8668   // Use dedicated unpack instructions for masks that match their pattern.
8669   if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
8670                                          0, 16, 1, 17, 2, 18, 3, 19,
8671                                          // High half.
8672                                          4, 20, 5, 21, 6, 22, 7, 23}))
8673     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V1, V2);
8674   if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
8675                                          8, 24, 9, 25, 10, 26, 11, 27,
8676                                          // High half.
8677                                          12, 28, 13, 29, 14, 30, 15, 31}))
8678     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V1, V2);
8679
8680   // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
8681   // with PSHUFB. It is important to do this before we attempt to generate any
8682   // blends but after all of the single-input lowerings. If the single input
8683   // lowerings can find an instruction sequence that is faster than a PSHUFB, we
8684   // want to preserve that and we can DAG combine any longer sequences into
8685   // a PSHUFB in the end. But once we start blending from multiple inputs,
8686   // the complexity of DAG combining bad patterns back into PSHUFB is too high,
8687   // and there are *very* few patterns that would actually be faster than the
8688   // PSHUFB approach because of its ability to zero lanes.
8689   //
8690   // FIXME: The only exceptions to the above are blends which are exact
8691   // interleavings with direct instructions supporting them. We currently don't
8692   // handle those well here.
8693   if (Subtarget->hasSSSE3()) {
8694     bool V1InUse = false;
8695     bool V2InUse = false;
8696
8697     SDValue PSHUFB = lowerVectorShuffleAsPSHUFB(DL, MVT::v16i8, V1, V2, Mask,
8698                                                 DAG, V1InUse, V2InUse);
8699
8700     // If both V1 and V2 are in use and we can use a direct blend or an unpack,
8701     // do so. This avoids using them to handle blends-with-zero which is
8702     // important as a single pshufb is significantly faster for that.
8703     if (V1InUse && V2InUse) {
8704       if (Subtarget->hasSSE41())
8705         if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i8, V1, V2,
8706                                                       Mask, Subtarget, DAG))
8707           return Blend;
8708
8709       // We can use an unpack to do the blending rather than an or in some
8710       // cases. Even though the or may be (very minorly) more efficient, we
8711       // preference this lowering because there are common cases where part of
8712       // the complexity of the shuffles goes away when we do the final blend as
8713       // an unpack.
8714       // FIXME: It might be worth trying to detect if the unpack-feeding
8715       // shuffles will both be pshufb, in which case we shouldn't bother with
8716       // this.
8717       if (SDValue Unpack =
8718               lowerVectorShuffleAsUnpack(DL, MVT::v16i8, V1, V2, Mask, DAG))
8719         return Unpack;
8720     }
8721
8722     return PSHUFB;
8723   }
8724
8725   // There are special ways we can lower some single-element blends.
8726   if (NumV2Elements == 1)
8727     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v16i8, V1, V2,
8728                                                          Mask, Subtarget, DAG))
8729       return V;
8730
8731   if (SDValue BitBlend =
8732           lowerVectorShuffleAsBitBlend(DL, MVT::v16i8, V1, V2, Mask, DAG))
8733     return BitBlend;
8734
8735   // Check whether a compaction lowering can be done. This handles shuffles
8736   // which take every Nth element for some even N. See the helper function for
8737   // details.
8738   //
8739   // We special case these as they can be particularly efficiently handled with
8740   // the PACKUSB instruction on x86 and they show up in common patterns of
8741   // rearranging bytes to truncate wide elements.
8742   if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
8743     // NumEvenDrops is the power of two stride of the elements. Another way of
8744     // thinking about it is that we need to drop the even elements this many
8745     // times to get the original input.
8746     bool IsSingleInput = isSingleInputShuffleMask(Mask);
8747
8748     // First we need to zero all the dropped bytes.
8749     assert(NumEvenDrops <= 3 &&
8750            "No support for dropping even elements more than 3 times.");
8751     // We use the mask type to pick which bytes are preserved based on how many
8752     // elements are dropped.
8753     MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
8754     SDValue ByteClearMask =
8755         DAG.getNode(ISD::BITCAST, DL, MVT::v16i8,
8756                     DAG.getConstant(0xFF, MaskVTs[NumEvenDrops - 1]));
8757     V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
8758     if (!IsSingleInput)
8759       V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
8760
8761     // Now pack things back together.
8762     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1);
8763     V2 = IsSingleInput ? V1 : DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V2);
8764     SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
8765     for (int i = 1; i < NumEvenDrops; ++i) {
8766       Result = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, Result);
8767       Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
8768     }
8769
8770     return Result;
8771   }
8772
8773   // Handle multi-input cases by blending single-input shuffles.
8774   if (NumV2Elements > 0)
8775     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v16i8, V1, V2,
8776                                                       Mask, DAG);
8777
8778   // The fallback path for single-input shuffles widens this into two v8i16
8779   // vectors with unpacks, shuffles those, and then pulls them back together
8780   // with a pack.
8781   SDValue V = V1;
8782
8783   int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8784   int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8785   for (int i = 0; i < 16; ++i)
8786     if (Mask[i] >= 0)
8787       (i < 8 ? LoBlendMask[i] : HiBlendMask[i % 8]) = Mask[i];
8788
8789   SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
8790
8791   SDValue VLoHalf, VHiHalf;
8792   // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
8793   // them out and avoid using UNPCK{L,H} to extract the elements of V as
8794   // i16s.
8795   if (std::none_of(std::begin(LoBlendMask), std::end(LoBlendMask),
8796                    [](int M) { return M >= 0 && M % 2 == 1; }) &&
8797       std::none_of(std::begin(HiBlendMask), std::end(HiBlendMask),
8798                    [](int M) { return M >= 0 && M % 2 == 1; })) {
8799     // Use a mask to drop the high bytes.
8800     VLoHalf = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V);
8801     VLoHalf = DAG.getNode(ISD::AND, DL, MVT::v8i16, VLoHalf,
8802                      DAG.getConstant(0x00FF, MVT::v8i16));
8803
8804     // This will be a single vector shuffle instead of a blend so nuke VHiHalf.
8805     VHiHalf = DAG.getUNDEF(MVT::v8i16);
8806
8807     // Squash the masks to point directly into VLoHalf.
8808     for (int &M : LoBlendMask)
8809       if (M >= 0)
8810         M /= 2;
8811     for (int &M : HiBlendMask)
8812       if (M >= 0)
8813         M /= 2;
8814   } else {
8815     // Otherwise just unpack the low half of V into VLoHalf and the high half into
8816     // VHiHalf so that we can blend them as i16s.
8817     VLoHalf = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8818                      DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
8819     VHiHalf = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8820                      DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
8821   }
8822
8823   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, LoBlendMask);
8824   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, HiBlendMask);
8825
8826   return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
8827 }
8828
8829 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
8830 ///
8831 /// This routine breaks down the specific type of 128-bit shuffle and
8832 /// dispatches to the lowering routines accordingly.
8833 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8834                                         MVT VT, const X86Subtarget *Subtarget,
8835                                         SelectionDAG &DAG) {
8836   switch (VT.SimpleTy) {
8837   case MVT::v2i64:
8838     return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8839   case MVT::v2f64:
8840     return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8841   case MVT::v4i32:
8842     return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
8843   case MVT::v4f32:
8844     return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
8845   case MVT::v8i16:
8846     return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
8847   case MVT::v16i8:
8848     return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
8849
8850   default:
8851     llvm_unreachable("Unimplemented!");
8852   }
8853 }
8854
8855 /// \brief Helper function to test whether a shuffle mask could be
8856 /// simplified by widening the elements being shuffled.
8857 ///
8858 /// Appends the mask for wider elements in WidenedMask if valid. Otherwise
8859 /// leaves it in an unspecified state.
8860 ///
8861 /// NOTE: This must handle normal vector shuffle masks and *target* vector
8862 /// shuffle masks. The latter have the special property of a '-2' representing
8863 /// a zero-ed lane of a vector.
8864 static bool canWidenShuffleElements(ArrayRef<int> Mask,
8865                                     SmallVectorImpl<int> &WidenedMask) {
8866   for (int i = 0, Size = Mask.size(); i < Size; i += 2) {
8867     // If both elements are undef, its trivial.
8868     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] == SM_SentinelUndef) {
8869       WidenedMask.push_back(SM_SentinelUndef);
8870       continue;
8871     }
8872
8873     // Check for an undef mask and a mask value properly aligned to fit with
8874     // a pair of values. If we find such a case, use the non-undef mask's value.
8875     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] >= 0 && Mask[i + 1] % 2 == 1) {
8876       WidenedMask.push_back(Mask[i + 1] / 2);
8877       continue;
8878     }
8879     if (Mask[i + 1] == SM_SentinelUndef && Mask[i] >= 0 && Mask[i] % 2 == 0) {
8880       WidenedMask.push_back(Mask[i] / 2);
8881       continue;
8882     }
8883
8884     // When zeroing, we need to spread the zeroing across both lanes to widen.
8885     if (Mask[i] == SM_SentinelZero || Mask[i + 1] == SM_SentinelZero) {
8886       if ((Mask[i] == SM_SentinelZero || Mask[i] == SM_SentinelUndef) &&
8887           (Mask[i + 1] == SM_SentinelZero || Mask[i + 1] == SM_SentinelUndef)) {
8888         WidenedMask.push_back(SM_SentinelZero);
8889         continue;
8890       }
8891       return false;
8892     }
8893
8894     // Finally check if the two mask values are adjacent and aligned with
8895     // a pair.
8896     if (Mask[i] != SM_SentinelUndef && Mask[i] % 2 == 0 && Mask[i] + 1 == Mask[i + 1]) {
8897       WidenedMask.push_back(Mask[i] / 2);
8898       continue;
8899     }
8900
8901     // Otherwise we can't safely widen the elements used in this shuffle.
8902     return false;
8903   }
8904   assert(WidenedMask.size() == Mask.size() / 2 &&
8905          "Incorrect size of mask after widening the elements!");
8906
8907   return true;
8908 }
8909
8910 /// \brief Generic routine to split vector shuffle into half-sized shuffles.
8911 ///
8912 /// This routine just extracts two subvectors, shuffles them independently, and
8913 /// then concatenates them back together. This should work effectively with all
8914 /// AVX vector shuffle types.
8915 static SDValue splitAndLowerVectorShuffle(SDLoc DL, MVT VT, SDValue V1,
8916                                           SDValue V2, ArrayRef<int> Mask,
8917                                           SelectionDAG &DAG) {
8918   assert(VT.getSizeInBits() >= 256 &&
8919          "Only for 256-bit or wider vector shuffles!");
8920   assert(V1.getSimpleValueType() == VT && "Bad operand type!");
8921   assert(V2.getSimpleValueType() == VT && "Bad operand type!");
8922
8923   ArrayRef<int> LoMask = Mask.slice(0, Mask.size() / 2);
8924   ArrayRef<int> HiMask = Mask.slice(Mask.size() / 2);
8925
8926   int NumElements = VT.getVectorNumElements();
8927   int SplitNumElements = NumElements / 2;
8928   MVT ScalarVT = VT.getScalarType();
8929   MVT SplitVT = MVT::getVectorVT(ScalarVT, NumElements / 2);
8930
8931   // Rather than splitting build-vectors, just build two narrower build
8932   // vectors. This helps shuffling with splats and zeros.
8933   auto SplitVector = [&](SDValue V) {
8934     while (V.getOpcode() == ISD::BITCAST)
8935       V = V->getOperand(0);
8936
8937     MVT OrigVT = V.getSimpleValueType();
8938     int OrigNumElements = OrigVT.getVectorNumElements();
8939     int OrigSplitNumElements = OrigNumElements / 2;
8940     MVT OrigScalarVT = OrigVT.getScalarType();
8941     MVT OrigSplitVT = MVT::getVectorVT(OrigScalarVT, OrigNumElements / 2);
8942
8943     SDValue LoV, HiV;
8944
8945     auto *BV = dyn_cast<BuildVectorSDNode>(V);
8946     if (!BV) {
8947       LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
8948                         DAG.getIntPtrConstant(0));
8949       HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
8950                         DAG.getIntPtrConstant(OrigSplitNumElements));
8951     } else {
8952
8953       SmallVector<SDValue, 16> LoOps, HiOps;
8954       for (int i = 0; i < OrigSplitNumElements; ++i) {
8955         LoOps.push_back(BV->getOperand(i));
8956         HiOps.push_back(BV->getOperand(i + OrigSplitNumElements));
8957       }
8958       LoV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, LoOps);
8959       HiV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, HiOps);
8960     }
8961     return std::make_pair(DAG.getNode(ISD::BITCAST, DL, SplitVT, LoV),
8962                           DAG.getNode(ISD::BITCAST, DL, SplitVT, HiV));
8963   };
8964
8965   SDValue LoV1, HiV1, LoV2, HiV2;
8966   std::tie(LoV1, HiV1) = SplitVector(V1);
8967   std::tie(LoV2, HiV2) = SplitVector(V2);
8968
8969   // Now create two 4-way blends of these half-width vectors.
8970   auto HalfBlend = [&](ArrayRef<int> HalfMask) {
8971     bool UseLoV1 = false, UseHiV1 = false, UseLoV2 = false, UseHiV2 = false;
8972     SmallVector<int, 32> V1BlendMask, V2BlendMask, BlendMask;
8973     for (int i = 0; i < SplitNumElements; ++i) {
8974       int M = HalfMask[i];
8975       if (M >= NumElements) {
8976         if (M >= NumElements + SplitNumElements)
8977           UseHiV2 = true;
8978         else
8979           UseLoV2 = true;
8980         V2BlendMask.push_back(M - NumElements);
8981         V1BlendMask.push_back(-1);
8982         BlendMask.push_back(SplitNumElements + i);
8983       } else if (M >= 0) {
8984         if (M >= SplitNumElements)
8985           UseHiV1 = true;
8986         else
8987           UseLoV1 = true;
8988         V2BlendMask.push_back(-1);
8989         V1BlendMask.push_back(M);
8990         BlendMask.push_back(i);
8991       } else {
8992         V2BlendMask.push_back(-1);
8993         V1BlendMask.push_back(-1);
8994         BlendMask.push_back(-1);
8995       }
8996     }
8997
8998     // Because the lowering happens after all combining takes place, we need to
8999     // manually combine these blend masks as much as possible so that we create
9000     // a minimal number of high-level vector shuffle nodes.
9001
9002     // First try just blending the halves of V1 or V2.
9003     if (!UseLoV1 && !UseHiV1 && !UseLoV2 && !UseHiV2)
9004       return DAG.getUNDEF(SplitVT);
9005     if (!UseLoV2 && !UseHiV2)
9006       return DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9007     if (!UseLoV1 && !UseHiV1)
9008       return DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9009
9010     SDValue V1Blend, V2Blend;
9011     if (UseLoV1 && UseHiV1) {
9012       V1Blend =
9013         DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9014     } else {
9015       // We only use half of V1 so map the usage down into the final blend mask.
9016       V1Blend = UseLoV1 ? LoV1 : HiV1;
9017       for (int i = 0; i < SplitNumElements; ++i)
9018         if (BlendMask[i] >= 0 && BlendMask[i] < SplitNumElements)
9019           BlendMask[i] = V1BlendMask[i] - (UseLoV1 ? 0 : SplitNumElements);
9020     }
9021     if (UseLoV2 && UseHiV2) {
9022       V2Blend =
9023         DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9024     } else {
9025       // We only use half of V2 so map the usage down into the final blend mask.
9026       V2Blend = UseLoV2 ? LoV2 : HiV2;
9027       for (int i = 0; i < SplitNumElements; ++i)
9028         if (BlendMask[i] >= SplitNumElements)
9029           BlendMask[i] = V2BlendMask[i] + (UseLoV2 ? SplitNumElements : 0);
9030     }
9031     return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
9032   };
9033   SDValue Lo = HalfBlend(LoMask);
9034   SDValue Hi = HalfBlend(HiMask);
9035   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
9036 }
9037
9038 /// \brief Either split a vector in halves or decompose the shuffles and the
9039 /// blend.
9040 ///
9041 /// This is provided as a good fallback for many lowerings of non-single-input
9042 /// shuffles with more than one 128-bit lane. In those cases, we want to select
9043 /// between splitting the shuffle into 128-bit components and stitching those
9044 /// back together vs. extracting the single-input shuffles and blending those
9045 /// results.
9046 static SDValue lowerVectorShuffleAsSplitOrBlend(SDLoc DL, MVT VT, SDValue V1,
9047                                                 SDValue V2, ArrayRef<int> Mask,
9048                                                 SelectionDAG &DAG) {
9049   assert(!isSingleInputShuffleMask(Mask) && "This routine must not be used to "
9050                                             "lower single-input shuffles as it "
9051                                             "could then recurse on itself.");
9052   int Size = Mask.size();
9053
9054   // If this can be modeled as a broadcast of two elements followed by a blend,
9055   // prefer that lowering. This is especially important because broadcasts can
9056   // often fold with memory operands.
9057   auto DoBothBroadcast = [&] {
9058     int V1BroadcastIdx = -1, V2BroadcastIdx = -1;
9059     for (int M : Mask)
9060       if (M >= Size) {
9061         if (V2BroadcastIdx == -1)
9062           V2BroadcastIdx = M - Size;
9063         else if (M - Size != V2BroadcastIdx)
9064           return false;
9065       } else if (M >= 0) {
9066         if (V1BroadcastIdx == -1)
9067           V1BroadcastIdx = M;
9068         else if (M != V1BroadcastIdx)
9069           return false;
9070       }
9071     return true;
9072   };
9073   if (DoBothBroadcast())
9074     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask,
9075                                                       DAG);
9076
9077   // If the inputs all stem from a single 128-bit lane of each input, then we
9078   // split them rather than blending because the split will decompose to
9079   // unusually few instructions.
9080   int LaneCount = VT.getSizeInBits() / 128;
9081   int LaneSize = Size / LaneCount;
9082   SmallBitVector LaneInputs[2];
9083   LaneInputs[0].resize(LaneCount, false);
9084   LaneInputs[1].resize(LaneCount, false);
9085   for (int i = 0; i < Size; ++i)
9086     if (Mask[i] >= 0)
9087       LaneInputs[Mask[i] / Size][(Mask[i] % Size) / LaneSize] = true;
9088   if (LaneInputs[0].count() <= 1 && LaneInputs[1].count() <= 1)
9089     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9090
9091   // Otherwise, just fall back to decomposed shuffles and a blend. This requires
9092   // that the decomposed single-input shuffles don't end up here.
9093   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9094 }
9095
9096 /// \brief Lower a vector shuffle crossing multiple 128-bit lanes as
9097 /// a permutation and blend of those lanes.
9098 ///
9099 /// This essentially blends the out-of-lane inputs to each lane into the lane
9100 /// from a permuted copy of the vector. This lowering strategy results in four
9101 /// instructions in the worst case for a single-input cross lane shuffle which
9102 /// is lower than any other fully general cross-lane shuffle strategy I'm aware
9103 /// of. Special cases for each particular shuffle pattern should be handled
9104 /// prior to trying this lowering.
9105 static SDValue lowerVectorShuffleAsLanePermuteAndBlend(SDLoc DL, MVT VT,
9106                                                        SDValue V1, SDValue V2,
9107                                                        ArrayRef<int> Mask,
9108                                                        SelectionDAG &DAG) {
9109   // FIXME: This should probably be generalized for 512-bit vectors as well.
9110   assert(VT.getSizeInBits() == 256 && "Only for 256-bit vector shuffles!");
9111   int LaneSize = Mask.size() / 2;
9112
9113   // If there are only inputs from one 128-bit lane, splitting will in fact be
9114   // less expensive. The flags track whether the given lane contains an element
9115   // that crosses to another lane.
9116   bool LaneCrossing[2] = {false, false};
9117   for (int i = 0, Size = Mask.size(); i < Size; ++i)
9118     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
9119       LaneCrossing[(Mask[i] % Size) / LaneSize] = true;
9120   if (!LaneCrossing[0] || !LaneCrossing[1])
9121     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9122
9123   if (isSingleInputShuffleMask(Mask)) {
9124     SmallVector<int, 32> FlippedBlendMask;
9125     for (int i = 0, Size = Mask.size(); i < Size; ++i)
9126       FlippedBlendMask.push_back(
9127           Mask[i] < 0 ? -1 : (((Mask[i] % Size) / LaneSize == i / LaneSize)
9128                                   ? Mask[i]
9129                                   : Mask[i] % LaneSize +
9130                                         (i / LaneSize) * LaneSize + Size));
9131
9132     // Flip the vector, and blend the results which should now be in-lane. The
9133     // VPERM2X128 mask uses the low 2 bits for the low source and bits 4 and
9134     // 5 for the high source. The value 3 selects the high half of source 2 and
9135     // the value 2 selects the low half of source 2. We only use source 2 to
9136     // allow folding it into a memory operand.
9137     unsigned PERMMask = 3 | 2 << 4;
9138     SDValue Flipped = DAG.getNode(X86ISD::VPERM2X128, DL, VT, DAG.getUNDEF(VT),
9139                                   V1, DAG.getConstant(PERMMask, MVT::i8));
9140     return DAG.getVectorShuffle(VT, DL, V1, Flipped, FlippedBlendMask);
9141   }
9142
9143   // This now reduces to two single-input shuffles of V1 and V2 which at worst
9144   // will be handled by the above logic and a blend of the results, much like
9145   // other patterns in AVX.
9146   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9147 }
9148
9149 /// \brief Handle lowering 2-lane 128-bit shuffles.
9150 static SDValue lowerV2X128VectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9151                                         SDValue V2, ArrayRef<int> Mask,
9152                                         const X86Subtarget *Subtarget,
9153                                         SelectionDAG &DAG) {
9154   // TODO: If minimizing size and one of the inputs is a zero vector and the
9155   // the zero vector has only one use, we could use a VPERM2X128 to save the
9156   // instruction bytes needed to explicitly generate the zero vector.
9157
9158   // Blends are faster and handle all the non-lane-crossing cases.
9159   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, VT, V1, V2, Mask,
9160                                                 Subtarget, DAG))
9161     return Blend;
9162
9163   bool IsV1Zero = ISD::isBuildVectorAllZeros(V1.getNode());
9164   bool IsV2Zero = ISD::isBuildVectorAllZeros(V2.getNode());
9165
9166   // If either input operand is a zero vector, use VPERM2X128 because its mask
9167   // allows us to replace the zero input with an implicit zero.
9168   if (!IsV1Zero && !IsV2Zero) {
9169     // Check for patterns which can be matched with a single insert of a 128-bit
9170     // subvector.
9171     bool OnlyUsesV1 = isShuffleEquivalent(V1, V2, Mask, {0, 1, 0, 1});
9172     if (OnlyUsesV1 || isShuffleEquivalent(V1, V2, Mask, {0, 1, 4, 5})) {
9173       MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(),
9174                                    VT.getVectorNumElements() / 2);
9175       SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
9176                                 DAG.getIntPtrConstant(0));
9177       SDValue HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT,
9178                                 OnlyUsesV1 ? V1 : V2, DAG.getIntPtrConstant(0));
9179       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoV, HiV);
9180     }
9181   }
9182
9183   // Otherwise form a 128-bit permutation. After accounting for undefs,
9184   // convert the 64-bit shuffle mask selection values into 128-bit
9185   // selection bits by dividing the indexes by 2 and shifting into positions
9186   // defined by a vperm2*128 instruction's immediate control byte.
9187
9188   // The immediate permute control byte looks like this:
9189   //    [1:0] - select 128 bits from sources for low half of destination
9190   //    [2]   - ignore
9191   //    [3]   - zero low half of destination
9192   //    [5:4] - select 128 bits from sources for high half of destination
9193   //    [6]   - ignore
9194   //    [7]   - zero high half of destination
9195
9196   int MaskLO = Mask[0];
9197   if (MaskLO == SM_SentinelUndef)
9198     MaskLO = Mask[1] == SM_SentinelUndef ? 0 : Mask[1];
9199
9200   int MaskHI = Mask[2];
9201   if (MaskHI == SM_SentinelUndef)
9202     MaskHI = Mask[3] == SM_SentinelUndef ? 0 : Mask[3];
9203
9204   unsigned PermMask = MaskLO / 2 | (MaskHI / 2) << 4;
9205
9206   // If either input is a zero vector, replace it with an undef input.
9207   // Shuffle mask values <  4 are selecting elements of V1.
9208   // Shuffle mask values >= 4 are selecting elements of V2.
9209   // Adjust each half of the permute mask by clearing the half that was
9210   // selecting the zero vector and setting the zero mask bit.
9211   if (IsV1Zero) {
9212     V1 = DAG.getUNDEF(VT);
9213     if (MaskLO < 4)
9214       PermMask = (PermMask & 0xf0) | 0x08;
9215     if (MaskHI < 4)
9216       PermMask = (PermMask & 0x0f) | 0x80;
9217   }
9218   if (IsV2Zero) {
9219     V2 = DAG.getUNDEF(VT);
9220     if (MaskLO >= 4)
9221       PermMask = (PermMask & 0xf0) | 0x08;
9222     if (MaskHI >= 4)
9223       PermMask = (PermMask & 0x0f) | 0x80;
9224   }
9225
9226   return DAG.getNode(X86ISD::VPERM2X128, DL, VT, V1, V2,
9227                      DAG.getConstant(PermMask, MVT::i8));
9228 }
9229
9230 /// \brief Lower a vector shuffle by first fixing the 128-bit lanes and then
9231 /// shuffling each lane.
9232 ///
9233 /// This will only succeed when the result of fixing the 128-bit lanes results
9234 /// in a single-input non-lane-crossing shuffle with a repeating shuffle mask in
9235 /// each 128-bit lanes. This handles many cases where we can quickly blend away
9236 /// the lane crosses early and then use simpler shuffles within each lane.
9237 ///
9238 /// FIXME: It might be worthwhile at some point to support this without
9239 /// requiring the 128-bit lane-relative shuffles to be repeating, but currently
9240 /// in x86 only floating point has interesting non-repeating shuffles, and even
9241 /// those are still *marginally* more expensive.
9242 static SDValue lowerVectorShuffleByMerging128BitLanes(
9243     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
9244     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
9245   assert(!isSingleInputShuffleMask(Mask) &&
9246          "This is only useful with multiple inputs.");
9247
9248   int Size = Mask.size();
9249   int LaneSize = 128 / VT.getScalarSizeInBits();
9250   int NumLanes = Size / LaneSize;
9251   assert(NumLanes > 1 && "Only handles 256-bit and wider shuffles.");
9252
9253   // See if we can build a hypothetical 128-bit lane-fixing shuffle mask. Also
9254   // check whether the in-128-bit lane shuffles share a repeating pattern.
9255   SmallVector<int, 4> Lanes;
9256   Lanes.resize(NumLanes, -1);
9257   SmallVector<int, 4> InLaneMask;
9258   InLaneMask.resize(LaneSize, -1);
9259   for (int i = 0; i < Size; ++i) {
9260     if (Mask[i] < 0)
9261       continue;
9262
9263     int j = i / LaneSize;
9264
9265     if (Lanes[j] < 0) {
9266       // First entry we've seen for this lane.
9267       Lanes[j] = Mask[i] / LaneSize;
9268     } else if (Lanes[j] != Mask[i] / LaneSize) {
9269       // This doesn't match the lane selected previously!
9270       return SDValue();
9271     }
9272
9273     // Check that within each lane we have a consistent shuffle mask.
9274     int k = i % LaneSize;
9275     if (InLaneMask[k] < 0) {
9276       InLaneMask[k] = Mask[i] % LaneSize;
9277     } else if (InLaneMask[k] != Mask[i] % LaneSize) {
9278       // This doesn't fit a repeating in-lane mask.
9279       return SDValue();
9280     }
9281   }
9282
9283   // First shuffle the lanes into place.
9284   MVT LaneVT = MVT::getVectorVT(VT.isFloatingPoint() ? MVT::f64 : MVT::i64,
9285                                 VT.getSizeInBits() / 64);
9286   SmallVector<int, 8> LaneMask;
9287   LaneMask.resize(NumLanes * 2, -1);
9288   for (int i = 0; i < NumLanes; ++i)
9289     if (Lanes[i] >= 0) {
9290       LaneMask[2 * i + 0] = 2*Lanes[i] + 0;
9291       LaneMask[2 * i + 1] = 2*Lanes[i] + 1;
9292     }
9293
9294   V1 = DAG.getNode(ISD::BITCAST, DL, LaneVT, V1);
9295   V2 = DAG.getNode(ISD::BITCAST, DL, LaneVT, V2);
9296   SDValue LaneShuffle = DAG.getVectorShuffle(LaneVT, DL, V1, V2, LaneMask);
9297
9298   // Cast it back to the type we actually want.
9299   LaneShuffle = DAG.getNode(ISD::BITCAST, DL, VT, LaneShuffle);
9300
9301   // Now do a simple shuffle that isn't lane crossing.
9302   SmallVector<int, 8> NewMask;
9303   NewMask.resize(Size, -1);
9304   for (int i = 0; i < Size; ++i)
9305     if (Mask[i] >= 0)
9306       NewMask[i] = (i / LaneSize) * LaneSize + Mask[i] % LaneSize;
9307   assert(!is128BitLaneCrossingShuffleMask(VT, NewMask) &&
9308          "Must not introduce lane crosses at this point!");
9309
9310   return DAG.getVectorShuffle(VT, DL, LaneShuffle, DAG.getUNDEF(VT), NewMask);
9311 }
9312
9313 /// \brief Test whether the specified input (0 or 1) is in-place blended by the
9314 /// given mask.
9315 ///
9316 /// This returns true if the elements from a particular input are already in the
9317 /// slot required by the given mask and require no permutation.
9318 static bool isShuffleMaskInputInPlace(int Input, ArrayRef<int> Mask) {
9319   assert((Input == 0 || Input == 1) && "Only two inputs to shuffles.");
9320   int Size = Mask.size();
9321   for (int i = 0; i < Size; ++i)
9322     if (Mask[i] >= 0 && Mask[i] / Size == Input && Mask[i] % Size != i)
9323       return false;
9324
9325   return true;
9326 }
9327
9328 /// \brief Handle lowering of 4-lane 64-bit floating point shuffles.
9329 ///
9330 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
9331 /// isn't available.
9332 static SDValue lowerV4F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9333                                        const X86Subtarget *Subtarget,
9334                                        SelectionDAG &DAG) {
9335   SDLoc DL(Op);
9336   assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9337   assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9338   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9339   ArrayRef<int> Mask = SVOp->getMask();
9340   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9341
9342   SmallVector<int, 4> WidenedMask;
9343   if (canWidenShuffleElements(Mask, WidenedMask))
9344     return lowerV2X128VectorShuffle(DL, MVT::v4f64, V1, V2, Mask, Subtarget,
9345                                     DAG);
9346
9347   if (isSingleInputShuffleMask(Mask)) {
9348     // Check for being able to broadcast a single element.
9349     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f64, V1,
9350                                                           Mask, Subtarget, DAG))
9351       return Broadcast;
9352
9353     // Use low duplicate instructions for masks that match their pattern.
9354     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
9355       return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v4f64, V1);
9356
9357     if (!is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask)) {
9358       // Non-half-crossing single input shuffles can be lowerid with an
9359       // interleaved permutation.
9360       unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
9361                               ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
9362       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f64, V1,
9363                          DAG.getConstant(VPERMILPMask, MVT::i8));
9364     }
9365
9366     // With AVX2 we have direct support for this permutation.
9367     if (Subtarget->hasAVX2())
9368       return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4f64, V1,
9369                          getV4X86ShuffleImm8ForMask(Mask, DAG));
9370
9371     // Otherwise, fall back.
9372     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v4f64, V1, V2, Mask,
9373                                                    DAG);
9374   }
9375
9376   // X86 has dedicated unpack instructions that can handle specific blend
9377   // operations: UNPCKH and UNPCKL.
9378   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9379     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V1, V2);
9380   if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9381     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V1, V2);
9382   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9383     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V2, V1);
9384   if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9385     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V2, V1);
9386
9387   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f64, V1, V2, Mask,
9388                                                 Subtarget, DAG))
9389     return Blend;
9390
9391   // Check if the blend happens to exactly fit that of SHUFPD.
9392   if ((Mask[0] == -1 || Mask[0] < 2) &&
9393       (Mask[1] == -1 || (Mask[1] >= 4 && Mask[1] < 6)) &&
9394       (Mask[2] == -1 || (Mask[2] >= 2 && Mask[2] < 4)) &&
9395       (Mask[3] == -1 || Mask[3] >= 6)) {
9396     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 5) << 1) |
9397                           ((Mask[2] == 3) << 2) | ((Mask[3] == 7) << 3);
9398     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f64, V1, V2,
9399                        DAG.getConstant(SHUFPDMask, MVT::i8));
9400   }
9401   if ((Mask[0] == -1 || (Mask[0] >= 4 && Mask[0] < 6)) &&
9402       (Mask[1] == -1 || Mask[1] < 2) &&
9403       (Mask[2] == -1 || Mask[2] >= 6) &&
9404       (Mask[3] == -1 || (Mask[3] >= 2 && Mask[3] < 4))) {
9405     unsigned SHUFPDMask = (Mask[0] == 5) | ((Mask[1] == 1) << 1) |
9406                           ((Mask[2] == 7) << 2) | ((Mask[3] == 3) << 3);
9407     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f64, V2, V1,
9408                        DAG.getConstant(SHUFPDMask, MVT::i8));
9409   }
9410
9411   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9412   // shuffle. However, if we have AVX2 and either inputs are already in place,
9413   // we will be able to shuffle even across lanes the other input in a single
9414   // instruction so skip this pattern.
9415   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9416                                  isShuffleMaskInputInPlace(1, Mask))))
9417     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9418             DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
9419       return Result;
9420
9421   // If we have AVX2 then we always want to lower with a blend because an v4 we
9422   // can fully permute the elements.
9423   if (Subtarget->hasAVX2())
9424     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4f64, V1, V2,
9425                                                       Mask, DAG);
9426
9427   // Otherwise fall back on generic lowering.
9428   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v4f64, V1, V2, Mask, DAG);
9429 }
9430
9431 /// \brief Handle lowering of 4-lane 64-bit integer shuffles.
9432 ///
9433 /// This routine is only called when we have AVX2 and thus a reasonable
9434 /// instruction set for v4i64 shuffling..
9435 static SDValue lowerV4I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9436                                        const X86Subtarget *Subtarget,
9437                                        SelectionDAG &DAG) {
9438   SDLoc DL(Op);
9439   assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9440   assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9441   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9442   ArrayRef<int> Mask = SVOp->getMask();
9443   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9444   assert(Subtarget->hasAVX2() && "We can only lower v4i64 with AVX2!");
9445
9446   SmallVector<int, 4> WidenedMask;
9447   if (canWidenShuffleElements(Mask, WidenedMask))
9448     return lowerV2X128VectorShuffle(DL, MVT::v4i64, V1, V2, Mask, Subtarget,
9449                                     DAG);
9450
9451   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i64, V1, V2, Mask,
9452                                                 Subtarget, DAG))
9453     return Blend;
9454
9455   // Check for being able to broadcast a single element.
9456   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i64, V1,
9457                                                         Mask, Subtarget, DAG))
9458     return Broadcast;
9459
9460   // When the shuffle is mirrored between the 128-bit lanes of the unit, we can
9461   // use lower latency instructions that will operate on both 128-bit lanes.
9462   SmallVector<int, 2> RepeatedMask;
9463   if (is128BitLaneRepeatedShuffleMask(MVT::v4i64, Mask, RepeatedMask)) {
9464     if (isSingleInputShuffleMask(Mask)) {
9465       int PSHUFDMask[] = {-1, -1, -1, -1};
9466       for (int i = 0; i < 2; ++i)
9467         if (RepeatedMask[i] >= 0) {
9468           PSHUFDMask[2 * i] = 2 * RepeatedMask[i];
9469           PSHUFDMask[2 * i + 1] = 2 * RepeatedMask[i] + 1;
9470         }
9471       return DAG.getNode(
9472           ISD::BITCAST, DL, MVT::v4i64,
9473           DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32,
9474                       DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, V1),
9475                       getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
9476     }
9477   }
9478
9479   // AVX2 provides a direct instruction for permuting a single input across
9480   // lanes.
9481   if (isSingleInputShuffleMask(Mask))
9482     return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4i64, V1,
9483                        getV4X86ShuffleImm8ForMask(Mask, DAG));
9484
9485   // Try to use shift instructions.
9486   if (SDValue Shift =
9487           lowerVectorShuffleAsShift(DL, MVT::v4i64, V1, V2, Mask, DAG))
9488     return Shift;
9489
9490   // Use dedicated unpack instructions for masks that match their pattern.
9491   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9492     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V1, V2);
9493   if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9494     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V1, V2);
9495   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9496     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V2, V1);
9497   if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9498     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V2, V1);
9499
9500   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9501   // shuffle. However, if we have AVX2 and either inputs are already in place,
9502   // we will be able to shuffle even across lanes the other input in a single
9503   // instruction so skip this pattern.
9504   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9505                                  isShuffleMaskInputInPlace(1, Mask))))
9506     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9507             DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
9508       return Result;
9509
9510   // Otherwise fall back on generic blend lowering.
9511   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i64, V1, V2,
9512                                                     Mask, DAG);
9513 }
9514
9515 /// \brief Handle lowering of 8-lane 32-bit floating point shuffles.
9516 ///
9517 /// Also ends up handling lowering of 8-lane 32-bit integer shuffles when AVX2
9518 /// isn't available.
9519 static SDValue lowerV8F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9520                                        const X86Subtarget *Subtarget,
9521                                        SelectionDAG &DAG) {
9522   SDLoc DL(Op);
9523   assert(V1.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
9524   assert(V2.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
9525   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9526   ArrayRef<int> Mask = SVOp->getMask();
9527   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9528
9529   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8f32, V1, V2, Mask,
9530                                                 Subtarget, DAG))
9531     return Blend;
9532
9533   // Check for being able to broadcast a single element.
9534   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8f32, V1,
9535                                                         Mask, Subtarget, DAG))
9536     return Broadcast;
9537
9538   // If the shuffle mask is repeated in each 128-bit lane, we have many more
9539   // options to efficiently lower the shuffle.
9540   SmallVector<int, 4> RepeatedMask;
9541   if (is128BitLaneRepeatedShuffleMask(MVT::v8f32, Mask, RepeatedMask)) {
9542     assert(RepeatedMask.size() == 4 &&
9543            "Repeated masks must be half the mask width!");
9544
9545     // Use even/odd duplicate instructions for masks that match their pattern.
9546     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2, 4, 4, 6, 6}))
9547       return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v8f32, V1);
9548     if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3, 5, 5, 7, 7}))
9549       return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v8f32, V1);
9550
9551     if (isSingleInputShuffleMask(Mask))
9552       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, V1,
9553                          getV4X86ShuffleImm8ForMask(RepeatedMask, DAG));
9554
9555     // Use dedicated unpack instructions for masks that match their pattern.
9556     if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
9557       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V1, V2);
9558     if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
9559       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V1, V2);
9560     if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
9561       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V2, V1);
9562     if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
9563       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V2, V1);
9564
9565     // Otherwise, fall back to a SHUFPS sequence. Here it is important that we
9566     // have already handled any direct blends. We also need to squash the
9567     // repeated mask into a simulated v4f32 mask.
9568     for (int i = 0; i < 4; ++i)
9569       if (RepeatedMask[i] >= 8)
9570         RepeatedMask[i] -= 4;
9571     return lowerVectorShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask, V1, V2, DAG);
9572   }
9573
9574   // If we have a single input shuffle with different shuffle patterns in the
9575   // two 128-bit lanes use the variable mask to VPERMILPS.
9576   if (isSingleInputShuffleMask(Mask)) {
9577     SDValue VPermMask[8];
9578     for (int i = 0; i < 8; ++i)
9579       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
9580                                  : DAG.getConstant(Mask[i], MVT::i32);
9581     if (!is128BitLaneCrossingShuffleMask(MVT::v8f32, Mask))
9582       return DAG.getNode(
9583           X86ISD::VPERMILPV, DL, MVT::v8f32, V1,
9584           DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask));
9585
9586     if (Subtarget->hasAVX2())
9587       return DAG.getNode(X86ISD::VPERMV, DL, MVT::v8f32,
9588                          DAG.getNode(ISD::BITCAST, DL, MVT::v8f32,
9589                                      DAG.getNode(ISD::BUILD_VECTOR, DL,
9590                                                  MVT::v8i32, VPermMask)),
9591                          V1);
9592
9593     // Otherwise, fall back.
9594     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v8f32, V1, V2, Mask,
9595                                                    DAG);
9596   }
9597
9598   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9599   // shuffle.
9600   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9601           DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
9602     return Result;
9603
9604   // If we have AVX2 then we always want to lower with a blend because at v8 we
9605   // can fully permute the elements.
9606   if (Subtarget->hasAVX2())
9607     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8f32, V1, V2,
9608                                                       Mask, DAG);
9609
9610   // Otherwise fall back on generic lowering.
9611   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask, DAG);
9612 }
9613
9614 /// \brief Handle lowering of 8-lane 32-bit integer shuffles.
9615 ///
9616 /// This routine is only called when we have AVX2 and thus a reasonable
9617 /// instruction set for v8i32 shuffling..
9618 static SDValue lowerV8I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9619                                        const X86Subtarget *Subtarget,
9620                                        SelectionDAG &DAG) {
9621   SDLoc DL(Op);
9622   assert(V1.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
9623   assert(V2.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
9624   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9625   ArrayRef<int> Mask = SVOp->getMask();
9626   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9627   assert(Subtarget->hasAVX2() && "We can only lower v8i32 with AVX2!");
9628
9629   // Whenever we can lower this as a zext, that instruction is strictly faster
9630   // than any alternative. It also allows us to fold memory operands into the
9631   // shuffle in many cases.
9632   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v8i32, V1, V2,
9633                                                          Mask, Subtarget, DAG))
9634     return ZExt;
9635
9636   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i32, V1, V2, Mask,
9637                                                 Subtarget, DAG))
9638     return Blend;
9639
9640   // Check for being able to broadcast a single element.
9641   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i32, V1,
9642                                                         Mask, Subtarget, DAG))
9643     return Broadcast;
9644
9645   // If the shuffle mask is repeated in each 128-bit lane we can use more
9646   // efficient instructions that mirror the shuffles across the two 128-bit
9647   // lanes.
9648   SmallVector<int, 4> RepeatedMask;
9649   if (is128BitLaneRepeatedShuffleMask(MVT::v8i32, Mask, RepeatedMask)) {
9650     assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
9651     if (isSingleInputShuffleMask(Mask))
9652       return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32, V1,
9653                          getV4X86ShuffleImm8ForMask(RepeatedMask, DAG));
9654
9655     // Use dedicated unpack instructions for masks that match their pattern.
9656     if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
9657       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V1, V2);
9658     if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
9659       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V1, V2);
9660     if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
9661       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V2, V1);
9662     if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
9663       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V2, V1);
9664   }
9665
9666   // Try to use shift instructions.
9667   if (SDValue Shift =
9668           lowerVectorShuffleAsShift(DL, MVT::v8i32, V1, V2, Mask, DAG))
9669     return Shift;
9670
9671   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9672           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
9673     return Rotate;
9674
9675   // If the shuffle patterns aren't repeated but it is a single input, directly
9676   // generate a cross-lane VPERMD instruction.
9677   if (isSingleInputShuffleMask(Mask)) {
9678     SDValue VPermMask[8];
9679     for (int i = 0; i < 8; ++i)
9680       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
9681                                  : DAG.getConstant(Mask[i], MVT::i32);
9682     return DAG.getNode(
9683         X86ISD::VPERMV, DL, MVT::v8i32,
9684         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask), V1);
9685   }
9686
9687   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9688   // shuffle.
9689   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9690           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
9691     return Result;
9692
9693   // Otherwise fall back on generic blend lowering.
9694   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i32, V1, V2,
9695                                                     Mask, DAG);
9696 }
9697
9698 /// \brief Handle lowering of 16-lane 16-bit integer shuffles.
9699 ///
9700 /// This routine is only called when we have AVX2 and thus a reasonable
9701 /// instruction set for v16i16 shuffling..
9702 static SDValue lowerV16I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9703                                         const X86Subtarget *Subtarget,
9704                                         SelectionDAG &DAG) {
9705   SDLoc DL(Op);
9706   assert(V1.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
9707   assert(V2.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
9708   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9709   ArrayRef<int> Mask = SVOp->getMask();
9710   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
9711   assert(Subtarget->hasAVX2() && "We can only lower v16i16 with AVX2!");
9712
9713   // Whenever we can lower this as a zext, that instruction is strictly faster
9714   // than any alternative. It also allows us to fold memory operands into the
9715   // shuffle in many cases.
9716   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v16i16, V1, V2,
9717                                                          Mask, Subtarget, DAG))
9718     return ZExt;
9719
9720   // Check for being able to broadcast a single element.
9721   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i16, V1,
9722                                                         Mask, Subtarget, DAG))
9723     return Broadcast;
9724
9725   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i16, V1, V2, Mask,
9726                                                 Subtarget, DAG))
9727     return Blend;
9728
9729   // Use dedicated unpack instructions for masks that match their pattern.
9730   if (isShuffleEquivalent(V1, V2, Mask,
9731                           {// First 128-bit lane:
9732                            0, 16, 1, 17, 2, 18, 3, 19,
9733                            // Second 128-bit lane:
9734                            8, 24, 9, 25, 10, 26, 11, 27}))
9735     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i16, V1, V2);
9736   if (isShuffleEquivalent(V1, V2, Mask,
9737                           {// First 128-bit lane:
9738                            4, 20, 5, 21, 6, 22, 7, 23,
9739                            // Second 128-bit lane:
9740                            12, 28, 13, 29, 14, 30, 15, 31}))
9741     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i16, V1, V2);
9742
9743   // Try to use shift instructions.
9744   if (SDValue Shift =
9745           lowerVectorShuffleAsShift(DL, MVT::v16i16, V1, V2, Mask, DAG))
9746     return Shift;
9747
9748   // Try to use byte rotation instructions.
9749   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9750           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
9751     return Rotate;
9752
9753   if (isSingleInputShuffleMask(Mask)) {
9754     // There are no generalized cross-lane shuffle operations available on i16
9755     // element types.
9756     if (is128BitLaneCrossingShuffleMask(MVT::v16i16, Mask))
9757       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v16i16, V1, V2,
9758                                                      Mask, DAG);
9759
9760     SmallVector<int, 8> RepeatedMask;
9761     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
9762       // As this is a single-input shuffle, the repeated mask should be
9763       // a strictly valid v8i16 mask that we can pass through to the v8i16
9764       // lowering to handle even the v16 case.
9765       return lowerV8I16GeneralSingleInputVectorShuffle(
9766           DL, MVT::v16i16, V1, RepeatedMask, Subtarget, DAG);
9767     }
9768
9769     SDValue PSHUFBMask[32];
9770     for (int i = 0; i < 16; ++i) {
9771       if (Mask[i] == -1) {
9772         PSHUFBMask[2 * i] = PSHUFBMask[2 * i + 1] = DAG.getUNDEF(MVT::i8);
9773         continue;
9774       }
9775
9776       int M = i < 8 ? Mask[i] : Mask[i] - 8;
9777       assert(M >= 0 && M < 8 && "Invalid single-input mask!");
9778       PSHUFBMask[2 * i] = DAG.getConstant(2 * M, MVT::i8);
9779       PSHUFBMask[2 * i + 1] = DAG.getConstant(2 * M + 1, MVT::i8);
9780     }
9781     return DAG.getNode(
9782         ISD::BITCAST, DL, MVT::v16i16,
9783         DAG.getNode(
9784             X86ISD::PSHUFB, DL, MVT::v32i8,
9785             DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, V1),
9786             DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask)));
9787   }
9788
9789   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9790   // shuffle.
9791   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9792           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
9793     return Result;
9794
9795   // Otherwise fall back on generic lowering.
9796   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v16i16, V1, V2, Mask, DAG);
9797 }
9798
9799 /// \brief Handle lowering of 32-lane 8-bit integer shuffles.
9800 ///
9801 /// This routine is only called when we have AVX2 and thus a reasonable
9802 /// instruction set for v32i8 shuffling..
9803 static SDValue lowerV32I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9804                                        const X86Subtarget *Subtarget,
9805                                        SelectionDAG &DAG) {
9806   SDLoc DL(Op);
9807   assert(V1.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
9808   assert(V2.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
9809   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9810   ArrayRef<int> Mask = SVOp->getMask();
9811   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
9812   assert(Subtarget->hasAVX2() && "We can only lower v32i8 with AVX2!");
9813
9814   // Whenever we can lower this as a zext, that instruction is strictly faster
9815   // than any alternative. It also allows us to fold memory operands into the
9816   // shuffle in many cases.
9817   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v32i8, V1, V2,
9818                                                          Mask, Subtarget, DAG))
9819     return ZExt;
9820
9821   // Check for being able to broadcast a single element.
9822   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v32i8, V1,
9823                                                         Mask, Subtarget, DAG))
9824     return Broadcast;
9825
9826   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v32i8, V1, V2, Mask,
9827                                                 Subtarget, DAG))
9828     return Blend;
9829
9830   // Use dedicated unpack instructions for masks that match their pattern.
9831   // Note that these are repeated 128-bit lane unpacks, not unpacks across all
9832   // 256-bit lanes.
9833   if (isShuffleEquivalent(
9834           V1, V2, Mask,
9835           {// First 128-bit lane:
9836            0, 32, 1, 33, 2, 34, 3, 35, 4, 36, 5, 37, 6, 38, 7, 39,
9837            // Second 128-bit lane:
9838            16, 48, 17, 49, 18, 50, 19, 51, 20, 52, 21, 53, 22, 54, 23, 55}))
9839     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v32i8, V1, V2);
9840   if (isShuffleEquivalent(
9841           V1, V2, Mask,
9842           {// First 128-bit lane:
9843            8, 40, 9, 41, 10, 42, 11, 43, 12, 44, 13, 45, 14, 46, 15, 47,
9844            // Second 128-bit lane:
9845            24, 56, 25, 57, 26, 58, 27, 59, 28, 60, 29, 61, 30, 62, 31, 63}))
9846     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v32i8, V1, V2);
9847
9848   // Try to use shift instructions.
9849   if (SDValue Shift =
9850           lowerVectorShuffleAsShift(DL, MVT::v32i8, V1, V2, Mask, DAG))
9851     return Shift;
9852
9853   // Try to use byte rotation instructions.
9854   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9855           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
9856     return Rotate;
9857
9858   if (isSingleInputShuffleMask(Mask)) {
9859     // There are no generalized cross-lane shuffle operations available on i8
9860     // element types.
9861     if (is128BitLaneCrossingShuffleMask(MVT::v32i8, Mask))
9862       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v32i8, V1, V2,
9863                                                      Mask, DAG);
9864
9865     SDValue PSHUFBMask[32];
9866     for (int i = 0; i < 32; ++i)
9867       PSHUFBMask[i] =
9868           Mask[i] < 0
9869               ? DAG.getUNDEF(MVT::i8)
9870               : DAG.getConstant(Mask[i] < 16 ? Mask[i] : Mask[i] - 16, MVT::i8);
9871
9872     return DAG.getNode(
9873         X86ISD::PSHUFB, DL, MVT::v32i8, V1,
9874         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask));
9875   }
9876
9877   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9878   // shuffle.
9879   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9880           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
9881     return Result;
9882
9883   // Otherwise fall back on generic lowering.
9884   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v32i8, V1, V2, Mask, DAG);
9885 }
9886
9887 /// \brief High-level routine to lower various 256-bit x86 vector shuffles.
9888 ///
9889 /// This routine either breaks down the specific type of a 256-bit x86 vector
9890 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
9891 /// together based on the available instructions.
9892 static SDValue lower256BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9893                                         MVT VT, const X86Subtarget *Subtarget,
9894                                         SelectionDAG &DAG) {
9895   SDLoc DL(Op);
9896   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9897   ArrayRef<int> Mask = SVOp->getMask();
9898
9899   // If we have a single input to the zero element, insert that into V1 if we
9900   // can do so cheaply.
9901   int NumElts = VT.getVectorNumElements();
9902   int NumV2Elements = std::count_if(Mask.begin(), Mask.end(), [NumElts](int M) {
9903     return M >= NumElts;
9904   });
9905
9906   if (NumV2Elements == 1 && Mask[0] >= NumElts)
9907     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
9908                               DL, VT, V1, V2, Mask, Subtarget, DAG))
9909       return Insertion;
9910
9911   // There is a really nice hard cut-over between AVX1 and AVX2 that means we can
9912   // check for those subtargets here and avoid much of the subtarget querying in
9913   // the per-vector-type lowering routines. With AVX1 we have essentially *zero*
9914   // ability to manipulate a 256-bit vector with integer types. Since we'll use
9915   // floating point types there eventually, just immediately cast everything to
9916   // a float and operate entirely in that domain.
9917   if (VT.isInteger() && !Subtarget->hasAVX2()) {
9918     int ElementBits = VT.getScalarSizeInBits();
9919     if (ElementBits < 32)
9920       // No floating point type available, decompose into 128-bit vectors.
9921       return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9922
9923     MVT FpVT = MVT::getVectorVT(MVT::getFloatingPointVT(ElementBits),
9924                                 VT.getVectorNumElements());
9925     V1 = DAG.getNode(ISD::BITCAST, DL, FpVT, V1);
9926     V2 = DAG.getNode(ISD::BITCAST, DL, FpVT, V2);
9927     return DAG.getNode(ISD::BITCAST, DL, VT,
9928                        DAG.getVectorShuffle(FpVT, DL, V1, V2, Mask));
9929   }
9930
9931   switch (VT.SimpleTy) {
9932   case MVT::v4f64:
9933     return lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9934   case MVT::v4i64:
9935     return lowerV4I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9936   case MVT::v8f32:
9937     return lowerV8F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9938   case MVT::v8i32:
9939     return lowerV8I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9940   case MVT::v16i16:
9941     return lowerV16I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
9942   case MVT::v32i8:
9943     return lowerV32I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
9944
9945   default:
9946     llvm_unreachable("Not a valid 256-bit x86 vector type!");
9947   }
9948 }
9949
9950 /// \brief Handle lowering of 8-lane 64-bit floating point shuffles.
9951 static SDValue lowerV8F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9952                                        const X86Subtarget *Subtarget,
9953                                        SelectionDAG &DAG) {
9954   SDLoc DL(Op);
9955   assert(V1.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
9956   assert(V2.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
9957   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9958   ArrayRef<int> Mask = SVOp->getMask();
9959   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9960
9961   // X86 has dedicated unpack instructions that can handle specific blend
9962   // operations: UNPCKH and UNPCKL.
9963   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
9964     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f64, V1, V2);
9965   if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
9966     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f64, V1, V2);
9967
9968   // FIXME: Implement direct support for this type!
9969   return splitAndLowerVectorShuffle(DL, MVT::v8f64, V1, V2, Mask, DAG);
9970 }
9971
9972 /// \brief Handle lowering of 16-lane 32-bit floating point shuffles.
9973 static SDValue lowerV16F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9974                                        const X86Subtarget *Subtarget,
9975                                        SelectionDAG &DAG) {
9976   SDLoc DL(Op);
9977   assert(V1.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
9978   assert(V2.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
9979   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9980   ArrayRef<int> Mask = SVOp->getMask();
9981   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
9982
9983   // Use dedicated unpack instructions for masks that match their pattern.
9984   if (isShuffleEquivalent(V1, V2, Mask,
9985                           {// First 128-bit lane.
9986                            0, 16, 1, 17, 4, 20, 5, 21,
9987                            // Second 128-bit lane.
9988                            8, 24, 9, 25, 12, 28, 13, 29}))
9989     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16f32, V1, V2);
9990   if (isShuffleEquivalent(V1, V2, Mask,
9991                           {// First 128-bit lane.
9992                            2, 18, 3, 19, 6, 22, 7, 23,
9993                            // Second 128-bit lane.
9994                            10, 26, 11, 27, 14, 30, 15, 31}))
9995     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16f32, V1, V2);
9996
9997   // FIXME: Implement direct support for this type!
9998   return splitAndLowerVectorShuffle(DL, MVT::v16f32, V1, V2, Mask, DAG);
9999 }
10000
10001 /// \brief Handle lowering of 8-lane 64-bit integer shuffles.
10002 static SDValue lowerV8I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10003                                        const X86Subtarget *Subtarget,
10004                                        SelectionDAG &DAG) {
10005   SDLoc DL(Op);
10006   assert(V1.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10007   assert(V2.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10008   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10009   ArrayRef<int> Mask = SVOp->getMask();
10010   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10011
10012   // X86 has dedicated unpack instructions that can handle specific blend
10013   // operations: UNPCKH and UNPCKL.
10014   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
10015     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i64, V1, V2);
10016   if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
10017     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i64, V1, V2);
10018
10019   // FIXME: Implement direct support for this type!
10020   return splitAndLowerVectorShuffle(DL, MVT::v8i64, V1, V2, Mask, DAG);
10021 }
10022
10023 /// \brief Handle lowering of 16-lane 32-bit integer shuffles.
10024 static SDValue lowerV16I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10025                                        const X86Subtarget *Subtarget,
10026                                        SelectionDAG &DAG) {
10027   SDLoc DL(Op);
10028   assert(V1.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10029   assert(V2.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10030   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10031   ArrayRef<int> Mask = SVOp->getMask();
10032   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10033
10034   // Use dedicated unpack instructions for masks that match their pattern.
10035   if (isShuffleEquivalent(V1, V2, Mask,
10036                           {// First 128-bit lane.
10037                            0, 16, 1, 17, 4, 20, 5, 21,
10038                            // Second 128-bit lane.
10039                            8, 24, 9, 25, 12, 28, 13, 29}))
10040     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i32, V1, V2);
10041   if (isShuffleEquivalent(V1, V2, Mask,
10042                           {// First 128-bit lane.
10043                            2, 18, 3, 19, 6, 22, 7, 23,
10044                            // Second 128-bit lane.
10045                            10, 26, 11, 27, 14, 30, 15, 31}))
10046     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i32, V1, V2);
10047
10048   // FIXME: Implement direct support for this type!
10049   return splitAndLowerVectorShuffle(DL, MVT::v16i32, V1, V2, Mask, DAG);
10050 }
10051
10052 /// \brief Handle lowering of 32-lane 16-bit integer shuffles.
10053 static SDValue lowerV32I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10054                                         const X86Subtarget *Subtarget,
10055                                         SelectionDAG &DAG) {
10056   SDLoc DL(Op);
10057   assert(V1.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10058   assert(V2.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10059   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10060   ArrayRef<int> Mask = SVOp->getMask();
10061   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10062   assert(Subtarget->hasBWI() && "We can only lower v32i16 with AVX-512-BWI!");
10063
10064   // FIXME: Implement direct support for this type!
10065   return splitAndLowerVectorShuffle(DL, MVT::v32i16, V1, V2, Mask, DAG);
10066 }
10067
10068 /// \brief Handle lowering of 64-lane 8-bit integer shuffles.
10069 static SDValue lowerV64I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10070                                        const X86Subtarget *Subtarget,
10071                                        SelectionDAG &DAG) {
10072   SDLoc DL(Op);
10073   assert(V1.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10074   assert(V2.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10075   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10076   ArrayRef<int> Mask = SVOp->getMask();
10077   assert(Mask.size() == 64 && "Unexpected mask size for v64 shuffle!");
10078   assert(Subtarget->hasBWI() && "We can only lower v64i8 with AVX-512-BWI!");
10079
10080   // FIXME: Implement direct support for this type!
10081   return splitAndLowerVectorShuffle(DL, MVT::v64i8, V1, V2, Mask, DAG);
10082 }
10083
10084 /// \brief High-level routine to lower various 512-bit x86 vector shuffles.
10085 ///
10086 /// This routine either breaks down the specific type of a 512-bit x86 vector
10087 /// shuffle or splits it into two 256-bit shuffles and fuses the results back
10088 /// together based on the available instructions.
10089 static SDValue lower512BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10090                                         MVT VT, const X86Subtarget *Subtarget,
10091                                         SelectionDAG &DAG) {
10092   SDLoc DL(Op);
10093   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10094   ArrayRef<int> Mask = SVOp->getMask();
10095   assert(Subtarget->hasAVX512() &&
10096          "Cannot lower 512-bit vectors w/ basic ISA!");
10097
10098   // Check for being able to broadcast a single element.
10099   if (SDValue Broadcast =
10100           lowerVectorShuffleAsBroadcast(DL, VT, V1, Mask, Subtarget, DAG))
10101     return Broadcast;
10102
10103   // Dispatch to each element type for lowering. If we don't have supprot for
10104   // specific element type shuffles at 512 bits, immediately split them and
10105   // lower them. Each lowering routine of a given type is allowed to assume that
10106   // the requisite ISA extensions for that element type are available.
10107   switch (VT.SimpleTy) {
10108   case MVT::v8f64:
10109     return lowerV8F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10110   case MVT::v16f32:
10111     return lowerV16F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10112   case MVT::v8i64:
10113     return lowerV8I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10114   case MVT::v16i32:
10115     return lowerV16I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10116   case MVT::v32i16:
10117     if (Subtarget->hasBWI())
10118       return lowerV32I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10119     break;
10120   case MVT::v64i8:
10121     if (Subtarget->hasBWI())
10122       return lowerV64I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10123     break;
10124
10125   default:
10126     llvm_unreachable("Not a valid 512-bit x86 vector type!");
10127   }
10128
10129   // Otherwise fall back on splitting.
10130   return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10131 }
10132
10133 /// \brief Top-level lowering for x86 vector shuffles.
10134 ///
10135 /// This handles decomposition, canonicalization, and lowering of all x86
10136 /// vector shuffles. Most of the specific lowering strategies are encapsulated
10137 /// above in helper routines. The canonicalization attempts to widen shuffles
10138 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
10139 /// s.t. only one of the two inputs needs to be tested, etc.
10140 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
10141                                   SelectionDAG &DAG) {
10142   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10143   ArrayRef<int> Mask = SVOp->getMask();
10144   SDValue V1 = Op.getOperand(0);
10145   SDValue V2 = Op.getOperand(1);
10146   MVT VT = Op.getSimpleValueType();
10147   int NumElements = VT.getVectorNumElements();
10148   SDLoc dl(Op);
10149
10150   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
10151
10152   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
10153   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
10154   if (V1IsUndef && V2IsUndef)
10155     return DAG.getUNDEF(VT);
10156
10157   // When we create a shuffle node we put the UNDEF node to second operand,
10158   // but in some cases the first operand may be transformed to UNDEF.
10159   // In this case we should just commute the node.
10160   if (V1IsUndef)
10161     return DAG.getCommutedVectorShuffle(*SVOp);
10162
10163   // Check for non-undef masks pointing at an undef vector and make the masks
10164   // undef as well. This makes it easier to match the shuffle based solely on
10165   // the mask.
10166   if (V2IsUndef)
10167     for (int M : Mask)
10168       if (M >= NumElements) {
10169         SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
10170         for (int &M : NewMask)
10171           if (M >= NumElements)
10172             M = -1;
10173         return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
10174       }
10175
10176   // We actually see shuffles that are entirely re-arrangements of a set of
10177   // zero inputs. This mostly happens while decomposing complex shuffles into
10178   // simple ones. Directly lower these as a buildvector of zeros.
10179   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
10180   if (Zeroable.all())
10181     return getZeroVector(VT, Subtarget, DAG, dl);
10182
10183   // Try to collapse shuffles into using a vector type with fewer elements but
10184   // wider element types. We cap this to not form integers or floating point
10185   // elements wider than 64 bits, but it might be interesting to form i128
10186   // integers to handle flipping the low and high halves of AVX 256-bit vectors.
10187   SmallVector<int, 16> WidenedMask;
10188   if (VT.getScalarSizeInBits() < 64 &&
10189       canWidenShuffleElements(Mask, WidenedMask)) {
10190     MVT NewEltVT = VT.isFloatingPoint()
10191                        ? MVT::getFloatingPointVT(VT.getScalarSizeInBits() * 2)
10192                        : MVT::getIntegerVT(VT.getScalarSizeInBits() * 2);
10193     MVT NewVT = MVT::getVectorVT(NewEltVT, VT.getVectorNumElements() / 2);
10194     // Make sure that the new vector type is legal. For example, v2f64 isn't
10195     // legal on SSE1.
10196     if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
10197       V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
10198       V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
10199       return DAG.getNode(ISD::BITCAST, dl, VT,
10200                          DAG.getVectorShuffle(NewVT, dl, V1, V2, WidenedMask));
10201     }
10202   }
10203
10204   int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
10205   for (int M : SVOp->getMask())
10206     if (M < 0)
10207       ++NumUndefElements;
10208     else if (M < NumElements)
10209       ++NumV1Elements;
10210     else
10211       ++NumV2Elements;
10212
10213   // Commute the shuffle as needed such that more elements come from V1 than
10214   // V2. This allows us to match the shuffle pattern strictly on how many
10215   // elements come from V1 without handling the symmetric cases.
10216   if (NumV2Elements > NumV1Elements)
10217     return DAG.getCommutedVectorShuffle(*SVOp);
10218
10219   // When the number of V1 and V2 elements are the same, try to minimize the
10220   // number of uses of V2 in the low half of the vector. When that is tied,
10221   // ensure that the sum of indices for V1 is equal to or lower than the sum
10222   // indices for V2. When those are equal, try to ensure that the number of odd
10223   // indices for V1 is lower than the number of odd indices for V2.
10224   if (NumV1Elements == NumV2Elements) {
10225     int LowV1Elements = 0, LowV2Elements = 0;
10226     for (int M : SVOp->getMask().slice(0, NumElements / 2))
10227       if (M >= NumElements)
10228         ++LowV2Elements;
10229       else if (M >= 0)
10230         ++LowV1Elements;
10231     if (LowV2Elements > LowV1Elements) {
10232       return DAG.getCommutedVectorShuffle(*SVOp);
10233     } else if (LowV2Elements == LowV1Elements) {
10234       int SumV1Indices = 0, SumV2Indices = 0;
10235       for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10236         if (SVOp->getMask()[i] >= NumElements)
10237           SumV2Indices += i;
10238         else if (SVOp->getMask()[i] >= 0)
10239           SumV1Indices += i;
10240       if (SumV2Indices < SumV1Indices) {
10241         return DAG.getCommutedVectorShuffle(*SVOp);
10242       } else if (SumV2Indices == SumV1Indices) {
10243         int NumV1OddIndices = 0, NumV2OddIndices = 0;
10244         for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10245           if (SVOp->getMask()[i] >= NumElements)
10246             NumV2OddIndices += i % 2;
10247           else if (SVOp->getMask()[i] >= 0)
10248             NumV1OddIndices += i % 2;
10249         if (NumV2OddIndices < NumV1OddIndices)
10250           return DAG.getCommutedVectorShuffle(*SVOp);
10251       }
10252     }
10253   }
10254
10255   // For each vector width, delegate to a specialized lowering routine.
10256   if (VT.getSizeInBits() == 128)
10257     return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10258
10259   if (VT.getSizeInBits() == 256)
10260     return lower256BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10261
10262   // Force AVX-512 vectors to be scalarized for now.
10263   // FIXME: Implement AVX-512 support!
10264   if (VT.getSizeInBits() == 512)
10265     return lower512BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10266
10267   llvm_unreachable("Unimplemented!");
10268 }
10269
10270 // This function assumes its argument is a BUILD_VECTOR of constants or
10271 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
10272 // true.
10273 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
10274                                     unsigned &MaskValue) {
10275   MaskValue = 0;
10276   unsigned NumElems = BuildVector->getNumOperands();
10277   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
10278   unsigned NumLanes = (NumElems - 1) / 8 + 1;
10279   unsigned NumElemsInLane = NumElems / NumLanes;
10280
10281   // Blend for v16i16 should be symetric for the both lanes.
10282   for (unsigned i = 0; i < NumElemsInLane; ++i) {
10283     SDValue EltCond = BuildVector->getOperand(i);
10284     SDValue SndLaneEltCond =
10285         (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
10286
10287     int Lane1Cond = -1, Lane2Cond = -1;
10288     if (isa<ConstantSDNode>(EltCond))
10289       Lane1Cond = !isZero(EltCond);
10290     if (isa<ConstantSDNode>(SndLaneEltCond))
10291       Lane2Cond = !isZero(SndLaneEltCond);
10292
10293     if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
10294       // Lane1Cond != 0, means we want the first argument.
10295       // Lane1Cond == 0, means we want the second argument.
10296       // The encoding of this argument is 0 for the first argument, 1
10297       // for the second. Therefore, invert the condition.
10298       MaskValue |= !Lane1Cond << i;
10299     else if (Lane1Cond < 0)
10300       MaskValue |= !Lane2Cond << i;
10301     else
10302       return false;
10303   }
10304   return true;
10305 }
10306
10307 /// \brief Try to lower a VSELECT instruction to a vector shuffle.
10308 static SDValue lowerVSELECTtoVectorShuffle(SDValue Op,
10309                                            const X86Subtarget *Subtarget,
10310                                            SelectionDAG &DAG) {
10311   SDValue Cond = Op.getOperand(0);
10312   SDValue LHS = Op.getOperand(1);
10313   SDValue RHS = Op.getOperand(2);
10314   SDLoc dl(Op);
10315   MVT VT = Op.getSimpleValueType();
10316
10317   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
10318     return SDValue();
10319   auto *CondBV = cast<BuildVectorSDNode>(Cond);
10320
10321   // Only non-legal VSELECTs reach this lowering, convert those into generic
10322   // shuffles and re-use the shuffle lowering path for blends.
10323   SmallVector<int, 32> Mask;
10324   for (int i = 0, Size = VT.getVectorNumElements(); i < Size; ++i) {
10325     SDValue CondElt = CondBV->getOperand(i);
10326     Mask.push_back(
10327         isa<ConstantSDNode>(CondElt) ? i + (isZero(CondElt) ? Size : 0) : -1);
10328   }
10329   return DAG.getVectorShuffle(VT, dl, LHS, RHS, Mask);
10330 }
10331
10332 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
10333   // A vselect where all conditions and data are constants can be optimized into
10334   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
10335   if (ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(0).getNode()) &&
10336       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(1).getNode()) &&
10337       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(2).getNode()))
10338     return SDValue();
10339
10340   // Try to lower this to a blend-style vector shuffle. This can handle all
10341   // constant condition cases.
10342   if (SDValue BlendOp = lowerVSELECTtoVectorShuffle(Op, Subtarget, DAG))
10343     return BlendOp;
10344
10345   // Variable blends are only legal from SSE4.1 onward.
10346   if (!Subtarget->hasSSE41())
10347     return SDValue();
10348
10349   // Only some types will be legal on some subtargets. If we can emit a legal
10350   // VSELECT-matching blend, return Op, and but if we need to expand, return
10351   // a null value.
10352   switch (Op.getSimpleValueType().SimpleTy) {
10353   default:
10354     // Most of the vector types have blends past SSE4.1.
10355     return Op;
10356
10357   case MVT::v32i8:
10358     // The byte blends for AVX vectors were introduced only in AVX2.
10359     if (Subtarget->hasAVX2())
10360       return Op;
10361
10362     return SDValue();
10363
10364   case MVT::v8i16:
10365   case MVT::v16i16:
10366     // AVX-512 BWI and VLX features support VSELECT with i16 elements.
10367     if (Subtarget->hasBWI() && Subtarget->hasVLX())
10368       return Op;
10369
10370     // FIXME: We should custom lower this by fixing the condition and using i8
10371     // blends.
10372     return SDValue();
10373   }
10374 }
10375
10376 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
10377   MVT VT = Op.getSimpleValueType();
10378   SDLoc dl(Op);
10379
10380   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
10381     return SDValue();
10382
10383   if (VT.getSizeInBits() == 8) {
10384     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
10385                                   Op.getOperand(0), Op.getOperand(1));
10386     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10387                                   DAG.getValueType(VT));
10388     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10389   }
10390
10391   if (VT.getSizeInBits() == 16) {
10392     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10393     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
10394     if (Idx == 0)
10395       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
10396                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10397                                      DAG.getNode(ISD::BITCAST, dl,
10398                                                  MVT::v4i32,
10399                                                  Op.getOperand(0)),
10400                                      Op.getOperand(1)));
10401     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
10402                                   Op.getOperand(0), Op.getOperand(1));
10403     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10404                                   DAG.getValueType(VT));
10405     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10406   }
10407
10408   if (VT == MVT::f32) {
10409     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
10410     // the result back to FR32 register. It's only worth matching if the
10411     // result has a single use which is a store or a bitcast to i32.  And in
10412     // the case of a store, it's not worth it if the index is a constant 0,
10413     // because a MOVSSmr can be used instead, which is smaller and faster.
10414     if (!Op.hasOneUse())
10415       return SDValue();
10416     SDNode *User = *Op.getNode()->use_begin();
10417     if ((User->getOpcode() != ISD::STORE ||
10418          (isa<ConstantSDNode>(Op.getOperand(1)) &&
10419           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
10420         (User->getOpcode() != ISD::BITCAST ||
10421          User->getValueType(0) != MVT::i32))
10422       return SDValue();
10423     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10424                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
10425                                               Op.getOperand(0)),
10426                                               Op.getOperand(1));
10427     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
10428   }
10429
10430   if (VT == MVT::i32 || VT == MVT::i64) {
10431     // ExtractPS/pextrq works with constant index.
10432     if (isa<ConstantSDNode>(Op.getOperand(1)))
10433       return Op;
10434   }
10435   return SDValue();
10436 }
10437
10438 /// Extract one bit from mask vector, like v16i1 or v8i1.
10439 /// AVX-512 feature.
10440 SDValue
10441 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
10442   SDValue Vec = Op.getOperand(0);
10443   SDLoc dl(Vec);
10444   MVT VecVT = Vec.getSimpleValueType();
10445   SDValue Idx = Op.getOperand(1);
10446   MVT EltVT = Op.getSimpleValueType();
10447
10448   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
10449   assert((VecVT.getVectorNumElements() <= 16 || Subtarget->hasBWI()) &&
10450          "Unexpected vector type in ExtractBitFromMaskVector");
10451
10452   // variable index can't be handled in mask registers,
10453   // extend vector to VR512
10454   if (!isa<ConstantSDNode>(Idx)) {
10455     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
10456     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
10457     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
10458                               ExtVT.getVectorElementType(), Ext, Idx);
10459     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
10460   }
10461
10462   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10463   const TargetRegisterClass* rc = getRegClassFor(VecVT);
10464   if (!Subtarget->hasDQI() && (VecVT.getVectorNumElements() <= 8))
10465     rc = getRegClassFor(MVT::v16i1);
10466   unsigned MaxSift = rc->getSize()*8 - 1;
10467   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
10468                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
10469   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
10470                     DAG.getConstant(MaxSift, MVT::i8));
10471   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
10472                        DAG.getIntPtrConstant(0));
10473 }
10474
10475 SDValue
10476 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
10477                                            SelectionDAG &DAG) const {
10478   SDLoc dl(Op);
10479   SDValue Vec = Op.getOperand(0);
10480   MVT VecVT = Vec.getSimpleValueType();
10481   SDValue Idx = Op.getOperand(1);
10482
10483   if (Op.getSimpleValueType() == MVT::i1)
10484     return ExtractBitFromMaskVector(Op, DAG);
10485
10486   if (!isa<ConstantSDNode>(Idx)) {
10487     if (VecVT.is512BitVector() ||
10488         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
10489          VecVT.getVectorElementType().getSizeInBits() == 32)) {
10490
10491       MVT MaskEltVT =
10492         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
10493       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
10494                                     MaskEltVT.getSizeInBits());
10495
10496       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
10497       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
10498                                 getZeroVector(MaskVT, Subtarget, DAG, dl),
10499                                 Idx, DAG.getConstant(0, getPointerTy()));
10500       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
10501       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
10502                         Perm, DAG.getConstant(0, getPointerTy()));
10503     }
10504     return SDValue();
10505   }
10506
10507   // If this is a 256-bit vector result, first extract the 128-bit vector and
10508   // then extract the element from the 128-bit vector.
10509   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
10510
10511     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10512     // Get the 128-bit vector.
10513     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
10514     MVT EltVT = VecVT.getVectorElementType();
10515
10516     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
10517
10518     //if (IdxVal >= NumElems/2)
10519     //  IdxVal -= NumElems/2;
10520     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
10521     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
10522                        DAG.getConstant(IdxVal, MVT::i32));
10523   }
10524
10525   assert(VecVT.is128BitVector() && "Unexpected vector length");
10526
10527   if (Subtarget->hasSSE41()) {
10528     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
10529     if (Res.getNode())
10530       return Res;
10531   }
10532
10533   MVT VT = Op.getSimpleValueType();
10534   // TODO: handle v16i8.
10535   if (VT.getSizeInBits() == 16) {
10536     SDValue Vec = Op.getOperand(0);
10537     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10538     if (Idx == 0)
10539       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
10540                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10541                                      DAG.getNode(ISD::BITCAST, dl,
10542                                                  MVT::v4i32, Vec),
10543                                      Op.getOperand(1)));
10544     // Transform it so it match pextrw which produces a 32-bit result.
10545     MVT EltVT = MVT::i32;
10546     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
10547                                   Op.getOperand(0), Op.getOperand(1));
10548     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
10549                                   DAG.getValueType(VT));
10550     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10551   }
10552
10553   if (VT.getSizeInBits() == 32) {
10554     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10555     if (Idx == 0)
10556       return Op;
10557
10558     // SHUFPS the element to the lowest double word, then movss.
10559     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
10560     MVT VVT = Op.getOperand(0).getSimpleValueType();
10561     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10562                                        DAG.getUNDEF(VVT), Mask);
10563     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10564                        DAG.getIntPtrConstant(0));
10565   }
10566
10567   if (VT.getSizeInBits() == 64) {
10568     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
10569     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
10570     //        to match extract_elt for f64.
10571     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10572     if (Idx == 0)
10573       return Op;
10574
10575     // UNPCKHPD the element to the lowest double word, then movsd.
10576     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
10577     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
10578     int Mask[2] = { 1, -1 };
10579     MVT VVT = Op.getOperand(0).getSimpleValueType();
10580     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10581                                        DAG.getUNDEF(VVT), Mask);
10582     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10583                        DAG.getIntPtrConstant(0));
10584   }
10585
10586   return SDValue();
10587 }
10588
10589 /// Insert one bit to mask vector, like v16i1 or v8i1.
10590 /// AVX-512 feature.
10591 SDValue
10592 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
10593   SDLoc dl(Op);
10594   SDValue Vec = Op.getOperand(0);
10595   SDValue Elt = Op.getOperand(1);
10596   SDValue Idx = Op.getOperand(2);
10597   MVT VecVT = Vec.getSimpleValueType();
10598
10599   if (!isa<ConstantSDNode>(Idx)) {
10600     // Non constant index. Extend source and destination,
10601     // insert element and then truncate the result.
10602     MVT ExtVecVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
10603     MVT ExtEltVT = (VecVT == MVT::v8i1 ?  MVT::i64 : MVT::i32);
10604     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
10605       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
10606       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
10607     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
10608   }
10609
10610   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10611   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
10612   if (Vec.getOpcode() == ISD::UNDEF)
10613     return DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
10614                        DAG.getConstant(IdxVal, MVT::i8));
10615   const TargetRegisterClass* rc = getRegClassFor(VecVT);
10616   unsigned MaxSift = rc->getSize()*8 - 1;
10617   EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
10618                     DAG.getConstant(MaxSift, MVT::i8));
10619   EltInVec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, EltInVec,
10620                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
10621   return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
10622 }
10623
10624 SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
10625                                                   SelectionDAG &DAG) const {
10626   MVT VT = Op.getSimpleValueType();
10627   MVT EltVT = VT.getVectorElementType();
10628
10629   if (EltVT == MVT::i1)
10630     return InsertBitToMaskVector(Op, DAG);
10631
10632   SDLoc dl(Op);
10633   SDValue N0 = Op.getOperand(0);
10634   SDValue N1 = Op.getOperand(1);
10635   SDValue N2 = Op.getOperand(2);
10636   if (!isa<ConstantSDNode>(N2))
10637     return SDValue();
10638   auto *N2C = cast<ConstantSDNode>(N2);
10639   unsigned IdxVal = N2C->getZExtValue();
10640
10641   // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
10642   // into that, and then insert the subvector back into the result.
10643   if (VT.is256BitVector() || VT.is512BitVector()) {
10644     // With a 256-bit vector, we can insert into the zero element efficiently
10645     // using a blend if we have AVX or AVX2 and the right data type.
10646     if (VT.is256BitVector() && IdxVal == 0) {
10647       // TODO: It is worthwhile to cast integer to floating point and back
10648       // and incur a domain crossing penalty if that's what we'll end up
10649       // doing anyway after extracting to a 128-bit vector.
10650       if ((Subtarget->hasAVX() && (EltVT == MVT::f64 || EltVT == MVT::f32)) ||
10651           (Subtarget->hasAVX2() && EltVT == MVT::i32)) {
10652         SDValue N1Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, N1);
10653         N2 = DAG.getIntPtrConstant(1);
10654         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1Vec, N2);
10655       }
10656     }
10657
10658     // Get the desired 128-bit vector chunk.
10659     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
10660
10661     // Insert the element into the desired chunk.
10662     unsigned NumEltsIn128 = 128 / EltVT.getSizeInBits();
10663     unsigned IdxIn128 = IdxVal - (IdxVal / NumEltsIn128) * NumEltsIn128;
10664
10665     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
10666                     DAG.getConstant(IdxIn128, MVT::i32));
10667
10668     // Insert the changed part back into the bigger vector
10669     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
10670   }
10671   assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
10672
10673   if (Subtarget->hasSSE41()) {
10674     if (EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) {
10675       unsigned Opc;
10676       if (VT == MVT::v8i16) {
10677         Opc = X86ISD::PINSRW;
10678       } else {
10679         assert(VT == MVT::v16i8);
10680         Opc = X86ISD::PINSRB;
10681       }
10682
10683       // Transform it so it match pinsr{b,w} which expects a GR32 as its second
10684       // argument.
10685       if (N1.getValueType() != MVT::i32)
10686         N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
10687       if (N2.getValueType() != MVT::i32)
10688         N2 = DAG.getIntPtrConstant(IdxVal);
10689       return DAG.getNode(Opc, dl, VT, N0, N1, N2);
10690     }
10691
10692     if (EltVT == MVT::f32) {
10693       // Bits [7:6] of the constant are the source select. This will always be
10694       //   zero here. The DAG Combiner may combine an extract_elt index into
10695       //   these bits. For example (insert (extract, 3), 2) could be matched by
10696       //   putting the '3' into bits [7:6] of X86ISD::INSERTPS.
10697       // Bits [5:4] of the constant are the destination select. This is the
10698       //   value of the incoming immediate.
10699       // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
10700       //   combine either bitwise AND or insert of float 0.0 to set these bits.
10701
10702       const Function *F = DAG.getMachineFunction().getFunction();
10703       bool MinSize = F->hasFnAttribute(Attribute::MinSize);
10704       if (IdxVal == 0 && (!MinSize || !MayFoldLoad(N1))) {
10705         // If this is an insertion of 32-bits into the low 32-bits of
10706         // a vector, we prefer to generate a blend with immediate rather
10707         // than an insertps. Blends are simpler operations in hardware and so
10708         // will always have equal or better performance than insertps.
10709         // But if optimizing for size and there's a load folding opportunity,
10710         // generate insertps because blendps does not have a 32-bit memory
10711         // operand form.
10712         N2 = DAG.getIntPtrConstant(1);
10713         N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
10714         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1, N2);
10715       }
10716       N2 = DAG.getIntPtrConstant(IdxVal << 4);
10717       // Create this as a scalar to vector..
10718       N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
10719       return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
10720     }
10721
10722     if (EltVT == MVT::i32 || EltVT == MVT::i64) {
10723       // PINSR* works with constant index.
10724       return Op;
10725     }
10726   }
10727
10728   if (EltVT == MVT::i8)
10729     return SDValue();
10730
10731   if (EltVT.getSizeInBits() == 16) {
10732     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
10733     // as its second argument.
10734     if (N1.getValueType() != MVT::i32)
10735       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
10736     if (N2.getValueType() != MVT::i32)
10737       N2 = DAG.getIntPtrConstant(IdxVal);
10738     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
10739   }
10740   return SDValue();
10741 }
10742
10743 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
10744   SDLoc dl(Op);
10745   MVT OpVT = Op.getSimpleValueType();
10746
10747   // If this is a 256-bit vector result, first insert into a 128-bit
10748   // vector and then insert into the 256-bit vector.
10749   if (!OpVT.is128BitVector()) {
10750     // Insert into a 128-bit vector.
10751     unsigned SizeFactor = OpVT.getSizeInBits()/128;
10752     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
10753                                  OpVT.getVectorNumElements() / SizeFactor);
10754
10755     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
10756
10757     // Insert the 128-bit vector.
10758     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
10759   }
10760
10761   if (OpVT == MVT::v1i64 &&
10762       Op.getOperand(0).getValueType() == MVT::i64)
10763     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
10764
10765   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
10766   assert(OpVT.is128BitVector() && "Expected an SSE type!");
10767   return DAG.getNode(ISD::BITCAST, dl, OpVT,
10768                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
10769 }
10770
10771 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
10772 // a simple subregister reference or explicit instructions to grab
10773 // upper bits of a vector.
10774 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10775                                       SelectionDAG &DAG) {
10776   SDLoc dl(Op);
10777   SDValue In =  Op.getOperand(0);
10778   SDValue Idx = Op.getOperand(1);
10779   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10780   MVT ResVT   = Op.getSimpleValueType();
10781   MVT InVT    = In.getSimpleValueType();
10782
10783   if (Subtarget->hasFp256()) {
10784     if (ResVT.is128BitVector() &&
10785         (InVT.is256BitVector() || InVT.is512BitVector()) &&
10786         isa<ConstantSDNode>(Idx)) {
10787       return Extract128BitVector(In, IdxVal, DAG, dl);
10788     }
10789     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
10790         isa<ConstantSDNode>(Idx)) {
10791       return Extract256BitVector(In, IdxVal, DAG, dl);
10792     }
10793   }
10794   return SDValue();
10795 }
10796
10797 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
10798 // simple superregister reference or explicit instructions to insert
10799 // the upper bits of a vector.
10800 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10801                                      SelectionDAG &DAG) {
10802   if (!Subtarget->hasAVX())
10803     return SDValue();
10804
10805   SDLoc dl(Op);
10806   SDValue Vec = Op.getOperand(0);
10807   SDValue SubVec = Op.getOperand(1);
10808   SDValue Idx = Op.getOperand(2);
10809
10810   if (!isa<ConstantSDNode>(Idx))
10811     return SDValue();
10812
10813   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10814   MVT OpVT = Op.getSimpleValueType();
10815   MVT SubVecVT = SubVec.getSimpleValueType();
10816
10817   // Fold two 16-byte subvector loads into one 32-byte load:
10818   // (insert_subvector (insert_subvector undef, (load addr), 0),
10819   //                   (load addr + 16), Elts/2)
10820   // --> load32 addr
10821   if ((IdxVal == OpVT.getVectorNumElements() / 2) &&
10822       Vec.getOpcode() == ISD::INSERT_SUBVECTOR &&
10823       OpVT.is256BitVector() && SubVecVT.is128BitVector() &&
10824       !Subtarget->isUnalignedMem32Slow()) {
10825     SDValue SubVec2 = Vec.getOperand(1);
10826     if (auto *Idx2 = dyn_cast<ConstantSDNode>(Vec.getOperand(2))) {
10827       if (Idx2->getZExtValue() == 0) {
10828         SDValue Ops[] = { SubVec2, SubVec };
10829         SDValue LD = EltsFromConsecutiveLoads(OpVT, Ops, dl, DAG, false);
10830         if (LD.getNode())
10831           return LD;
10832       }
10833     }
10834   }
10835
10836   if ((OpVT.is256BitVector() || OpVT.is512BitVector()) &&
10837       SubVecVT.is128BitVector())
10838     return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
10839
10840   if (OpVT.is512BitVector() && SubVecVT.is256BitVector())
10841     return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
10842
10843   if (OpVT.getVectorElementType() == MVT::i1) {
10844     if (IdxVal == 0  && Vec.getOpcode() == ISD::UNDEF) // the operation is legal
10845       return Op;
10846     SDValue ZeroIdx = DAG.getIntPtrConstant(0);
10847     SDValue Undef = DAG.getUNDEF(OpVT);
10848     unsigned NumElems = OpVT.getVectorNumElements();
10849     SDValue ShiftBits = DAG.getConstant(NumElems/2, MVT::i8);
10850
10851     if (IdxVal == OpVT.getVectorNumElements() / 2) {
10852       // Zero upper bits of the Vec
10853       Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
10854       Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
10855
10856       SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
10857                                  SubVec, ZeroIdx);
10858       Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
10859       return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
10860     }
10861     if (IdxVal == 0) {
10862       SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
10863                                  SubVec, ZeroIdx);
10864       // Zero upper bits of the Vec2
10865       Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
10866       Vec2 = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec2, ShiftBits);
10867       // Zero lower bits of the Vec
10868       Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
10869       Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
10870       // Merge them together
10871       return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
10872     }
10873   }
10874   return SDValue();
10875 }
10876
10877 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
10878 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
10879 // one of the above mentioned nodes. It has to be wrapped because otherwise
10880 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
10881 // be used to form addressing mode. These wrapped nodes will be selected
10882 // into MOV32ri.
10883 SDValue
10884 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
10885   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
10886
10887   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10888   // global base reg.
10889   unsigned char OpFlag = 0;
10890   unsigned WrapperKind = X86ISD::Wrapper;
10891   CodeModel::Model M = DAG.getTarget().getCodeModel();
10892
10893   if (Subtarget->isPICStyleRIPRel() &&
10894       (M == CodeModel::Small || M == CodeModel::Kernel))
10895     WrapperKind = X86ISD::WrapperRIP;
10896   else if (Subtarget->isPICStyleGOT())
10897     OpFlag = X86II::MO_GOTOFF;
10898   else if (Subtarget->isPICStyleStubPIC())
10899     OpFlag = X86II::MO_PIC_BASE_OFFSET;
10900
10901   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
10902                                              CP->getAlignment(),
10903                                              CP->getOffset(), OpFlag);
10904   SDLoc DL(CP);
10905   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10906   // With PIC, the address is actually $g + Offset.
10907   if (OpFlag) {
10908     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10909                          DAG.getNode(X86ISD::GlobalBaseReg,
10910                                      SDLoc(), getPointerTy()),
10911                          Result);
10912   }
10913
10914   return Result;
10915 }
10916
10917 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
10918   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
10919
10920   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10921   // global base reg.
10922   unsigned char OpFlag = 0;
10923   unsigned WrapperKind = X86ISD::Wrapper;
10924   CodeModel::Model M = DAG.getTarget().getCodeModel();
10925
10926   if (Subtarget->isPICStyleRIPRel() &&
10927       (M == CodeModel::Small || M == CodeModel::Kernel))
10928     WrapperKind = X86ISD::WrapperRIP;
10929   else if (Subtarget->isPICStyleGOT())
10930     OpFlag = X86II::MO_GOTOFF;
10931   else if (Subtarget->isPICStyleStubPIC())
10932     OpFlag = X86II::MO_PIC_BASE_OFFSET;
10933
10934   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
10935                                           OpFlag);
10936   SDLoc DL(JT);
10937   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10938
10939   // With PIC, the address is actually $g + Offset.
10940   if (OpFlag)
10941     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10942                          DAG.getNode(X86ISD::GlobalBaseReg,
10943                                      SDLoc(), getPointerTy()),
10944                          Result);
10945
10946   return Result;
10947 }
10948
10949 SDValue
10950 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
10951   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
10952
10953   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10954   // global base reg.
10955   unsigned char OpFlag = 0;
10956   unsigned WrapperKind = X86ISD::Wrapper;
10957   CodeModel::Model M = DAG.getTarget().getCodeModel();
10958
10959   if (Subtarget->isPICStyleRIPRel() &&
10960       (M == CodeModel::Small || M == CodeModel::Kernel)) {
10961     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
10962       OpFlag = X86II::MO_GOTPCREL;
10963     WrapperKind = X86ISD::WrapperRIP;
10964   } else if (Subtarget->isPICStyleGOT()) {
10965     OpFlag = X86II::MO_GOT;
10966   } else if (Subtarget->isPICStyleStubPIC()) {
10967     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
10968   } else if (Subtarget->isPICStyleStubNoDynamic()) {
10969     OpFlag = X86II::MO_DARWIN_NONLAZY;
10970   }
10971
10972   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
10973
10974   SDLoc DL(Op);
10975   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10976
10977   // With PIC, the address is actually $g + Offset.
10978   if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
10979       !Subtarget->is64Bit()) {
10980     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10981                          DAG.getNode(X86ISD::GlobalBaseReg,
10982                                      SDLoc(), getPointerTy()),
10983                          Result);
10984   }
10985
10986   // For symbols that require a load from a stub to get the address, emit the
10987   // load.
10988   if (isGlobalStubReference(OpFlag))
10989     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
10990                          MachinePointerInfo::getGOT(), false, false, false, 0);
10991
10992   return Result;
10993 }
10994
10995 SDValue
10996 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
10997   // Create the TargetBlockAddressAddress node.
10998   unsigned char OpFlags =
10999     Subtarget->ClassifyBlockAddressReference();
11000   CodeModel::Model M = DAG.getTarget().getCodeModel();
11001   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
11002   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
11003   SDLoc dl(Op);
11004   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
11005                                              OpFlags);
11006
11007   if (Subtarget->isPICStyleRIPRel() &&
11008       (M == CodeModel::Small || M == CodeModel::Kernel))
11009     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
11010   else
11011     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
11012
11013   // With PIC, the address is actually $g + Offset.
11014   if (isGlobalRelativeToPICBase(OpFlags)) {
11015     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
11016                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
11017                          Result);
11018   }
11019
11020   return Result;
11021 }
11022
11023 SDValue
11024 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
11025                                       int64_t Offset, SelectionDAG &DAG) const {
11026   // Create the TargetGlobalAddress node, folding in the constant
11027   // offset if it is legal.
11028   unsigned char OpFlags =
11029       Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
11030   CodeModel::Model M = DAG.getTarget().getCodeModel();
11031   SDValue Result;
11032   if (OpFlags == X86II::MO_NO_FLAG &&
11033       X86::isOffsetSuitableForCodeModel(Offset, M)) {
11034     // A direct static reference to a global.
11035     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
11036     Offset = 0;
11037   } else {
11038     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
11039   }
11040
11041   if (Subtarget->isPICStyleRIPRel() &&
11042       (M == CodeModel::Small || M == CodeModel::Kernel))
11043     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
11044   else
11045     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
11046
11047   // With PIC, the address is actually $g + Offset.
11048   if (isGlobalRelativeToPICBase(OpFlags)) {
11049     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
11050                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
11051                          Result);
11052   }
11053
11054   // For globals that require a load from a stub to get the address, emit the
11055   // load.
11056   if (isGlobalStubReference(OpFlags))
11057     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
11058                          MachinePointerInfo::getGOT(), false, false, false, 0);
11059
11060   // If there was a non-zero offset that we didn't fold, create an explicit
11061   // addition for it.
11062   if (Offset != 0)
11063     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
11064                          DAG.getConstant(Offset, getPointerTy()));
11065
11066   return Result;
11067 }
11068
11069 SDValue
11070 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
11071   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
11072   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
11073   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
11074 }
11075
11076 static SDValue
11077 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
11078            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
11079            unsigned char OperandFlags, bool LocalDynamic = false) {
11080   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11081   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11082   SDLoc dl(GA);
11083   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11084                                            GA->getValueType(0),
11085                                            GA->getOffset(),
11086                                            OperandFlags);
11087
11088   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
11089                                            : X86ISD::TLSADDR;
11090
11091   if (InFlag) {
11092     SDValue Ops[] = { Chain,  TGA, *InFlag };
11093     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11094   } else {
11095     SDValue Ops[]  = { Chain, TGA };
11096     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11097   }
11098
11099   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
11100   MFI->setAdjustsStack(true);
11101   MFI->setHasCalls(true);
11102
11103   SDValue Flag = Chain.getValue(1);
11104   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
11105 }
11106
11107 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
11108 static SDValue
11109 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11110                                 const EVT PtrVT) {
11111   SDValue InFlag;
11112   SDLoc dl(GA);  // ? function entry point might be better
11113   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11114                                    DAG.getNode(X86ISD::GlobalBaseReg,
11115                                                SDLoc(), PtrVT), InFlag);
11116   InFlag = Chain.getValue(1);
11117
11118   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
11119 }
11120
11121 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
11122 static SDValue
11123 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11124                                 const EVT PtrVT) {
11125   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
11126                     X86::RAX, X86II::MO_TLSGD);
11127 }
11128
11129 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
11130                                            SelectionDAG &DAG,
11131                                            const EVT PtrVT,
11132                                            bool is64Bit) {
11133   SDLoc dl(GA);
11134
11135   // Get the start address of the TLS block for this module.
11136   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
11137       .getInfo<X86MachineFunctionInfo>();
11138   MFI->incNumLocalDynamicTLSAccesses();
11139
11140   SDValue Base;
11141   if (is64Bit) {
11142     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
11143                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
11144   } else {
11145     SDValue InFlag;
11146     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11147         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
11148     InFlag = Chain.getValue(1);
11149     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
11150                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
11151   }
11152
11153   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
11154   // of Base.
11155
11156   // Build x@dtpoff.
11157   unsigned char OperandFlags = X86II::MO_DTPOFF;
11158   unsigned WrapperKind = X86ISD::Wrapper;
11159   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11160                                            GA->getValueType(0),
11161                                            GA->getOffset(), OperandFlags);
11162   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11163
11164   // Add x@dtpoff with the base.
11165   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
11166 }
11167
11168 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
11169 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11170                                    const EVT PtrVT, TLSModel::Model model,
11171                                    bool is64Bit, bool isPIC) {
11172   SDLoc dl(GA);
11173
11174   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
11175   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
11176                                                          is64Bit ? 257 : 256));
11177
11178   SDValue ThreadPointer =
11179       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
11180                   MachinePointerInfo(Ptr), false, false, false, 0);
11181
11182   unsigned char OperandFlags = 0;
11183   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
11184   // initialexec.
11185   unsigned WrapperKind = X86ISD::Wrapper;
11186   if (model == TLSModel::LocalExec) {
11187     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
11188   } else if (model == TLSModel::InitialExec) {
11189     if (is64Bit) {
11190       OperandFlags = X86II::MO_GOTTPOFF;
11191       WrapperKind = X86ISD::WrapperRIP;
11192     } else {
11193       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
11194     }
11195   } else {
11196     llvm_unreachable("Unexpected model");
11197   }
11198
11199   // emit "addl x@ntpoff,%eax" (local exec)
11200   // or "addl x@indntpoff,%eax" (initial exec)
11201   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
11202   SDValue TGA =
11203       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
11204                                  GA->getOffset(), OperandFlags);
11205   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11206
11207   if (model == TLSModel::InitialExec) {
11208     if (isPIC && !is64Bit) {
11209       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
11210                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
11211                            Offset);
11212     }
11213
11214     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
11215                          MachinePointerInfo::getGOT(), false, false, false, 0);
11216   }
11217
11218   // The address of the thread local variable is the add of the thread
11219   // pointer with the offset of the variable.
11220   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
11221 }
11222
11223 SDValue
11224 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
11225
11226   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
11227   const GlobalValue *GV = GA->getGlobal();
11228
11229   if (Subtarget->isTargetELF()) {
11230     TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
11231
11232     switch (model) {
11233       case TLSModel::GeneralDynamic:
11234         if (Subtarget->is64Bit())
11235           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
11236         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
11237       case TLSModel::LocalDynamic:
11238         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
11239                                            Subtarget->is64Bit());
11240       case TLSModel::InitialExec:
11241       case TLSModel::LocalExec:
11242         return LowerToTLSExecModel(
11243             GA, DAG, getPointerTy(), model, Subtarget->is64Bit(),
11244             DAG.getTarget().getRelocationModel() == Reloc::PIC_);
11245     }
11246     llvm_unreachable("Unknown TLS model.");
11247   }
11248
11249   if (Subtarget->isTargetDarwin()) {
11250     // Darwin only has one model of TLS.  Lower to that.
11251     unsigned char OpFlag = 0;
11252     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
11253                            X86ISD::WrapperRIP : X86ISD::Wrapper;
11254
11255     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11256     // global base reg.
11257     bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
11258                  !Subtarget->is64Bit();
11259     if (PIC32)
11260       OpFlag = X86II::MO_TLVP_PIC_BASE;
11261     else
11262       OpFlag = X86II::MO_TLVP;
11263     SDLoc DL(Op);
11264     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
11265                                                 GA->getValueType(0),
11266                                                 GA->getOffset(), OpFlag);
11267     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
11268
11269     // With PIC32, the address is actually $g + Offset.
11270     if (PIC32)
11271       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11272                            DAG.getNode(X86ISD::GlobalBaseReg,
11273                                        SDLoc(), getPointerTy()),
11274                            Offset);
11275
11276     // Lowering the machine isd will make sure everything is in the right
11277     // location.
11278     SDValue Chain = DAG.getEntryNode();
11279     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11280     SDValue Args[] = { Chain, Offset };
11281     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
11282
11283     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
11284     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11285     MFI->setAdjustsStack(true);
11286
11287     // And our return value (tls address) is in the standard call return value
11288     // location.
11289     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11290     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
11291                               Chain.getValue(1));
11292   }
11293
11294   if (Subtarget->isTargetKnownWindowsMSVC() ||
11295       Subtarget->isTargetWindowsGNU()) {
11296     // Just use the implicit TLS architecture
11297     // Need to generate someting similar to:
11298     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
11299     //                                  ; from TEB
11300     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
11301     //   mov     rcx, qword [rdx+rcx*8]
11302     //   mov     eax, .tls$:tlsvar
11303     //   [rax+rcx] contains the address
11304     // Windows 64bit: gs:0x58
11305     // Windows 32bit: fs:__tls_array
11306
11307     SDLoc dl(GA);
11308     SDValue Chain = DAG.getEntryNode();
11309
11310     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
11311     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
11312     // use its literal value of 0x2C.
11313     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
11314                                         ? Type::getInt8PtrTy(*DAG.getContext(),
11315                                                              256)
11316                                         : Type::getInt32PtrTy(*DAG.getContext(),
11317                                                               257));
11318
11319     SDValue TlsArray =
11320         Subtarget->is64Bit()
11321             ? DAG.getIntPtrConstant(0x58)
11322             : (Subtarget->isTargetWindowsGNU()
11323                    ? DAG.getIntPtrConstant(0x2C)
11324                    : DAG.getExternalSymbol("_tls_array", getPointerTy()));
11325
11326     SDValue ThreadPointer =
11327         DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
11328                     MachinePointerInfo(Ptr), false, false, false, 0);
11329
11330     // Load the _tls_index variable
11331     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
11332     if (Subtarget->is64Bit())
11333       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
11334                            IDX, MachinePointerInfo(), MVT::i32,
11335                            false, false, false, 0);
11336     else
11337       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
11338                         false, false, false, 0);
11339
11340     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
11341                                     getPointerTy());
11342     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
11343
11344     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
11345     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
11346                       false, false, false, 0);
11347
11348     // Get the offset of start of .tls section
11349     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11350                                              GA->getValueType(0),
11351                                              GA->getOffset(), X86II::MO_SECREL);
11352     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
11353
11354     // The address of the thread local variable is the add of the thread
11355     // pointer with the offset of the variable.
11356     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
11357   }
11358
11359   llvm_unreachable("TLS not implemented for this target.");
11360 }
11361
11362 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
11363 /// and take a 2 x i32 value to shift plus a shift amount.
11364 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
11365   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
11366   MVT VT = Op.getSimpleValueType();
11367   unsigned VTBits = VT.getSizeInBits();
11368   SDLoc dl(Op);
11369   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
11370   SDValue ShOpLo = Op.getOperand(0);
11371   SDValue ShOpHi = Op.getOperand(1);
11372   SDValue ShAmt  = Op.getOperand(2);
11373   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
11374   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
11375   // during isel.
11376   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11377                                   DAG.getConstant(VTBits - 1, MVT::i8));
11378   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
11379                                      DAG.getConstant(VTBits - 1, MVT::i8))
11380                        : DAG.getConstant(0, VT);
11381
11382   SDValue Tmp2, Tmp3;
11383   if (Op.getOpcode() == ISD::SHL_PARTS) {
11384     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
11385     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
11386   } else {
11387     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
11388     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
11389   }
11390
11391   // If the shift amount is larger or equal than the width of a part we can't
11392   // rely on the results of shld/shrd. Insert a test and select the appropriate
11393   // values for large shift amounts.
11394   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11395                                 DAG.getConstant(VTBits, MVT::i8));
11396   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11397                              AndNode, DAG.getConstant(0, MVT::i8));
11398
11399   SDValue Hi, Lo;
11400   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11401   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
11402   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
11403
11404   if (Op.getOpcode() == ISD::SHL_PARTS) {
11405     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11406     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11407   } else {
11408     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11409     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11410   }
11411
11412   SDValue Ops[2] = { Lo, Hi };
11413   return DAG.getMergeValues(Ops, dl);
11414 }
11415
11416 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
11417                                            SelectionDAG &DAG) const {
11418   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
11419   SDLoc dl(Op);
11420
11421   if (SrcVT.isVector()) {
11422     if (SrcVT.getVectorElementType() == MVT::i1) {
11423       MVT IntegerVT = MVT::getVectorVT(MVT::i32, SrcVT.getVectorNumElements());
11424       return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
11425                          DAG.getNode(ISD::SIGN_EXTEND, dl, IntegerVT,
11426                                      Op.getOperand(0)));
11427     }
11428     return SDValue();
11429   }
11430
11431   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
11432          "Unknown SINT_TO_FP to lower!");
11433
11434   // These are really Legal; return the operand so the caller accepts it as
11435   // Legal.
11436   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
11437     return Op;
11438   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
11439       Subtarget->is64Bit()) {
11440     return Op;
11441   }
11442
11443   unsigned Size = SrcVT.getSizeInBits()/8;
11444   MachineFunction &MF = DAG.getMachineFunction();
11445   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
11446   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11447   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11448                                StackSlot,
11449                                MachinePointerInfo::getFixedStack(SSFI),
11450                                false, false, 0);
11451   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
11452 }
11453
11454 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
11455                                      SDValue StackSlot,
11456                                      SelectionDAG &DAG) const {
11457   // Build the FILD
11458   SDLoc DL(Op);
11459   SDVTList Tys;
11460   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
11461   if (useSSE)
11462     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
11463   else
11464     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
11465
11466   unsigned ByteSize = SrcVT.getSizeInBits()/8;
11467
11468   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
11469   MachineMemOperand *MMO;
11470   if (FI) {
11471     int SSFI = FI->getIndex();
11472     MMO =
11473       DAG.getMachineFunction()
11474       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11475                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
11476   } else {
11477     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
11478     StackSlot = StackSlot.getOperand(1);
11479   }
11480   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
11481   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
11482                                            X86ISD::FILD, DL,
11483                                            Tys, Ops, SrcVT, MMO);
11484
11485   if (useSSE) {
11486     Chain = Result.getValue(1);
11487     SDValue InFlag = Result.getValue(2);
11488
11489     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
11490     // shouldn't be necessary except that RFP cannot be live across
11491     // multiple blocks. When stackifier is fixed, they can be uncoupled.
11492     MachineFunction &MF = DAG.getMachineFunction();
11493     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
11494     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
11495     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11496     Tys = DAG.getVTList(MVT::Other);
11497     SDValue Ops[] = {
11498       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
11499     };
11500     MachineMemOperand *MMO =
11501       DAG.getMachineFunction()
11502       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11503                             MachineMemOperand::MOStore, SSFISize, SSFISize);
11504
11505     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
11506                                     Ops, Op.getValueType(), MMO);
11507     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
11508                          MachinePointerInfo::getFixedStack(SSFI),
11509                          false, false, false, 0);
11510   }
11511
11512   return Result;
11513 }
11514
11515 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
11516 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
11517                                                SelectionDAG &DAG) const {
11518   // This algorithm is not obvious. Here it is what we're trying to output:
11519   /*
11520      movq       %rax,  %xmm0
11521      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
11522      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
11523      #ifdef __SSE3__
11524        haddpd   %xmm0, %xmm0
11525      #else
11526        pshufd   $0x4e, %xmm0, %xmm1
11527        addpd    %xmm1, %xmm0
11528      #endif
11529   */
11530
11531   SDLoc dl(Op);
11532   LLVMContext *Context = DAG.getContext();
11533
11534   // Build some magic constants.
11535   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
11536   Constant *C0 = ConstantDataVector::get(*Context, CV0);
11537   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
11538
11539   SmallVector<Constant*,2> CV1;
11540   CV1.push_back(
11541     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11542                                       APInt(64, 0x4330000000000000ULL))));
11543   CV1.push_back(
11544     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11545                                       APInt(64, 0x4530000000000000ULL))));
11546   Constant *C1 = ConstantVector::get(CV1);
11547   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
11548
11549   // Load the 64-bit value into an XMM register.
11550   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
11551                             Op.getOperand(0));
11552   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
11553                               MachinePointerInfo::getConstantPool(),
11554                               false, false, false, 16);
11555   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
11556                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
11557                               CLod0);
11558
11559   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
11560                               MachinePointerInfo::getConstantPool(),
11561                               false, false, false, 16);
11562   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
11563   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
11564   SDValue Result;
11565
11566   if (Subtarget->hasSSE3()) {
11567     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
11568     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
11569   } else {
11570     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
11571     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
11572                                            S2F, 0x4E, DAG);
11573     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
11574                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
11575                          Sub);
11576   }
11577
11578   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
11579                      DAG.getIntPtrConstant(0));
11580 }
11581
11582 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
11583 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
11584                                                SelectionDAG &DAG) const {
11585   SDLoc dl(Op);
11586   // FP constant to bias correct the final result.
11587   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
11588                                    MVT::f64);
11589
11590   // Load the 32-bit value into an XMM register.
11591   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
11592                              Op.getOperand(0));
11593
11594   // Zero out the upper parts of the register.
11595   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
11596
11597   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11598                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
11599                      DAG.getIntPtrConstant(0));
11600
11601   // Or the load with the bias.
11602   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
11603                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
11604                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
11605                                                    MVT::v2f64, Load)),
11606                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
11607                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
11608                                                    MVT::v2f64, Bias)));
11609   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11610                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
11611                    DAG.getIntPtrConstant(0));
11612
11613   // Subtract the bias.
11614   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
11615
11616   // Handle final rounding.
11617   EVT DestVT = Op.getValueType();
11618
11619   if (DestVT.bitsLT(MVT::f64))
11620     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
11621                        DAG.getIntPtrConstant(0));
11622   if (DestVT.bitsGT(MVT::f64))
11623     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
11624
11625   // Handle final rounding.
11626   return Sub;
11627 }
11628
11629 static SDValue lowerUINT_TO_FP_vXi32(SDValue Op, SelectionDAG &DAG,
11630                                      const X86Subtarget &Subtarget) {
11631   // The algorithm is the following:
11632   // #ifdef __SSE4_1__
11633   //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
11634   //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
11635   //                                 (uint4) 0x53000000, 0xaa);
11636   // #else
11637   //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
11638   //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
11639   // #endif
11640   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
11641   //     return (float4) lo + fhi;
11642
11643   SDLoc DL(Op);
11644   SDValue V = Op->getOperand(0);
11645   EVT VecIntVT = V.getValueType();
11646   bool Is128 = VecIntVT == MVT::v4i32;
11647   EVT VecFloatVT = Is128 ? MVT::v4f32 : MVT::v8f32;
11648   // If we convert to something else than the supported type, e.g., to v4f64,
11649   // abort early.
11650   if (VecFloatVT != Op->getValueType(0))
11651     return SDValue();
11652
11653   unsigned NumElts = VecIntVT.getVectorNumElements();
11654   assert((VecIntVT == MVT::v4i32 || VecIntVT == MVT::v8i32) &&
11655          "Unsupported custom type");
11656   assert(NumElts <= 8 && "The size of the constant array must be fixed");
11657
11658   // In the #idef/#else code, we have in common:
11659   // - The vector of constants:
11660   // -- 0x4b000000
11661   // -- 0x53000000
11662   // - A shift:
11663   // -- v >> 16
11664
11665   // Create the splat vector for 0x4b000000.
11666   SDValue CstLow = DAG.getConstant(0x4b000000, MVT::i32);
11667   SDValue CstLowArray[] = {CstLow, CstLow, CstLow, CstLow,
11668                            CstLow, CstLow, CstLow, CstLow};
11669   SDValue VecCstLow = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
11670                                   makeArrayRef(&CstLowArray[0], NumElts));
11671   // Create the splat vector for 0x53000000.
11672   SDValue CstHigh = DAG.getConstant(0x53000000, MVT::i32);
11673   SDValue CstHighArray[] = {CstHigh, CstHigh, CstHigh, CstHigh,
11674                             CstHigh, CstHigh, CstHigh, CstHigh};
11675   SDValue VecCstHigh = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
11676                                    makeArrayRef(&CstHighArray[0], NumElts));
11677
11678   // Create the right shift.
11679   SDValue CstShift = DAG.getConstant(16, MVT::i32);
11680   SDValue CstShiftArray[] = {CstShift, CstShift, CstShift, CstShift,
11681                              CstShift, CstShift, CstShift, CstShift};
11682   SDValue VecCstShift = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
11683                                     makeArrayRef(&CstShiftArray[0], NumElts));
11684   SDValue HighShift = DAG.getNode(ISD::SRL, DL, VecIntVT, V, VecCstShift);
11685
11686   SDValue Low, High;
11687   if (Subtarget.hasSSE41()) {
11688     EVT VecI16VT = Is128 ? MVT::v8i16 : MVT::v16i16;
11689     //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
11690     SDValue VecCstLowBitcast =
11691         DAG.getNode(ISD::BITCAST, DL, VecI16VT, VecCstLow);
11692     SDValue VecBitcast = DAG.getNode(ISD::BITCAST, DL, VecI16VT, V);
11693     // Low will be bitcasted right away, so do not bother bitcasting back to its
11694     // original type.
11695     Low = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecBitcast,
11696                       VecCstLowBitcast, DAG.getConstant(0xaa, MVT::i32));
11697     //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
11698     //                                 (uint4) 0x53000000, 0xaa);
11699     SDValue VecCstHighBitcast =
11700         DAG.getNode(ISD::BITCAST, DL, VecI16VT, VecCstHigh);
11701     SDValue VecShiftBitcast =
11702         DAG.getNode(ISD::BITCAST, DL, VecI16VT, HighShift);
11703     // High will be bitcasted right away, so do not bother bitcasting back to
11704     // its original type.
11705     High = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecShiftBitcast,
11706                        VecCstHighBitcast, DAG.getConstant(0xaa, MVT::i32));
11707   } else {
11708     SDValue CstMask = DAG.getConstant(0xffff, MVT::i32);
11709     SDValue VecCstMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT, CstMask,
11710                                      CstMask, CstMask, CstMask);
11711     //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
11712     SDValue LowAnd = DAG.getNode(ISD::AND, DL, VecIntVT, V, VecCstMask);
11713     Low = DAG.getNode(ISD::OR, DL, VecIntVT, LowAnd, VecCstLow);
11714
11715     //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
11716     High = DAG.getNode(ISD::OR, DL, VecIntVT, HighShift, VecCstHigh);
11717   }
11718
11719   // Create the vector constant for -(0x1.0p39f + 0x1.0p23f).
11720   SDValue CstFAdd = DAG.getConstantFP(
11721       APFloat(APFloat::IEEEsingle, APInt(32, 0xD3000080)), MVT::f32);
11722   SDValue CstFAddArray[] = {CstFAdd, CstFAdd, CstFAdd, CstFAdd,
11723                             CstFAdd, CstFAdd, CstFAdd, CstFAdd};
11724   SDValue VecCstFAdd = DAG.getNode(ISD::BUILD_VECTOR, DL, VecFloatVT,
11725                                    makeArrayRef(&CstFAddArray[0], NumElts));
11726
11727   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
11728   SDValue HighBitcast = DAG.getNode(ISD::BITCAST, DL, VecFloatVT, High);
11729   SDValue FHigh =
11730       DAG.getNode(ISD::FADD, DL, VecFloatVT, HighBitcast, VecCstFAdd);
11731   //     return (float4) lo + fhi;
11732   SDValue LowBitcast = DAG.getNode(ISD::BITCAST, DL, VecFloatVT, Low);
11733   return DAG.getNode(ISD::FADD, DL, VecFloatVT, LowBitcast, FHigh);
11734 }
11735
11736 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
11737                                                SelectionDAG &DAG) const {
11738   SDValue N0 = Op.getOperand(0);
11739   MVT SVT = N0.getSimpleValueType();
11740   SDLoc dl(Op);
11741
11742   switch (SVT.SimpleTy) {
11743   default:
11744     llvm_unreachable("Custom UINT_TO_FP is not supported!");
11745   case MVT::v4i8:
11746   case MVT::v4i16:
11747   case MVT::v8i8:
11748   case MVT::v8i16: {
11749     MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
11750     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
11751                        DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
11752   }
11753   case MVT::v4i32:
11754   case MVT::v8i32:
11755     return lowerUINT_TO_FP_vXi32(Op, DAG, *Subtarget);
11756   }
11757   llvm_unreachable(nullptr);
11758 }
11759
11760 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
11761                                            SelectionDAG &DAG) const {
11762   SDValue N0 = Op.getOperand(0);
11763   SDLoc dl(Op);
11764
11765   if (Op.getValueType().isVector())
11766     return lowerUINT_TO_FP_vec(Op, DAG);
11767
11768   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
11769   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
11770   // the optimization here.
11771   if (DAG.SignBitIsZero(N0))
11772     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
11773
11774   MVT SrcVT = N0.getSimpleValueType();
11775   MVT DstVT = Op.getSimpleValueType();
11776   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
11777     return LowerUINT_TO_FP_i64(Op, DAG);
11778   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
11779     return LowerUINT_TO_FP_i32(Op, DAG);
11780   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
11781     return SDValue();
11782
11783   // Make a 64-bit buffer, and use it to build an FILD.
11784   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
11785   if (SrcVT == MVT::i32) {
11786     SDValue WordOff = DAG.getConstant(4, getPointerTy());
11787     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
11788                                      getPointerTy(), StackSlot, WordOff);
11789     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11790                                   StackSlot, MachinePointerInfo(),
11791                                   false, false, 0);
11792     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
11793                                   OffsetSlot, MachinePointerInfo(),
11794                                   false, false, 0);
11795     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
11796     return Fild;
11797   }
11798
11799   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
11800   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11801                                StackSlot, MachinePointerInfo(),
11802                                false, false, 0);
11803   // For i64 source, we need to add the appropriate power of 2 if the input
11804   // was negative.  This is the same as the optimization in
11805   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
11806   // we must be careful to do the computation in x87 extended precision, not
11807   // in SSE. (The generic code can't know it's OK to do this, or how to.)
11808   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
11809   MachineMemOperand *MMO =
11810     DAG.getMachineFunction()
11811     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11812                           MachineMemOperand::MOLoad, 8, 8);
11813
11814   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
11815   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
11816   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
11817                                          MVT::i64, MMO);
11818
11819   APInt FF(32, 0x5F800000ULL);
11820
11821   // Check whether the sign bit is set.
11822   SDValue SignSet = DAG.getSetCC(dl,
11823                                  getSetCCResultType(*DAG.getContext(), MVT::i64),
11824                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
11825                                  ISD::SETLT);
11826
11827   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
11828   SDValue FudgePtr = DAG.getConstantPool(
11829                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
11830                                          getPointerTy());
11831
11832   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
11833   SDValue Zero = DAG.getIntPtrConstant(0);
11834   SDValue Four = DAG.getIntPtrConstant(4);
11835   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
11836                                Zero, Four);
11837   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
11838
11839   // Load the value out, extending it from f32 to f80.
11840   // FIXME: Avoid the extend by constructing the right constant pool?
11841   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
11842                                  FudgePtr, MachinePointerInfo::getConstantPool(),
11843                                  MVT::f32, false, false, false, 4);
11844   // Extend everything to 80 bits to force it to be done on x87.
11845   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
11846   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
11847 }
11848
11849 std::pair<SDValue,SDValue>
11850 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
11851                                     bool IsSigned, bool IsReplace) const {
11852   SDLoc DL(Op);
11853
11854   EVT DstTy = Op.getValueType();
11855
11856   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
11857     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
11858     DstTy = MVT::i64;
11859   }
11860
11861   assert(DstTy.getSimpleVT() <= MVT::i64 &&
11862          DstTy.getSimpleVT() >= MVT::i16 &&
11863          "Unknown FP_TO_INT to lower!");
11864
11865   // These are really Legal.
11866   if (DstTy == MVT::i32 &&
11867       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
11868     return std::make_pair(SDValue(), SDValue());
11869   if (Subtarget->is64Bit() &&
11870       DstTy == MVT::i64 &&
11871       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
11872     return std::make_pair(SDValue(), SDValue());
11873
11874   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
11875   // stack slot, or into the FTOL runtime function.
11876   MachineFunction &MF = DAG.getMachineFunction();
11877   unsigned MemSize = DstTy.getSizeInBits()/8;
11878   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
11879   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11880
11881   unsigned Opc;
11882   if (!IsSigned && isIntegerTypeFTOL(DstTy))
11883     Opc = X86ISD::WIN_FTOL;
11884   else
11885     switch (DstTy.getSimpleVT().SimpleTy) {
11886     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
11887     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
11888     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
11889     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
11890     }
11891
11892   SDValue Chain = DAG.getEntryNode();
11893   SDValue Value = Op.getOperand(0);
11894   EVT TheVT = Op.getOperand(0).getValueType();
11895   // FIXME This causes a redundant load/store if the SSE-class value is already
11896   // in memory, such as if it is on the callstack.
11897   if (isScalarFPTypeInSSEReg(TheVT)) {
11898     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
11899     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
11900                          MachinePointerInfo::getFixedStack(SSFI),
11901                          false, false, 0);
11902     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
11903     SDValue Ops[] = {
11904       Chain, StackSlot, DAG.getValueType(TheVT)
11905     };
11906
11907     MachineMemOperand *MMO =
11908       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11909                               MachineMemOperand::MOLoad, MemSize, MemSize);
11910     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
11911     Chain = Value.getValue(1);
11912     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
11913     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11914   }
11915
11916   MachineMemOperand *MMO =
11917     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11918                             MachineMemOperand::MOStore, MemSize, MemSize);
11919
11920   if (Opc != X86ISD::WIN_FTOL) {
11921     // Build the FP_TO_INT*_IN_MEM
11922     SDValue Ops[] = { Chain, Value, StackSlot };
11923     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
11924                                            Ops, DstTy, MMO);
11925     return std::make_pair(FIST, StackSlot);
11926   } else {
11927     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
11928       DAG.getVTList(MVT::Other, MVT::Glue),
11929       Chain, Value);
11930     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
11931       MVT::i32, ftol.getValue(1));
11932     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
11933       MVT::i32, eax.getValue(2));
11934     SDValue Ops[] = { eax, edx };
11935     SDValue pair = IsReplace
11936       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
11937       : DAG.getMergeValues(Ops, DL);
11938     return std::make_pair(pair, SDValue());
11939   }
11940 }
11941
11942 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
11943                               const X86Subtarget *Subtarget) {
11944   MVT VT = Op->getSimpleValueType(0);
11945   SDValue In = Op->getOperand(0);
11946   MVT InVT = In.getSimpleValueType();
11947   SDLoc dl(Op);
11948
11949   // Optimize vectors in AVX mode:
11950   //
11951   //   v8i16 -> v8i32
11952   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
11953   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
11954   //   Concat upper and lower parts.
11955   //
11956   //   v4i32 -> v4i64
11957   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
11958   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
11959   //   Concat upper and lower parts.
11960   //
11961
11962   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
11963       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
11964       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
11965     return SDValue();
11966
11967   if (Subtarget->hasInt256())
11968     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
11969
11970   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
11971   SDValue Undef = DAG.getUNDEF(InVT);
11972   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
11973   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
11974   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
11975
11976   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
11977                              VT.getVectorNumElements()/2);
11978
11979   OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
11980   OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
11981
11982   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
11983 }
11984
11985 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
11986                                         SelectionDAG &DAG) {
11987   MVT VT = Op->getSimpleValueType(0);
11988   SDValue In = Op->getOperand(0);
11989   MVT InVT = In.getSimpleValueType();
11990   SDLoc DL(Op);
11991   unsigned int NumElts = VT.getVectorNumElements();
11992   if (NumElts != 8 && NumElts != 16)
11993     return SDValue();
11994
11995   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
11996     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
11997
11998   EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
11999   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12000   // Now we have only mask extension
12001   assert(InVT.getVectorElementType() == MVT::i1);
12002   SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
12003   const Constant *C = cast<ConstantSDNode>(Cst)->getConstantIntValue();
12004   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
12005   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
12006   SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
12007                            MachinePointerInfo::getConstantPool(),
12008                            false, false, false, Alignment);
12009
12010   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
12011   if (VT.is512BitVector())
12012     return Brcst;
12013   return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
12014 }
12015
12016 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12017                                SelectionDAG &DAG) {
12018   if (Subtarget->hasFp256()) {
12019     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
12020     if (Res.getNode())
12021       return Res;
12022   }
12023
12024   return SDValue();
12025 }
12026
12027 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12028                                 SelectionDAG &DAG) {
12029   SDLoc DL(Op);
12030   MVT VT = Op.getSimpleValueType();
12031   SDValue In = Op.getOperand(0);
12032   MVT SVT = In.getSimpleValueType();
12033
12034   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
12035     return LowerZERO_EXTEND_AVX512(Op, DAG);
12036
12037   if (Subtarget->hasFp256()) {
12038     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
12039     if (Res.getNode())
12040       return Res;
12041   }
12042
12043   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
12044          VT.getVectorNumElements() != SVT.getVectorNumElements());
12045   return SDValue();
12046 }
12047
12048 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
12049   SDLoc DL(Op);
12050   MVT VT = Op.getSimpleValueType();
12051   SDValue In = Op.getOperand(0);
12052   MVT InVT = In.getSimpleValueType();
12053
12054   if (VT == MVT::i1) {
12055     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
12056            "Invalid scalar TRUNCATE operation");
12057     if (InVT.getSizeInBits() >= 32)
12058       return SDValue();
12059     In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
12060     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
12061   }
12062   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
12063          "Invalid TRUNCATE operation");
12064
12065   // move vector to mask - truncate solution for SKX
12066   if (VT.getVectorElementType() == MVT::i1) {
12067     if (InVT.is512BitVector() && InVT.getScalarSizeInBits() <= 16 &&
12068         Subtarget->hasBWI())
12069       return Op; // legal, will go to VPMOVB2M, VPMOVW2M
12070     if ((InVT.is256BitVector() || InVT.is128BitVector()) 
12071         && InVT.getScalarSizeInBits() <= 16 &&
12072         Subtarget->hasBWI() && Subtarget->hasVLX())
12073       return Op; // legal, will go to VPMOVB2M, VPMOVW2M
12074     if (InVT.is512BitVector() && InVT.getScalarSizeInBits() >= 32 &&
12075         Subtarget->hasDQI())
12076       return Op; // legal, will go to VPMOVD2M, VPMOVQ2M
12077     if ((InVT.is256BitVector() || InVT.is128BitVector()) 
12078         && InVT.getScalarSizeInBits() >= 32 &&
12079         Subtarget->hasDQI() && Subtarget->hasVLX())
12080       return Op; // legal, will go to VPMOVB2M, VPMOVQ2M
12081   }
12082   if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
12083     if (VT.getVectorElementType().getSizeInBits() >=8)
12084       return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
12085
12086     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
12087     unsigned NumElts = InVT.getVectorNumElements();
12088     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
12089     if (InVT.getSizeInBits() < 512) {
12090       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
12091       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
12092       InVT = ExtVT;
12093     }
12094
12095     SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
12096     const Constant *C = cast<ConstantSDNode>(Cst)->getConstantIntValue();
12097     SDValue CP = DAG.getConstantPool(C, getPointerTy());
12098     unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
12099     SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
12100                            MachinePointerInfo::getConstantPool(),
12101                            false, false, false, Alignment);
12102     SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
12103     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
12104     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
12105   }
12106
12107   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
12108     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
12109     if (Subtarget->hasInt256()) {
12110       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
12111       In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
12112       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
12113                                 ShufMask);
12114       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
12115                          DAG.getIntPtrConstant(0));
12116     }
12117
12118     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12119                                DAG.getIntPtrConstant(0));
12120     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12121                                DAG.getIntPtrConstant(2));
12122     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
12123     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
12124     static const int ShufMask[] = {0, 2, 4, 6};
12125     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
12126   }
12127
12128   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
12129     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
12130     if (Subtarget->hasInt256()) {
12131       In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
12132
12133       SmallVector<SDValue,32> pshufbMask;
12134       for (unsigned i = 0; i < 2; ++i) {
12135         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
12136         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
12137         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
12138         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
12139         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
12140         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
12141         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
12142         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
12143         for (unsigned j = 0; j < 8; ++j)
12144           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
12145       }
12146       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
12147       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
12148       In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
12149
12150       static const int ShufMask[] = {0,  2,  -1,  -1};
12151       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
12152                                 &ShufMask[0]);
12153       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12154                        DAG.getIntPtrConstant(0));
12155       return DAG.getNode(ISD::BITCAST, DL, VT, In);
12156     }
12157
12158     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12159                                DAG.getIntPtrConstant(0));
12160
12161     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12162                                DAG.getIntPtrConstant(4));
12163
12164     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
12165     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
12166
12167     // The PSHUFB mask:
12168     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
12169                                    -1, -1, -1, -1, -1, -1, -1, -1};
12170
12171     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
12172     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
12173     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
12174
12175     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
12176     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
12177
12178     // The MOVLHPS Mask:
12179     static const int ShufMask2[] = {0, 1, 4, 5};
12180     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
12181     return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
12182   }
12183
12184   // Handle truncation of V256 to V128 using shuffles.
12185   if (!VT.is128BitVector() || !InVT.is256BitVector())
12186     return SDValue();
12187
12188   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
12189
12190   unsigned NumElems = VT.getVectorNumElements();
12191   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
12192
12193   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
12194   // Prepare truncation shuffle mask
12195   for (unsigned i = 0; i != NumElems; ++i)
12196     MaskVec[i] = i * 2;
12197   SDValue V = DAG.getVectorShuffle(NVT, DL,
12198                                    DAG.getNode(ISD::BITCAST, DL, NVT, In),
12199                                    DAG.getUNDEF(NVT), &MaskVec[0]);
12200   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
12201                      DAG.getIntPtrConstant(0));
12202 }
12203
12204 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
12205                                            SelectionDAG &DAG) const {
12206   assert(!Op.getSimpleValueType().isVector());
12207
12208   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12209     /*IsSigned=*/ true, /*IsReplace=*/ false);
12210   SDValue FIST = Vals.first, StackSlot = Vals.second;
12211   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
12212   if (!FIST.getNode()) return Op;
12213
12214   if (StackSlot.getNode())
12215     // Load the result.
12216     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12217                        FIST, StackSlot, MachinePointerInfo(),
12218                        false, false, false, 0);
12219
12220   // The node is the result.
12221   return FIST;
12222 }
12223
12224 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
12225                                            SelectionDAG &DAG) const {
12226   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12227     /*IsSigned=*/ false, /*IsReplace=*/ false);
12228   SDValue FIST = Vals.first, StackSlot = Vals.second;
12229   assert(FIST.getNode() && "Unexpected failure");
12230
12231   if (StackSlot.getNode())
12232     // Load the result.
12233     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12234                        FIST, StackSlot, MachinePointerInfo(),
12235                        false, false, false, 0);
12236
12237   // The node is the result.
12238   return FIST;
12239 }
12240
12241 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
12242   SDLoc DL(Op);
12243   MVT VT = Op.getSimpleValueType();
12244   SDValue In = Op.getOperand(0);
12245   MVT SVT = In.getSimpleValueType();
12246
12247   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
12248
12249   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
12250                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
12251                                  In, DAG.getUNDEF(SVT)));
12252 }
12253
12254 /// The only differences between FABS and FNEG are the mask and the logic op.
12255 /// FNEG also has a folding opportunity for FNEG(FABS(x)).
12256 static SDValue LowerFABSorFNEG(SDValue Op, SelectionDAG &DAG) {
12257   assert((Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) &&
12258          "Wrong opcode for lowering FABS or FNEG.");
12259
12260   bool IsFABS = (Op.getOpcode() == ISD::FABS);
12261
12262   // If this is a FABS and it has an FNEG user, bail out to fold the combination
12263   // into an FNABS. We'll lower the FABS after that if it is still in use.
12264   if (IsFABS)
12265     for (SDNode *User : Op->uses())
12266       if (User->getOpcode() == ISD::FNEG)
12267         return Op;
12268
12269   SDValue Op0 = Op.getOperand(0);
12270   bool IsFNABS = !IsFABS && (Op0.getOpcode() == ISD::FABS);
12271
12272   SDLoc dl(Op);
12273   MVT VT = Op.getSimpleValueType();
12274   // Assume scalar op for initialization; update for vector if needed.
12275   // Note that there are no scalar bitwise logical SSE/AVX instructions, so we
12276   // generate a 16-byte vector constant and logic op even for the scalar case.
12277   // Using a 16-byte mask allows folding the load of the mask with
12278   // the logic op, so it can save (~4 bytes) on code size.
12279   MVT EltVT = VT;
12280   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
12281   // FIXME: Use function attribute "OptimizeForSize" and/or CodeGenOpt::Level to
12282   // decide if we should generate a 16-byte constant mask when we only need 4 or
12283   // 8 bytes for the scalar case.
12284   if (VT.isVector()) {
12285     EltVT = VT.getVectorElementType();
12286     NumElts = VT.getVectorNumElements();
12287   }
12288
12289   unsigned EltBits = EltVT.getSizeInBits();
12290   LLVMContext *Context = DAG.getContext();
12291   // For FABS, mask is 0x7f...; for FNEG, mask is 0x80...
12292   APInt MaskElt =
12293     IsFABS ? APInt::getSignedMaxValue(EltBits) : APInt::getSignBit(EltBits);
12294   Constant *C = ConstantInt::get(*Context, MaskElt);
12295   C = ConstantVector::getSplat(NumElts, C);
12296   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12297   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
12298   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
12299   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
12300                              MachinePointerInfo::getConstantPool(),
12301                              false, false, false, Alignment);
12302
12303   if (VT.isVector()) {
12304     // For a vector, cast operands to a vector type, perform the logic op,
12305     // and cast the result back to the original value type.
12306     MVT VecVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
12307     SDValue MaskCasted = DAG.getNode(ISD::BITCAST, dl, VecVT, Mask);
12308     SDValue Operand = IsFNABS ?
12309       DAG.getNode(ISD::BITCAST, dl, VecVT, Op0.getOperand(0)) :
12310       DAG.getNode(ISD::BITCAST, dl, VecVT, Op0);
12311     unsigned BitOp = IsFABS ? ISD::AND : IsFNABS ? ISD::OR : ISD::XOR;
12312     return DAG.getNode(ISD::BITCAST, dl, VT,
12313                        DAG.getNode(BitOp, dl, VecVT, Operand, MaskCasted));
12314   }
12315
12316   // If not vector, then scalar.
12317   unsigned BitOp = IsFABS ? X86ISD::FAND : IsFNABS ? X86ISD::FOR : X86ISD::FXOR;
12318   SDValue Operand = IsFNABS ? Op0.getOperand(0) : Op0;
12319   return DAG.getNode(BitOp, dl, VT, Operand, Mask);
12320 }
12321
12322 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
12323   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12324   LLVMContext *Context = DAG.getContext();
12325   SDValue Op0 = Op.getOperand(0);
12326   SDValue Op1 = Op.getOperand(1);
12327   SDLoc dl(Op);
12328   MVT VT = Op.getSimpleValueType();
12329   MVT SrcVT = Op1.getSimpleValueType();
12330
12331   // If second operand is smaller, extend it first.
12332   if (SrcVT.bitsLT(VT)) {
12333     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
12334     SrcVT = VT;
12335   }
12336   // And if it is bigger, shrink it first.
12337   if (SrcVT.bitsGT(VT)) {
12338     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
12339     SrcVT = VT;
12340   }
12341
12342   // At this point the operands and the result should have the same
12343   // type, and that won't be f80 since that is not custom lowered.
12344
12345   const fltSemantics &Sem =
12346       VT == MVT::f64 ? APFloat::IEEEdouble : APFloat::IEEEsingle;
12347   const unsigned SizeInBits = VT.getSizeInBits();
12348
12349   SmallVector<Constant *, 4> CV(
12350       VT == MVT::f64 ? 2 : 4,
12351       ConstantFP::get(*Context, APFloat(Sem, APInt(SizeInBits, 0))));
12352
12353   // First, clear all bits but the sign bit from the second operand (sign).
12354   CV[0] = ConstantFP::get(*Context,
12355                           APFloat(Sem, APInt::getHighBitsSet(SizeInBits, 1)));
12356   Constant *C = ConstantVector::get(CV);
12357   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
12358   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
12359                               MachinePointerInfo::getConstantPool(),
12360                               false, false, false, 16);
12361   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
12362
12363   // Next, clear the sign bit from the first operand (magnitude).
12364   // If it's a constant, we can clear it here.
12365   if (ConstantFPSDNode *Op0CN = dyn_cast<ConstantFPSDNode>(Op0)) {
12366     APFloat APF = Op0CN->getValueAPF();
12367     // If the magnitude is a positive zero, the sign bit alone is enough.
12368     if (APF.isPosZero())
12369       return SignBit;
12370     APF.clearSign();
12371     CV[0] = ConstantFP::get(*Context, APF);
12372   } else {
12373     CV[0] = ConstantFP::get(
12374         *Context,
12375         APFloat(Sem, APInt::getLowBitsSet(SizeInBits, SizeInBits - 1)));
12376   }
12377   C = ConstantVector::get(CV);
12378   CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
12379   SDValue Val = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
12380                             MachinePointerInfo::getConstantPool(),
12381                             false, false, false, 16);
12382   // If the magnitude operand wasn't a constant, we need to AND out the sign.
12383   if (!isa<ConstantFPSDNode>(Op0))
12384     Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Val);
12385
12386   // OR the magnitude value with the sign bit.
12387   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
12388 }
12389
12390 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
12391   SDValue N0 = Op.getOperand(0);
12392   SDLoc dl(Op);
12393   MVT VT = Op.getSimpleValueType();
12394
12395   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
12396   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
12397                                   DAG.getConstant(1, VT));
12398   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
12399 }
12400
12401 // Check whether an OR'd tree is PTEST-able.
12402 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
12403                                       SelectionDAG &DAG) {
12404   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
12405
12406   if (!Subtarget->hasSSE41())
12407     return SDValue();
12408
12409   if (!Op->hasOneUse())
12410     return SDValue();
12411
12412   SDNode *N = Op.getNode();
12413   SDLoc DL(N);
12414
12415   SmallVector<SDValue, 8> Opnds;
12416   DenseMap<SDValue, unsigned> VecInMap;
12417   SmallVector<SDValue, 8> VecIns;
12418   EVT VT = MVT::Other;
12419
12420   // Recognize a special case where a vector is casted into wide integer to
12421   // test all 0s.
12422   Opnds.push_back(N->getOperand(0));
12423   Opnds.push_back(N->getOperand(1));
12424
12425   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
12426     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
12427     // BFS traverse all OR'd operands.
12428     if (I->getOpcode() == ISD::OR) {
12429       Opnds.push_back(I->getOperand(0));
12430       Opnds.push_back(I->getOperand(1));
12431       // Re-evaluate the number of nodes to be traversed.
12432       e += 2; // 2 more nodes (LHS and RHS) are pushed.
12433       continue;
12434     }
12435
12436     // Quit if a non-EXTRACT_VECTOR_ELT
12437     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
12438       return SDValue();
12439
12440     // Quit if without a constant index.
12441     SDValue Idx = I->getOperand(1);
12442     if (!isa<ConstantSDNode>(Idx))
12443       return SDValue();
12444
12445     SDValue ExtractedFromVec = I->getOperand(0);
12446     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
12447     if (M == VecInMap.end()) {
12448       VT = ExtractedFromVec.getValueType();
12449       // Quit if not 128/256-bit vector.
12450       if (!VT.is128BitVector() && !VT.is256BitVector())
12451         return SDValue();
12452       // Quit if not the same type.
12453       if (VecInMap.begin() != VecInMap.end() &&
12454           VT != VecInMap.begin()->first.getValueType())
12455         return SDValue();
12456       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
12457       VecIns.push_back(ExtractedFromVec);
12458     }
12459     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
12460   }
12461
12462   assert((VT.is128BitVector() || VT.is256BitVector()) &&
12463          "Not extracted from 128-/256-bit vector.");
12464
12465   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
12466
12467   for (DenseMap<SDValue, unsigned>::const_iterator
12468         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
12469     // Quit if not all elements are used.
12470     if (I->second != FullMask)
12471       return SDValue();
12472   }
12473
12474   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
12475
12476   // Cast all vectors into TestVT for PTEST.
12477   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
12478     VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
12479
12480   // If more than one full vectors are evaluated, OR them first before PTEST.
12481   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
12482     // Each iteration will OR 2 nodes and append the result until there is only
12483     // 1 node left, i.e. the final OR'd value of all vectors.
12484     SDValue LHS = VecIns[Slot];
12485     SDValue RHS = VecIns[Slot + 1];
12486     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
12487   }
12488
12489   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
12490                      VecIns.back(), VecIns.back());
12491 }
12492
12493 /// \brief return true if \c Op has a use that doesn't just read flags.
12494 static bool hasNonFlagsUse(SDValue Op) {
12495   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
12496        ++UI) {
12497     SDNode *User = *UI;
12498     unsigned UOpNo = UI.getOperandNo();
12499     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
12500       // Look pass truncate.
12501       UOpNo = User->use_begin().getOperandNo();
12502       User = *User->use_begin();
12503     }
12504
12505     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
12506         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
12507       return true;
12508   }
12509   return false;
12510 }
12511
12512 /// Emit nodes that will be selected as "test Op0,Op0", or something
12513 /// equivalent.
12514 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
12515                                     SelectionDAG &DAG) const {
12516   if (Op.getValueType() == MVT::i1) {
12517     SDValue ExtOp = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i8, Op);
12518     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, ExtOp,
12519                        DAG.getConstant(0, MVT::i8));
12520   }
12521   // CF and OF aren't always set the way we want. Determine which
12522   // of these we need.
12523   bool NeedCF = false;
12524   bool NeedOF = false;
12525   switch (X86CC) {
12526   default: break;
12527   case X86::COND_A: case X86::COND_AE:
12528   case X86::COND_B: case X86::COND_BE:
12529     NeedCF = true;
12530     break;
12531   case X86::COND_G: case X86::COND_GE:
12532   case X86::COND_L: case X86::COND_LE:
12533   case X86::COND_O: case X86::COND_NO: {
12534     // Check if we really need to set the
12535     // Overflow flag. If NoSignedWrap is present
12536     // that is not actually needed.
12537     switch (Op->getOpcode()) {
12538     case ISD::ADD:
12539     case ISD::SUB:
12540     case ISD::MUL:
12541     case ISD::SHL: {
12542       const BinaryWithFlagsSDNode *BinNode =
12543           cast<BinaryWithFlagsSDNode>(Op.getNode());
12544       if (BinNode->hasNoSignedWrap())
12545         break;
12546     }
12547     default:
12548       NeedOF = true;
12549       break;
12550     }
12551     break;
12552   }
12553   }
12554   // See if we can use the EFLAGS value from the operand instead of
12555   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
12556   // we prove that the arithmetic won't overflow, we can't use OF or CF.
12557   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
12558     // Emit a CMP with 0, which is the TEST pattern.
12559     //if (Op.getValueType() == MVT::i1)
12560     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
12561     //                     DAG.getConstant(0, MVT::i1));
12562     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12563                        DAG.getConstant(0, Op.getValueType()));
12564   }
12565   unsigned Opcode = 0;
12566   unsigned NumOperands = 0;
12567
12568   // Truncate operations may prevent the merge of the SETCC instruction
12569   // and the arithmetic instruction before it. Attempt to truncate the operands
12570   // of the arithmetic instruction and use a reduced bit-width instruction.
12571   bool NeedTruncation = false;
12572   SDValue ArithOp = Op;
12573   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
12574     SDValue Arith = Op->getOperand(0);
12575     // Both the trunc and the arithmetic op need to have one user each.
12576     if (Arith->hasOneUse())
12577       switch (Arith.getOpcode()) {
12578         default: break;
12579         case ISD::ADD:
12580         case ISD::SUB:
12581         case ISD::AND:
12582         case ISD::OR:
12583         case ISD::XOR: {
12584           NeedTruncation = true;
12585           ArithOp = Arith;
12586         }
12587       }
12588   }
12589
12590   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
12591   // which may be the result of a CAST.  We use the variable 'Op', which is the
12592   // non-casted variable when we check for possible users.
12593   switch (ArithOp.getOpcode()) {
12594   case ISD::ADD:
12595     // Due to an isel shortcoming, be conservative if this add is likely to be
12596     // selected as part of a load-modify-store instruction. When the root node
12597     // in a match is a store, isel doesn't know how to remap non-chain non-flag
12598     // uses of other nodes in the match, such as the ADD in this case. This
12599     // leads to the ADD being left around and reselected, with the result being
12600     // two adds in the output.  Alas, even if none our users are stores, that
12601     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
12602     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
12603     // climbing the DAG back to the root, and it doesn't seem to be worth the
12604     // effort.
12605     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12606          UE = Op.getNode()->use_end(); UI != UE; ++UI)
12607       if (UI->getOpcode() != ISD::CopyToReg &&
12608           UI->getOpcode() != ISD::SETCC &&
12609           UI->getOpcode() != ISD::STORE)
12610         goto default_case;
12611
12612     if (ConstantSDNode *C =
12613         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
12614       // An add of one will be selected as an INC.
12615       if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
12616         Opcode = X86ISD::INC;
12617         NumOperands = 1;
12618         break;
12619       }
12620
12621       // An add of negative one (subtract of one) will be selected as a DEC.
12622       if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
12623         Opcode = X86ISD::DEC;
12624         NumOperands = 1;
12625         break;
12626       }
12627     }
12628
12629     // Otherwise use a regular EFLAGS-setting add.
12630     Opcode = X86ISD::ADD;
12631     NumOperands = 2;
12632     break;
12633   case ISD::SHL:
12634   case ISD::SRL:
12635     // If we have a constant logical shift that's only used in a comparison
12636     // against zero turn it into an equivalent AND. This allows turning it into
12637     // a TEST instruction later.
12638     if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
12639         isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
12640       EVT VT = Op.getValueType();
12641       unsigned BitWidth = VT.getSizeInBits();
12642       unsigned ShAmt = Op->getConstantOperandVal(1);
12643       if (ShAmt >= BitWidth) // Avoid undefined shifts.
12644         break;
12645       APInt Mask = ArithOp.getOpcode() == ISD::SRL
12646                        ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
12647                        : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
12648       if (!Mask.isSignedIntN(32)) // Avoid large immediates.
12649         break;
12650       SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
12651                                 DAG.getConstant(Mask, VT));
12652       DAG.ReplaceAllUsesWith(Op, New);
12653       Op = New;
12654     }
12655     break;
12656
12657   case ISD::AND:
12658     // If the primary and result isn't used, don't bother using X86ISD::AND,
12659     // because a TEST instruction will be better.
12660     if (!hasNonFlagsUse(Op))
12661       break;
12662     // FALL THROUGH
12663   case ISD::SUB:
12664   case ISD::OR:
12665   case ISD::XOR:
12666     // Due to the ISEL shortcoming noted above, be conservative if this op is
12667     // likely to be selected as part of a load-modify-store instruction.
12668     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12669            UE = Op.getNode()->use_end(); UI != UE; ++UI)
12670       if (UI->getOpcode() == ISD::STORE)
12671         goto default_case;
12672
12673     // Otherwise use a regular EFLAGS-setting instruction.
12674     switch (ArithOp.getOpcode()) {
12675     default: llvm_unreachable("unexpected operator!");
12676     case ISD::SUB: Opcode = X86ISD::SUB; break;
12677     case ISD::XOR: Opcode = X86ISD::XOR; break;
12678     case ISD::AND: Opcode = X86ISD::AND; break;
12679     case ISD::OR: {
12680       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
12681         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
12682         if (EFLAGS.getNode())
12683           return EFLAGS;
12684       }
12685       Opcode = X86ISD::OR;
12686       break;
12687     }
12688     }
12689
12690     NumOperands = 2;
12691     break;
12692   case X86ISD::ADD:
12693   case X86ISD::SUB:
12694   case X86ISD::INC:
12695   case X86ISD::DEC:
12696   case X86ISD::OR:
12697   case X86ISD::XOR:
12698   case X86ISD::AND:
12699     return SDValue(Op.getNode(), 1);
12700   default:
12701   default_case:
12702     break;
12703   }
12704
12705   // If we found that truncation is beneficial, perform the truncation and
12706   // update 'Op'.
12707   if (NeedTruncation) {
12708     EVT VT = Op.getValueType();
12709     SDValue WideVal = Op->getOperand(0);
12710     EVT WideVT = WideVal.getValueType();
12711     unsigned ConvertedOp = 0;
12712     // Use a target machine opcode to prevent further DAGCombine
12713     // optimizations that may separate the arithmetic operations
12714     // from the setcc node.
12715     switch (WideVal.getOpcode()) {
12716       default: break;
12717       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
12718       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
12719       case ISD::AND: ConvertedOp = X86ISD::AND; break;
12720       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
12721       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
12722     }
12723
12724     if (ConvertedOp) {
12725       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12726       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
12727         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
12728         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
12729         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
12730       }
12731     }
12732   }
12733
12734   if (Opcode == 0)
12735     // Emit a CMP with 0, which is the TEST pattern.
12736     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12737                        DAG.getConstant(0, Op.getValueType()));
12738
12739   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12740   SmallVector<SDValue, 4> Ops(Op->op_begin(), Op->op_begin() + NumOperands);
12741
12742   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
12743   DAG.ReplaceAllUsesWith(Op, New);
12744   return SDValue(New.getNode(), 1);
12745 }
12746
12747 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
12748 /// equivalent.
12749 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
12750                                    SDLoc dl, SelectionDAG &DAG) const {
12751   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
12752     if (C->getAPIntValue() == 0)
12753       return EmitTest(Op0, X86CC, dl, DAG);
12754
12755      if (Op0.getValueType() == MVT::i1)
12756        llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
12757   }
12758
12759   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
12760        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
12761     // Do the comparison at i32 if it's smaller, besides the Atom case.
12762     // This avoids subregister aliasing issues. Keep the smaller reference
12763     // if we're optimizing for size, however, as that'll allow better folding
12764     // of memory operations.
12765     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
12766         !DAG.getMachineFunction().getFunction()->hasFnAttribute(
12767             Attribute::MinSize) &&
12768         !Subtarget->isAtom()) {
12769       unsigned ExtendOp =
12770           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
12771       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
12772       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
12773     }
12774     // Use SUB instead of CMP to enable CSE between SUB and CMP.
12775     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
12776     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
12777                               Op0, Op1);
12778     return SDValue(Sub.getNode(), 1);
12779   }
12780   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
12781 }
12782
12783 /// Convert a comparison if required by the subtarget.
12784 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
12785                                                  SelectionDAG &DAG) const {
12786   // If the subtarget does not support the FUCOMI instruction, floating-point
12787   // comparisons have to be converted.
12788   if (Subtarget->hasCMov() ||
12789       Cmp.getOpcode() != X86ISD::CMP ||
12790       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
12791       !Cmp.getOperand(1).getValueType().isFloatingPoint())
12792     return Cmp;
12793
12794   // The instruction selector will select an FUCOM instruction instead of
12795   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
12796   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
12797   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
12798   SDLoc dl(Cmp);
12799   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
12800   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
12801   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
12802                             DAG.getConstant(8, MVT::i8));
12803   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
12804   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
12805 }
12806
12807 /// The minimum architected relative accuracy is 2^-12. We need one
12808 /// Newton-Raphson step to have a good float result (24 bits of precision).
12809 SDValue X86TargetLowering::getRsqrtEstimate(SDValue Op,
12810                                             DAGCombinerInfo &DCI,
12811                                             unsigned &RefinementSteps,
12812                                             bool &UseOneConstNR) const {
12813   // FIXME: We should use instruction latency models to calculate the cost of
12814   // each potential sequence, but this is very hard to do reliably because
12815   // at least Intel's Core* chips have variable timing based on the number of
12816   // significant digits in the divisor and/or sqrt operand.
12817   if (!Subtarget->useSqrtEst())
12818     return SDValue();
12819
12820   EVT VT = Op.getValueType();
12821
12822   // SSE1 has rsqrtss and rsqrtps.
12823   // TODO: Add support for AVX512 (v16f32).
12824   // It is likely not profitable to do this for f64 because a double-precision
12825   // rsqrt estimate with refinement on x86 prior to FMA requires at least 16
12826   // instructions: convert to single, rsqrtss, convert back to double, refine
12827   // (3 steps = at least 13 insts). If an 'rsqrtsd' variant was added to the ISA
12828   // along with FMA, this could be a throughput win.
12829   if ((Subtarget->hasSSE1() && (VT == MVT::f32 || VT == MVT::v4f32)) ||
12830       (Subtarget->hasAVX() && VT == MVT::v8f32)) {
12831     RefinementSteps = 1;
12832     UseOneConstNR = false;
12833     return DCI.DAG.getNode(X86ISD::FRSQRT, SDLoc(Op), VT, Op);
12834   }
12835   return SDValue();
12836 }
12837
12838 /// The minimum architected relative accuracy is 2^-12. We need one
12839 /// Newton-Raphson step to have a good float result (24 bits of precision).
12840 SDValue X86TargetLowering::getRecipEstimate(SDValue Op,
12841                                             DAGCombinerInfo &DCI,
12842                                             unsigned &RefinementSteps) const {
12843   // FIXME: We should use instruction latency models to calculate the cost of
12844   // each potential sequence, but this is very hard to do reliably because
12845   // at least Intel's Core* chips have variable timing based on the number of
12846   // significant digits in the divisor.
12847   if (!Subtarget->useReciprocalEst())
12848     return SDValue();
12849
12850   EVT VT = Op.getValueType();
12851
12852   // SSE1 has rcpss and rcpps. AVX adds a 256-bit variant for rcpps.
12853   // TODO: Add support for AVX512 (v16f32).
12854   // It is likely not profitable to do this for f64 because a double-precision
12855   // reciprocal estimate with refinement on x86 prior to FMA requires
12856   // 15 instructions: convert to single, rcpss, convert back to double, refine
12857   // (3 steps = 12 insts). If an 'rcpsd' variant was added to the ISA
12858   // along with FMA, this could be a throughput win.
12859   if ((Subtarget->hasSSE1() && (VT == MVT::f32 || VT == MVT::v4f32)) ||
12860       (Subtarget->hasAVX() && VT == MVT::v8f32)) {
12861     RefinementSteps = ReciprocalEstimateRefinementSteps;
12862     return DCI.DAG.getNode(X86ISD::FRCP, SDLoc(Op), VT, Op);
12863   }
12864   return SDValue();
12865 }
12866
12867 /// If we have at least two divisions that use the same divisor, convert to
12868 /// multplication by a reciprocal. This may need to be adjusted for a given
12869 /// CPU if a division's cost is not at least twice the cost of a multiplication.
12870 /// This is because we still need one division to calculate the reciprocal and
12871 /// then we need two multiplies by that reciprocal as replacements for the
12872 /// original divisions.
12873 bool X86TargetLowering::combineRepeatedFPDivisors(unsigned NumUsers) const {
12874   return NumUsers > 1;
12875 }
12876
12877 static bool isAllOnes(SDValue V) {
12878   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
12879   return C && C->isAllOnesValue();
12880 }
12881
12882 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
12883 /// if it's possible.
12884 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
12885                                      SDLoc dl, SelectionDAG &DAG) const {
12886   SDValue Op0 = And.getOperand(0);
12887   SDValue Op1 = And.getOperand(1);
12888   if (Op0.getOpcode() == ISD::TRUNCATE)
12889     Op0 = Op0.getOperand(0);
12890   if (Op1.getOpcode() == ISD::TRUNCATE)
12891     Op1 = Op1.getOperand(0);
12892
12893   SDValue LHS, RHS;
12894   if (Op1.getOpcode() == ISD::SHL)
12895     std::swap(Op0, Op1);
12896   if (Op0.getOpcode() == ISD::SHL) {
12897     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
12898       if (And00C->getZExtValue() == 1) {
12899         // If we looked past a truncate, check that it's only truncating away
12900         // known zeros.
12901         unsigned BitWidth = Op0.getValueSizeInBits();
12902         unsigned AndBitWidth = And.getValueSizeInBits();
12903         if (BitWidth > AndBitWidth) {
12904           APInt Zeros, Ones;
12905           DAG.computeKnownBits(Op0, Zeros, Ones);
12906           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
12907             return SDValue();
12908         }
12909         LHS = Op1;
12910         RHS = Op0.getOperand(1);
12911       }
12912   } else if (Op1.getOpcode() == ISD::Constant) {
12913     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
12914     uint64_t AndRHSVal = AndRHS->getZExtValue();
12915     SDValue AndLHS = Op0;
12916
12917     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
12918       LHS = AndLHS.getOperand(0);
12919       RHS = AndLHS.getOperand(1);
12920     }
12921
12922     // Use BT if the immediate can't be encoded in a TEST instruction.
12923     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
12924       LHS = AndLHS;
12925       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
12926     }
12927   }
12928
12929   if (LHS.getNode()) {
12930     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
12931     // instruction.  Since the shift amount is in-range-or-undefined, we know
12932     // that doing a bittest on the i32 value is ok.  We extend to i32 because
12933     // the encoding for the i16 version is larger than the i32 version.
12934     // Also promote i16 to i32 for performance / code size reason.
12935     if (LHS.getValueType() == MVT::i8 ||
12936         LHS.getValueType() == MVT::i16)
12937       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
12938
12939     // If the operand types disagree, extend the shift amount to match.  Since
12940     // BT ignores high bits (like shifts) we can use anyextend.
12941     if (LHS.getValueType() != RHS.getValueType())
12942       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
12943
12944     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
12945     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
12946     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12947                        DAG.getConstant(Cond, MVT::i8), BT);
12948   }
12949
12950   return SDValue();
12951 }
12952
12953 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
12954 /// mask CMPs.
12955 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
12956                               SDValue &Op1) {
12957   unsigned SSECC;
12958   bool Swap = false;
12959
12960   // SSE Condition code mapping:
12961   //  0 - EQ
12962   //  1 - LT
12963   //  2 - LE
12964   //  3 - UNORD
12965   //  4 - NEQ
12966   //  5 - NLT
12967   //  6 - NLE
12968   //  7 - ORD
12969   switch (SetCCOpcode) {
12970   default: llvm_unreachable("Unexpected SETCC condition");
12971   case ISD::SETOEQ:
12972   case ISD::SETEQ:  SSECC = 0; break;
12973   case ISD::SETOGT:
12974   case ISD::SETGT:  Swap = true; // Fallthrough
12975   case ISD::SETLT:
12976   case ISD::SETOLT: SSECC = 1; break;
12977   case ISD::SETOGE:
12978   case ISD::SETGE:  Swap = true; // Fallthrough
12979   case ISD::SETLE:
12980   case ISD::SETOLE: SSECC = 2; break;
12981   case ISD::SETUO:  SSECC = 3; break;
12982   case ISD::SETUNE:
12983   case ISD::SETNE:  SSECC = 4; break;
12984   case ISD::SETULE: Swap = true; // Fallthrough
12985   case ISD::SETUGE: SSECC = 5; break;
12986   case ISD::SETULT: Swap = true; // Fallthrough
12987   case ISD::SETUGT: SSECC = 6; break;
12988   case ISD::SETO:   SSECC = 7; break;
12989   case ISD::SETUEQ:
12990   case ISD::SETONE: SSECC = 8; break;
12991   }
12992   if (Swap)
12993     std::swap(Op0, Op1);
12994
12995   return SSECC;
12996 }
12997
12998 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
12999 // ones, and then concatenate the result back.
13000 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
13001   MVT VT = Op.getSimpleValueType();
13002
13003   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
13004          "Unsupported value type for operation");
13005
13006   unsigned NumElems = VT.getVectorNumElements();
13007   SDLoc dl(Op);
13008   SDValue CC = Op.getOperand(2);
13009
13010   // Extract the LHS vectors
13011   SDValue LHS = Op.getOperand(0);
13012   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13013   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13014
13015   // Extract the RHS vectors
13016   SDValue RHS = Op.getOperand(1);
13017   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
13018   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
13019
13020   // Issue the operation on the smaller types and concatenate the result back
13021   MVT EltVT = VT.getVectorElementType();
13022   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13023   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
13024                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
13025                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
13026 }
13027
13028 static SDValue LowerBoolVSETCC_AVX512(SDValue Op, SelectionDAG &DAG) {
13029   SDValue Op0 = Op.getOperand(0);
13030   SDValue Op1 = Op.getOperand(1);
13031   SDValue CC = Op.getOperand(2);
13032   MVT VT = Op.getSimpleValueType();
13033   SDLoc dl(Op);
13034
13035   assert(Op0.getValueType().getVectorElementType() == MVT::i1 &&
13036          "Unexpected type for boolean compare operation");
13037   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13038   SDValue NotOp0 = DAG.getNode(ISD::XOR, dl, VT, Op0,
13039                                DAG.getConstant(-1, VT));
13040   SDValue NotOp1 = DAG.getNode(ISD::XOR, dl, VT, Op1,
13041                                DAG.getConstant(-1, VT));
13042   switch (SetCCOpcode) {
13043   default: llvm_unreachable("Unexpected SETCC condition");
13044   case ISD::SETNE:
13045     // (x != y) -> ~(x ^ y)
13046     return DAG.getNode(ISD::XOR, dl, VT,
13047                        DAG.getNode(ISD::XOR, dl, VT, Op0, Op1),
13048                        DAG.getConstant(-1, VT));
13049   case ISD::SETEQ:
13050     // (x == y) -> (x ^ y)
13051     return DAG.getNode(ISD::XOR, dl, VT, Op0, Op1);
13052   case ISD::SETUGT:
13053   case ISD::SETGT:
13054     // (x > y) -> (x & ~y)
13055     return DAG.getNode(ISD::AND, dl, VT, Op0, NotOp1);
13056   case ISD::SETULT:
13057   case ISD::SETLT:
13058     // (x < y) -> (~x & y)
13059     return DAG.getNode(ISD::AND, dl, VT, NotOp0, Op1);
13060   case ISD::SETULE:
13061   case ISD::SETLE:
13062     // (x <= y) -> (~x | y)
13063     return DAG.getNode(ISD::OR, dl, VT, NotOp0, Op1);
13064   case ISD::SETUGE:
13065   case ISD::SETGE:
13066     // (x >=y) -> (x | ~y)
13067     return DAG.getNode(ISD::OR, dl, VT, Op0, NotOp1);
13068   }
13069 }
13070
13071 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
13072                                      const X86Subtarget *Subtarget) {
13073   SDValue Op0 = Op.getOperand(0);
13074   SDValue Op1 = Op.getOperand(1);
13075   SDValue CC = Op.getOperand(2);
13076   MVT VT = Op.getSimpleValueType();
13077   SDLoc dl(Op);
13078
13079   assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 8 &&
13080          Op.getValueType().getScalarType() == MVT::i1 &&
13081          "Cannot set masked compare for this operation");
13082
13083   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13084   unsigned  Opc = 0;
13085   bool Unsigned = false;
13086   bool Swap = false;
13087   unsigned SSECC;
13088   switch (SetCCOpcode) {
13089   default: llvm_unreachable("Unexpected SETCC condition");
13090   case ISD::SETNE:  SSECC = 4; break;
13091   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
13092   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
13093   case ISD::SETLT:  Swap = true; //fall-through
13094   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
13095   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
13096   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
13097   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
13098   case ISD::SETULE: Unsigned = true; //fall-through
13099   case ISD::SETLE:  SSECC = 2; break;
13100   }
13101
13102   if (Swap)
13103     std::swap(Op0, Op1);
13104   if (Opc)
13105     return DAG.getNode(Opc, dl, VT, Op0, Op1);
13106   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
13107   return DAG.getNode(Opc, dl, VT, Op0, Op1,
13108                      DAG.getConstant(SSECC, MVT::i8));
13109 }
13110
13111 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
13112 /// operand \p Op1.  If non-trivial (for example because it's not constant)
13113 /// return an empty value.
13114 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
13115 {
13116   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
13117   if (!BV)
13118     return SDValue();
13119
13120   MVT VT = Op1.getSimpleValueType();
13121   MVT EVT = VT.getVectorElementType();
13122   unsigned n = VT.getVectorNumElements();
13123   SmallVector<SDValue, 8> ULTOp1;
13124
13125   for (unsigned i = 0; i < n; ++i) {
13126     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
13127     if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
13128       return SDValue();
13129
13130     // Avoid underflow.
13131     APInt Val = Elt->getAPIntValue();
13132     if (Val == 0)
13133       return SDValue();
13134
13135     ULTOp1.push_back(DAG.getConstant(Val - 1, EVT));
13136   }
13137
13138   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
13139 }
13140
13141 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
13142                            SelectionDAG &DAG) {
13143   SDValue Op0 = Op.getOperand(0);
13144   SDValue Op1 = Op.getOperand(1);
13145   SDValue CC = Op.getOperand(2);
13146   MVT VT = Op.getSimpleValueType();
13147   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13148   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
13149   SDLoc dl(Op);
13150
13151   if (isFP) {
13152 #ifndef NDEBUG
13153     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
13154     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
13155 #endif
13156
13157     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
13158     unsigned Opc = X86ISD::CMPP;
13159     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
13160       assert(VT.getVectorNumElements() <= 16);
13161       Opc = X86ISD::CMPM;
13162     }
13163     // In the two special cases we can't handle, emit two comparisons.
13164     if (SSECC == 8) {
13165       unsigned CC0, CC1;
13166       unsigned CombineOpc;
13167       if (SetCCOpcode == ISD::SETUEQ) {
13168         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
13169       } else {
13170         assert(SetCCOpcode == ISD::SETONE);
13171         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
13172       }
13173
13174       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13175                                  DAG.getConstant(CC0, MVT::i8));
13176       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13177                                  DAG.getConstant(CC1, MVT::i8));
13178       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
13179     }
13180     // Handle all other FP comparisons here.
13181     return DAG.getNode(Opc, dl, VT, Op0, Op1,
13182                        DAG.getConstant(SSECC, MVT::i8));
13183   }
13184
13185   // Break 256-bit integer vector compare into smaller ones.
13186   if (VT.is256BitVector() && !Subtarget->hasInt256())
13187     return Lower256IntVSETCC(Op, DAG);
13188
13189   EVT OpVT = Op1.getValueType();
13190   if (OpVT.getVectorElementType() == MVT::i1)
13191     return LowerBoolVSETCC_AVX512(Op, DAG);
13192
13193   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
13194   if (Subtarget->hasAVX512()) {
13195     if (Op1.getValueType().is512BitVector() ||
13196         (Subtarget->hasBWI() && Subtarget->hasVLX()) ||
13197         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
13198       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
13199
13200     // In AVX-512 architecture setcc returns mask with i1 elements,
13201     // But there is no compare instruction for i8 and i16 elements in KNL.
13202     // We are not talking about 512-bit operands in this case, these
13203     // types are illegal.
13204     if (MaskResult &&
13205         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
13206          OpVT.getVectorElementType().getSizeInBits() >= 8))
13207       return DAG.getNode(ISD::TRUNCATE, dl, VT,
13208                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
13209   }
13210
13211   // We are handling one of the integer comparisons here.  Since SSE only has
13212   // GT and EQ comparisons for integer, swapping operands and multiple
13213   // operations may be required for some comparisons.
13214   unsigned Opc;
13215   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
13216   bool Subus = false;
13217
13218   switch (SetCCOpcode) {
13219   default: llvm_unreachable("Unexpected SETCC condition");
13220   case ISD::SETNE:  Invert = true;
13221   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
13222   case ISD::SETLT:  Swap = true;
13223   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
13224   case ISD::SETGE:  Swap = true;
13225   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
13226                     Invert = true; break;
13227   case ISD::SETULT: Swap = true;
13228   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
13229                     FlipSigns = true; break;
13230   case ISD::SETUGE: Swap = true;
13231   case ISD::SETULE: Opc = X86ISD::PCMPGT;
13232                     FlipSigns = true; Invert = true; break;
13233   }
13234
13235   // Special case: Use min/max operations for SETULE/SETUGE
13236   MVT VET = VT.getVectorElementType();
13237   bool hasMinMax =
13238        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
13239     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
13240
13241   if (hasMinMax) {
13242     switch (SetCCOpcode) {
13243     default: break;
13244     case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
13245     case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
13246     }
13247
13248     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
13249   }
13250
13251   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
13252   if (!MinMax && hasSubus) {
13253     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
13254     // Op0 u<= Op1:
13255     //   t = psubus Op0, Op1
13256     //   pcmpeq t, <0..0>
13257     switch (SetCCOpcode) {
13258     default: break;
13259     case ISD::SETULT: {
13260       // If the comparison is against a constant we can turn this into a
13261       // setule.  With psubus, setule does not require a swap.  This is
13262       // beneficial because the constant in the register is no longer
13263       // destructed as the destination so it can be hoisted out of a loop.
13264       // Only do this pre-AVX since vpcmp* is no longer destructive.
13265       if (Subtarget->hasAVX())
13266         break;
13267       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
13268       if (ULEOp1.getNode()) {
13269         Op1 = ULEOp1;
13270         Subus = true; Invert = false; Swap = false;
13271       }
13272       break;
13273     }
13274     // Psubus is better than flip-sign because it requires no inversion.
13275     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
13276     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
13277     }
13278
13279     if (Subus) {
13280       Opc = X86ISD::SUBUS;
13281       FlipSigns = false;
13282     }
13283   }
13284
13285   if (Swap)
13286     std::swap(Op0, Op1);
13287
13288   // Check that the operation in question is available (most are plain SSE2,
13289   // but PCMPGTQ and PCMPEQQ have different requirements).
13290   if (VT == MVT::v2i64) {
13291     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
13292       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
13293
13294       // First cast everything to the right type.
13295       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
13296       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
13297
13298       // Since SSE has no unsigned integer comparisons, we need to flip the sign
13299       // bits of the inputs before performing those operations. The lower
13300       // compare is always unsigned.
13301       SDValue SB;
13302       if (FlipSigns) {
13303         SB = DAG.getConstant(0x80000000U, MVT::v4i32);
13304       } else {
13305         SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
13306         SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
13307         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
13308                          Sign, Zero, Sign, Zero);
13309       }
13310       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
13311       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
13312
13313       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
13314       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
13315       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
13316
13317       // Create masks for only the low parts/high parts of the 64 bit integers.
13318       static const int MaskHi[] = { 1, 1, 3, 3 };
13319       static const int MaskLo[] = { 0, 0, 2, 2 };
13320       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
13321       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
13322       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
13323
13324       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
13325       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
13326
13327       if (Invert)
13328         Result = DAG.getNOT(dl, Result, MVT::v4i32);
13329
13330       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
13331     }
13332
13333     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
13334       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
13335       // pcmpeqd + pshufd + pand.
13336       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
13337
13338       // First cast everything to the right type.
13339       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
13340       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
13341
13342       // Do the compare.
13343       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
13344
13345       // Make sure the lower and upper halves are both all-ones.
13346       static const int Mask[] = { 1, 0, 3, 2 };
13347       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
13348       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
13349
13350       if (Invert)
13351         Result = DAG.getNOT(dl, Result, MVT::v4i32);
13352
13353       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
13354     }
13355   }
13356
13357   // Since SSE has no unsigned integer comparisons, we need to flip the sign
13358   // bits of the inputs before performing those operations.
13359   if (FlipSigns) {
13360     EVT EltVT = VT.getVectorElementType();
13361     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
13362     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
13363     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
13364   }
13365
13366   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
13367
13368   // If the logical-not of the result is required, perform that now.
13369   if (Invert)
13370     Result = DAG.getNOT(dl, Result, VT);
13371
13372   if (MinMax)
13373     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
13374
13375   if (Subus)
13376     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
13377                          getZeroVector(VT, Subtarget, DAG, dl));
13378
13379   return Result;
13380 }
13381
13382 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
13383
13384   MVT VT = Op.getSimpleValueType();
13385
13386   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
13387
13388   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
13389          && "SetCC type must be 8-bit or 1-bit integer");
13390   SDValue Op0 = Op.getOperand(0);
13391   SDValue Op1 = Op.getOperand(1);
13392   SDLoc dl(Op);
13393   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
13394
13395   // Optimize to BT if possible.
13396   // Lower (X & (1 << N)) == 0 to BT(X, N).
13397   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
13398   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
13399   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
13400       Op1.getOpcode() == ISD::Constant &&
13401       cast<ConstantSDNode>(Op1)->isNullValue() &&
13402       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13403     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
13404     if (NewSetCC.getNode()) {
13405       if (VT == MVT::i1)
13406         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewSetCC);
13407       return NewSetCC;
13408     }
13409   }
13410
13411   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
13412   // these.
13413   if (Op1.getOpcode() == ISD::Constant &&
13414       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
13415        cast<ConstantSDNode>(Op1)->isNullValue()) &&
13416       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13417
13418     // If the input is a setcc, then reuse the input setcc or use a new one with
13419     // the inverted condition.
13420     if (Op0.getOpcode() == X86ISD::SETCC) {
13421       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
13422       bool Invert = (CC == ISD::SETNE) ^
13423         cast<ConstantSDNode>(Op1)->isNullValue();
13424       if (!Invert)
13425         return Op0;
13426
13427       CCode = X86::GetOppositeBranchCondition(CCode);
13428       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13429                                   DAG.getConstant(CCode, MVT::i8),
13430                                   Op0.getOperand(1));
13431       if (VT == MVT::i1)
13432         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13433       return SetCC;
13434     }
13435   }
13436   if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
13437       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
13438       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13439
13440     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
13441     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, MVT::i1), NewCC);
13442   }
13443
13444   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
13445   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
13446   if (X86CC == X86::COND_INVALID)
13447     return SDValue();
13448
13449   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
13450   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
13451   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13452                               DAG.getConstant(X86CC, MVT::i8), EFLAGS);
13453   if (VT == MVT::i1)
13454     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13455   return SetCC;
13456 }
13457
13458 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
13459 static bool isX86LogicalCmp(SDValue Op) {
13460   unsigned Opc = Op.getNode()->getOpcode();
13461   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
13462       Opc == X86ISD::SAHF)
13463     return true;
13464   if (Op.getResNo() == 1 &&
13465       (Opc == X86ISD::ADD ||
13466        Opc == X86ISD::SUB ||
13467        Opc == X86ISD::ADC ||
13468        Opc == X86ISD::SBB ||
13469        Opc == X86ISD::SMUL ||
13470        Opc == X86ISD::UMUL ||
13471        Opc == X86ISD::INC ||
13472        Opc == X86ISD::DEC ||
13473        Opc == X86ISD::OR ||
13474        Opc == X86ISD::XOR ||
13475        Opc == X86ISD::AND))
13476     return true;
13477
13478   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
13479     return true;
13480
13481   return false;
13482 }
13483
13484 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
13485   if (V.getOpcode() != ISD::TRUNCATE)
13486     return false;
13487
13488   SDValue VOp0 = V.getOperand(0);
13489   unsigned InBits = VOp0.getValueSizeInBits();
13490   unsigned Bits = V.getValueSizeInBits();
13491   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
13492 }
13493
13494 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
13495   bool addTest = true;
13496   SDValue Cond  = Op.getOperand(0);
13497   SDValue Op1 = Op.getOperand(1);
13498   SDValue Op2 = Op.getOperand(2);
13499   SDLoc DL(Op);
13500   EVT VT = Op1.getValueType();
13501   SDValue CC;
13502
13503   // Lower FP selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
13504   // are available or VBLENDV if AVX is available.
13505   // Otherwise FP cmovs get lowered into a less efficient branch sequence later.
13506   if (Cond.getOpcode() == ISD::SETCC &&
13507       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
13508        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
13509       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
13510     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
13511     int SSECC = translateX86FSETCC(
13512         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
13513
13514     if (SSECC != 8) {
13515       if (Subtarget->hasAVX512()) {
13516         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
13517                                   DAG.getConstant(SSECC, MVT::i8));
13518         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
13519       }
13520
13521       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
13522                                 DAG.getConstant(SSECC, MVT::i8));
13523
13524       // If we have AVX, we can use a variable vector select (VBLENDV) instead
13525       // of 3 logic instructions for size savings and potentially speed.
13526       // Unfortunately, there is no scalar form of VBLENDV.
13527
13528       // If either operand is a constant, don't try this. We can expect to
13529       // optimize away at least one of the logic instructions later in that
13530       // case, so that sequence would be faster than a variable blend.
13531
13532       // BLENDV was introduced with SSE 4.1, but the 2 register form implicitly
13533       // uses XMM0 as the selection register. That may need just as many
13534       // instructions as the AND/ANDN/OR sequence due to register moves, so
13535       // don't bother.
13536
13537       if (Subtarget->hasAVX() &&
13538           !isa<ConstantFPSDNode>(Op1) && !isa<ConstantFPSDNode>(Op2)) {
13539
13540         // Convert to vectors, do a VSELECT, and convert back to scalar.
13541         // All of the conversions should be optimized away.
13542
13543         EVT VecVT = VT == MVT::f32 ? MVT::v4f32 : MVT::v2f64;
13544         SDValue VOp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op1);
13545         SDValue VOp2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op2);
13546         SDValue VCmp = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Cmp);
13547
13548         EVT VCmpVT = VT == MVT::f32 ? MVT::v4i32 : MVT::v2i64;
13549         VCmp = DAG.getNode(ISD::BITCAST, DL, VCmpVT, VCmp);
13550
13551         SDValue VSel = DAG.getNode(ISD::VSELECT, DL, VecVT, VCmp, VOp1, VOp2);
13552
13553         return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
13554                            VSel, DAG.getIntPtrConstant(0));
13555       }
13556       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
13557       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
13558       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
13559     }
13560   }
13561
13562   if (Cond.getOpcode() == ISD::SETCC) {
13563     SDValue NewCond = LowerSETCC(Cond, DAG);
13564     if (NewCond.getNode())
13565       Cond = NewCond;
13566   }
13567
13568   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
13569   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
13570   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
13571   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
13572   if (Cond.getOpcode() == X86ISD::SETCC &&
13573       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
13574       isZero(Cond.getOperand(1).getOperand(1))) {
13575     SDValue Cmp = Cond.getOperand(1);
13576
13577     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
13578
13579     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
13580         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
13581       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
13582
13583       SDValue CmpOp0 = Cmp.getOperand(0);
13584       // Apply further optimizations for special cases
13585       // (select (x != 0), -1, 0) -> neg & sbb
13586       // (select (x == 0), 0, -1) -> neg & sbb
13587       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
13588         if (YC->isNullValue() &&
13589             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
13590           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
13591           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
13592                                     DAG.getConstant(0, CmpOp0.getValueType()),
13593                                     CmpOp0);
13594           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13595                                     DAG.getConstant(X86::COND_B, MVT::i8),
13596                                     SDValue(Neg.getNode(), 1));
13597           return Res;
13598         }
13599
13600       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
13601                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
13602       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
13603
13604       SDValue Res =   // Res = 0 or -1.
13605         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13606                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
13607
13608       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
13609         Res = DAG.getNOT(DL, Res, Res.getValueType());
13610
13611       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
13612       if (!N2C || !N2C->isNullValue())
13613         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
13614       return Res;
13615     }
13616   }
13617
13618   // Look past (and (setcc_carry (cmp ...)), 1).
13619   if (Cond.getOpcode() == ISD::AND &&
13620       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
13621     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
13622     if (C && C->getAPIntValue() == 1)
13623       Cond = Cond.getOperand(0);
13624   }
13625
13626   // If condition flag is set by a X86ISD::CMP, then use it as the condition
13627   // setting operand in place of the X86ISD::SETCC.
13628   unsigned CondOpcode = Cond.getOpcode();
13629   if (CondOpcode == X86ISD::SETCC ||
13630       CondOpcode == X86ISD::SETCC_CARRY) {
13631     CC = Cond.getOperand(0);
13632
13633     SDValue Cmp = Cond.getOperand(1);
13634     unsigned Opc = Cmp.getOpcode();
13635     MVT VT = Op.getSimpleValueType();
13636
13637     bool IllegalFPCMov = false;
13638     if (VT.isFloatingPoint() && !VT.isVector() &&
13639         !isScalarFPTypeInSSEReg(VT))  // FPStack?
13640       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
13641
13642     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
13643         Opc == X86ISD::BT) { // FIXME
13644       Cond = Cmp;
13645       addTest = false;
13646     }
13647   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
13648              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
13649              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
13650               Cond.getOperand(0).getValueType() != MVT::i8)) {
13651     SDValue LHS = Cond.getOperand(0);
13652     SDValue RHS = Cond.getOperand(1);
13653     unsigned X86Opcode;
13654     unsigned X86Cond;
13655     SDVTList VTs;
13656     switch (CondOpcode) {
13657     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
13658     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
13659     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
13660     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
13661     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
13662     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
13663     default: llvm_unreachable("unexpected overflowing operator");
13664     }
13665     if (CondOpcode == ISD::UMULO)
13666       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
13667                           MVT::i32);
13668     else
13669       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
13670
13671     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
13672
13673     if (CondOpcode == ISD::UMULO)
13674       Cond = X86Op.getValue(2);
13675     else
13676       Cond = X86Op.getValue(1);
13677
13678     CC = DAG.getConstant(X86Cond, MVT::i8);
13679     addTest = false;
13680   }
13681
13682   if (addTest) {
13683     // Look pass the truncate if the high bits are known zero.
13684     if (isTruncWithZeroHighBitsInput(Cond, DAG))
13685         Cond = Cond.getOperand(0);
13686
13687     // We know the result of AND is compared against zero. Try to match
13688     // it to BT.
13689     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
13690       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
13691       if (NewSetCC.getNode()) {
13692         CC = NewSetCC.getOperand(0);
13693         Cond = NewSetCC.getOperand(1);
13694         addTest = false;
13695       }
13696     }
13697   }
13698
13699   if (addTest) {
13700     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
13701     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
13702   }
13703
13704   // a <  b ? -1 :  0 -> RES = ~setcc_carry
13705   // a <  b ?  0 : -1 -> RES = setcc_carry
13706   // a >= b ? -1 :  0 -> RES = setcc_carry
13707   // a >= b ?  0 : -1 -> RES = ~setcc_carry
13708   if (Cond.getOpcode() == X86ISD::SUB) {
13709     Cond = ConvertCmpIfNecessary(Cond, DAG);
13710     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
13711
13712     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
13713         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
13714       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13715                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
13716       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
13717         return DAG.getNOT(DL, Res, Res.getValueType());
13718       return Res;
13719     }
13720   }
13721
13722   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
13723   // widen the cmov and push the truncate through. This avoids introducing a new
13724   // branch during isel and doesn't add any extensions.
13725   if (Op.getValueType() == MVT::i8 &&
13726       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
13727     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
13728     if (T1.getValueType() == T2.getValueType() &&
13729         // Blacklist CopyFromReg to avoid partial register stalls.
13730         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
13731       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
13732       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
13733       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
13734     }
13735   }
13736
13737   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
13738   // condition is true.
13739   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
13740   SDValue Ops[] = { Op2, Op1, CC, Cond };
13741   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
13742 }
13743
13744 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, const X86Subtarget *Subtarget,
13745                                        SelectionDAG &DAG) {
13746   MVT VT = Op->getSimpleValueType(0);
13747   SDValue In = Op->getOperand(0);
13748   MVT InVT = In.getSimpleValueType();
13749   MVT VTElt = VT.getVectorElementType();
13750   MVT InVTElt = InVT.getVectorElementType();
13751   SDLoc dl(Op);
13752
13753   // SKX processor
13754   if ((InVTElt == MVT::i1) &&
13755       (((Subtarget->hasBWI() && Subtarget->hasVLX() &&
13756         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() <= 16)) ||
13757
13758        ((Subtarget->hasBWI() && VT.is512BitVector() &&
13759         VTElt.getSizeInBits() <= 16)) ||
13760
13761        ((Subtarget->hasDQI() && Subtarget->hasVLX() &&
13762         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() >= 32)) ||
13763
13764        ((Subtarget->hasDQI() && VT.is512BitVector() &&
13765         VTElt.getSizeInBits() >= 32))))
13766     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13767
13768   unsigned int NumElts = VT.getVectorNumElements();
13769
13770   if (NumElts != 8 && NumElts != 16)
13771     return SDValue();
13772
13773   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1) {
13774     if (In.getOpcode() == X86ISD::VSEXT || In.getOpcode() == X86ISD::VZEXT)
13775       return DAG.getNode(In.getOpcode(), dl, VT, In.getOperand(0));
13776     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13777   }
13778
13779   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13780   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
13781
13782   MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
13783   Constant *C = ConstantInt::get(*DAG.getContext(),
13784     APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
13785
13786   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
13787   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
13788   SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
13789                           MachinePointerInfo::getConstantPool(),
13790                           false, false, false, Alignment);
13791   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
13792   if (VT.is512BitVector())
13793     return Brcst;
13794   return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
13795 }
13796
13797 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
13798                                 SelectionDAG &DAG) {
13799   MVT VT = Op->getSimpleValueType(0);
13800   SDValue In = Op->getOperand(0);
13801   MVT InVT = In.getSimpleValueType();
13802   SDLoc dl(Op);
13803
13804   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
13805     return LowerSIGN_EXTEND_AVX512(Op, Subtarget, DAG);
13806
13807   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
13808       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
13809       (VT != MVT::v16i16 || InVT != MVT::v16i8))
13810     return SDValue();
13811
13812   if (Subtarget->hasInt256())
13813     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13814
13815   // Optimize vectors in AVX mode
13816   // Sign extend  v8i16 to v8i32 and
13817   //              v4i32 to v4i64
13818   //
13819   // Divide input vector into two parts
13820   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
13821   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
13822   // concat the vectors to original VT
13823
13824   unsigned NumElems = InVT.getVectorNumElements();
13825   SDValue Undef = DAG.getUNDEF(InVT);
13826
13827   SmallVector<int,8> ShufMask1(NumElems, -1);
13828   for (unsigned i = 0; i != NumElems/2; ++i)
13829     ShufMask1[i] = i;
13830
13831   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
13832
13833   SmallVector<int,8> ShufMask2(NumElems, -1);
13834   for (unsigned i = 0; i != NumElems/2; ++i)
13835     ShufMask2[i] = i + NumElems/2;
13836
13837   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
13838
13839   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
13840                                 VT.getVectorNumElements()/2);
13841
13842   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
13843   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
13844
13845   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
13846 }
13847
13848 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
13849 // may emit an illegal shuffle but the expansion is still better than scalar
13850 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
13851 // we'll emit a shuffle and a arithmetic shift.
13852 // FIXME: Is the expansion actually better than scalar code? It doesn't seem so.
13853 // TODO: It is possible to support ZExt by zeroing the undef values during
13854 // the shuffle phase or after the shuffle.
13855 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
13856                                  SelectionDAG &DAG) {
13857   MVT RegVT = Op.getSimpleValueType();
13858   assert(RegVT.isVector() && "We only custom lower vector sext loads.");
13859   assert(RegVT.isInteger() &&
13860          "We only custom lower integer vector sext loads.");
13861
13862   // Nothing useful we can do without SSE2 shuffles.
13863   assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
13864
13865   LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
13866   SDLoc dl(Ld);
13867   EVT MemVT = Ld->getMemoryVT();
13868   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13869   unsigned RegSz = RegVT.getSizeInBits();
13870
13871   ISD::LoadExtType Ext = Ld->getExtensionType();
13872
13873   assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
13874          && "Only anyext and sext are currently implemented.");
13875   assert(MemVT != RegVT && "Cannot extend to the same type");
13876   assert(MemVT.isVector() && "Must load a vector from memory");
13877
13878   unsigned NumElems = RegVT.getVectorNumElements();
13879   unsigned MemSz = MemVT.getSizeInBits();
13880   assert(RegSz > MemSz && "Register size must be greater than the mem size");
13881
13882   if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
13883     // The only way in which we have a legal 256-bit vector result but not the
13884     // integer 256-bit operations needed to directly lower a sextload is if we
13885     // have AVX1 but not AVX2. In that case, we can always emit a sextload to
13886     // a 128-bit vector and a normal sign_extend to 256-bits that should get
13887     // correctly legalized. We do this late to allow the canonical form of
13888     // sextload to persist throughout the rest of the DAG combiner -- it wants
13889     // to fold together any extensions it can, and so will fuse a sign_extend
13890     // of an sextload into a sextload targeting a wider value.
13891     SDValue Load;
13892     if (MemSz == 128) {
13893       // Just switch this to a normal load.
13894       assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
13895                                        "it must be a legal 128-bit vector "
13896                                        "type!");
13897       Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
13898                   Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
13899                   Ld->isInvariant(), Ld->getAlignment());
13900     } else {
13901       assert(MemSz < 128 &&
13902              "Can't extend a type wider than 128 bits to a 256 bit vector!");
13903       // Do an sext load to a 128-bit vector type. We want to use the same
13904       // number of elements, but elements half as wide. This will end up being
13905       // recursively lowered by this routine, but will succeed as we definitely
13906       // have all the necessary features if we're using AVX1.
13907       EVT HalfEltVT =
13908           EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
13909       EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
13910       Load =
13911           DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
13912                          Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
13913                          Ld->isNonTemporal(), Ld->isInvariant(),
13914                          Ld->getAlignment());
13915     }
13916
13917     // Replace chain users with the new chain.
13918     assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
13919     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
13920
13921     // Finally, do a normal sign-extend to the desired register.
13922     return DAG.getSExtOrTrunc(Load, dl, RegVT);
13923   }
13924
13925   // All sizes must be a power of two.
13926   assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
13927          "Non-power-of-two elements are not custom lowered!");
13928
13929   // Attempt to load the original value using scalar loads.
13930   // Find the largest scalar type that divides the total loaded size.
13931   MVT SclrLoadTy = MVT::i8;
13932   for (MVT Tp : MVT::integer_valuetypes()) {
13933     if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
13934       SclrLoadTy = Tp;
13935     }
13936   }
13937
13938   // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
13939   if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
13940       (64 <= MemSz))
13941     SclrLoadTy = MVT::f64;
13942
13943   // Calculate the number of scalar loads that we need to perform
13944   // in order to load our vector from memory.
13945   unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
13946
13947   assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
13948          "Can only lower sext loads with a single scalar load!");
13949
13950   unsigned loadRegZize = RegSz;
13951   if (Ext == ISD::SEXTLOAD && RegSz == 256)
13952     loadRegZize /= 2;
13953
13954   // Represent our vector as a sequence of elements which are the
13955   // largest scalar that we can load.
13956   EVT LoadUnitVecVT = EVT::getVectorVT(
13957       *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
13958
13959   // Represent the data using the same element type that is stored in
13960   // memory. In practice, we ''widen'' MemVT.
13961   EVT WideVecVT =
13962       EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
13963                        loadRegZize / MemVT.getScalarType().getSizeInBits());
13964
13965   assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
13966          "Invalid vector type");
13967
13968   // We can't shuffle using an illegal type.
13969   assert(TLI.isTypeLegal(WideVecVT) &&
13970          "We only lower types that form legal widened vector types");
13971
13972   SmallVector<SDValue, 8> Chains;
13973   SDValue Ptr = Ld->getBasePtr();
13974   SDValue Increment =
13975       DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, TLI.getPointerTy());
13976   SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
13977
13978   for (unsigned i = 0; i < NumLoads; ++i) {
13979     // Perform a single load.
13980     SDValue ScalarLoad =
13981         DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
13982                     Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
13983                     Ld->getAlignment());
13984     Chains.push_back(ScalarLoad.getValue(1));
13985     // Create the first element type using SCALAR_TO_VECTOR in order to avoid
13986     // another round of DAGCombining.
13987     if (i == 0)
13988       Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
13989     else
13990       Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
13991                         ScalarLoad, DAG.getIntPtrConstant(i));
13992
13993     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
13994   }
13995
13996   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
13997
13998   // Bitcast the loaded value to a vector of the original element type, in
13999   // the size of the target vector type.
14000   SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
14001   unsigned SizeRatio = RegSz / MemSz;
14002
14003   if (Ext == ISD::SEXTLOAD) {
14004     // If we have SSE4.1, we can directly emit a VSEXT node.
14005     if (Subtarget->hasSSE41()) {
14006       SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
14007       DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14008       return Sext;
14009     }
14010
14011     // Otherwise we'll shuffle the small elements in the high bits of the
14012     // larger type and perform an arithmetic shift. If the shift is not legal
14013     // it's better to scalarize.
14014     assert(TLI.isOperationLegalOrCustom(ISD::SRA, RegVT) &&
14015            "We can't implement a sext load without an arithmetic right shift!");
14016
14017     // Redistribute the loaded elements into the different locations.
14018     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
14019     for (unsigned i = 0; i != NumElems; ++i)
14020       ShuffleVec[i * SizeRatio + SizeRatio - 1] = i;
14021
14022     SDValue Shuff = DAG.getVectorShuffle(
14023         WideVecVT, dl, SlicedVec, DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
14024
14025     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
14026
14027     // Build the arithmetic shift.
14028     unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
14029                    MemVT.getVectorElementType().getSizeInBits();
14030     Shuff =
14031         DAG.getNode(ISD::SRA, dl, RegVT, Shuff, DAG.getConstant(Amt, RegVT));
14032
14033     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14034     return Shuff;
14035   }
14036
14037   // Redistribute the loaded elements into the different locations.
14038   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
14039   for (unsigned i = 0; i != NumElems; ++i)
14040     ShuffleVec[i * SizeRatio] = i;
14041
14042   SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
14043                                        DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
14044
14045   // Bitcast to the requested type.
14046   Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
14047   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14048   return Shuff;
14049 }
14050
14051 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
14052 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
14053 // from the AND / OR.
14054 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
14055   Opc = Op.getOpcode();
14056   if (Opc != ISD::OR && Opc != ISD::AND)
14057     return false;
14058   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
14059           Op.getOperand(0).hasOneUse() &&
14060           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
14061           Op.getOperand(1).hasOneUse());
14062 }
14063
14064 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
14065 // 1 and that the SETCC node has a single use.
14066 static bool isXor1OfSetCC(SDValue Op) {
14067   if (Op.getOpcode() != ISD::XOR)
14068     return false;
14069   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
14070   if (N1C && N1C->getAPIntValue() == 1) {
14071     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
14072       Op.getOperand(0).hasOneUse();
14073   }
14074   return false;
14075 }
14076
14077 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
14078   bool addTest = true;
14079   SDValue Chain = Op.getOperand(0);
14080   SDValue Cond  = Op.getOperand(1);
14081   SDValue Dest  = Op.getOperand(2);
14082   SDLoc dl(Op);
14083   SDValue CC;
14084   bool Inverted = false;
14085
14086   if (Cond.getOpcode() == ISD::SETCC) {
14087     // Check for setcc([su]{add,sub,mul}o == 0).
14088     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
14089         isa<ConstantSDNode>(Cond.getOperand(1)) &&
14090         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
14091         Cond.getOperand(0).getResNo() == 1 &&
14092         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
14093          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
14094          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
14095          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
14096          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
14097          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
14098       Inverted = true;
14099       Cond = Cond.getOperand(0);
14100     } else {
14101       SDValue NewCond = LowerSETCC(Cond, DAG);
14102       if (NewCond.getNode())
14103         Cond = NewCond;
14104     }
14105   }
14106 #if 0
14107   // FIXME: LowerXALUO doesn't handle these!!
14108   else if (Cond.getOpcode() == X86ISD::ADD  ||
14109            Cond.getOpcode() == X86ISD::SUB  ||
14110            Cond.getOpcode() == X86ISD::SMUL ||
14111            Cond.getOpcode() == X86ISD::UMUL)
14112     Cond = LowerXALUO(Cond, DAG);
14113 #endif
14114
14115   // Look pass (and (setcc_carry (cmp ...)), 1).
14116   if (Cond.getOpcode() == ISD::AND &&
14117       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
14118     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
14119     if (C && C->getAPIntValue() == 1)
14120       Cond = Cond.getOperand(0);
14121   }
14122
14123   // If condition flag is set by a X86ISD::CMP, then use it as the condition
14124   // setting operand in place of the X86ISD::SETCC.
14125   unsigned CondOpcode = Cond.getOpcode();
14126   if (CondOpcode == X86ISD::SETCC ||
14127       CondOpcode == X86ISD::SETCC_CARRY) {
14128     CC = Cond.getOperand(0);
14129
14130     SDValue Cmp = Cond.getOperand(1);
14131     unsigned Opc = Cmp.getOpcode();
14132     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
14133     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
14134       Cond = Cmp;
14135       addTest = false;
14136     } else {
14137       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
14138       default: break;
14139       case X86::COND_O:
14140       case X86::COND_B:
14141         // These can only come from an arithmetic instruction with overflow,
14142         // e.g. SADDO, UADDO.
14143         Cond = Cond.getNode()->getOperand(1);
14144         addTest = false;
14145         break;
14146       }
14147     }
14148   }
14149   CondOpcode = Cond.getOpcode();
14150   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
14151       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
14152       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
14153        Cond.getOperand(0).getValueType() != MVT::i8)) {
14154     SDValue LHS = Cond.getOperand(0);
14155     SDValue RHS = Cond.getOperand(1);
14156     unsigned X86Opcode;
14157     unsigned X86Cond;
14158     SDVTList VTs;
14159     // Keep this in sync with LowerXALUO, otherwise we might create redundant
14160     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
14161     // X86ISD::INC).
14162     switch (CondOpcode) {
14163     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
14164     case ISD::SADDO:
14165       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14166         if (C->isOne()) {
14167           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
14168           break;
14169         }
14170       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
14171     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
14172     case ISD::SSUBO:
14173       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14174         if (C->isOne()) {
14175           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
14176           break;
14177         }
14178       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
14179     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
14180     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
14181     default: llvm_unreachable("unexpected overflowing operator");
14182     }
14183     if (Inverted)
14184       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
14185     if (CondOpcode == ISD::UMULO)
14186       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
14187                           MVT::i32);
14188     else
14189       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14190
14191     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
14192
14193     if (CondOpcode == ISD::UMULO)
14194       Cond = X86Op.getValue(2);
14195     else
14196       Cond = X86Op.getValue(1);
14197
14198     CC = DAG.getConstant(X86Cond, MVT::i8);
14199     addTest = false;
14200   } else {
14201     unsigned CondOpc;
14202     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
14203       SDValue Cmp = Cond.getOperand(0).getOperand(1);
14204       if (CondOpc == ISD::OR) {
14205         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
14206         // two branches instead of an explicit OR instruction with a
14207         // separate test.
14208         if (Cmp == Cond.getOperand(1).getOperand(1) &&
14209             isX86LogicalCmp(Cmp)) {
14210           CC = Cond.getOperand(0).getOperand(0);
14211           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14212                               Chain, Dest, CC, Cmp);
14213           CC = Cond.getOperand(1).getOperand(0);
14214           Cond = Cmp;
14215           addTest = false;
14216         }
14217       } else { // ISD::AND
14218         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
14219         // two branches instead of an explicit AND instruction with a
14220         // separate test. However, we only do this if this block doesn't
14221         // have a fall-through edge, because this requires an explicit
14222         // jmp when the condition is false.
14223         if (Cmp == Cond.getOperand(1).getOperand(1) &&
14224             isX86LogicalCmp(Cmp) &&
14225             Op.getNode()->hasOneUse()) {
14226           X86::CondCode CCode =
14227             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
14228           CCode = X86::GetOppositeBranchCondition(CCode);
14229           CC = DAG.getConstant(CCode, MVT::i8);
14230           SDNode *User = *Op.getNode()->use_begin();
14231           // Look for an unconditional branch following this conditional branch.
14232           // We need this because we need to reverse the successors in order
14233           // to implement FCMP_OEQ.
14234           if (User->getOpcode() == ISD::BR) {
14235             SDValue FalseBB = User->getOperand(1);
14236             SDNode *NewBR =
14237               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14238             assert(NewBR == User);
14239             (void)NewBR;
14240             Dest = FalseBB;
14241
14242             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14243                                 Chain, Dest, CC, Cmp);
14244             X86::CondCode CCode =
14245               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
14246             CCode = X86::GetOppositeBranchCondition(CCode);
14247             CC = DAG.getConstant(CCode, MVT::i8);
14248             Cond = Cmp;
14249             addTest = false;
14250           }
14251         }
14252       }
14253     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
14254       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
14255       // It should be transformed during dag combiner except when the condition
14256       // is set by a arithmetics with overflow node.
14257       X86::CondCode CCode =
14258         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
14259       CCode = X86::GetOppositeBranchCondition(CCode);
14260       CC = DAG.getConstant(CCode, MVT::i8);
14261       Cond = Cond.getOperand(0).getOperand(1);
14262       addTest = false;
14263     } else if (Cond.getOpcode() == ISD::SETCC &&
14264                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
14265       // For FCMP_OEQ, we can emit
14266       // two branches instead of an explicit AND instruction with a
14267       // separate test. However, we only do this if this block doesn't
14268       // have a fall-through edge, because this requires an explicit
14269       // jmp when the condition is false.
14270       if (Op.getNode()->hasOneUse()) {
14271         SDNode *User = *Op.getNode()->use_begin();
14272         // Look for an unconditional branch following this conditional branch.
14273         // We need this because we need to reverse the successors in order
14274         // to implement FCMP_OEQ.
14275         if (User->getOpcode() == ISD::BR) {
14276           SDValue FalseBB = User->getOperand(1);
14277           SDNode *NewBR =
14278             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14279           assert(NewBR == User);
14280           (void)NewBR;
14281           Dest = FalseBB;
14282
14283           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14284                                     Cond.getOperand(0), Cond.getOperand(1));
14285           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14286           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
14287           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14288                               Chain, Dest, CC, Cmp);
14289           CC = DAG.getConstant(X86::COND_P, MVT::i8);
14290           Cond = Cmp;
14291           addTest = false;
14292         }
14293       }
14294     } else if (Cond.getOpcode() == ISD::SETCC &&
14295                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
14296       // For FCMP_UNE, we can emit
14297       // two branches instead of an explicit AND instruction with a
14298       // separate test. However, we only do this if this block doesn't
14299       // have a fall-through edge, because this requires an explicit
14300       // jmp when the condition is false.
14301       if (Op.getNode()->hasOneUse()) {
14302         SDNode *User = *Op.getNode()->use_begin();
14303         // Look for an unconditional branch following this conditional branch.
14304         // We need this because we need to reverse the successors in order
14305         // to implement FCMP_UNE.
14306         if (User->getOpcode() == ISD::BR) {
14307           SDValue FalseBB = User->getOperand(1);
14308           SDNode *NewBR =
14309             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14310           assert(NewBR == User);
14311           (void)NewBR;
14312
14313           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14314                                     Cond.getOperand(0), Cond.getOperand(1));
14315           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14316           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
14317           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14318                               Chain, Dest, CC, Cmp);
14319           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
14320           Cond = Cmp;
14321           addTest = false;
14322           Dest = FalseBB;
14323         }
14324       }
14325     }
14326   }
14327
14328   if (addTest) {
14329     // Look pass the truncate if the high bits are known zero.
14330     if (isTruncWithZeroHighBitsInput(Cond, DAG))
14331         Cond = Cond.getOperand(0);
14332
14333     // We know the result of AND is compared against zero. Try to match
14334     // it to BT.
14335     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
14336       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
14337       if (NewSetCC.getNode()) {
14338         CC = NewSetCC.getOperand(0);
14339         Cond = NewSetCC.getOperand(1);
14340         addTest = false;
14341       }
14342     }
14343   }
14344
14345   if (addTest) {
14346     X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
14347     CC = DAG.getConstant(X86Cond, MVT::i8);
14348     Cond = EmitTest(Cond, X86Cond, dl, DAG);
14349   }
14350   Cond = ConvertCmpIfNecessary(Cond, DAG);
14351   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14352                      Chain, Dest, CC, Cond);
14353 }
14354
14355 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
14356 // Calls to _alloca are needed to probe the stack when allocating more than 4k
14357 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
14358 // that the guard pages used by the OS virtual memory manager are allocated in
14359 // correct sequence.
14360 SDValue
14361 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
14362                                            SelectionDAG &DAG) const {
14363   MachineFunction &MF = DAG.getMachineFunction();
14364   bool SplitStack = MF.shouldSplitStack();
14365   bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMachO()) ||
14366                SplitStack;
14367   SDLoc dl(Op);
14368
14369   if (!Lower) {
14370     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14371     SDNode* Node = Op.getNode();
14372
14373     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
14374     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
14375         " not tell us which reg is the stack pointer!");
14376     EVT VT = Node->getValueType(0);
14377     SDValue Tmp1 = SDValue(Node, 0);
14378     SDValue Tmp2 = SDValue(Node, 1);
14379     SDValue Tmp3 = Node->getOperand(2);
14380     SDValue Chain = Tmp1.getOperand(0);
14381
14382     // Chain the dynamic stack allocation so that it doesn't modify the stack
14383     // pointer when other instructions are using the stack.
14384     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true),
14385         SDLoc(Node));
14386
14387     SDValue Size = Tmp2.getOperand(1);
14388     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
14389     Chain = SP.getValue(1);
14390     unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
14391     const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
14392     unsigned StackAlign = TFI.getStackAlignment();
14393     Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
14394     if (Align > StackAlign)
14395       Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
14396           DAG.getConstant(-(uint64_t)Align, VT));
14397     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
14398
14399     Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
14400         DAG.getIntPtrConstant(0, true), SDValue(),
14401         SDLoc(Node));
14402
14403     SDValue Ops[2] = { Tmp1, Tmp2 };
14404     return DAG.getMergeValues(Ops, dl);
14405   }
14406
14407   // Get the inputs.
14408   SDValue Chain = Op.getOperand(0);
14409   SDValue Size  = Op.getOperand(1);
14410   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
14411   EVT VT = Op.getNode()->getValueType(0);
14412
14413   bool Is64Bit = Subtarget->is64Bit();
14414   EVT SPTy = getPointerTy();
14415
14416   if (SplitStack) {
14417     MachineRegisterInfo &MRI = MF.getRegInfo();
14418
14419     if (Is64Bit) {
14420       // The 64 bit implementation of segmented stacks needs to clobber both r10
14421       // r11. This makes it impossible to use it along with nested parameters.
14422       const Function *F = MF.getFunction();
14423
14424       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
14425            I != E; ++I)
14426         if (I->hasNestAttr())
14427           report_fatal_error("Cannot use segmented stacks with functions that "
14428                              "have nested arguments.");
14429     }
14430
14431     const TargetRegisterClass *AddrRegClass =
14432       getRegClassFor(getPointerTy());
14433     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
14434     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
14435     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
14436                                 DAG.getRegister(Vreg, SPTy));
14437     SDValue Ops1[2] = { Value, Chain };
14438     return DAG.getMergeValues(Ops1, dl);
14439   } else {
14440     SDValue Flag;
14441     const unsigned Reg = (Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX);
14442
14443     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
14444     Flag = Chain.getValue(1);
14445     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
14446
14447     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
14448
14449     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
14450     unsigned SPReg = RegInfo->getStackRegister();
14451     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
14452     Chain = SP.getValue(1);
14453
14454     if (Align) {
14455       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
14456                        DAG.getConstant(-(uint64_t)Align, VT));
14457       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
14458     }
14459
14460     SDValue Ops1[2] = { SP, Chain };
14461     return DAG.getMergeValues(Ops1, dl);
14462   }
14463 }
14464
14465 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
14466   MachineFunction &MF = DAG.getMachineFunction();
14467   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
14468
14469   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
14470   SDLoc DL(Op);
14471
14472   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
14473     // vastart just stores the address of the VarArgsFrameIndex slot into the
14474     // memory location argument.
14475     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
14476                                    getPointerTy());
14477     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
14478                         MachinePointerInfo(SV), false, false, 0);
14479   }
14480
14481   // __va_list_tag:
14482   //   gp_offset         (0 - 6 * 8)
14483   //   fp_offset         (48 - 48 + 8 * 16)
14484   //   overflow_arg_area (point to parameters coming in memory).
14485   //   reg_save_area
14486   SmallVector<SDValue, 8> MemOps;
14487   SDValue FIN = Op.getOperand(1);
14488   // Store gp_offset
14489   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
14490                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
14491                                                MVT::i32),
14492                                FIN, MachinePointerInfo(SV), false, false, 0);
14493   MemOps.push_back(Store);
14494
14495   // Store fp_offset
14496   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14497                     FIN, DAG.getIntPtrConstant(4));
14498   Store = DAG.getStore(Op.getOperand(0), DL,
14499                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
14500                                        MVT::i32),
14501                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
14502   MemOps.push_back(Store);
14503
14504   // Store ptr to overflow_arg_area
14505   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14506                     FIN, DAG.getIntPtrConstant(4));
14507   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
14508                                     getPointerTy());
14509   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
14510                        MachinePointerInfo(SV, 8),
14511                        false, false, 0);
14512   MemOps.push_back(Store);
14513
14514   // Store ptr to reg_save_area.
14515   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14516                     FIN, DAG.getIntPtrConstant(8));
14517   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
14518                                     getPointerTy());
14519   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
14520                        MachinePointerInfo(SV, 16), false, false, 0);
14521   MemOps.push_back(Store);
14522   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
14523 }
14524
14525 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
14526   assert(Subtarget->is64Bit() &&
14527          "LowerVAARG only handles 64-bit va_arg!");
14528   assert((Subtarget->isTargetLinux() ||
14529           Subtarget->isTargetDarwin()) &&
14530           "Unhandled target in LowerVAARG");
14531   assert(Op.getNode()->getNumOperands() == 4);
14532   SDValue Chain = Op.getOperand(0);
14533   SDValue SrcPtr = Op.getOperand(1);
14534   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
14535   unsigned Align = Op.getConstantOperandVal(3);
14536   SDLoc dl(Op);
14537
14538   EVT ArgVT = Op.getNode()->getValueType(0);
14539   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
14540   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
14541   uint8_t ArgMode;
14542
14543   // Decide which area this value should be read from.
14544   // TODO: Implement the AMD64 ABI in its entirety. This simple
14545   // selection mechanism works only for the basic types.
14546   if (ArgVT == MVT::f80) {
14547     llvm_unreachable("va_arg for f80 not yet implemented");
14548   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
14549     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
14550   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
14551     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
14552   } else {
14553     llvm_unreachable("Unhandled argument type in LowerVAARG");
14554   }
14555
14556   if (ArgMode == 2) {
14557     // Sanity Check: Make sure using fp_offset makes sense.
14558     assert(!DAG.getTarget().Options.UseSoftFloat &&
14559            !(DAG.getMachineFunction().getFunction()->hasFnAttribute(
14560                Attribute::NoImplicitFloat)) &&
14561            Subtarget->hasSSE1());
14562   }
14563
14564   // Insert VAARG_64 node into the DAG
14565   // VAARG_64 returns two values: Variable Argument Address, Chain
14566   SDValue InstOps[] = {Chain, SrcPtr, DAG.getConstant(ArgSize, MVT::i32),
14567                        DAG.getConstant(ArgMode, MVT::i8),
14568                        DAG.getConstant(Align, MVT::i32)};
14569   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
14570   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
14571                                           VTs, InstOps, MVT::i64,
14572                                           MachinePointerInfo(SV),
14573                                           /*Align=*/0,
14574                                           /*Volatile=*/false,
14575                                           /*ReadMem=*/true,
14576                                           /*WriteMem=*/true);
14577   Chain = VAARG.getValue(1);
14578
14579   // Load the next argument and return it
14580   return DAG.getLoad(ArgVT, dl,
14581                      Chain,
14582                      VAARG,
14583                      MachinePointerInfo(),
14584                      false, false, false, 0);
14585 }
14586
14587 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
14588                            SelectionDAG &DAG) {
14589   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
14590   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
14591   SDValue Chain = Op.getOperand(0);
14592   SDValue DstPtr = Op.getOperand(1);
14593   SDValue SrcPtr = Op.getOperand(2);
14594   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
14595   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
14596   SDLoc DL(Op);
14597
14598   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
14599                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
14600                        false, false,
14601                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
14602 }
14603
14604 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
14605 // amount is a constant. Takes immediate version of shift as input.
14606 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
14607                                           SDValue SrcOp, uint64_t ShiftAmt,
14608                                           SelectionDAG &DAG) {
14609   MVT ElementType = VT.getVectorElementType();
14610
14611   // Fold this packed shift into its first operand if ShiftAmt is 0.
14612   if (ShiftAmt == 0)
14613     return SrcOp;
14614
14615   // Check for ShiftAmt >= element width
14616   if (ShiftAmt >= ElementType.getSizeInBits()) {
14617     if (Opc == X86ISD::VSRAI)
14618       ShiftAmt = ElementType.getSizeInBits() - 1;
14619     else
14620       return DAG.getConstant(0, VT);
14621   }
14622
14623   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
14624          && "Unknown target vector shift-by-constant node");
14625
14626   // Fold this packed vector shift into a build vector if SrcOp is a
14627   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
14628   if (VT == SrcOp.getSimpleValueType() &&
14629       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
14630     SmallVector<SDValue, 8> Elts;
14631     unsigned NumElts = SrcOp->getNumOperands();
14632     ConstantSDNode *ND;
14633
14634     switch(Opc) {
14635     default: llvm_unreachable(nullptr);
14636     case X86ISD::VSHLI:
14637       for (unsigned i=0; i!=NumElts; ++i) {
14638         SDValue CurrentOp = SrcOp->getOperand(i);
14639         if (CurrentOp->getOpcode() == ISD::UNDEF) {
14640           Elts.push_back(CurrentOp);
14641           continue;
14642         }
14643         ND = cast<ConstantSDNode>(CurrentOp);
14644         const APInt &C = ND->getAPIntValue();
14645         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), ElementType));
14646       }
14647       break;
14648     case X86ISD::VSRLI:
14649       for (unsigned i=0; i!=NumElts; ++i) {
14650         SDValue CurrentOp = SrcOp->getOperand(i);
14651         if (CurrentOp->getOpcode() == ISD::UNDEF) {
14652           Elts.push_back(CurrentOp);
14653           continue;
14654         }
14655         ND = cast<ConstantSDNode>(CurrentOp);
14656         const APInt &C = ND->getAPIntValue();
14657         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), ElementType));
14658       }
14659       break;
14660     case X86ISD::VSRAI:
14661       for (unsigned i=0; i!=NumElts; ++i) {
14662         SDValue CurrentOp = SrcOp->getOperand(i);
14663         if (CurrentOp->getOpcode() == ISD::UNDEF) {
14664           Elts.push_back(CurrentOp);
14665           continue;
14666         }
14667         ND = cast<ConstantSDNode>(CurrentOp);
14668         const APInt &C = ND->getAPIntValue();
14669         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), ElementType));
14670       }
14671       break;
14672     }
14673
14674     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
14675   }
14676
14677   return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
14678 }
14679
14680 // getTargetVShiftNode - Handle vector element shifts where the shift amount
14681 // may or may not be a constant. Takes immediate version of shift as input.
14682 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
14683                                    SDValue SrcOp, SDValue ShAmt,
14684                                    SelectionDAG &DAG) {
14685   MVT SVT = ShAmt.getSimpleValueType();
14686   assert((SVT == MVT::i32 || SVT == MVT::i64) && "Unexpected value type!");
14687
14688   // Catch shift-by-constant.
14689   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
14690     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
14691                                       CShAmt->getZExtValue(), DAG);
14692
14693   // Change opcode to non-immediate version
14694   switch (Opc) {
14695     default: llvm_unreachable("Unknown target vector shift node");
14696     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
14697     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
14698     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
14699   }
14700
14701   const X86Subtarget &Subtarget =
14702       static_cast<const X86Subtarget &>(DAG.getSubtarget());
14703   if (Subtarget.hasSSE41() && ShAmt.getOpcode() == ISD::ZERO_EXTEND &&
14704       ShAmt.getOperand(0).getSimpleValueType() == MVT::i16) {
14705     // Let the shuffle legalizer expand this shift amount node.
14706     SDValue Op0 = ShAmt.getOperand(0);
14707     Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(Op0), MVT::v8i16, Op0);
14708     ShAmt = getShuffleVectorZeroOrUndef(Op0, 0, true, &Subtarget, DAG);
14709   } else {
14710     // Need to build a vector containing shift amount.
14711     // SSE/AVX packed shifts only use the lower 64-bit of the shift count.
14712     SmallVector<SDValue, 4> ShOps;
14713     ShOps.push_back(ShAmt);
14714     if (SVT == MVT::i32) {
14715       ShOps.push_back(DAG.getConstant(0, SVT));
14716       ShOps.push_back(DAG.getUNDEF(SVT));
14717     }
14718     ShOps.push_back(DAG.getUNDEF(SVT));
14719
14720     MVT BVT = SVT == MVT::i32 ? MVT::v4i32 : MVT::v2i64;
14721     ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, BVT, ShOps);
14722   }
14723
14724   // The return type has to be a 128-bit type with the same element
14725   // type as the input type.
14726   MVT EltVT = VT.getVectorElementType();
14727   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
14728
14729   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
14730   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
14731 }
14732
14733 /// \brief Return (and \p Op, \p Mask) for compare instructions or
14734 /// (vselect \p Mask, \p Op, \p PreservedSrc) for others along with the
14735 /// necessary casting for \p Mask when lowering masking intrinsics.
14736 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
14737                                     SDValue PreservedSrc,
14738                                     const X86Subtarget *Subtarget,
14739                                     SelectionDAG &DAG) {
14740     EVT VT = Op.getValueType();
14741     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
14742                                   MVT::i1, VT.getVectorNumElements());
14743     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14744                                      Mask.getValueType().getSizeInBits());
14745     SDLoc dl(Op);
14746
14747     assert(MaskVT.isSimple() && "invalid mask type");
14748
14749     if (isAllOnes(Mask))
14750       return Op;
14751
14752     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
14753     // are extracted by EXTRACT_SUBVECTOR.
14754     SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
14755                               DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
14756                               DAG.getIntPtrConstant(0));
14757
14758     switch (Op.getOpcode()) {
14759       default: break;
14760       case X86ISD::PCMPEQM:
14761       case X86ISD::PCMPGTM:
14762       case X86ISD::CMPM:
14763       case X86ISD::CMPMU:
14764         return DAG.getNode(ISD::AND, dl, VT, Op, VMask);
14765     }
14766     if (PreservedSrc.getOpcode() == ISD::UNDEF)
14767       PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
14768     return DAG.getNode(ISD::VSELECT, dl, VT, VMask, Op, PreservedSrc);
14769 }
14770
14771 /// \brief Creates an SDNode for a predicated scalar operation.
14772 /// \returns (X86vselect \p Mask, \p Op, \p PreservedSrc).
14773 /// The mask is comming as MVT::i8 and it should be truncated
14774 /// to MVT::i1 while lowering masking intrinsics.
14775 /// The main difference between ScalarMaskingNode and VectorMaskingNode is using
14776 /// "X86select" instead of "vselect". We just can't create the "vselect" node for
14777 /// a scalar instruction.
14778 static SDValue getScalarMaskingNode(SDValue Op, SDValue Mask,
14779                                     SDValue PreservedSrc,
14780                                     const X86Subtarget *Subtarget,
14781                                     SelectionDAG &DAG) {
14782     if (isAllOnes(Mask))
14783       return Op;
14784
14785     EVT VT = Op.getValueType();
14786     SDLoc dl(Op);
14787     // The mask should be of type MVT::i1
14788     SDValue IMask = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Mask);
14789
14790     if (PreservedSrc.getOpcode() == ISD::UNDEF)
14791       PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
14792     return DAG.getNode(X86ISD::SELECT, dl, VT, IMask, Op, PreservedSrc);
14793 }
14794
14795 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
14796                                        SelectionDAG &DAG) {
14797   SDLoc dl(Op);
14798   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14799   EVT VT = Op.getValueType();
14800   const IntrinsicData* IntrData = getIntrinsicWithoutChain(IntNo);
14801   if (IntrData) {
14802     switch(IntrData->Type) {
14803     case INTR_TYPE_1OP:
14804       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1));
14805     case INTR_TYPE_2OP:
14806       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
14807         Op.getOperand(2));
14808     case INTR_TYPE_3OP:
14809       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
14810         Op.getOperand(2), Op.getOperand(3));
14811     case INTR_TYPE_1OP_MASK_RM: {
14812       SDValue Src = Op.getOperand(1);
14813       SDValue Src0 = Op.getOperand(2);
14814       SDValue Mask = Op.getOperand(3);
14815       SDValue RoundingMode = Op.getOperand(4);
14816       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src,
14817                                               RoundingMode),
14818                                   Mask, Src0, Subtarget, DAG);
14819     }
14820     case INTR_TYPE_SCALAR_MASK_RM: {
14821       SDValue Src1 = Op.getOperand(1);
14822       SDValue Src2 = Op.getOperand(2);
14823       SDValue Src0 = Op.getOperand(3);
14824       SDValue Mask = Op.getOperand(4);
14825       // There are 2 kinds of intrinsics in this group:
14826       // (1) With supress-all-exceptions (sae) - 6 operands
14827       // (2) With rounding mode and sae - 7 operands.
14828       if (Op.getNumOperands() == 6) {
14829         SDValue Sae  = Op.getOperand(5);
14830         return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
14831                                                 Sae),
14832                                     Mask, Src0, Subtarget, DAG);
14833       }
14834       assert(Op.getNumOperands() == 7 && "Unexpected intrinsic form");
14835       SDValue RoundingMode  = Op.getOperand(5);
14836       SDValue Sae  = Op.getOperand(6);
14837       return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
14838                                               RoundingMode, Sae),
14839                                   Mask, Src0, Subtarget, DAG);
14840     }
14841     case INTR_TYPE_2OP_MASK: {
14842       SDValue Src1 = Op.getOperand(1);
14843       SDValue Src2 = Op.getOperand(2);
14844       SDValue PassThru = Op.getOperand(3);
14845       SDValue Mask = Op.getOperand(4);
14846       // We specify 2 possible opcodes for intrinsics with rounding modes.
14847       // First, we check if the intrinsic may have non-default rounding mode,
14848       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
14849       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
14850       if (IntrWithRoundingModeOpcode != 0) {
14851         SDValue Rnd = Op.getOperand(5);
14852         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
14853         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
14854           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
14855                                       dl, Op.getValueType(),
14856                                       Src1, Src2, Rnd),
14857                                       Mask, PassThru, Subtarget, DAG);
14858         }
14859       }
14860       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
14861                                               Src1,Src2),
14862                                   Mask, PassThru, Subtarget, DAG);
14863     }
14864     case FMA_OP_MASK: {
14865       SDValue Src1 = Op.getOperand(1);
14866       SDValue Src2 = Op.getOperand(2);
14867       SDValue Src3 = Op.getOperand(3);
14868       SDValue Mask = Op.getOperand(4);
14869       // We specify 2 possible opcodes for intrinsics with rounding modes.
14870       // First, we check if the intrinsic may have non-default rounding mode,
14871       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
14872       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
14873       if (IntrWithRoundingModeOpcode != 0) {
14874         SDValue Rnd = Op.getOperand(5);
14875         if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
14876             X86::STATIC_ROUNDING::CUR_DIRECTION)
14877           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
14878                                                   dl, Op.getValueType(),
14879                                                   Src1, Src2, Src3, Rnd),
14880                                       Mask, Src1, Subtarget, DAG);
14881       }
14882       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0,
14883                                               dl, Op.getValueType(),
14884                                               Src1, Src2, Src3),
14885                                   Mask, Src1, Subtarget, DAG);
14886     }
14887     case CMP_MASK:
14888     case CMP_MASK_CC: {
14889       // Comparison intrinsics with masks.
14890       // Example of transformation:
14891       // (i8 (int_x86_avx512_mask_pcmpeq_q_128
14892       //             (v2i64 %a), (v2i64 %b), (i8 %mask))) ->
14893       // (i8 (bitcast
14894       //   (v8i1 (insert_subvector undef,
14895       //           (v2i1 (and (PCMPEQM %a, %b),
14896       //                      (extract_subvector
14897       //                         (v8i1 (bitcast %mask)), 0))), 0))))
14898       EVT VT = Op.getOperand(1).getValueType();
14899       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14900                                     VT.getVectorNumElements());
14901       SDValue Mask = Op.getOperand((IntrData->Type == CMP_MASK_CC) ? 4 : 3);
14902       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14903                                        Mask.getValueType().getSizeInBits());
14904       SDValue Cmp;
14905       if (IntrData->Type == CMP_MASK_CC) {
14906         Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
14907                     Op.getOperand(2), Op.getOperand(3));
14908       } else {
14909         assert(IntrData->Type == CMP_MASK && "Unexpected intrinsic type!");
14910         Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
14911                     Op.getOperand(2));
14912       }
14913       SDValue CmpMask = getVectorMaskingNode(Cmp, Mask,
14914                                              DAG.getTargetConstant(0, MaskVT),
14915                                              Subtarget, DAG);
14916       SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
14917                                 DAG.getUNDEF(BitcastVT), CmpMask,
14918                                 DAG.getIntPtrConstant(0));
14919       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
14920     }
14921     case COMI: { // Comparison intrinsics
14922       ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
14923       SDValue LHS = Op.getOperand(1);
14924       SDValue RHS = Op.getOperand(2);
14925       unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
14926       assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
14927       SDValue Cond = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
14928       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14929                                   DAG.getConstant(X86CC, MVT::i8), Cond);
14930       return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14931     }
14932     case VSHIFT:
14933       return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
14934                                  Op.getOperand(1), Op.getOperand(2), DAG);
14935     case VSHIFT_MASK:
14936       return getVectorMaskingNode(getTargetVShiftNode(IntrData->Opc0, dl,
14937                                                       Op.getSimpleValueType(),
14938                                                       Op.getOperand(1),
14939                                                       Op.getOperand(2), DAG),
14940                                   Op.getOperand(4), Op.getOperand(3), Subtarget,
14941                                   DAG);
14942     case COMPRESS_EXPAND_IN_REG: {
14943       SDValue Mask = Op.getOperand(3);
14944       SDValue DataToCompress = Op.getOperand(1);
14945       SDValue PassThru = Op.getOperand(2);
14946       if (isAllOnes(Mask)) // return data as is
14947         return Op.getOperand(1);
14948       EVT VT = Op.getValueType();
14949       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14950                                     VT.getVectorNumElements());
14951       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14952                                        Mask.getValueType().getSizeInBits());
14953       SDLoc dl(Op);
14954       SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
14955                                   DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
14956                                   DAG.getIntPtrConstant(0));
14957
14958       return DAG.getNode(IntrData->Opc0, dl, VT, VMask, DataToCompress,
14959                          PassThru);
14960     }
14961     case BLEND: {
14962       SDValue Mask = Op.getOperand(3);
14963       EVT VT = Op.getValueType();
14964       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14965                                     VT.getVectorNumElements());
14966       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14967                                        Mask.getValueType().getSizeInBits());
14968       SDLoc dl(Op);
14969       SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
14970                                   DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
14971                                   DAG.getIntPtrConstant(0));
14972       return DAG.getNode(IntrData->Opc0, dl, VT, VMask, Op.getOperand(1),
14973                          Op.getOperand(2));
14974     }
14975     default:
14976       break;
14977     }
14978   }
14979
14980   switch (IntNo) {
14981   default: return SDValue();    // Don't custom lower most intrinsics.
14982
14983   case Intrinsic::x86_avx2_permd:
14984   case Intrinsic::x86_avx2_permps:
14985     // Operands intentionally swapped. Mask is last operand to intrinsic,
14986     // but second operand for node/instruction.
14987     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
14988                        Op.getOperand(2), Op.getOperand(1));
14989
14990   case Intrinsic::x86_avx512_mask_valign_q_512:
14991   case Intrinsic::x86_avx512_mask_valign_d_512:
14992     // Vector source operands are swapped.
14993     return getVectorMaskingNode(DAG.getNode(X86ISD::VALIGN, dl,
14994                                             Op.getValueType(), Op.getOperand(2),
14995                                             Op.getOperand(1),
14996                                             Op.getOperand(3)),
14997                                 Op.getOperand(5), Op.getOperand(4),
14998                                 Subtarget, DAG);
14999
15000   // ptest and testp intrinsics. The intrinsic these come from are designed to
15001   // return an integer value, not just an instruction so lower it to the ptest
15002   // or testp pattern and a setcc for the result.
15003   case Intrinsic::x86_sse41_ptestz:
15004   case Intrinsic::x86_sse41_ptestc:
15005   case Intrinsic::x86_sse41_ptestnzc:
15006   case Intrinsic::x86_avx_ptestz_256:
15007   case Intrinsic::x86_avx_ptestc_256:
15008   case Intrinsic::x86_avx_ptestnzc_256:
15009   case Intrinsic::x86_avx_vtestz_ps:
15010   case Intrinsic::x86_avx_vtestc_ps:
15011   case Intrinsic::x86_avx_vtestnzc_ps:
15012   case Intrinsic::x86_avx_vtestz_pd:
15013   case Intrinsic::x86_avx_vtestc_pd:
15014   case Intrinsic::x86_avx_vtestnzc_pd:
15015   case Intrinsic::x86_avx_vtestz_ps_256:
15016   case Intrinsic::x86_avx_vtestc_ps_256:
15017   case Intrinsic::x86_avx_vtestnzc_ps_256:
15018   case Intrinsic::x86_avx_vtestz_pd_256:
15019   case Intrinsic::x86_avx_vtestc_pd_256:
15020   case Intrinsic::x86_avx_vtestnzc_pd_256: {
15021     bool IsTestPacked = false;
15022     unsigned X86CC;
15023     switch (IntNo) {
15024     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
15025     case Intrinsic::x86_avx_vtestz_ps:
15026     case Intrinsic::x86_avx_vtestz_pd:
15027     case Intrinsic::x86_avx_vtestz_ps_256:
15028     case Intrinsic::x86_avx_vtestz_pd_256:
15029       IsTestPacked = true; // Fallthrough
15030     case Intrinsic::x86_sse41_ptestz:
15031     case Intrinsic::x86_avx_ptestz_256:
15032       // ZF = 1
15033       X86CC = X86::COND_E;
15034       break;
15035     case Intrinsic::x86_avx_vtestc_ps:
15036     case Intrinsic::x86_avx_vtestc_pd:
15037     case Intrinsic::x86_avx_vtestc_ps_256:
15038     case Intrinsic::x86_avx_vtestc_pd_256:
15039       IsTestPacked = true; // Fallthrough
15040     case Intrinsic::x86_sse41_ptestc:
15041     case Intrinsic::x86_avx_ptestc_256:
15042       // CF = 1
15043       X86CC = X86::COND_B;
15044       break;
15045     case Intrinsic::x86_avx_vtestnzc_ps:
15046     case Intrinsic::x86_avx_vtestnzc_pd:
15047     case Intrinsic::x86_avx_vtestnzc_ps_256:
15048     case Intrinsic::x86_avx_vtestnzc_pd_256:
15049       IsTestPacked = true; // Fallthrough
15050     case Intrinsic::x86_sse41_ptestnzc:
15051     case Intrinsic::x86_avx_ptestnzc_256:
15052       // ZF and CF = 0
15053       X86CC = X86::COND_A;
15054       break;
15055     }
15056
15057     SDValue LHS = Op.getOperand(1);
15058     SDValue RHS = Op.getOperand(2);
15059     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
15060     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
15061     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
15062     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
15063     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15064   }
15065   case Intrinsic::x86_avx512_kortestz_w:
15066   case Intrinsic::x86_avx512_kortestc_w: {
15067     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
15068     SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
15069     SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
15070     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
15071     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
15072     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
15073     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15074   }
15075
15076   case Intrinsic::x86_sse42_pcmpistria128:
15077   case Intrinsic::x86_sse42_pcmpestria128:
15078   case Intrinsic::x86_sse42_pcmpistric128:
15079   case Intrinsic::x86_sse42_pcmpestric128:
15080   case Intrinsic::x86_sse42_pcmpistrio128:
15081   case Intrinsic::x86_sse42_pcmpestrio128:
15082   case Intrinsic::x86_sse42_pcmpistris128:
15083   case Intrinsic::x86_sse42_pcmpestris128:
15084   case Intrinsic::x86_sse42_pcmpistriz128:
15085   case Intrinsic::x86_sse42_pcmpestriz128: {
15086     unsigned Opcode;
15087     unsigned X86CC;
15088     switch (IntNo) {
15089     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
15090     case Intrinsic::x86_sse42_pcmpistria128:
15091       Opcode = X86ISD::PCMPISTRI;
15092       X86CC = X86::COND_A;
15093       break;
15094     case Intrinsic::x86_sse42_pcmpestria128:
15095       Opcode = X86ISD::PCMPESTRI;
15096       X86CC = X86::COND_A;
15097       break;
15098     case Intrinsic::x86_sse42_pcmpistric128:
15099       Opcode = X86ISD::PCMPISTRI;
15100       X86CC = X86::COND_B;
15101       break;
15102     case Intrinsic::x86_sse42_pcmpestric128:
15103       Opcode = X86ISD::PCMPESTRI;
15104       X86CC = X86::COND_B;
15105       break;
15106     case Intrinsic::x86_sse42_pcmpistrio128:
15107       Opcode = X86ISD::PCMPISTRI;
15108       X86CC = X86::COND_O;
15109       break;
15110     case Intrinsic::x86_sse42_pcmpestrio128:
15111       Opcode = X86ISD::PCMPESTRI;
15112       X86CC = X86::COND_O;
15113       break;
15114     case Intrinsic::x86_sse42_pcmpistris128:
15115       Opcode = X86ISD::PCMPISTRI;
15116       X86CC = X86::COND_S;
15117       break;
15118     case Intrinsic::x86_sse42_pcmpestris128:
15119       Opcode = X86ISD::PCMPESTRI;
15120       X86CC = X86::COND_S;
15121       break;
15122     case Intrinsic::x86_sse42_pcmpistriz128:
15123       Opcode = X86ISD::PCMPISTRI;
15124       X86CC = X86::COND_E;
15125       break;
15126     case Intrinsic::x86_sse42_pcmpestriz128:
15127       Opcode = X86ISD::PCMPESTRI;
15128       X86CC = X86::COND_E;
15129       break;
15130     }
15131     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
15132     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
15133     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
15134     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15135                                 DAG.getConstant(X86CC, MVT::i8),
15136                                 SDValue(PCMP.getNode(), 1));
15137     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15138   }
15139
15140   case Intrinsic::x86_sse42_pcmpistri128:
15141   case Intrinsic::x86_sse42_pcmpestri128: {
15142     unsigned Opcode;
15143     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
15144       Opcode = X86ISD::PCMPISTRI;
15145     else
15146       Opcode = X86ISD::PCMPESTRI;
15147
15148     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
15149     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
15150     return DAG.getNode(Opcode, dl, VTs, NewOps);
15151   }
15152   }
15153 }
15154
15155 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15156                               SDValue Src, SDValue Mask, SDValue Base,
15157                               SDValue Index, SDValue ScaleOp, SDValue Chain,
15158                               const X86Subtarget * Subtarget) {
15159   SDLoc dl(Op);
15160   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15161   assert(C && "Invalid scale type");
15162   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
15163   EVT MaskVT = MVT::getVectorVT(MVT::i1,
15164                              Index.getSimpleValueType().getVectorNumElements());
15165   SDValue MaskInReg;
15166   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15167   if (MaskC)
15168     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
15169   else
15170     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
15171   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
15172   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
15173   SDValue Segment = DAG.getRegister(0, MVT::i32);
15174   if (Src.getOpcode() == ISD::UNDEF)
15175     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
15176   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
15177   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
15178   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
15179   return DAG.getMergeValues(RetOps, dl);
15180 }
15181
15182 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15183                                SDValue Src, SDValue Mask, SDValue Base,
15184                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
15185   SDLoc dl(Op);
15186   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15187   assert(C && "Invalid scale type");
15188   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
15189   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
15190   SDValue Segment = DAG.getRegister(0, MVT::i32);
15191   EVT MaskVT = MVT::getVectorVT(MVT::i1,
15192                              Index.getSimpleValueType().getVectorNumElements());
15193   SDValue MaskInReg;
15194   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15195   if (MaskC)
15196     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
15197   else
15198     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
15199   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
15200   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
15201   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
15202   return SDValue(Res, 1);
15203 }
15204
15205 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15206                                SDValue Mask, SDValue Base, SDValue Index,
15207                                SDValue ScaleOp, SDValue Chain) {
15208   SDLoc dl(Op);
15209   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15210   assert(C && "Invalid scale type");
15211   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
15212   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
15213   SDValue Segment = DAG.getRegister(0, MVT::i32);
15214   EVT MaskVT =
15215     MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
15216   SDValue MaskInReg;
15217   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15218   if (MaskC)
15219     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
15220   else
15221     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
15222   //SDVTList VTs = DAG.getVTList(MVT::Other);
15223   SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
15224   SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
15225   return SDValue(Res, 0);
15226 }
15227
15228 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
15229 // read performance monitor counters (x86_rdpmc).
15230 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
15231                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
15232                               SmallVectorImpl<SDValue> &Results) {
15233   assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
15234   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
15235   SDValue LO, HI;
15236
15237   // The ECX register is used to select the index of the performance counter
15238   // to read.
15239   SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
15240                                    N->getOperand(2));
15241   SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
15242
15243   // Reads the content of a 64-bit performance counter and returns it in the
15244   // registers EDX:EAX.
15245   if (Subtarget->is64Bit()) {
15246     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
15247     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
15248                             LO.getValue(2));
15249   } else {
15250     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
15251     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
15252                             LO.getValue(2));
15253   }
15254   Chain = HI.getValue(1);
15255
15256   if (Subtarget->is64Bit()) {
15257     // The EAX register is loaded with the low-order 32 bits. The EDX register
15258     // is loaded with the supported high-order bits of the counter.
15259     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
15260                               DAG.getConstant(32, MVT::i8));
15261     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
15262     Results.push_back(Chain);
15263     return;
15264   }
15265
15266   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
15267   SDValue Ops[] = { LO, HI };
15268   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
15269   Results.push_back(Pair);
15270   Results.push_back(Chain);
15271 }
15272
15273 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
15274 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
15275 // also used to custom lower READCYCLECOUNTER nodes.
15276 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
15277                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
15278                               SmallVectorImpl<SDValue> &Results) {
15279   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
15280   SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
15281   SDValue LO, HI;
15282
15283   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
15284   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
15285   // and the EAX register is loaded with the low-order 32 bits.
15286   if (Subtarget->is64Bit()) {
15287     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
15288     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
15289                             LO.getValue(2));
15290   } else {
15291     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
15292     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
15293                             LO.getValue(2));
15294   }
15295   SDValue Chain = HI.getValue(1);
15296
15297   if (Opcode == X86ISD::RDTSCP_DAG) {
15298     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
15299
15300     // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
15301     // the ECX register. Add 'ecx' explicitly to the chain.
15302     SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
15303                                      HI.getValue(2));
15304     // Explicitly store the content of ECX at the location passed in input
15305     // to the 'rdtscp' intrinsic.
15306     Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
15307                          MachinePointerInfo(), false, false, 0);
15308   }
15309
15310   if (Subtarget->is64Bit()) {
15311     // The EDX register is loaded with the high-order 32 bits of the MSR, and
15312     // the EAX register is loaded with the low-order 32 bits.
15313     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
15314                               DAG.getConstant(32, MVT::i8));
15315     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
15316     Results.push_back(Chain);
15317     return;
15318   }
15319
15320   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
15321   SDValue Ops[] = { LO, HI };
15322   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
15323   Results.push_back(Pair);
15324   Results.push_back(Chain);
15325 }
15326
15327 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
15328                                      SelectionDAG &DAG) {
15329   SmallVector<SDValue, 2> Results;
15330   SDLoc DL(Op);
15331   getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
15332                           Results);
15333   return DAG.getMergeValues(Results, DL);
15334 }
15335
15336
15337 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
15338                                       SelectionDAG &DAG) {
15339   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
15340
15341   const IntrinsicData* IntrData = getIntrinsicWithChain(IntNo);
15342   if (!IntrData)
15343     return SDValue();
15344
15345   SDLoc dl(Op);
15346   switch(IntrData->Type) {
15347   default:
15348     llvm_unreachable("Unknown Intrinsic Type");
15349     break;
15350   case RDSEED:
15351   case RDRAND: {
15352     // Emit the node with the right value type.
15353     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
15354     SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
15355
15356     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
15357     // Otherwise return the value from Rand, which is always 0, casted to i32.
15358     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
15359                       DAG.getConstant(1, Op->getValueType(1)),
15360                       DAG.getConstant(X86::COND_B, MVT::i32),
15361                       SDValue(Result.getNode(), 1) };
15362     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
15363                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
15364                                   Ops);
15365
15366     // Return { result, isValid, chain }.
15367     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
15368                        SDValue(Result.getNode(), 2));
15369   }
15370   case GATHER: {
15371   //gather(v1, mask, index, base, scale);
15372     SDValue Chain = Op.getOperand(0);
15373     SDValue Src   = Op.getOperand(2);
15374     SDValue Base  = Op.getOperand(3);
15375     SDValue Index = Op.getOperand(4);
15376     SDValue Mask  = Op.getOperand(5);
15377     SDValue Scale = Op.getOperand(6);
15378     return getGatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
15379                           Subtarget);
15380   }
15381   case SCATTER: {
15382   //scatter(base, mask, index, v1, scale);
15383     SDValue Chain = Op.getOperand(0);
15384     SDValue Base  = Op.getOperand(2);
15385     SDValue Mask  = Op.getOperand(3);
15386     SDValue Index = Op.getOperand(4);
15387     SDValue Src   = Op.getOperand(5);
15388     SDValue Scale = Op.getOperand(6);
15389     return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
15390   }
15391   case PREFETCH: {
15392     SDValue Hint = Op.getOperand(6);
15393     unsigned HintVal = cast<ConstantSDNode>(Hint)->getZExtValue();
15394     assert(HintVal < 2 && "Wrong prefetch hint in intrinsic: should be 0 or 1");
15395     unsigned Opcode = (HintVal ? IntrData->Opc1 : IntrData->Opc0);
15396     SDValue Chain = Op.getOperand(0);
15397     SDValue Mask  = Op.getOperand(2);
15398     SDValue Index = Op.getOperand(3);
15399     SDValue Base  = Op.getOperand(4);
15400     SDValue Scale = Op.getOperand(5);
15401     return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
15402   }
15403   // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
15404   case RDTSC: {
15405     SmallVector<SDValue, 2> Results;
15406     getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget, Results);
15407     return DAG.getMergeValues(Results, dl);
15408   }
15409   // Read Performance Monitoring Counters.
15410   case RDPMC: {
15411     SmallVector<SDValue, 2> Results;
15412     getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
15413     return DAG.getMergeValues(Results, dl);
15414   }
15415   // XTEST intrinsics.
15416   case XTEST: {
15417     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
15418     SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
15419     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15420                                 DAG.getConstant(X86::COND_NE, MVT::i8),
15421                                 InTrans);
15422     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
15423     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
15424                        Ret, SDValue(InTrans.getNode(), 1));
15425   }
15426   // ADC/ADCX/SBB
15427   case ADX: {
15428     SmallVector<SDValue, 2> Results;
15429     SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
15430     SDVTList VTs = DAG.getVTList(Op.getOperand(3)->getValueType(0), MVT::Other);
15431     SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(2),
15432                                 DAG.getConstant(-1, MVT::i8));
15433     SDValue Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(3),
15434                               Op.getOperand(4), GenCF.getValue(1));
15435     SDValue Store = DAG.getStore(Op.getOperand(0), dl, Res.getValue(0),
15436                                  Op.getOperand(5), MachinePointerInfo(),
15437                                  false, false, 0);
15438     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15439                                 DAG.getConstant(X86::COND_B, MVT::i8),
15440                                 Res.getValue(1));
15441     Results.push_back(SetCC);
15442     Results.push_back(Store);
15443     return DAG.getMergeValues(Results, dl);
15444   }
15445   case COMPRESS_TO_MEM: {
15446     SDLoc dl(Op);
15447     SDValue Mask = Op.getOperand(4);
15448     SDValue DataToCompress = Op.getOperand(3);
15449     SDValue Addr = Op.getOperand(2);
15450     SDValue Chain = Op.getOperand(0);
15451
15452     if (isAllOnes(Mask)) // return just a store
15453       return DAG.getStore(Chain, dl, DataToCompress, Addr,
15454                           MachinePointerInfo(), false, false, 0);
15455
15456     EVT VT = DataToCompress.getValueType();
15457     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15458                                   VT.getVectorNumElements());
15459     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15460                                      Mask.getValueType().getSizeInBits());
15461     SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15462                                 DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
15463                                 DAG.getIntPtrConstant(0));
15464
15465     SDValue Compressed =  DAG.getNode(IntrData->Opc0, dl, VT, VMask,
15466                                       DataToCompress, DAG.getUNDEF(VT));
15467     return DAG.getStore(Chain, dl, Compressed, Addr,
15468                         MachinePointerInfo(), false, false, 0);
15469   }
15470   case EXPAND_FROM_MEM: {
15471     SDLoc dl(Op);
15472     SDValue Mask = Op.getOperand(4);
15473     SDValue PathThru = Op.getOperand(3);
15474     SDValue Addr = Op.getOperand(2);
15475     SDValue Chain = Op.getOperand(0);
15476     EVT VT = Op.getValueType();
15477
15478     if (isAllOnes(Mask)) // return just a load
15479       return DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(), false, false,
15480                          false, 0);
15481     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15482                                   VT.getVectorNumElements());
15483     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15484                                      Mask.getValueType().getSizeInBits());
15485     SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15486                                 DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
15487                                 DAG.getIntPtrConstant(0));
15488
15489     SDValue DataToExpand = DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(),
15490                                    false, false, false, 0);
15491
15492     SDValue Results[] = {
15493         DAG.getNode(IntrData->Opc0, dl, VT, VMask, DataToExpand, PathThru),
15494         Chain};
15495     return DAG.getMergeValues(Results, dl);
15496   }
15497   }
15498 }
15499
15500 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
15501                                            SelectionDAG &DAG) const {
15502   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
15503   MFI->setReturnAddressIsTaken(true);
15504
15505   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
15506     return SDValue();
15507
15508   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15509   SDLoc dl(Op);
15510   EVT PtrVT = getPointerTy();
15511
15512   if (Depth > 0) {
15513     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
15514     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15515     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
15516     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15517                        DAG.getNode(ISD::ADD, dl, PtrVT,
15518                                    FrameAddr, Offset),
15519                        MachinePointerInfo(), false, false, false, 0);
15520   }
15521
15522   // Just load the return address.
15523   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
15524   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15525                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
15526 }
15527
15528 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
15529   MachineFunction &MF = DAG.getMachineFunction();
15530   MachineFrameInfo *MFI = MF.getFrameInfo();
15531   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
15532   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15533   EVT VT = Op.getValueType();
15534
15535   MFI->setFrameAddressIsTaken(true);
15536
15537   if (MF.getTarget().getMCAsmInfo()->usesWindowsCFI()) {
15538     // Depth > 0 makes no sense on targets which use Windows unwind codes.  It
15539     // is not possible to crawl up the stack without looking at the unwind codes
15540     // simultaneously.
15541     int FrameAddrIndex = FuncInfo->getFAIndex();
15542     if (!FrameAddrIndex) {
15543       // Set up a frame object for the return address.
15544       unsigned SlotSize = RegInfo->getSlotSize();
15545       FrameAddrIndex = MF.getFrameInfo()->CreateFixedObject(
15546           SlotSize, /*Offset=*/INT64_MIN, /*IsImmutable=*/false);
15547       FuncInfo->setFAIndex(FrameAddrIndex);
15548     }
15549     return DAG.getFrameIndex(FrameAddrIndex, VT);
15550   }
15551
15552   unsigned FrameReg =
15553       RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
15554   SDLoc dl(Op);  // FIXME probably not meaningful
15555   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15556   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
15557           (FrameReg == X86::EBP && VT == MVT::i32)) &&
15558          "Invalid Frame Register!");
15559   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
15560   while (Depth--)
15561     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
15562                             MachinePointerInfo(),
15563                             false, false, false, 0);
15564   return FrameAddr;
15565 }
15566
15567 // FIXME? Maybe this could be a TableGen attribute on some registers and
15568 // this table could be generated automatically from RegInfo.
15569 unsigned X86TargetLowering::getRegisterByName(const char* RegName,
15570                                               EVT VT) const {
15571   unsigned Reg = StringSwitch<unsigned>(RegName)
15572                        .Case("esp", X86::ESP)
15573                        .Case("rsp", X86::RSP)
15574                        .Default(0);
15575   if (Reg)
15576     return Reg;
15577   report_fatal_error("Invalid register name global variable");
15578 }
15579
15580 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
15581                                                      SelectionDAG &DAG) const {
15582   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15583   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
15584 }
15585
15586 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
15587   SDValue Chain     = Op.getOperand(0);
15588   SDValue Offset    = Op.getOperand(1);
15589   SDValue Handler   = Op.getOperand(2);
15590   SDLoc dl      (Op);
15591
15592   EVT PtrVT = getPointerTy();
15593   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15594   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
15595   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
15596           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
15597          "Invalid Frame Register!");
15598   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
15599   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
15600
15601   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
15602                                  DAG.getIntPtrConstant(RegInfo->getSlotSize()));
15603   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
15604   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
15605                        false, false, 0);
15606   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
15607
15608   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
15609                      DAG.getRegister(StoreAddrReg, PtrVT));
15610 }
15611
15612 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
15613                                                SelectionDAG &DAG) const {
15614   SDLoc DL(Op);
15615   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
15616                      DAG.getVTList(MVT::i32, MVT::Other),
15617                      Op.getOperand(0), Op.getOperand(1));
15618 }
15619
15620 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
15621                                                 SelectionDAG &DAG) const {
15622   SDLoc DL(Op);
15623   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
15624                      Op.getOperand(0), Op.getOperand(1));
15625 }
15626
15627 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
15628   return Op.getOperand(0);
15629 }
15630
15631 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
15632                                                 SelectionDAG &DAG) const {
15633   SDValue Root = Op.getOperand(0);
15634   SDValue Trmp = Op.getOperand(1); // trampoline
15635   SDValue FPtr = Op.getOperand(2); // nested function
15636   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
15637   SDLoc dl (Op);
15638
15639   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
15640   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
15641
15642   if (Subtarget->is64Bit()) {
15643     SDValue OutChains[6];
15644
15645     // Large code-model.
15646     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
15647     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
15648
15649     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
15650     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
15651
15652     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
15653
15654     // Load the pointer to the nested function into R11.
15655     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
15656     SDValue Addr = Trmp;
15657     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
15658                                 Addr, MachinePointerInfo(TrmpAddr),
15659                                 false, false, 0);
15660
15661     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15662                        DAG.getConstant(2, MVT::i64));
15663     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
15664                                 MachinePointerInfo(TrmpAddr, 2),
15665                                 false, false, 2);
15666
15667     // Load the 'nest' parameter value into R10.
15668     // R10 is specified in X86CallingConv.td
15669     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
15670     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15671                        DAG.getConstant(10, MVT::i64));
15672     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
15673                                 Addr, MachinePointerInfo(TrmpAddr, 10),
15674                                 false, false, 0);
15675
15676     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15677                        DAG.getConstant(12, MVT::i64));
15678     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
15679                                 MachinePointerInfo(TrmpAddr, 12),
15680                                 false, false, 2);
15681
15682     // Jump to the nested function.
15683     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
15684     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15685                        DAG.getConstant(20, MVT::i64));
15686     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
15687                                 Addr, MachinePointerInfo(TrmpAddr, 20),
15688                                 false, false, 0);
15689
15690     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
15691     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15692                        DAG.getConstant(22, MVT::i64));
15693     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
15694                                 MachinePointerInfo(TrmpAddr, 22),
15695                                 false, false, 0);
15696
15697     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
15698   } else {
15699     const Function *Func =
15700       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
15701     CallingConv::ID CC = Func->getCallingConv();
15702     unsigned NestReg;
15703
15704     switch (CC) {
15705     default:
15706       llvm_unreachable("Unsupported calling convention");
15707     case CallingConv::C:
15708     case CallingConv::X86_StdCall: {
15709       // Pass 'nest' parameter in ECX.
15710       // Must be kept in sync with X86CallingConv.td
15711       NestReg = X86::ECX;
15712
15713       // Check that ECX wasn't needed by an 'inreg' parameter.
15714       FunctionType *FTy = Func->getFunctionType();
15715       const AttributeSet &Attrs = Func->getAttributes();
15716
15717       if (!Attrs.isEmpty() && !Func->isVarArg()) {
15718         unsigned InRegCount = 0;
15719         unsigned Idx = 1;
15720
15721         for (FunctionType::param_iterator I = FTy->param_begin(),
15722              E = FTy->param_end(); I != E; ++I, ++Idx)
15723           if (Attrs.hasAttribute(Idx, Attribute::InReg))
15724             // FIXME: should only count parameters that are lowered to integers.
15725             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
15726
15727         if (InRegCount > 2) {
15728           report_fatal_error("Nest register in use - reduce number of inreg"
15729                              " parameters!");
15730         }
15731       }
15732       break;
15733     }
15734     case CallingConv::X86_FastCall:
15735     case CallingConv::X86_ThisCall:
15736     case CallingConv::Fast:
15737       // Pass 'nest' parameter in EAX.
15738       // Must be kept in sync with X86CallingConv.td
15739       NestReg = X86::EAX;
15740       break;
15741     }
15742
15743     SDValue OutChains[4];
15744     SDValue Addr, Disp;
15745
15746     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15747                        DAG.getConstant(10, MVT::i32));
15748     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
15749
15750     // This is storing the opcode for MOV32ri.
15751     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
15752     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
15753     OutChains[0] = DAG.getStore(Root, dl,
15754                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
15755                                 Trmp, MachinePointerInfo(TrmpAddr),
15756                                 false, false, 0);
15757
15758     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15759                        DAG.getConstant(1, MVT::i32));
15760     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
15761                                 MachinePointerInfo(TrmpAddr, 1),
15762                                 false, false, 1);
15763
15764     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
15765     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15766                        DAG.getConstant(5, MVT::i32));
15767     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
15768                                 MachinePointerInfo(TrmpAddr, 5),
15769                                 false, false, 1);
15770
15771     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15772                        DAG.getConstant(6, MVT::i32));
15773     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
15774                                 MachinePointerInfo(TrmpAddr, 6),
15775                                 false, false, 1);
15776
15777     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
15778   }
15779 }
15780
15781 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
15782                                             SelectionDAG &DAG) const {
15783   /*
15784    The rounding mode is in bits 11:10 of FPSR, and has the following
15785    settings:
15786      00 Round to nearest
15787      01 Round to -inf
15788      10 Round to +inf
15789      11 Round to 0
15790
15791   FLT_ROUNDS, on the other hand, expects the following:
15792     -1 Undefined
15793      0 Round to 0
15794      1 Round to nearest
15795      2 Round to +inf
15796      3 Round to -inf
15797
15798   To perform the conversion, we do:
15799     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
15800   */
15801
15802   MachineFunction &MF = DAG.getMachineFunction();
15803   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
15804   unsigned StackAlignment = TFI.getStackAlignment();
15805   MVT VT = Op.getSimpleValueType();
15806   SDLoc DL(Op);
15807
15808   // Save FP Control Word to stack slot
15809   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
15810   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
15811
15812   MachineMemOperand *MMO =
15813    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
15814                            MachineMemOperand::MOStore, 2, 2);
15815
15816   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
15817   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
15818                                           DAG.getVTList(MVT::Other),
15819                                           Ops, MVT::i16, MMO);
15820
15821   // Load FP Control Word from stack slot
15822   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
15823                             MachinePointerInfo(), false, false, false, 0);
15824
15825   // Transform as necessary
15826   SDValue CWD1 =
15827     DAG.getNode(ISD::SRL, DL, MVT::i16,
15828                 DAG.getNode(ISD::AND, DL, MVT::i16,
15829                             CWD, DAG.getConstant(0x800, MVT::i16)),
15830                 DAG.getConstant(11, MVT::i8));
15831   SDValue CWD2 =
15832     DAG.getNode(ISD::SRL, DL, MVT::i16,
15833                 DAG.getNode(ISD::AND, DL, MVT::i16,
15834                             CWD, DAG.getConstant(0x400, MVT::i16)),
15835                 DAG.getConstant(9, MVT::i8));
15836
15837   SDValue RetVal =
15838     DAG.getNode(ISD::AND, DL, MVT::i16,
15839                 DAG.getNode(ISD::ADD, DL, MVT::i16,
15840                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
15841                             DAG.getConstant(1, MVT::i16)),
15842                 DAG.getConstant(3, MVT::i16));
15843
15844   return DAG.getNode((VT.getSizeInBits() < 16 ?
15845                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
15846 }
15847
15848 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
15849   MVT VT = Op.getSimpleValueType();
15850   EVT OpVT = VT;
15851   unsigned NumBits = VT.getSizeInBits();
15852   SDLoc dl(Op);
15853
15854   Op = Op.getOperand(0);
15855   if (VT == MVT::i8) {
15856     // Zero extend to i32 since there is not an i8 bsr.
15857     OpVT = MVT::i32;
15858     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
15859   }
15860
15861   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
15862   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
15863   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
15864
15865   // If src is zero (i.e. bsr sets ZF), returns NumBits.
15866   SDValue Ops[] = {
15867     Op,
15868     DAG.getConstant(NumBits+NumBits-1, OpVT),
15869     DAG.getConstant(X86::COND_E, MVT::i8),
15870     Op.getValue(1)
15871   };
15872   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
15873
15874   // Finally xor with NumBits-1.
15875   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
15876
15877   if (VT == MVT::i8)
15878     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
15879   return Op;
15880 }
15881
15882 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
15883   MVT VT = Op.getSimpleValueType();
15884   EVT OpVT = VT;
15885   unsigned NumBits = VT.getSizeInBits();
15886   SDLoc dl(Op);
15887
15888   Op = Op.getOperand(0);
15889   if (VT == MVT::i8) {
15890     // Zero extend to i32 since there is not an i8 bsr.
15891     OpVT = MVT::i32;
15892     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
15893   }
15894
15895   // Issue a bsr (scan bits in reverse).
15896   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
15897   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
15898
15899   // And xor with NumBits-1.
15900   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
15901
15902   if (VT == MVT::i8)
15903     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
15904   return Op;
15905 }
15906
15907 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
15908   MVT VT = Op.getSimpleValueType();
15909   unsigned NumBits = VT.getSizeInBits();
15910   SDLoc dl(Op);
15911   Op = Op.getOperand(0);
15912
15913   // Issue a bsf (scan bits forward) which also sets EFLAGS.
15914   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
15915   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
15916
15917   // If src is zero (i.e. bsf sets ZF), returns NumBits.
15918   SDValue Ops[] = {
15919     Op,
15920     DAG.getConstant(NumBits, VT),
15921     DAG.getConstant(X86::COND_E, MVT::i8),
15922     Op.getValue(1)
15923   };
15924   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
15925 }
15926
15927 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
15928 // ones, and then concatenate the result back.
15929 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
15930   MVT VT = Op.getSimpleValueType();
15931
15932   assert(VT.is256BitVector() && VT.isInteger() &&
15933          "Unsupported value type for operation");
15934
15935   unsigned NumElems = VT.getVectorNumElements();
15936   SDLoc dl(Op);
15937
15938   // Extract the LHS vectors
15939   SDValue LHS = Op.getOperand(0);
15940   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
15941   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
15942
15943   // Extract the RHS vectors
15944   SDValue RHS = Op.getOperand(1);
15945   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
15946   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
15947
15948   MVT EltVT = VT.getVectorElementType();
15949   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
15950
15951   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
15952                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
15953                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
15954 }
15955
15956 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
15957   assert(Op.getSimpleValueType().is256BitVector() &&
15958          Op.getSimpleValueType().isInteger() &&
15959          "Only handle AVX 256-bit vector integer operation");
15960   return Lower256IntArith(Op, DAG);
15961 }
15962
15963 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
15964   assert(Op.getSimpleValueType().is256BitVector() &&
15965          Op.getSimpleValueType().isInteger() &&
15966          "Only handle AVX 256-bit vector integer operation");
15967   return Lower256IntArith(Op, DAG);
15968 }
15969
15970 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
15971                         SelectionDAG &DAG) {
15972   SDLoc dl(Op);
15973   MVT VT = Op.getSimpleValueType();
15974
15975   // Decompose 256-bit ops into smaller 128-bit ops.
15976   if (VT.is256BitVector() && !Subtarget->hasInt256())
15977     return Lower256IntArith(Op, DAG);
15978
15979   SDValue A = Op.getOperand(0);
15980   SDValue B = Op.getOperand(1);
15981
15982   // Lower v16i8/v32i8 mul as promotion to v8i16/v16i16 vector
15983   // pairs, multiply and truncate.
15984   if (VT == MVT::v16i8 || VT == MVT::v32i8) {
15985     if (Subtarget->hasInt256()) {
15986       if (VT == MVT::v32i8) {
15987         MVT SubVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() / 2);
15988         SDValue Lo = DAG.getIntPtrConstant(0);
15989         SDValue Hi = DAG.getIntPtrConstant(VT.getVectorNumElements() / 2);
15990         SDValue ALo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Lo);
15991         SDValue BLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Lo);
15992         SDValue AHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Hi);
15993         SDValue BHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Hi);
15994         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
15995                            DAG.getNode(ISD::MUL, dl, SubVT, ALo, BLo),
15996                            DAG.getNode(ISD::MUL, dl, SubVT, AHi, BHi));
15997       }
15998
15999       MVT ExVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements());
16000       return DAG.getNode(
16001           ISD::TRUNCATE, dl, VT,
16002           DAG.getNode(ISD::MUL, dl, ExVT,
16003                       DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, A),
16004                       DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, B)));
16005     }
16006
16007     assert(VT == MVT::v16i8 &&
16008            "Pre-AVX2 support only supports v16i8 multiplication");
16009     MVT ExVT = MVT::v8i16;
16010
16011     // Extract the lo parts and sign extend to i16
16012     SDValue ALo, BLo;
16013     if (Subtarget->hasSSE41()) {
16014       ALo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, A);
16015       BLo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, B);
16016     } else {
16017       const int ShufMask[] = {0, -1, 1, -1, 2, -1, 3, -1,
16018                               4, -1, 5, -1, 6, -1, 7, -1};
16019       ALo = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16020       BLo = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16021       ALo = DAG.getNode(ISD::BITCAST, dl, ExVT, ALo);
16022       BLo = DAG.getNode(ISD::BITCAST, dl, ExVT, BLo);
16023       ALo = DAG.getNode(ISD::SRA, dl, ExVT, ALo, DAG.getConstant(8, ExVT));
16024       BLo = DAG.getNode(ISD::SRA, dl, ExVT, BLo, DAG.getConstant(8, ExVT));
16025     }
16026
16027     // Extract the hi parts and sign extend to i16
16028     SDValue AHi, BHi;
16029     if (Subtarget->hasSSE41()) {
16030       const int ShufMask[] = {8,  9,  10, 11, 12, 13, 14, 15,
16031                               -1, -1, -1, -1, -1, -1, -1, -1};
16032       AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16033       BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16034       AHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, AHi);
16035       BHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, BHi);
16036     } else {
16037       const int ShufMask[] = {8,  -1, 9,  -1, 10, -1, 11, -1,
16038                               12, -1, 13, -1, 14, -1, 15, -1};
16039       AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16040       BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16041       AHi = DAG.getNode(ISD::BITCAST, dl, ExVT, AHi);
16042       BHi = DAG.getNode(ISD::BITCAST, dl, ExVT, BHi);
16043       AHi = DAG.getNode(ISD::SRA, dl, ExVT, AHi, DAG.getConstant(8, ExVT));
16044       BHi = DAG.getNode(ISD::SRA, dl, ExVT, BHi, DAG.getConstant(8, ExVT));
16045     }
16046
16047     // Multiply, mask the lower 8bits of the lo/hi results and pack
16048     SDValue RLo = DAG.getNode(ISD::MUL, dl, ExVT, ALo, BLo);
16049     SDValue RHi = DAG.getNode(ISD::MUL, dl, ExVT, AHi, BHi);
16050     RLo = DAG.getNode(ISD::AND, dl, ExVT, RLo, DAG.getConstant(255, ExVT));
16051     RHi = DAG.getNode(ISD::AND, dl, ExVT, RHi, DAG.getConstant(255, ExVT));
16052     return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
16053   }
16054
16055   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
16056   if (VT == MVT::v4i32) {
16057     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
16058            "Should not custom lower when pmuldq is available!");
16059
16060     // Extract the odd parts.
16061     static const int UnpackMask[] = { 1, -1, 3, -1 };
16062     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
16063     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
16064
16065     // Multiply the even parts.
16066     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
16067     // Now multiply odd parts.
16068     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
16069
16070     Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
16071     Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
16072
16073     // Merge the two vectors back together with a shuffle. This expands into 2
16074     // shuffles.
16075     static const int ShufMask[] = { 0, 4, 2, 6 };
16076     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
16077   }
16078
16079   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
16080          "Only know how to lower V2I64/V4I64/V8I64 multiply");
16081
16082   //  Ahi = psrlqi(a, 32);
16083   //  Bhi = psrlqi(b, 32);
16084   //
16085   //  AloBlo = pmuludq(a, b);
16086   //  AloBhi = pmuludq(a, Bhi);
16087   //  AhiBlo = pmuludq(Ahi, b);
16088
16089   //  AloBhi = psllqi(AloBhi, 32);
16090   //  AhiBlo = psllqi(AhiBlo, 32);
16091   //  return AloBlo + AloBhi + AhiBlo;
16092
16093   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
16094   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
16095
16096   // Bit cast to 32-bit vectors for MULUDQ
16097   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
16098                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
16099   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
16100   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
16101   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
16102   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
16103
16104   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
16105   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
16106   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
16107
16108   AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
16109   AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
16110
16111   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
16112   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
16113 }
16114
16115 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
16116   assert(Subtarget->isTargetWin64() && "Unexpected target");
16117   EVT VT = Op.getValueType();
16118   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
16119          "Unexpected return type for lowering");
16120
16121   RTLIB::Libcall LC;
16122   bool isSigned;
16123   switch (Op->getOpcode()) {
16124   default: llvm_unreachable("Unexpected request for libcall!");
16125   case ISD::SDIV:      isSigned = true;  LC = RTLIB::SDIV_I128;    break;
16126   case ISD::UDIV:      isSigned = false; LC = RTLIB::UDIV_I128;    break;
16127   case ISD::SREM:      isSigned = true;  LC = RTLIB::SREM_I128;    break;
16128   case ISD::UREM:      isSigned = false; LC = RTLIB::UREM_I128;    break;
16129   case ISD::SDIVREM:   isSigned = true;  LC = RTLIB::SDIVREM_I128; break;
16130   case ISD::UDIVREM:   isSigned = false; LC = RTLIB::UDIVREM_I128; break;
16131   }
16132
16133   SDLoc dl(Op);
16134   SDValue InChain = DAG.getEntryNode();
16135
16136   TargetLowering::ArgListTy Args;
16137   TargetLowering::ArgListEntry Entry;
16138   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
16139     EVT ArgVT = Op->getOperand(i).getValueType();
16140     assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
16141            "Unexpected argument type for lowering");
16142     SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
16143     Entry.Node = StackPtr;
16144     InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
16145                            false, false, 16);
16146     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
16147     Entry.Ty = PointerType::get(ArgTy,0);
16148     Entry.isSExt = false;
16149     Entry.isZExt = false;
16150     Args.push_back(Entry);
16151   }
16152
16153   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
16154                                          getPointerTy());
16155
16156   TargetLowering::CallLoweringInfo CLI(DAG);
16157   CLI.setDebugLoc(dl).setChain(InChain)
16158     .setCallee(getLibcallCallingConv(LC),
16159                static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
16160                Callee, std::move(Args), 0)
16161     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
16162
16163   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
16164   return DAG.getNode(ISD::BITCAST, dl, VT, CallInfo.first);
16165 }
16166
16167 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
16168                              SelectionDAG &DAG) {
16169   SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
16170   EVT VT = Op0.getValueType();
16171   SDLoc dl(Op);
16172
16173   assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
16174          (VT == MVT::v8i32 && Subtarget->hasInt256()));
16175
16176   // PMULxD operations multiply each even value (starting at 0) of LHS with
16177   // the related value of RHS and produce a widen result.
16178   // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
16179   // => <2 x i64> <ae|cg>
16180   //
16181   // In other word, to have all the results, we need to perform two PMULxD:
16182   // 1. one with the even values.
16183   // 2. one with the odd values.
16184   // To achieve #2, with need to place the odd values at an even position.
16185   //
16186   // Place the odd value at an even position (basically, shift all values 1
16187   // step to the left):
16188   const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
16189   // <a|b|c|d> => <b|undef|d|undef>
16190   SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
16191   // <e|f|g|h> => <f|undef|h|undef>
16192   SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
16193
16194   // Emit two multiplies, one for the lower 2 ints and one for the higher 2
16195   // ints.
16196   MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
16197   bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
16198   unsigned Opcode =
16199       (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
16200   // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
16201   // => <2 x i64> <ae|cg>
16202   SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
16203                              DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
16204   // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
16205   // => <2 x i64> <bf|dh>
16206   SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
16207                              DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
16208
16209   // Shuffle it back into the right order.
16210   SDValue Highs, Lows;
16211   if (VT == MVT::v8i32) {
16212     const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
16213     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
16214     const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
16215     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
16216   } else {
16217     const int HighMask[] = {1, 5, 3, 7};
16218     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
16219     const int LowMask[] = {0, 4, 2, 6};
16220     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
16221   }
16222
16223   // If we have a signed multiply but no PMULDQ fix up the high parts of a
16224   // unsigned multiply.
16225   if (IsSigned && !Subtarget->hasSSE41()) {
16226     SDValue ShAmt =
16227         DAG.getConstant(31, DAG.getTargetLoweringInfo().getShiftAmountTy(VT));
16228     SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
16229                              DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
16230     SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
16231                              DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
16232
16233     SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
16234     Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
16235   }
16236
16237   // The first result of MUL_LOHI is actually the low value, followed by the
16238   // high value.
16239   SDValue Ops[] = {Lows, Highs};
16240   return DAG.getMergeValues(Ops, dl);
16241 }
16242
16243 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
16244                                          const X86Subtarget *Subtarget) {
16245   MVT VT = Op.getSimpleValueType();
16246   SDLoc dl(Op);
16247   SDValue R = Op.getOperand(0);
16248   SDValue Amt = Op.getOperand(1);
16249
16250   // Optimize shl/srl/sra with constant shift amount.
16251   if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
16252     if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
16253       uint64_t ShiftAmt = ShiftConst->getZExtValue();
16254
16255       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
16256           (Subtarget->hasInt256() &&
16257            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
16258           (Subtarget->hasAVX512() &&
16259            (VT == MVT::v8i64 || VT == MVT::v16i32))) {
16260         if (Op.getOpcode() == ISD::SHL)
16261           return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
16262                                             DAG);
16263         if (Op.getOpcode() == ISD::SRL)
16264           return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
16265                                             DAG);
16266         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
16267           return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
16268                                             DAG);
16269       }
16270
16271       if (VT == MVT::v16i8 || (Subtarget->hasInt256() && VT == MVT::v32i8)) {
16272         unsigned NumElts = VT.getVectorNumElements();
16273         MVT ShiftVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
16274
16275         if (Op.getOpcode() == ISD::SHL) {
16276           // Make a large shift.
16277           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ShiftVT,
16278                                                    R, ShiftAmt, DAG);
16279           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
16280           // Zero out the rightmost bits.
16281           SmallVector<SDValue, 32> V(
16282               NumElts, DAG.getConstant(uint8_t(-1U << ShiftAmt), MVT::i8));
16283           return DAG.getNode(ISD::AND, dl, VT, SHL,
16284                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
16285         }
16286         if (Op.getOpcode() == ISD::SRL) {
16287           // Make a large shift.
16288           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ShiftVT,
16289                                                    R, ShiftAmt, DAG);
16290           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
16291           // Zero out the leftmost bits.
16292           SmallVector<SDValue, 32> V(
16293               NumElts, DAG.getConstant(uint8_t(-1U) >> ShiftAmt, MVT::i8));
16294           return DAG.getNode(ISD::AND, dl, VT, SRL,
16295                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
16296         }
16297         if (Op.getOpcode() == ISD::SRA) {
16298           if (ShiftAmt == 7) {
16299             // R s>> 7  ===  R s< 0
16300             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
16301             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
16302           }
16303
16304           // R s>> a === ((R u>> a) ^ m) - m
16305           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
16306           SmallVector<SDValue, 32> V(NumElts,
16307                                      DAG.getConstant(128 >> ShiftAmt, MVT::i8));
16308           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
16309           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
16310           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
16311           return Res;
16312         }
16313         llvm_unreachable("Unknown shift opcode.");
16314       }
16315     }
16316   }
16317
16318   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
16319   if (!Subtarget->is64Bit() &&
16320       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
16321       Amt.getOpcode() == ISD::BITCAST &&
16322       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
16323     Amt = Amt.getOperand(0);
16324     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
16325                      VT.getVectorNumElements();
16326     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
16327     uint64_t ShiftAmt = 0;
16328     for (unsigned i = 0; i != Ratio; ++i) {
16329       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
16330       if (!C)
16331         return SDValue();
16332       // 6 == Log2(64)
16333       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
16334     }
16335     // Check remaining shift amounts.
16336     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
16337       uint64_t ShAmt = 0;
16338       for (unsigned j = 0; j != Ratio; ++j) {
16339         ConstantSDNode *C =
16340           dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
16341         if (!C)
16342           return SDValue();
16343         // 6 == Log2(64)
16344         ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
16345       }
16346       if (ShAmt != ShiftAmt)
16347         return SDValue();
16348     }
16349     switch (Op.getOpcode()) {
16350     default:
16351       llvm_unreachable("Unknown shift opcode!");
16352     case ISD::SHL:
16353       return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
16354                                         DAG);
16355     case ISD::SRL:
16356       return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
16357                                         DAG);
16358     case ISD::SRA:
16359       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
16360                                         DAG);
16361     }
16362   }
16363
16364   return SDValue();
16365 }
16366
16367 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
16368                                         const X86Subtarget* Subtarget) {
16369   MVT VT = Op.getSimpleValueType();
16370   SDLoc dl(Op);
16371   SDValue R = Op.getOperand(0);
16372   SDValue Amt = Op.getOperand(1);
16373
16374   if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
16375       VT == MVT::v4i32 || VT == MVT::v8i16 ||
16376       (Subtarget->hasInt256() &&
16377        ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
16378         VT == MVT::v8i32 || VT == MVT::v16i16)) ||
16379        (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
16380     SDValue BaseShAmt;
16381     EVT EltVT = VT.getVectorElementType();
16382
16383     if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Amt)) {
16384       // Check if this build_vector node is doing a splat.
16385       // If so, then set BaseShAmt equal to the splat value.
16386       BaseShAmt = BV->getSplatValue();
16387       if (BaseShAmt && BaseShAmt.getOpcode() == ISD::UNDEF)
16388         BaseShAmt = SDValue();
16389     } else {
16390       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
16391         Amt = Amt.getOperand(0);
16392
16393       ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt);
16394       if (SVN && SVN->isSplat()) {
16395         unsigned SplatIdx = (unsigned)SVN->getSplatIndex();
16396         SDValue InVec = Amt.getOperand(0);
16397         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
16398           assert((SplatIdx < InVec.getValueType().getVectorNumElements()) &&
16399                  "Unexpected shuffle index found!");
16400           BaseShAmt = InVec.getOperand(SplatIdx);
16401         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
16402            if (ConstantSDNode *C =
16403                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
16404              if (C->getZExtValue() == SplatIdx)
16405                BaseShAmt = InVec.getOperand(1);
16406            }
16407         }
16408
16409         if (!BaseShAmt)
16410           // Avoid introducing an extract element from a shuffle.
16411           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InVec,
16412                                     DAG.getIntPtrConstant(SplatIdx));
16413       }
16414     }
16415
16416     if (BaseShAmt.getNode()) {
16417       assert(EltVT.bitsLE(MVT::i64) && "Unexpected element type!");
16418       if (EltVT != MVT::i64 && EltVT.bitsGT(MVT::i32))
16419         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, BaseShAmt);
16420       else if (EltVT.bitsLT(MVT::i32))
16421         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
16422
16423       switch (Op.getOpcode()) {
16424       default:
16425         llvm_unreachable("Unknown shift opcode!");
16426       case ISD::SHL:
16427         switch (VT.SimpleTy) {
16428         default: return SDValue();
16429         case MVT::v2i64:
16430         case MVT::v4i32:
16431         case MVT::v8i16:
16432         case MVT::v4i64:
16433         case MVT::v8i32:
16434         case MVT::v16i16:
16435         case MVT::v16i32:
16436         case MVT::v8i64:
16437           return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
16438         }
16439       case ISD::SRA:
16440         switch (VT.SimpleTy) {
16441         default: return SDValue();
16442         case MVT::v4i32:
16443         case MVT::v8i16:
16444         case MVT::v8i32:
16445         case MVT::v16i16:
16446         case MVT::v16i32:
16447         case MVT::v8i64:
16448           return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
16449         }
16450       case ISD::SRL:
16451         switch (VT.SimpleTy) {
16452         default: return SDValue();
16453         case MVT::v2i64:
16454         case MVT::v4i32:
16455         case MVT::v8i16:
16456         case MVT::v4i64:
16457         case MVT::v8i32:
16458         case MVT::v16i16:
16459         case MVT::v16i32:
16460         case MVT::v8i64:
16461           return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
16462         }
16463       }
16464     }
16465   }
16466
16467   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
16468   if (!Subtarget->is64Bit() &&
16469       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
16470       (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
16471       Amt.getOpcode() == ISD::BITCAST &&
16472       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
16473     Amt = Amt.getOperand(0);
16474     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
16475                      VT.getVectorNumElements();
16476     std::vector<SDValue> Vals(Ratio);
16477     for (unsigned i = 0; i != Ratio; ++i)
16478       Vals[i] = Amt.getOperand(i);
16479     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
16480       for (unsigned j = 0; j != Ratio; ++j)
16481         if (Vals[j] != Amt.getOperand(i + j))
16482           return SDValue();
16483     }
16484     switch (Op.getOpcode()) {
16485     default:
16486       llvm_unreachable("Unknown shift opcode!");
16487     case ISD::SHL:
16488       return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
16489     case ISD::SRL:
16490       return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
16491     case ISD::SRA:
16492       return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
16493     }
16494   }
16495
16496   return SDValue();
16497 }
16498
16499 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
16500                           SelectionDAG &DAG) {
16501   MVT VT = Op.getSimpleValueType();
16502   SDLoc dl(Op);
16503   SDValue R = Op.getOperand(0);
16504   SDValue Amt = Op.getOperand(1);
16505
16506   assert(VT.isVector() && "Custom lowering only for vector shifts!");
16507   assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
16508
16509   if (SDValue V = LowerScalarImmediateShift(Op, DAG, Subtarget))
16510     return V;
16511
16512   if (SDValue V = LowerScalarVariableShift(Op, DAG, Subtarget))
16513       return V;
16514
16515   if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
16516     return Op;
16517
16518   // AVX2 has VPSLLV/VPSRAV/VPSRLV.
16519   if (Subtarget->hasInt256()) {
16520     if (Op.getOpcode() == ISD::SRL &&
16521         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
16522          VT == MVT::v4i64 || VT == MVT::v8i32))
16523       return Op;
16524     if (Op.getOpcode() == ISD::SHL &&
16525         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
16526          VT == MVT::v4i64 || VT == MVT::v8i32))
16527       return Op;
16528     if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
16529       return Op;
16530   }
16531
16532   // 2i64 vector logical shifts can efficiently avoid scalarization - do the
16533   // shifts per-lane and then shuffle the partial results back together.
16534   if (VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) {
16535     // Splat the shift amounts so the scalar shifts above will catch it.
16536     SDValue Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {0, 0});
16537     SDValue Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {1, 1});
16538     SDValue R0 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt0);
16539     SDValue R1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt1);
16540     return DAG.getVectorShuffle(VT, dl, R0, R1, {0, 3});
16541   }
16542
16543   // If possible, lower this packed shift into a vector multiply instead of
16544   // expanding it into a sequence of scalar shifts.
16545   // Do this only if the vector shift count is a constant build_vector.
16546   if (Op.getOpcode() == ISD::SHL &&
16547       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
16548        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
16549       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
16550     SmallVector<SDValue, 8> Elts;
16551     EVT SVT = VT.getScalarType();
16552     unsigned SVTBits = SVT.getSizeInBits();
16553     const APInt &One = APInt(SVTBits, 1);
16554     unsigned NumElems = VT.getVectorNumElements();
16555
16556     for (unsigned i=0; i !=NumElems; ++i) {
16557       SDValue Op = Amt->getOperand(i);
16558       if (Op->getOpcode() == ISD::UNDEF) {
16559         Elts.push_back(Op);
16560         continue;
16561       }
16562
16563       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
16564       const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
16565       uint64_t ShAmt = C.getZExtValue();
16566       if (ShAmt >= SVTBits) {
16567         Elts.push_back(DAG.getUNDEF(SVT));
16568         continue;
16569       }
16570       Elts.push_back(DAG.getConstant(One.shl(ShAmt), SVT));
16571     }
16572     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
16573     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
16574   }
16575
16576   // Lower SHL with variable shift amount.
16577   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
16578     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
16579
16580     Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
16581     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
16582     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
16583     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
16584   }
16585
16586   // If possible, lower this shift as a sequence of two shifts by
16587   // constant plus a MOVSS/MOVSD instead of scalarizing it.
16588   // Example:
16589   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
16590   //
16591   // Could be rewritten as:
16592   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
16593   //
16594   // The advantage is that the two shifts from the example would be
16595   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
16596   // the vector shift into four scalar shifts plus four pairs of vector
16597   // insert/extract.
16598   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
16599       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
16600     unsigned TargetOpcode = X86ISD::MOVSS;
16601     bool CanBeSimplified;
16602     // The splat value for the first packed shift (the 'X' from the example).
16603     SDValue Amt1 = Amt->getOperand(0);
16604     // The splat value for the second packed shift (the 'Y' from the example).
16605     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
16606                                         Amt->getOperand(2);
16607
16608     // See if it is possible to replace this node with a sequence of
16609     // two shifts followed by a MOVSS/MOVSD
16610     if (VT == MVT::v4i32) {
16611       // Check if it is legal to use a MOVSS.
16612       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
16613                         Amt2 == Amt->getOperand(3);
16614       if (!CanBeSimplified) {
16615         // Otherwise, check if we can still simplify this node using a MOVSD.
16616         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
16617                           Amt->getOperand(2) == Amt->getOperand(3);
16618         TargetOpcode = X86ISD::MOVSD;
16619         Amt2 = Amt->getOperand(2);
16620       }
16621     } else {
16622       // Do similar checks for the case where the machine value type
16623       // is MVT::v8i16.
16624       CanBeSimplified = Amt1 == Amt->getOperand(1);
16625       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
16626         CanBeSimplified = Amt2 == Amt->getOperand(i);
16627
16628       if (!CanBeSimplified) {
16629         TargetOpcode = X86ISD::MOVSD;
16630         CanBeSimplified = true;
16631         Amt2 = Amt->getOperand(4);
16632         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
16633           CanBeSimplified = Amt1 == Amt->getOperand(i);
16634         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
16635           CanBeSimplified = Amt2 == Amt->getOperand(j);
16636       }
16637     }
16638
16639     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
16640         isa<ConstantSDNode>(Amt2)) {
16641       // Replace this node with two shifts followed by a MOVSS/MOVSD.
16642       EVT CastVT = MVT::v4i32;
16643       SDValue Splat1 =
16644         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), VT);
16645       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
16646       SDValue Splat2 =
16647         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), VT);
16648       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
16649       if (TargetOpcode == X86ISD::MOVSD)
16650         CastVT = MVT::v2i64;
16651       SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
16652       SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
16653       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
16654                                             BitCast1, DAG);
16655       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
16656     }
16657   }
16658
16659   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
16660     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
16661
16662     // a = a << 5;
16663     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
16664     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
16665
16666     // Turn 'a' into a mask suitable for VSELECT
16667     SDValue VSelM = DAG.getConstant(0x80, VT);
16668     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16669     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16670
16671     SDValue CM1 = DAG.getConstant(0x0f, VT);
16672     SDValue CM2 = DAG.getConstant(0x3f, VT);
16673
16674     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
16675     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
16676     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
16677     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
16678     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
16679
16680     // a += a
16681     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
16682     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16683     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16684
16685     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
16686     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
16687     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
16688     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
16689     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
16690
16691     // a += a
16692     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
16693     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16694     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16695
16696     // return VSELECT(r, r+r, a);
16697     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
16698                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
16699     return R;
16700   }
16701
16702   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
16703   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
16704   // solution better.
16705   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
16706     MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
16707     unsigned ExtOpc =
16708         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
16709     R = DAG.getNode(ExtOpc, dl, NewVT, R);
16710     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
16711     return DAG.getNode(ISD::TRUNCATE, dl, VT,
16712                        DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
16713   }
16714
16715   // Decompose 256-bit shifts into smaller 128-bit shifts.
16716   if (VT.is256BitVector()) {
16717     unsigned NumElems = VT.getVectorNumElements();
16718     MVT EltVT = VT.getVectorElementType();
16719     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16720
16721     // Extract the two vectors
16722     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
16723     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
16724
16725     // Recreate the shift amount vectors
16726     SDValue Amt1, Amt2;
16727     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
16728       // Constant shift amount
16729       SmallVector<SDValue, 8> Ops(Amt->op_begin(), Amt->op_begin() + NumElems);
16730       ArrayRef<SDValue> Amt1Csts = makeArrayRef(Ops).slice(0, NumElems / 2);
16731       ArrayRef<SDValue> Amt2Csts = makeArrayRef(Ops).slice(NumElems / 2);
16732
16733       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
16734       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
16735     } else {
16736       // Variable shift amount
16737       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
16738       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
16739     }
16740
16741     // Issue new vector shifts for the smaller types
16742     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
16743     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
16744
16745     // Concatenate the result back
16746     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
16747   }
16748
16749   return SDValue();
16750 }
16751
16752 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
16753   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
16754   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
16755   // looks for this combo and may remove the "setcc" instruction if the "setcc"
16756   // has only one use.
16757   SDNode *N = Op.getNode();
16758   SDValue LHS = N->getOperand(0);
16759   SDValue RHS = N->getOperand(1);
16760   unsigned BaseOp = 0;
16761   unsigned Cond = 0;
16762   SDLoc DL(Op);
16763   switch (Op.getOpcode()) {
16764   default: llvm_unreachable("Unknown ovf instruction!");
16765   case ISD::SADDO:
16766     // A subtract of one will be selected as a INC. Note that INC doesn't
16767     // set CF, so we can't do this for UADDO.
16768     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16769       if (C->isOne()) {
16770         BaseOp = X86ISD::INC;
16771         Cond = X86::COND_O;
16772         break;
16773       }
16774     BaseOp = X86ISD::ADD;
16775     Cond = X86::COND_O;
16776     break;
16777   case ISD::UADDO:
16778     BaseOp = X86ISD::ADD;
16779     Cond = X86::COND_B;
16780     break;
16781   case ISD::SSUBO:
16782     // A subtract of one will be selected as a DEC. Note that DEC doesn't
16783     // set CF, so we can't do this for USUBO.
16784     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16785       if (C->isOne()) {
16786         BaseOp = X86ISD::DEC;
16787         Cond = X86::COND_O;
16788         break;
16789       }
16790     BaseOp = X86ISD::SUB;
16791     Cond = X86::COND_O;
16792     break;
16793   case ISD::USUBO:
16794     BaseOp = X86ISD::SUB;
16795     Cond = X86::COND_B;
16796     break;
16797   case ISD::SMULO:
16798     BaseOp = N->getValueType(0) == MVT::i8 ? X86ISD::SMUL8 : X86ISD::SMUL;
16799     Cond = X86::COND_O;
16800     break;
16801   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
16802     if (N->getValueType(0) == MVT::i8) {
16803       BaseOp = X86ISD::UMUL8;
16804       Cond = X86::COND_O;
16805       break;
16806     }
16807     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
16808                                  MVT::i32);
16809     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
16810
16811     SDValue SetCC =
16812       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16813                   DAG.getConstant(X86::COND_O, MVT::i32),
16814                   SDValue(Sum.getNode(), 2));
16815
16816     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
16817   }
16818   }
16819
16820   // Also sets EFLAGS.
16821   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
16822   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
16823
16824   SDValue SetCC =
16825     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
16826                 DAG.getConstant(Cond, MVT::i32),
16827                 SDValue(Sum.getNode(), 1));
16828
16829   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
16830 }
16831
16832 /// Returns true if the operand type is exactly twice the native width, and
16833 /// the corresponding cmpxchg8b or cmpxchg16b instruction is available.
16834 /// Used to know whether to use cmpxchg8/16b when expanding atomic operations
16835 /// (otherwise we leave them alone to become __sync_fetch_and_... calls).
16836 bool X86TargetLowering::needsCmpXchgNb(const Type *MemType) const {
16837   unsigned OpWidth = MemType->getPrimitiveSizeInBits();
16838
16839   if (OpWidth == 64)
16840     return !Subtarget->is64Bit(); // FIXME this should be Subtarget.hasCmpxchg8b
16841   else if (OpWidth == 128)
16842     return Subtarget->hasCmpxchg16b();
16843   else
16844     return false;
16845 }
16846
16847 bool X86TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
16848   return needsCmpXchgNb(SI->getValueOperand()->getType());
16849 }
16850
16851 // Note: this turns large loads into lock cmpxchg8b/16b.
16852 // FIXME: On 32 bits x86, fild/movq might be faster than lock cmpxchg8b.
16853 bool X86TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
16854   auto PTy = cast<PointerType>(LI->getPointerOperand()->getType());
16855   return needsCmpXchgNb(PTy->getElementType());
16856 }
16857
16858 TargetLoweringBase::AtomicRMWExpansionKind
16859 X86TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
16860   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
16861   const Type *MemType = AI->getType();
16862
16863   // If the operand is too big, we must see if cmpxchg8/16b is available
16864   // and default to library calls otherwise.
16865   if (MemType->getPrimitiveSizeInBits() > NativeWidth) {
16866     return needsCmpXchgNb(MemType) ? AtomicRMWExpansionKind::CmpXChg
16867                                    : AtomicRMWExpansionKind::None;
16868   }
16869
16870   AtomicRMWInst::BinOp Op = AI->getOperation();
16871   switch (Op) {
16872   default:
16873     llvm_unreachable("Unknown atomic operation");
16874   case AtomicRMWInst::Xchg:
16875   case AtomicRMWInst::Add:
16876   case AtomicRMWInst::Sub:
16877     // It's better to use xadd, xsub or xchg for these in all cases.
16878     return AtomicRMWExpansionKind::None;
16879   case AtomicRMWInst::Or:
16880   case AtomicRMWInst::And:
16881   case AtomicRMWInst::Xor:
16882     // If the atomicrmw's result isn't actually used, we can just add a "lock"
16883     // prefix to a normal instruction for these operations.
16884     return !AI->use_empty() ? AtomicRMWExpansionKind::CmpXChg
16885                             : AtomicRMWExpansionKind::None;
16886   case AtomicRMWInst::Nand:
16887   case AtomicRMWInst::Max:
16888   case AtomicRMWInst::Min:
16889   case AtomicRMWInst::UMax:
16890   case AtomicRMWInst::UMin:
16891     // These always require a non-trivial set of data operations on x86. We must
16892     // use a cmpxchg loop.
16893     return AtomicRMWExpansionKind::CmpXChg;
16894   }
16895 }
16896
16897 static bool hasMFENCE(const X86Subtarget& Subtarget) {
16898   // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
16899   // no-sse2). There isn't any reason to disable it if the target processor
16900   // supports it.
16901   return Subtarget.hasSSE2() || Subtarget.is64Bit();
16902 }
16903
16904 LoadInst *
16905 X86TargetLowering::lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *AI) const {
16906   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
16907   const Type *MemType = AI->getType();
16908   // Accesses larger than the native width are turned into cmpxchg/libcalls, so
16909   // there is no benefit in turning such RMWs into loads, and it is actually
16910   // harmful as it introduces a mfence.
16911   if (MemType->getPrimitiveSizeInBits() > NativeWidth)
16912     return nullptr;
16913
16914   auto Builder = IRBuilder<>(AI);
16915   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
16916   auto SynchScope = AI->getSynchScope();
16917   // We must restrict the ordering to avoid generating loads with Release or
16918   // ReleaseAcquire orderings.
16919   auto Order = AtomicCmpXchgInst::getStrongestFailureOrdering(AI->getOrdering());
16920   auto Ptr = AI->getPointerOperand();
16921
16922   // Before the load we need a fence. Here is an example lifted from
16923   // http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf showing why a fence
16924   // is required:
16925   // Thread 0:
16926   //   x.store(1, relaxed);
16927   //   r1 = y.fetch_add(0, release);
16928   // Thread 1:
16929   //   y.fetch_add(42, acquire);
16930   //   r2 = x.load(relaxed);
16931   // r1 = r2 = 0 is impossible, but becomes possible if the idempotent rmw is
16932   // lowered to just a load without a fence. A mfence flushes the store buffer,
16933   // making the optimization clearly correct.
16934   // FIXME: it is required if isAtLeastRelease(Order) but it is not clear
16935   // otherwise, we might be able to be more agressive on relaxed idempotent
16936   // rmw. In practice, they do not look useful, so we don't try to be
16937   // especially clever.
16938   if (SynchScope == SingleThread) {
16939     // FIXME: we could just insert an X86ISD::MEMBARRIER here, except we are at
16940     // the IR level, so we must wrap it in an intrinsic.
16941     return nullptr;
16942   } else if (hasMFENCE(*Subtarget)) {
16943     Function *MFence = llvm::Intrinsic::getDeclaration(M,
16944             Intrinsic::x86_sse2_mfence);
16945     Builder.CreateCall(MFence);
16946   } else {
16947     // FIXME: it might make sense to use a locked operation here but on a
16948     // different cache-line to prevent cache-line bouncing. In practice it
16949     // is probably a small win, and x86 processors without mfence are rare
16950     // enough that we do not bother.
16951     return nullptr;
16952   }
16953
16954   // Finally we can emit the atomic load.
16955   LoadInst *Loaded = Builder.CreateAlignedLoad(Ptr,
16956           AI->getType()->getPrimitiveSizeInBits());
16957   Loaded->setAtomic(Order, SynchScope);
16958   AI->replaceAllUsesWith(Loaded);
16959   AI->eraseFromParent();
16960   return Loaded;
16961 }
16962
16963 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
16964                                  SelectionDAG &DAG) {
16965   SDLoc dl(Op);
16966   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
16967     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
16968   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
16969     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
16970
16971   // The only fence that needs an instruction is a sequentially-consistent
16972   // cross-thread fence.
16973   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
16974     if (hasMFENCE(*Subtarget))
16975       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
16976
16977     SDValue Chain = Op.getOperand(0);
16978     SDValue Zero = DAG.getConstant(0, MVT::i32);
16979     SDValue Ops[] = {
16980       DAG.getRegister(X86::ESP, MVT::i32), // Base
16981       DAG.getTargetConstant(1, MVT::i8),   // Scale
16982       DAG.getRegister(0, MVT::i32),        // Index
16983       DAG.getTargetConstant(0, MVT::i32),  // Disp
16984       DAG.getRegister(0, MVT::i32),        // Segment.
16985       Zero,
16986       Chain
16987     };
16988     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
16989     return SDValue(Res, 0);
16990   }
16991
16992   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
16993   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
16994 }
16995
16996 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
16997                              SelectionDAG &DAG) {
16998   MVT T = Op.getSimpleValueType();
16999   SDLoc DL(Op);
17000   unsigned Reg = 0;
17001   unsigned size = 0;
17002   switch(T.SimpleTy) {
17003   default: llvm_unreachable("Invalid value type!");
17004   case MVT::i8:  Reg = X86::AL;  size = 1; break;
17005   case MVT::i16: Reg = X86::AX;  size = 2; break;
17006   case MVT::i32: Reg = X86::EAX; size = 4; break;
17007   case MVT::i64:
17008     assert(Subtarget->is64Bit() && "Node not type legal!");
17009     Reg = X86::RAX; size = 8;
17010     break;
17011   }
17012   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
17013                                   Op.getOperand(2), SDValue());
17014   SDValue Ops[] = { cpIn.getValue(0),
17015                     Op.getOperand(1),
17016                     Op.getOperand(3),
17017                     DAG.getTargetConstant(size, MVT::i8),
17018                     cpIn.getValue(1) };
17019   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
17020   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
17021   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
17022                                            Ops, T, MMO);
17023
17024   SDValue cpOut =
17025     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
17026   SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
17027                                       MVT::i32, cpOut.getValue(2));
17028   SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
17029                                 DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
17030
17031   DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
17032   DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
17033   DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
17034   return SDValue();
17035 }
17036
17037 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
17038                             SelectionDAG &DAG) {
17039   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
17040   MVT DstVT = Op.getSimpleValueType();
17041
17042   if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
17043     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
17044     if (DstVT != MVT::f64)
17045       // This conversion needs to be expanded.
17046       return SDValue();
17047
17048     SDValue InVec = Op->getOperand(0);
17049     SDLoc dl(Op);
17050     unsigned NumElts = SrcVT.getVectorNumElements();
17051     EVT SVT = SrcVT.getVectorElementType();
17052
17053     // Widen the vector in input in the case of MVT::v2i32.
17054     // Example: from MVT::v2i32 to MVT::v4i32.
17055     SmallVector<SDValue, 16> Elts;
17056     for (unsigned i = 0, e = NumElts; i != e; ++i)
17057       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
17058                                  DAG.getIntPtrConstant(i)));
17059
17060     // Explicitly mark the extra elements as Undef.
17061     Elts.append(NumElts, DAG.getUNDEF(SVT));
17062
17063     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
17064     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
17065     SDValue ToV2F64 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, BV);
17066     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
17067                        DAG.getIntPtrConstant(0));
17068   }
17069
17070   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
17071          Subtarget->hasMMX() && "Unexpected custom BITCAST");
17072   assert((DstVT == MVT::i64 ||
17073           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
17074          "Unexpected custom BITCAST");
17075   // i64 <=> MMX conversions are Legal.
17076   if (SrcVT==MVT::i64 && DstVT.isVector())
17077     return Op;
17078   if (DstVT==MVT::i64 && SrcVT.isVector())
17079     return Op;
17080   // MMX <=> MMX conversions are Legal.
17081   if (SrcVT.isVector() && DstVT.isVector())
17082     return Op;
17083   // All other conversions need to be expanded.
17084   return SDValue();
17085 }
17086
17087 static SDValue LowerCTPOP(SDValue Op, const X86Subtarget *Subtarget,
17088                           SelectionDAG &DAG) {
17089   SDNode *Node = Op.getNode();
17090   SDLoc dl(Node);
17091
17092   Op = Op.getOperand(0);
17093   EVT VT = Op.getValueType();
17094   assert((VT.is128BitVector() || VT.is256BitVector()) &&
17095          "CTPOP lowering only implemented for 128/256-bit wide vector types");
17096
17097   unsigned NumElts = VT.getVectorNumElements();
17098   EVT EltVT = VT.getVectorElementType();
17099   unsigned Len = EltVT.getSizeInBits();
17100
17101   // This is the vectorized version of the "best" algorithm from
17102   // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
17103   // with a minor tweak to use a series of adds + shifts instead of vector
17104   // multiplications. Implemented for the v2i64, v4i64, v4i32, v8i32 types:
17105   //
17106   //  v2i64, v4i64, v4i32 => Only profitable w/ popcnt disabled
17107   //  v8i32 => Always profitable
17108   //
17109   // FIXME: There a couple of possible improvements:
17110   //
17111   // 1) Support for i8 and i16 vectors (needs measurements if popcnt enabled).
17112   // 2) Use strategies from http://wm.ite.pl/articles/sse-popcount.html
17113   //
17114   assert(EltVT.isInteger() && (Len == 32 || Len == 64) && Len % 8 == 0 &&
17115          "CTPOP not implemented for this vector element type.");
17116
17117   // X86 canonicalize ANDs to vXi64, generate the appropriate bitcasts to avoid
17118   // extra legalization.
17119   bool NeedsBitcast = EltVT == MVT::i32;
17120   MVT BitcastVT = VT.is256BitVector() ? MVT::v4i64 : MVT::v2i64;
17121
17122   SDValue Cst55 = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x55)), EltVT);
17123   SDValue Cst33 = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x33)), EltVT);
17124   SDValue Cst0F = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x0F)), EltVT);
17125
17126   // v = v - ((v >> 1) & 0x55555555...)
17127   SmallVector<SDValue, 8> Ones(NumElts, DAG.getConstant(1, EltVT));
17128   SDValue OnesV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ones);
17129   SDValue Srl = DAG.getNode(ISD::SRL, dl, VT, Op, OnesV);
17130   if (NeedsBitcast)
17131     Srl = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Srl);
17132
17133   SmallVector<SDValue, 8> Mask55(NumElts, Cst55);
17134   SDValue M55 = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Mask55);
17135   if (NeedsBitcast)
17136     M55 = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M55);
17137
17138   SDValue And = DAG.getNode(ISD::AND, dl, Srl.getValueType(), Srl, M55);
17139   if (VT != And.getValueType())
17140     And = DAG.getNode(ISD::BITCAST, dl, VT, And);
17141   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, Op, And);
17142
17143   // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
17144   SmallVector<SDValue, 8> Mask33(NumElts, Cst33);
17145   SDValue M33 = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Mask33);
17146   SmallVector<SDValue, 8> Twos(NumElts, DAG.getConstant(2, EltVT));
17147   SDValue TwosV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Twos);
17148
17149   Srl = DAG.getNode(ISD::SRL, dl, VT, Sub, TwosV);
17150   if (NeedsBitcast) {
17151     Srl = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Srl);
17152     M33 = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M33);
17153     Sub = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Sub);
17154   }
17155
17156   SDValue AndRHS = DAG.getNode(ISD::AND, dl, M33.getValueType(), Srl, M33);
17157   SDValue AndLHS = DAG.getNode(ISD::AND, dl, M33.getValueType(), Sub, M33);
17158   if (VT != AndRHS.getValueType()) {
17159     AndRHS = DAG.getNode(ISD::BITCAST, dl, VT, AndRHS);
17160     AndLHS = DAG.getNode(ISD::BITCAST, dl, VT, AndLHS);
17161   }
17162   SDValue Add = DAG.getNode(ISD::ADD, dl, VT, AndLHS, AndRHS);
17163
17164   // v = (v + (v >> 4)) & 0x0F0F0F0F...
17165   SmallVector<SDValue, 8> Fours(NumElts, DAG.getConstant(4, EltVT));
17166   SDValue FoursV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Fours);
17167   Srl = DAG.getNode(ISD::SRL, dl, VT, Add, FoursV);
17168   Add = DAG.getNode(ISD::ADD, dl, VT, Add, Srl);
17169
17170   SmallVector<SDValue, 8> Mask0F(NumElts, Cst0F);
17171   SDValue M0F = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Mask0F);
17172   if (NeedsBitcast) {
17173     Add = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Add);
17174     M0F = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M0F);
17175   }
17176   And = DAG.getNode(ISD::AND, dl, M0F.getValueType(), Add, M0F);
17177   if (VT != And.getValueType())
17178     And = DAG.getNode(ISD::BITCAST, dl, VT, And);
17179
17180   // The algorithm mentioned above uses:
17181   //    v = (v * 0x01010101...) >> (Len - 8)
17182   //
17183   // Change it to use vector adds + vector shifts which yield faster results on
17184   // Haswell than using vector integer multiplication.
17185   //
17186   // For i32 elements:
17187   //    v = v + (v >> 8)
17188   //    v = v + (v >> 16)
17189   //
17190   // For i64 elements:
17191   //    v = v + (v >> 8)
17192   //    v = v + (v >> 16)
17193   //    v = v + (v >> 32)
17194   //
17195   Add = And;
17196   SmallVector<SDValue, 8> Csts;
17197   for (unsigned i = 8; i <= Len/2; i *= 2) {
17198     Csts.assign(NumElts, DAG.getConstant(i, EltVT));
17199     SDValue CstsV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Csts);
17200     Srl = DAG.getNode(ISD::SRL, dl, VT, Add, CstsV);
17201     Add = DAG.getNode(ISD::ADD, dl, VT, Add, Srl);
17202     Csts.clear();
17203   }
17204
17205   // The result is on the least significant 6-bits on i32 and 7-bits on i64.
17206   SDValue Cst3F = DAG.getConstant(APInt(Len, Len == 32 ? 0x3F : 0x7F), EltVT);
17207   SmallVector<SDValue, 8> Cst3FV(NumElts, Cst3F);
17208   SDValue M3F = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Cst3FV);
17209   if (NeedsBitcast) {
17210     Add = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Add);
17211     M3F = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M3F);
17212   }
17213   And = DAG.getNode(ISD::AND, dl, M3F.getValueType(), Add, M3F);
17214   if (VT != And.getValueType())
17215     And = DAG.getNode(ISD::BITCAST, dl, VT, And);
17216
17217   return And;
17218 }
17219
17220 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
17221   SDNode *Node = Op.getNode();
17222   SDLoc dl(Node);
17223   EVT T = Node->getValueType(0);
17224   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
17225                               DAG.getConstant(0, T), Node->getOperand(2));
17226   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
17227                        cast<AtomicSDNode>(Node)->getMemoryVT(),
17228                        Node->getOperand(0),
17229                        Node->getOperand(1), negOp,
17230                        cast<AtomicSDNode>(Node)->getMemOperand(),
17231                        cast<AtomicSDNode>(Node)->getOrdering(),
17232                        cast<AtomicSDNode>(Node)->getSynchScope());
17233 }
17234
17235 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
17236   SDNode *Node = Op.getNode();
17237   SDLoc dl(Node);
17238   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
17239
17240   // Convert seq_cst store -> xchg
17241   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
17242   // FIXME: On 32-bit, store -> fist or movq would be more efficient
17243   //        (The only way to get a 16-byte store is cmpxchg16b)
17244   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
17245   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
17246       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
17247     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
17248                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
17249                                  Node->getOperand(0),
17250                                  Node->getOperand(1), Node->getOperand(2),
17251                                  cast<AtomicSDNode>(Node)->getMemOperand(),
17252                                  cast<AtomicSDNode>(Node)->getOrdering(),
17253                                  cast<AtomicSDNode>(Node)->getSynchScope());
17254     return Swap.getValue(1);
17255   }
17256   // Other atomic stores have a simple pattern.
17257   return Op;
17258 }
17259
17260 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
17261   EVT VT = Op.getNode()->getSimpleValueType(0);
17262
17263   // Let legalize expand this if it isn't a legal type yet.
17264   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
17265     return SDValue();
17266
17267   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
17268
17269   unsigned Opc;
17270   bool ExtraOp = false;
17271   switch (Op.getOpcode()) {
17272   default: llvm_unreachable("Invalid code");
17273   case ISD::ADDC: Opc = X86ISD::ADD; break;
17274   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
17275   case ISD::SUBC: Opc = X86ISD::SUB; break;
17276   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
17277   }
17278
17279   if (!ExtraOp)
17280     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
17281                        Op.getOperand(1));
17282   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
17283                      Op.getOperand(1), Op.getOperand(2));
17284 }
17285
17286 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
17287                             SelectionDAG &DAG) {
17288   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
17289
17290   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
17291   // which returns the values as { float, float } (in XMM0) or
17292   // { double, double } (which is returned in XMM0, XMM1).
17293   SDLoc dl(Op);
17294   SDValue Arg = Op.getOperand(0);
17295   EVT ArgVT = Arg.getValueType();
17296   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
17297
17298   TargetLowering::ArgListTy Args;
17299   TargetLowering::ArgListEntry Entry;
17300
17301   Entry.Node = Arg;
17302   Entry.Ty = ArgTy;
17303   Entry.isSExt = false;
17304   Entry.isZExt = false;
17305   Args.push_back(Entry);
17306
17307   bool isF64 = ArgVT == MVT::f64;
17308   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
17309   // the small struct {f32, f32} is returned in (eax, edx). For f64,
17310   // the results are returned via SRet in memory.
17311   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
17312   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17313   SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
17314
17315   Type *RetTy = isF64
17316     ? (Type*)StructType::get(ArgTy, ArgTy, nullptr)
17317     : (Type*)VectorType::get(ArgTy, 4);
17318
17319   TargetLowering::CallLoweringInfo CLI(DAG);
17320   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
17321     .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
17322
17323   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
17324
17325   if (isF64)
17326     // Returned in xmm0 and xmm1.
17327     return CallResult.first;
17328
17329   // Returned in bits 0:31 and 32:64 xmm0.
17330   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
17331                                CallResult.first, DAG.getIntPtrConstant(0));
17332   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
17333                                CallResult.first, DAG.getIntPtrConstant(1));
17334   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
17335   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
17336 }
17337
17338 /// LowerOperation - Provide custom lowering hooks for some operations.
17339 ///
17340 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
17341   switch (Op.getOpcode()) {
17342   default: llvm_unreachable("Should not custom lower this!");
17343   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
17344   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
17345     return LowerCMP_SWAP(Op, Subtarget, DAG);
17346   case ISD::CTPOP:              return LowerCTPOP(Op, Subtarget, DAG);
17347   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
17348   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
17349   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
17350   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, Subtarget, DAG);
17351   case ISD::VECTOR_SHUFFLE:     return lowerVectorShuffle(Op, Subtarget, DAG);
17352   case ISD::VSELECT:            return LowerVSELECT(Op, DAG);
17353   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
17354   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
17355   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
17356   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
17357   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
17358   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
17359   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
17360   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
17361   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
17362   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
17363   case ISD::SHL_PARTS:
17364   case ISD::SRA_PARTS:
17365   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
17366   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
17367   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
17368   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
17369   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
17370   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
17371   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
17372   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
17373   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
17374   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
17375   case ISD::LOAD:               return LowerExtendedLoad(Op, Subtarget, DAG);
17376   case ISD::FABS:
17377   case ISD::FNEG:               return LowerFABSorFNEG(Op, DAG);
17378   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
17379   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
17380   case ISD::SETCC:              return LowerSETCC(Op, DAG);
17381   case ISD::SELECT:             return LowerSELECT(Op, DAG);
17382   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
17383   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
17384   case ISD::VASTART:            return LowerVASTART(Op, DAG);
17385   case ISD::VAARG:              return LowerVAARG(Op, DAG);
17386   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
17387   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, Subtarget, DAG);
17388   case ISD::INTRINSIC_VOID:
17389   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
17390   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
17391   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
17392   case ISD::FRAME_TO_ARGS_OFFSET:
17393                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
17394   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
17395   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
17396   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
17397   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
17398   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
17399   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
17400   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
17401   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
17402   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
17403   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
17404   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
17405   case ISD::UMUL_LOHI:
17406   case ISD::SMUL_LOHI:          return LowerMUL_LOHI(Op, Subtarget, DAG);
17407   case ISD::SRA:
17408   case ISD::SRL:
17409   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
17410   case ISD::SADDO:
17411   case ISD::UADDO:
17412   case ISD::SSUBO:
17413   case ISD::USUBO:
17414   case ISD::SMULO:
17415   case ISD::UMULO:              return LowerXALUO(Op, DAG);
17416   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
17417   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
17418   case ISD::ADDC:
17419   case ISD::ADDE:
17420   case ISD::SUBC:
17421   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
17422   case ISD::ADD:                return LowerADD(Op, DAG);
17423   case ISD::SUB:                return LowerSUB(Op, DAG);
17424   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
17425   }
17426 }
17427
17428 /// ReplaceNodeResults - Replace a node with an illegal result type
17429 /// with a new node built out of custom code.
17430 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
17431                                            SmallVectorImpl<SDValue>&Results,
17432                                            SelectionDAG &DAG) const {
17433   SDLoc dl(N);
17434   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17435   switch (N->getOpcode()) {
17436   default:
17437     llvm_unreachable("Do not know how to custom type legalize this operation!");
17438   // We might have generated v2f32 FMIN/FMAX operations. Widen them to v4f32.
17439   case X86ISD::FMINC:
17440   case X86ISD::FMIN:
17441   case X86ISD::FMAXC:
17442   case X86ISD::FMAX: {
17443     EVT VT = N->getValueType(0);
17444     if (VT != MVT::v2f32)
17445       llvm_unreachable("Unexpected type (!= v2f32) on FMIN/FMAX.");
17446     SDValue UNDEF = DAG.getUNDEF(VT);
17447     SDValue LHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
17448                               N->getOperand(0), UNDEF);
17449     SDValue RHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
17450                               N->getOperand(1), UNDEF);
17451     Results.push_back(DAG.getNode(N->getOpcode(), dl, MVT::v4f32, LHS, RHS));
17452     return;
17453   }
17454   case ISD::SIGN_EXTEND_INREG:
17455   case ISD::ADDC:
17456   case ISD::ADDE:
17457   case ISD::SUBC:
17458   case ISD::SUBE:
17459     // We don't want to expand or promote these.
17460     return;
17461   case ISD::SDIV:
17462   case ISD::UDIV:
17463   case ISD::SREM:
17464   case ISD::UREM:
17465   case ISD::SDIVREM:
17466   case ISD::UDIVREM: {
17467     SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
17468     Results.push_back(V);
17469     return;
17470   }
17471   case ISD::FP_TO_SINT:
17472   case ISD::FP_TO_UINT: {
17473     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
17474
17475     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
17476       return;
17477
17478     std::pair<SDValue,SDValue> Vals =
17479         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
17480     SDValue FIST = Vals.first, StackSlot = Vals.second;
17481     if (FIST.getNode()) {
17482       EVT VT = N->getValueType(0);
17483       // Return a load from the stack slot.
17484       if (StackSlot.getNode())
17485         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
17486                                       MachinePointerInfo(),
17487                                       false, false, false, 0));
17488       else
17489         Results.push_back(FIST);
17490     }
17491     return;
17492   }
17493   case ISD::UINT_TO_FP: {
17494     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
17495     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
17496         N->getValueType(0) != MVT::v2f32)
17497       return;
17498     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
17499                                  N->getOperand(0));
17500     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
17501                                      MVT::f64);
17502     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
17503     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
17504                              DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
17505     Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
17506     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
17507     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
17508     return;
17509   }
17510   case ISD::FP_ROUND: {
17511     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
17512         return;
17513     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
17514     Results.push_back(V);
17515     return;
17516   }
17517   case ISD::INTRINSIC_W_CHAIN: {
17518     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
17519     switch (IntNo) {
17520     default : llvm_unreachable("Do not know how to custom type "
17521                                "legalize this intrinsic operation!");
17522     case Intrinsic::x86_rdtsc:
17523       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
17524                                      Results);
17525     case Intrinsic::x86_rdtscp:
17526       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
17527                                      Results);
17528     case Intrinsic::x86_rdpmc:
17529       return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
17530     }
17531   }
17532   case ISD::READCYCLECOUNTER: {
17533     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
17534                                    Results);
17535   }
17536   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
17537     EVT T = N->getValueType(0);
17538     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
17539     bool Regs64bit = T == MVT::i128;
17540     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
17541     SDValue cpInL, cpInH;
17542     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
17543                         DAG.getConstant(0, HalfT));
17544     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
17545                         DAG.getConstant(1, HalfT));
17546     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
17547                              Regs64bit ? X86::RAX : X86::EAX,
17548                              cpInL, SDValue());
17549     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
17550                              Regs64bit ? X86::RDX : X86::EDX,
17551                              cpInH, cpInL.getValue(1));
17552     SDValue swapInL, swapInH;
17553     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
17554                           DAG.getConstant(0, HalfT));
17555     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
17556                           DAG.getConstant(1, HalfT));
17557     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
17558                                Regs64bit ? X86::RBX : X86::EBX,
17559                                swapInL, cpInH.getValue(1));
17560     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
17561                                Regs64bit ? X86::RCX : X86::ECX,
17562                                swapInH, swapInL.getValue(1));
17563     SDValue Ops[] = { swapInH.getValue(0),
17564                       N->getOperand(1),
17565                       swapInH.getValue(1) };
17566     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
17567     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
17568     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
17569                                   X86ISD::LCMPXCHG8_DAG;
17570     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
17571     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
17572                                         Regs64bit ? X86::RAX : X86::EAX,
17573                                         HalfT, Result.getValue(1));
17574     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
17575                                         Regs64bit ? X86::RDX : X86::EDX,
17576                                         HalfT, cpOutL.getValue(2));
17577     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
17578
17579     SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
17580                                         MVT::i32, cpOutH.getValue(2));
17581     SDValue Success =
17582         DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17583                     DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
17584     Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
17585
17586     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
17587     Results.push_back(Success);
17588     Results.push_back(EFLAGS.getValue(1));
17589     return;
17590   }
17591   case ISD::ATOMIC_SWAP:
17592   case ISD::ATOMIC_LOAD_ADD:
17593   case ISD::ATOMIC_LOAD_SUB:
17594   case ISD::ATOMIC_LOAD_AND:
17595   case ISD::ATOMIC_LOAD_OR:
17596   case ISD::ATOMIC_LOAD_XOR:
17597   case ISD::ATOMIC_LOAD_NAND:
17598   case ISD::ATOMIC_LOAD_MIN:
17599   case ISD::ATOMIC_LOAD_MAX:
17600   case ISD::ATOMIC_LOAD_UMIN:
17601   case ISD::ATOMIC_LOAD_UMAX:
17602   case ISD::ATOMIC_LOAD: {
17603     // Delegate to generic TypeLegalization. Situations we can really handle
17604     // should have already been dealt with by AtomicExpandPass.cpp.
17605     break;
17606   }
17607   case ISD::BITCAST: {
17608     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
17609     EVT DstVT = N->getValueType(0);
17610     EVT SrcVT = N->getOperand(0)->getValueType(0);
17611
17612     if (SrcVT != MVT::f64 ||
17613         (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
17614       return;
17615
17616     unsigned NumElts = DstVT.getVectorNumElements();
17617     EVT SVT = DstVT.getVectorElementType();
17618     EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
17619     SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
17620                                    MVT::v2f64, N->getOperand(0));
17621     SDValue ToVecInt = DAG.getNode(ISD::BITCAST, dl, WiderVT, Expanded);
17622
17623     if (ExperimentalVectorWideningLegalization) {
17624       // If we are legalizing vectors by widening, we already have the desired
17625       // legal vector type, just return it.
17626       Results.push_back(ToVecInt);
17627       return;
17628     }
17629
17630     SmallVector<SDValue, 8> Elts;
17631     for (unsigned i = 0, e = NumElts; i != e; ++i)
17632       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
17633                                    ToVecInt, DAG.getIntPtrConstant(i)));
17634
17635     Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
17636   }
17637   }
17638 }
17639
17640 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
17641   switch (Opcode) {
17642   default: return nullptr;
17643   case X86ISD::BSF:                return "X86ISD::BSF";
17644   case X86ISD::BSR:                return "X86ISD::BSR";
17645   case X86ISD::SHLD:               return "X86ISD::SHLD";
17646   case X86ISD::SHRD:               return "X86ISD::SHRD";
17647   case X86ISD::FAND:               return "X86ISD::FAND";
17648   case X86ISD::FANDN:              return "X86ISD::FANDN";
17649   case X86ISD::FOR:                return "X86ISD::FOR";
17650   case X86ISD::FXOR:               return "X86ISD::FXOR";
17651   case X86ISD::FSRL:               return "X86ISD::FSRL";
17652   case X86ISD::FILD:               return "X86ISD::FILD";
17653   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
17654   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
17655   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
17656   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
17657   case X86ISD::FLD:                return "X86ISD::FLD";
17658   case X86ISD::FST:                return "X86ISD::FST";
17659   case X86ISD::CALL:               return "X86ISD::CALL";
17660   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
17661   case X86ISD::RDTSCP_DAG:         return "X86ISD::RDTSCP_DAG";
17662   case X86ISD::RDPMC_DAG:          return "X86ISD::RDPMC_DAG";
17663   case X86ISD::BT:                 return "X86ISD::BT";
17664   case X86ISD::CMP:                return "X86ISD::CMP";
17665   case X86ISD::COMI:               return "X86ISD::COMI";
17666   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
17667   case X86ISD::CMPM:               return "X86ISD::CMPM";
17668   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
17669   case X86ISD::SETCC:              return "X86ISD::SETCC";
17670   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
17671   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
17672   case X86ISD::CMOV:               return "X86ISD::CMOV";
17673   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
17674   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
17675   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
17676   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
17677   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
17678   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
17679   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
17680   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
17681   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
17682   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
17683   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
17684   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
17685   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
17686   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
17687   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
17688   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
17689   case X86ISD::SHRUNKBLEND:        return "X86ISD::SHRUNKBLEND";
17690   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
17691   case X86ISD::HADD:               return "X86ISD::HADD";
17692   case X86ISD::HSUB:               return "X86ISD::HSUB";
17693   case X86ISD::FHADD:              return "X86ISD::FHADD";
17694   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
17695   case X86ISD::UMAX:               return "X86ISD::UMAX";
17696   case X86ISD::UMIN:               return "X86ISD::UMIN";
17697   case X86ISD::SMAX:               return "X86ISD::SMAX";
17698   case X86ISD::SMIN:               return "X86ISD::SMIN";
17699   case X86ISD::FMAX:               return "X86ISD::FMAX";
17700   case X86ISD::FMIN:               return "X86ISD::FMIN";
17701   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
17702   case X86ISD::FMINC:              return "X86ISD::FMINC";
17703   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
17704   case X86ISD::FRCP:               return "X86ISD::FRCP";
17705   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
17706   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
17707   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
17708   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
17709   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
17710   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
17711   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
17712   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
17713   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
17714   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
17715   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
17716   case X86ISD::LCMPXCHG16_DAG:     return "X86ISD::LCMPXCHG16_DAG";
17717   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
17718   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
17719   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
17720   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
17721   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
17722   case X86ISD::VTRUNCM:            return "X86ISD::VTRUNCM";
17723   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
17724   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
17725   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
17726   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
17727   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
17728   case X86ISD::VSHL:               return "X86ISD::VSHL";
17729   case X86ISD::VSRL:               return "X86ISD::VSRL";
17730   case X86ISD::VSRA:               return "X86ISD::VSRA";
17731   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
17732   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
17733   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
17734   case X86ISD::CMPP:               return "X86ISD::CMPP";
17735   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
17736   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
17737   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
17738   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
17739   case X86ISD::ADD:                return "X86ISD::ADD";
17740   case X86ISD::SUB:                return "X86ISD::SUB";
17741   case X86ISD::ADC:                return "X86ISD::ADC";
17742   case X86ISD::SBB:                return "X86ISD::SBB";
17743   case X86ISD::SMUL:               return "X86ISD::SMUL";
17744   case X86ISD::UMUL:               return "X86ISD::UMUL";
17745   case X86ISD::SMUL8:              return "X86ISD::SMUL8";
17746   case X86ISD::UMUL8:              return "X86ISD::UMUL8";
17747   case X86ISD::SDIVREM8_SEXT_HREG: return "X86ISD::SDIVREM8_SEXT_HREG";
17748   case X86ISD::UDIVREM8_ZEXT_HREG: return "X86ISD::UDIVREM8_ZEXT_HREG";
17749   case X86ISD::INC:                return "X86ISD::INC";
17750   case X86ISD::DEC:                return "X86ISD::DEC";
17751   case X86ISD::OR:                 return "X86ISD::OR";
17752   case X86ISD::XOR:                return "X86ISD::XOR";
17753   case X86ISD::AND:                return "X86ISD::AND";
17754   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
17755   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
17756   case X86ISD::PTEST:              return "X86ISD::PTEST";
17757   case X86ISD::TESTP:              return "X86ISD::TESTP";
17758   case X86ISD::TESTM:              return "X86ISD::TESTM";
17759   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
17760   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
17761   case X86ISD::PACKSS:             return "X86ISD::PACKSS";
17762   case X86ISD::PACKUS:             return "X86ISD::PACKUS";
17763   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
17764   case X86ISD::VALIGN:             return "X86ISD::VALIGN";
17765   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
17766   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
17767   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
17768   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
17769   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
17770   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
17771   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
17772   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
17773   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
17774   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
17775   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
17776   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
17777   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
17778   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
17779   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
17780   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
17781   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
17782   case X86ISD::VBROADCASTM:        return "X86ISD::VBROADCASTM";
17783   case X86ISD::VEXTRACT:           return "X86ISD::VEXTRACT";
17784   case X86ISD::VPERMILPI:          return "X86ISD::VPERMILPI";
17785   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
17786   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
17787   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
17788   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
17789   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
17790   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
17791   case X86ISD::PMULDQ:             return "X86ISD::PMULDQ";
17792   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
17793   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
17794   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
17795   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
17796   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
17797   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
17798   case X86ISD::SAHF:               return "X86ISD::SAHF";
17799   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
17800   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
17801   case X86ISD::FMADD:              return "X86ISD::FMADD";
17802   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
17803   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
17804   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
17805   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
17806   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
17807   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
17808   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
17809   case X86ISD::XTEST:              return "X86ISD::XTEST";
17810   case X86ISD::COMPRESS:           return "X86ISD::COMPRESS";
17811   case X86ISD::EXPAND:             return "X86ISD::EXPAND";
17812   case X86ISD::SELECT:             return "X86ISD::SELECT";
17813   case X86ISD::ADDSUB:             return "X86ISD::ADDSUB";
17814   case X86ISD::RCP28:              return "X86ISD::RCP28";
17815   case X86ISD::RSQRT28:            return "X86ISD::RSQRT28";
17816   case X86ISD::FADD_RND:           return "X86ISD::FADD_RND";
17817   case X86ISD::FSUB_RND:           return "X86ISD::FSUB_RND";
17818   case X86ISD::FMUL_RND:           return "X86ISD::FMUL_RND";
17819   case X86ISD::FDIV_RND:           return "X86ISD::FDIV_RND";
17820   }
17821 }
17822
17823 // isLegalAddressingMode - Return true if the addressing mode represented
17824 // by AM is legal for this target, for a load/store of the specified type.
17825 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
17826                                               Type *Ty) const {
17827   // X86 supports extremely general addressing modes.
17828   CodeModel::Model M = getTargetMachine().getCodeModel();
17829   Reloc::Model R = getTargetMachine().getRelocationModel();
17830
17831   // X86 allows a sign-extended 32-bit immediate field as a displacement.
17832   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
17833     return false;
17834
17835   if (AM.BaseGV) {
17836     unsigned GVFlags =
17837       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
17838
17839     // If a reference to this global requires an extra load, we can't fold it.
17840     if (isGlobalStubReference(GVFlags))
17841       return false;
17842
17843     // If BaseGV requires a register for the PIC base, we cannot also have a
17844     // BaseReg specified.
17845     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
17846       return false;
17847
17848     // If lower 4G is not available, then we must use rip-relative addressing.
17849     if ((M != CodeModel::Small || R != Reloc::Static) &&
17850         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
17851       return false;
17852   }
17853
17854   switch (AM.Scale) {
17855   case 0:
17856   case 1:
17857   case 2:
17858   case 4:
17859   case 8:
17860     // These scales always work.
17861     break;
17862   case 3:
17863   case 5:
17864   case 9:
17865     // These scales are formed with basereg+scalereg.  Only accept if there is
17866     // no basereg yet.
17867     if (AM.HasBaseReg)
17868       return false;
17869     break;
17870   default:  // Other stuff never works.
17871     return false;
17872   }
17873
17874   return true;
17875 }
17876
17877 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
17878   unsigned Bits = Ty->getScalarSizeInBits();
17879
17880   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
17881   // particularly cheaper than those without.
17882   if (Bits == 8)
17883     return false;
17884
17885   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
17886   // variable shifts just as cheap as scalar ones.
17887   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
17888     return false;
17889
17890   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
17891   // fully general vector.
17892   return true;
17893 }
17894
17895 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
17896   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
17897     return false;
17898   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
17899   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
17900   return NumBits1 > NumBits2;
17901 }
17902
17903 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
17904   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
17905     return false;
17906
17907   if (!isTypeLegal(EVT::getEVT(Ty1)))
17908     return false;
17909
17910   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
17911
17912   // Assuming the caller doesn't have a zeroext or signext return parameter,
17913   // truncation all the way down to i1 is valid.
17914   return true;
17915 }
17916
17917 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
17918   return isInt<32>(Imm);
17919 }
17920
17921 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
17922   // Can also use sub to handle negated immediates.
17923   return isInt<32>(Imm);
17924 }
17925
17926 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
17927   if (!VT1.isInteger() || !VT2.isInteger())
17928     return false;
17929   unsigned NumBits1 = VT1.getSizeInBits();
17930   unsigned NumBits2 = VT2.getSizeInBits();
17931   return NumBits1 > NumBits2;
17932 }
17933
17934 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
17935   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
17936   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
17937 }
17938
17939 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
17940   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
17941   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
17942 }
17943
17944 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
17945   EVT VT1 = Val.getValueType();
17946   if (isZExtFree(VT1, VT2))
17947     return true;
17948
17949   if (Val.getOpcode() != ISD::LOAD)
17950     return false;
17951
17952   if (!VT1.isSimple() || !VT1.isInteger() ||
17953       !VT2.isSimple() || !VT2.isInteger())
17954     return false;
17955
17956   switch (VT1.getSimpleVT().SimpleTy) {
17957   default: break;
17958   case MVT::i8:
17959   case MVT::i16:
17960   case MVT::i32:
17961     // X86 has 8, 16, and 32-bit zero-extending loads.
17962     return true;
17963   }
17964
17965   return false;
17966 }
17967
17968 bool X86TargetLowering::isVectorLoadExtDesirable(SDValue) const { return true; }
17969
17970 bool
17971 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
17972   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
17973     return false;
17974
17975   VT = VT.getScalarType();
17976
17977   if (!VT.isSimple())
17978     return false;
17979
17980   switch (VT.getSimpleVT().SimpleTy) {
17981   case MVT::f32:
17982   case MVT::f64:
17983     return true;
17984   default:
17985     break;
17986   }
17987
17988   return false;
17989 }
17990
17991 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
17992   // i16 instructions are longer (0x66 prefix) and potentially slower.
17993   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
17994 }
17995
17996 /// isShuffleMaskLegal - Targets can use this to indicate that they only
17997 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
17998 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
17999 /// are assumed to be legal.
18000 bool
18001 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
18002                                       EVT VT) const {
18003   if (!VT.isSimple())
18004     return false;
18005
18006   // Very little shuffling can be done for 64-bit vectors right now.
18007   if (VT.getSizeInBits() == 64)
18008     return false;
18009
18010   // We only care that the types being shuffled are legal. The lowering can
18011   // handle any possible shuffle mask that results.
18012   return isTypeLegal(VT.getSimpleVT());
18013 }
18014
18015 bool
18016 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
18017                                           EVT VT) const {
18018   // Just delegate to the generic legality, clear masks aren't special.
18019   return isShuffleMaskLegal(Mask, VT);
18020 }
18021
18022 //===----------------------------------------------------------------------===//
18023 //                           X86 Scheduler Hooks
18024 //===----------------------------------------------------------------------===//
18025
18026 /// Utility function to emit xbegin specifying the start of an RTM region.
18027 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
18028                                      const TargetInstrInfo *TII) {
18029   DebugLoc DL = MI->getDebugLoc();
18030
18031   const BasicBlock *BB = MBB->getBasicBlock();
18032   MachineFunction::iterator I = MBB;
18033   ++I;
18034
18035   // For the v = xbegin(), we generate
18036   //
18037   // thisMBB:
18038   //  xbegin sinkMBB
18039   //
18040   // mainMBB:
18041   //  eax = -1
18042   //
18043   // sinkMBB:
18044   //  v = eax
18045
18046   MachineBasicBlock *thisMBB = MBB;
18047   MachineFunction *MF = MBB->getParent();
18048   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
18049   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
18050   MF->insert(I, mainMBB);
18051   MF->insert(I, sinkMBB);
18052
18053   // Transfer the remainder of BB and its successor edges to sinkMBB.
18054   sinkMBB->splice(sinkMBB->begin(), MBB,
18055                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
18056   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
18057
18058   // thisMBB:
18059   //  xbegin sinkMBB
18060   //  # fallthrough to mainMBB
18061   //  # abortion to sinkMBB
18062   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
18063   thisMBB->addSuccessor(mainMBB);
18064   thisMBB->addSuccessor(sinkMBB);
18065
18066   // mainMBB:
18067   //  EAX = -1
18068   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
18069   mainMBB->addSuccessor(sinkMBB);
18070
18071   // sinkMBB:
18072   // EAX is live into the sinkMBB
18073   sinkMBB->addLiveIn(X86::EAX);
18074   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
18075           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
18076     .addReg(X86::EAX);
18077
18078   MI->eraseFromParent();
18079   return sinkMBB;
18080 }
18081
18082 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
18083 // or XMM0_V32I8 in AVX all of this code can be replaced with that
18084 // in the .td file.
18085 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
18086                                        const TargetInstrInfo *TII) {
18087   unsigned Opc;
18088   switch (MI->getOpcode()) {
18089   default: llvm_unreachable("illegal opcode!");
18090   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
18091   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
18092   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
18093   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
18094   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
18095   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
18096   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
18097   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
18098   }
18099
18100   DebugLoc dl = MI->getDebugLoc();
18101   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
18102
18103   unsigned NumArgs = MI->getNumOperands();
18104   for (unsigned i = 1; i < NumArgs; ++i) {
18105     MachineOperand &Op = MI->getOperand(i);
18106     if (!(Op.isReg() && Op.isImplicit()))
18107       MIB.addOperand(Op);
18108   }
18109   if (MI->hasOneMemOperand())
18110     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
18111
18112   BuildMI(*BB, MI, dl,
18113     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
18114     .addReg(X86::XMM0);
18115
18116   MI->eraseFromParent();
18117   return BB;
18118 }
18119
18120 // FIXME: Custom handling because TableGen doesn't support multiple implicit
18121 // defs in an instruction pattern
18122 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
18123                                        const TargetInstrInfo *TII) {
18124   unsigned Opc;
18125   switch (MI->getOpcode()) {
18126   default: llvm_unreachable("illegal opcode!");
18127   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
18128   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
18129   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
18130   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
18131   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
18132   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
18133   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
18134   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
18135   }
18136
18137   DebugLoc dl = MI->getDebugLoc();
18138   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
18139
18140   unsigned NumArgs = MI->getNumOperands(); // remove the results
18141   for (unsigned i = 1; i < NumArgs; ++i) {
18142     MachineOperand &Op = MI->getOperand(i);
18143     if (!(Op.isReg() && Op.isImplicit()))
18144       MIB.addOperand(Op);
18145   }
18146   if (MI->hasOneMemOperand())
18147     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
18148
18149   BuildMI(*BB, MI, dl,
18150     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
18151     .addReg(X86::ECX);
18152
18153   MI->eraseFromParent();
18154   return BB;
18155 }
18156
18157 static MachineBasicBlock *EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
18158                                       const X86Subtarget *Subtarget) {
18159   DebugLoc dl = MI->getDebugLoc();
18160   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18161   // Address into RAX/EAX, other two args into ECX, EDX.
18162   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
18163   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
18164   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
18165   for (int i = 0; i < X86::AddrNumOperands; ++i)
18166     MIB.addOperand(MI->getOperand(i));
18167
18168   unsigned ValOps = X86::AddrNumOperands;
18169   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
18170     .addReg(MI->getOperand(ValOps).getReg());
18171   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
18172     .addReg(MI->getOperand(ValOps+1).getReg());
18173
18174   // The instruction doesn't actually take any operands though.
18175   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
18176
18177   MI->eraseFromParent(); // The pseudo is gone now.
18178   return BB;
18179 }
18180
18181 MachineBasicBlock *
18182 X86TargetLowering::EmitVAARG64WithCustomInserter(MachineInstr *MI,
18183                                                  MachineBasicBlock *MBB) const {
18184   // Emit va_arg instruction on X86-64.
18185
18186   // Operands to this pseudo-instruction:
18187   // 0  ) Output        : destination address (reg)
18188   // 1-5) Input         : va_list address (addr, i64mem)
18189   // 6  ) ArgSize       : Size (in bytes) of vararg type
18190   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
18191   // 8  ) Align         : Alignment of type
18192   // 9  ) EFLAGS (implicit-def)
18193
18194   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
18195   static_assert(X86::AddrNumOperands == 5,
18196                 "VAARG_64 assumes 5 address operands");
18197
18198   unsigned DestReg = MI->getOperand(0).getReg();
18199   MachineOperand &Base = MI->getOperand(1);
18200   MachineOperand &Scale = MI->getOperand(2);
18201   MachineOperand &Index = MI->getOperand(3);
18202   MachineOperand &Disp = MI->getOperand(4);
18203   MachineOperand &Segment = MI->getOperand(5);
18204   unsigned ArgSize = MI->getOperand(6).getImm();
18205   unsigned ArgMode = MI->getOperand(7).getImm();
18206   unsigned Align = MI->getOperand(8).getImm();
18207
18208   // Memory Reference
18209   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
18210   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
18211   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
18212
18213   // Machine Information
18214   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18215   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
18216   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
18217   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
18218   DebugLoc DL = MI->getDebugLoc();
18219
18220   // struct va_list {
18221   //   i32   gp_offset
18222   //   i32   fp_offset
18223   //   i64   overflow_area (address)
18224   //   i64   reg_save_area (address)
18225   // }
18226   // sizeof(va_list) = 24
18227   // alignment(va_list) = 8
18228
18229   unsigned TotalNumIntRegs = 6;
18230   unsigned TotalNumXMMRegs = 8;
18231   bool UseGPOffset = (ArgMode == 1);
18232   bool UseFPOffset = (ArgMode == 2);
18233   unsigned MaxOffset = TotalNumIntRegs * 8 +
18234                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
18235
18236   /* Align ArgSize to a multiple of 8 */
18237   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
18238   bool NeedsAlign = (Align > 8);
18239
18240   MachineBasicBlock *thisMBB = MBB;
18241   MachineBasicBlock *overflowMBB;
18242   MachineBasicBlock *offsetMBB;
18243   MachineBasicBlock *endMBB;
18244
18245   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
18246   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
18247   unsigned OffsetReg = 0;
18248
18249   if (!UseGPOffset && !UseFPOffset) {
18250     // If we only pull from the overflow region, we don't create a branch.
18251     // We don't need to alter control flow.
18252     OffsetDestReg = 0; // unused
18253     OverflowDestReg = DestReg;
18254
18255     offsetMBB = nullptr;
18256     overflowMBB = thisMBB;
18257     endMBB = thisMBB;
18258   } else {
18259     // First emit code to check if gp_offset (or fp_offset) is below the bound.
18260     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
18261     // If not, pull from overflow_area. (branch to overflowMBB)
18262     //
18263     //       thisMBB
18264     //         |     .
18265     //         |        .
18266     //     offsetMBB   overflowMBB
18267     //         |        .
18268     //         |     .
18269     //        endMBB
18270
18271     // Registers for the PHI in endMBB
18272     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
18273     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
18274
18275     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
18276     MachineFunction *MF = MBB->getParent();
18277     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18278     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18279     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18280
18281     MachineFunction::iterator MBBIter = MBB;
18282     ++MBBIter;
18283
18284     // Insert the new basic blocks
18285     MF->insert(MBBIter, offsetMBB);
18286     MF->insert(MBBIter, overflowMBB);
18287     MF->insert(MBBIter, endMBB);
18288
18289     // Transfer the remainder of MBB and its successor edges to endMBB.
18290     endMBB->splice(endMBB->begin(), thisMBB,
18291                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
18292     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
18293
18294     // Make offsetMBB and overflowMBB successors of thisMBB
18295     thisMBB->addSuccessor(offsetMBB);
18296     thisMBB->addSuccessor(overflowMBB);
18297
18298     // endMBB is a successor of both offsetMBB and overflowMBB
18299     offsetMBB->addSuccessor(endMBB);
18300     overflowMBB->addSuccessor(endMBB);
18301
18302     // Load the offset value into a register
18303     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
18304     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
18305       .addOperand(Base)
18306       .addOperand(Scale)
18307       .addOperand(Index)
18308       .addDisp(Disp, UseFPOffset ? 4 : 0)
18309       .addOperand(Segment)
18310       .setMemRefs(MMOBegin, MMOEnd);
18311
18312     // Check if there is enough room left to pull this argument.
18313     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
18314       .addReg(OffsetReg)
18315       .addImm(MaxOffset + 8 - ArgSizeA8);
18316
18317     // Branch to "overflowMBB" if offset >= max
18318     // Fall through to "offsetMBB" otherwise
18319     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
18320       .addMBB(overflowMBB);
18321   }
18322
18323   // In offsetMBB, emit code to use the reg_save_area.
18324   if (offsetMBB) {
18325     assert(OffsetReg != 0);
18326
18327     // Read the reg_save_area address.
18328     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
18329     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
18330       .addOperand(Base)
18331       .addOperand(Scale)
18332       .addOperand(Index)
18333       .addDisp(Disp, 16)
18334       .addOperand(Segment)
18335       .setMemRefs(MMOBegin, MMOEnd);
18336
18337     // Zero-extend the offset
18338     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
18339       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
18340         .addImm(0)
18341         .addReg(OffsetReg)
18342         .addImm(X86::sub_32bit);
18343
18344     // Add the offset to the reg_save_area to get the final address.
18345     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
18346       .addReg(OffsetReg64)
18347       .addReg(RegSaveReg);
18348
18349     // Compute the offset for the next argument
18350     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
18351     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
18352       .addReg(OffsetReg)
18353       .addImm(UseFPOffset ? 16 : 8);
18354
18355     // Store it back into the va_list.
18356     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
18357       .addOperand(Base)
18358       .addOperand(Scale)
18359       .addOperand(Index)
18360       .addDisp(Disp, UseFPOffset ? 4 : 0)
18361       .addOperand(Segment)
18362       .addReg(NextOffsetReg)
18363       .setMemRefs(MMOBegin, MMOEnd);
18364
18365     // Jump to endMBB
18366     BuildMI(offsetMBB, DL, TII->get(X86::JMP_1))
18367       .addMBB(endMBB);
18368   }
18369
18370   //
18371   // Emit code to use overflow area
18372   //
18373
18374   // Load the overflow_area address into a register.
18375   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
18376   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
18377     .addOperand(Base)
18378     .addOperand(Scale)
18379     .addOperand(Index)
18380     .addDisp(Disp, 8)
18381     .addOperand(Segment)
18382     .setMemRefs(MMOBegin, MMOEnd);
18383
18384   // If we need to align it, do so. Otherwise, just copy the address
18385   // to OverflowDestReg.
18386   if (NeedsAlign) {
18387     // Align the overflow address
18388     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
18389     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
18390
18391     // aligned_addr = (addr + (align-1)) & ~(align-1)
18392     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
18393       .addReg(OverflowAddrReg)
18394       .addImm(Align-1);
18395
18396     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
18397       .addReg(TmpReg)
18398       .addImm(~(uint64_t)(Align-1));
18399   } else {
18400     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
18401       .addReg(OverflowAddrReg);
18402   }
18403
18404   // Compute the next overflow address after this argument.
18405   // (the overflow address should be kept 8-byte aligned)
18406   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
18407   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
18408     .addReg(OverflowDestReg)
18409     .addImm(ArgSizeA8);
18410
18411   // Store the new overflow address.
18412   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
18413     .addOperand(Base)
18414     .addOperand(Scale)
18415     .addOperand(Index)
18416     .addDisp(Disp, 8)
18417     .addOperand(Segment)
18418     .addReg(NextAddrReg)
18419     .setMemRefs(MMOBegin, MMOEnd);
18420
18421   // If we branched, emit the PHI to the front of endMBB.
18422   if (offsetMBB) {
18423     BuildMI(*endMBB, endMBB->begin(), DL,
18424             TII->get(X86::PHI), DestReg)
18425       .addReg(OffsetDestReg).addMBB(offsetMBB)
18426       .addReg(OverflowDestReg).addMBB(overflowMBB);
18427   }
18428
18429   // Erase the pseudo instruction
18430   MI->eraseFromParent();
18431
18432   return endMBB;
18433 }
18434
18435 MachineBasicBlock *
18436 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
18437                                                  MachineInstr *MI,
18438                                                  MachineBasicBlock *MBB) const {
18439   // Emit code to save XMM registers to the stack. The ABI says that the
18440   // number of registers to save is given in %al, so it's theoretically
18441   // possible to do an indirect jump trick to avoid saving all of them,
18442   // however this code takes a simpler approach and just executes all
18443   // of the stores if %al is non-zero. It's less code, and it's probably
18444   // easier on the hardware branch predictor, and stores aren't all that
18445   // expensive anyway.
18446
18447   // Create the new basic blocks. One block contains all the XMM stores,
18448   // and one block is the final destination regardless of whether any
18449   // stores were performed.
18450   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
18451   MachineFunction *F = MBB->getParent();
18452   MachineFunction::iterator MBBIter = MBB;
18453   ++MBBIter;
18454   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
18455   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
18456   F->insert(MBBIter, XMMSaveMBB);
18457   F->insert(MBBIter, EndMBB);
18458
18459   // Transfer the remainder of MBB and its successor edges to EndMBB.
18460   EndMBB->splice(EndMBB->begin(), MBB,
18461                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
18462   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
18463
18464   // The original block will now fall through to the XMM save block.
18465   MBB->addSuccessor(XMMSaveMBB);
18466   // The XMMSaveMBB will fall through to the end block.
18467   XMMSaveMBB->addSuccessor(EndMBB);
18468
18469   // Now add the instructions.
18470   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18471   DebugLoc DL = MI->getDebugLoc();
18472
18473   unsigned CountReg = MI->getOperand(0).getReg();
18474   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
18475   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
18476
18477   if (!Subtarget->isTargetWin64()) {
18478     // If %al is 0, branch around the XMM save block.
18479     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
18480     BuildMI(MBB, DL, TII->get(X86::JE_1)).addMBB(EndMBB);
18481     MBB->addSuccessor(EndMBB);
18482   }
18483
18484   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
18485   // that was just emitted, but clearly shouldn't be "saved".
18486   assert((MI->getNumOperands() <= 3 ||
18487           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
18488           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
18489          && "Expected last argument to be EFLAGS");
18490   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
18491   // In the XMM save block, save all the XMM argument registers.
18492   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
18493     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
18494     MachineMemOperand *MMO =
18495       F->getMachineMemOperand(
18496           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
18497         MachineMemOperand::MOStore,
18498         /*Size=*/16, /*Align=*/16);
18499     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
18500       .addFrameIndex(RegSaveFrameIndex)
18501       .addImm(/*Scale=*/1)
18502       .addReg(/*IndexReg=*/0)
18503       .addImm(/*Disp=*/Offset)
18504       .addReg(/*Segment=*/0)
18505       .addReg(MI->getOperand(i).getReg())
18506       .addMemOperand(MMO);
18507   }
18508
18509   MI->eraseFromParent();   // The pseudo instruction is gone now.
18510
18511   return EndMBB;
18512 }
18513
18514 // The EFLAGS operand of SelectItr might be missing a kill marker
18515 // because there were multiple uses of EFLAGS, and ISel didn't know
18516 // which to mark. Figure out whether SelectItr should have had a
18517 // kill marker, and set it if it should. Returns the correct kill
18518 // marker value.
18519 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
18520                                      MachineBasicBlock* BB,
18521                                      const TargetRegisterInfo* TRI) {
18522   // Scan forward through BB for a use/def of EFLAGS.
18523   MachineBasicBlock::iterator miI(std::next(SelectItr));
18524   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
18525     const MachineInstr& mi = *miI;
18526     if (mi.readsRegister(X86::EFLAGS))
18527       return false;
18528     if (mi.definesRegister(X86::EFLAGS))
18529       break; // Should have kill-flag - update below.
18530   }
18531
18532   // If we hit the end of the block, check whether EFLAGS is live into a
18533   // successor.
18534   if (miI == BB->end()) {
18535     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
18536                                           sEnd = BB->succ_end();
18537          sItr != sEnd; ++sItr) {
18538       MachineBasicBlock* succ = *sItr;
18539       if (succ->isLiveIn(X86::EFLAGS))
18540         return false;
18541     }
18542   }
18543
18544   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
18545   // out. SelectMI should have a kill flag on EFLAGS.
18546   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
18547   return true;
18548 }
18549
18550 MachineBasicBlock *
18551 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
18552                                      MachineBasicBlock *BB) const {
18553   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18554   DebugLoc DL = MI->getDebugLoc();
18555
18556   // To "insert" a SELECT_CC instruction, we actually have to insert the
18557   // diamond control-flow pattern.  The incoming instruction knows the
18558   // destination vreg to set, the condition code register to branch on, the
18559   // true/false values to select between, and a branch opcode to use.
18560   const BasicBlock *LLVM_BB = BB->getBasicBlock();
18561   MachineFunction::iterator It = BB;
18562   ++It;
18563
18564   //  thisMBB:
18565   //  ...
18566   //   TrueVal = ...
18567   //   cmpTY ccX, r1, r2
18568   //   bCC copy1MBB
18569   //   fallthrough --> copy0MBB
18570   MachineBasicBlock *thisMBB = BB;
18571   MachineFunction *F = BB->getParent();
18572
18573   // We also lower double CMOVs:
18574   //   (CMOV (CMOV F, T, cc1), T, cc2)
18575   // to two successives branches.  For that, we look for another CMOV as the
18576   // following instruction.
18577   //
18578   // Without this, we would add a PHI between the two jumps, which ends up
18579   // creating a few copies all around. For instance, for
18580   //
18581   //    (sitofp (zext (fcmp une)))
18582   //
18583   // we would generate:
18584   //
18585   //         ucomiss %xmm1, %xmm0
18586   //         movss  <1.0f>, %xmm0
18587   //         movaps  %xmm0, %xmm1
18588   //         jne     .LBB5_2
18589   //         xorps   %xmm1, %xmm1
18590   // .LBB5_2:
18591   //         jp      .LBB5_4
18592   //         movaps  %xmm1, %xmm0
18593   // .LBB5_4:
18594   //         retq
18595   //
18596   // because this custom-inserter would have generated:
18597   //
18598   //   A
18599   //   | \
18600   //   |  B
18601   //   | /
18602   //   C
18603   //   | \
18604   //   |  D
18605   //   | /
18606   //   E
18607   //
18608   // A: X = ...; Y = ...
18609   // B: empty
18610   // C: Z = PHI [X, A], [Y, B]
18611   // D: empty
18612   // E: PHI [X, C], [Z, D]
18613   //
18614   // If we lower both CMOVs in a single step, we can instead generate:
18615   //
18616   //   A
18617   //   | \
18618   //   |  C
18619   //   | /|
18620   //   |/ |
18621   //   |  |
18622   //   |  D
18623   //   | /
18624   //   E
18625   //
18626   // A: X = ...; Y = ...
18627   // D: empty
18628   // E: PHI [X, A], [X, C], [Y, D]
18629   //
18630   // Which, in our sitofp/fcmp example, gives us something like:
18631   //
18632   //         ucomiss %xmm1, %xmm0
18633   //         movss  <1.0f>, %xmm0
18634   //         jne     .LBB5_4
18635   //         jp      .LBB5_4
18636   //         xorps   %xmm0, %xmm0
18637   // .LBB5_4:
18638   //         retq
18639   //
18640   MachineInstr *NextCMOV = nullptr;
18641   MachineBasicBlock::iterator NextMIIt =
18642       std::next(MachineBasicBlock::iterator(MI));
18643   if (NextMIIt != BB->end() && NextMIIt->getOpcode() == MI->getOpcode() &&
18644       NextMIIt->getOperand(2).getReg() == MI->getOperand(2).getReg() &&
18645       NextMIIt->getOperand(1).getReg() == MI->getOperand(0).getReg())
18646     NextCMOV = &*NextMIIt;
18647
18648   MachineBasicBlock *jcc1MBB = nullptr;
18649
18650   // If we have a double CMOV, we lower it to two successive branches to
18651   // the same block.  EFLAGS is used by both, so mark it as live in the second.
18652   if (NextCMOV) {
18653     jcc1MBB = F->CreateMachineBasicBlock(LLVM_BB);
18654     F->insert(It, jcc1MBB);
18655     jcc1MBB->addLiveIn(X86::EFLAGS);
18656   }
18657
18658   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
18659   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
18660   F->insert(It, copy0MBB);
18661   F->insert(It, sinkMBB);
18662
18663   // If the EFLAGS register isn't dead in the terminator, then claim that it's
18664   // live into the sink and copy blocks.
18665   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
18666
18667   MachineInstr *LastEFLAGSUser = NextCMOV ? NextCMOV : MI;
18668   if (!LastEFLAGSUser->killsRegister(X86::EFLAGS) &&
18669       !checkAndUpdateEFLAGSKill(LastEFLAGSUser, BB, TRI)) {
18670     copy0MBB->addLiveIn(X86::EFLAGS);
18671     sinkMBB->addLiveIn(X86::EFLAGS);
18672   }
18673
18674   // Transfer the remainder of BB and its successor edges to sinkMBB.
18675   sinkMBB->splice(sinkMBB->begin(), BB,
18676                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
18677   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
18678
18679   // Add the true and fallthrough blocks as its successors.
18680   if (NextCMOV) {
18681     // The fallthrough block may be jcc1MBB, if we have a double CMOV.
18682     BB->addSuccessor(jcc1MBB);
18683
18684     // In that case, jcc1MBB will itself fallthrough the copy0MBB, and
18685     // jump to the sinkMBB.
18686     jcc1MBB->addSuccessor(copy0MBB);
18687     jcc1MBB->addSuccessor(sinkMBB);
18688   } else {
18689     BB->addSuccessor(copy0MBB);
18690   }
18691
18692   // The true block target of the first (or only) branch is always sinkMBB.
18693   BB->addSuccessor(sinkMBB);
18694
18695   // Create the conditional branch instruction.
18696   unsigned Opc =
18697     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
18698   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
18699
18700   if (NextCMOV) {
18701     unsigned Opc2 = X86::GetCondBranchFromCond(
18702         (X86::CondCode)NextCMOV->getOperand(3).getImm());
18703     BuildMI(jcc1MBB, DL, TII->get(Opc2)).addMBB(sinkMBB);
18704   }
18705
18706   //  copy0MBB:
18707   //   %FalseValue = ...
18708   //   # fallthrough to sinkMBB
18709   copy0MBB->addSuccessor(sinkMBB);
18710
18711   //  sinkMBB:
18712   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
18713   //  ...
18714   MachineInstrBuilder MIB =
18715       BuildMI(*sinkMBB, sinkMBB->begin(), DL, TII->get(X86::PHI),
18716               MI->getOperand(0).getReg())
18717           .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
18718           .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
18719
18720   // If we have a double CMOV, the second Jcc provides the same incoming
18721   // value as the first Jcc (the True operand of the SELECT_CC/CMOV nodes).
18722   if (NextCMOV) {
18723     MIB.addReg(MI->getOperand(2).getReg()).addMBB(jcc1MBB);
18724     // Copy the PHI result to the register defined by the second CMOV.
18725     BuildMI(*sinkMBB, std::next(MachineBasicBlock::iterator(MIB.getInstr())),
18726             DL, TII->get(TargetOpcode::COPY), NextCMOV->getOperand(0).getReg())
18727         .addReg(MI->getOperand(0).getReg());
18728     NextCMOV->eraseFromParent();
18729   }
18730
18731   MI->eraseFromParent();   // The pseudo instruction is gone now.
18732   return sinkMBB;
18733 }
18734
18735 MachineBasicBlock *
18736 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI,
18737                                         MachineBasicBlock *BB) const {
18738   MachineFunction *MF = BB->getParent();
18739   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18740   DebugLoc DL = MI->getDebugLoc();
18741   const BasicBlock *LLVM_BB = BB->getBasicBlock();
18742
18743   assert(MF->shouldSplitStack());
18744
18745   const bool Is64Bit = Subtarget->is64Bit();
18746   const bool IsLP64 = Subtarget->isTarget64BitLP64();
18747
18748   const unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
18749   const unsigned TlsOffset = IsLP64 ? 0x70 : Is64Bit ? 0x40 : 0x30;
18750
18751   // BB:
18752   //  ... [Till the alloca]
18753   // If stacklet is not large enough, jump to mallocMBB
18754   //
18755   // bumpMBB:
18756   //  Allocate by subtracting from RSP
18757   //  Jump to continueMBB
18758   //
18759   // mallocMBB:
18760   //  Allocate by call to runtime
18761   //
18762   // continueMBB:
18763   //  ...
18764   //  [rest of original BB]
18765   //
18766
18767   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18768   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18769   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18770
18771   MachineRegisterInfo &MRI = MF->getRegInfo();
18772   const TargetRegisterClass *AddrRegClass =
18773     getRegClassFor(getPointerTy());
18774
18775   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
18776     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
18777     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
18778     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
18779     sizeVReg = MI->getOperand(1).getReg(),
18780     physSPReg = IsLP64 || Subtarget->isTargetNaCl64() ? X86::RSP : X86::ESP;
18781
18782   MachineFunction::iterator MBBIter = BB;
18783   ++MBBIter;
18784
18785   MF->insert(MBBIter, bumpMBB);
18786   MF->insert(MBBIter, mallocMBB);
18787   MF->insert(MBBIter, continueMBB);
18788
18789   continueMBB->splice(continueMBB->begin(), BB,
18790                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
18791   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
18792
18793   // Add code to the main basic block to check if the stack limit has been hit,
18794   // and if so, jump to mallocMBB otherwise to bumpMBB.
18795   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
18796   BuildMI(BB, DL, TII->get(IsLP64 ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
18797     .addReg(tmpSPVReg).addReg(sizeVReg);
18798   BuildMI(BB, DL, TII->get(IsLP64 ? X86::CMP64mr:X86::CMP32mr))
18799     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
18800     .addReg(SPLimitVReg);
18801   BuildMI(BB, DL, TII->get(X86::JG_1)).addMBB(mallocMBB);
18802
18803   // bumpMBB simply decreases the stack pointer, since we know the current
18804   // stacklet has enough space.
18805   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
18806     .addReg(SPLimitVReg);
18807   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
18808     .addReg(SPLimitVReg);
18809   BuildMI(bumpMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
18810
18811   // Calls into a routine in libgcc to allocate more space from the heap.
18812   const uint32_t *RegMask =
18813       Subtarget->getRegisterInfo()->getCallPreservedMask(*MF, CallingConv::C);
18814   if (IsLP64) {
18815     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
18816       .addReg(sizeVReg);
18817     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
18818       .addExternalSymbol("__morestack_allocate_stack_space")
18819       .addRegMask(RegMask)
18820       .addReg(X86::RDI, RegState::Implicit)
18821       .addReg(X86::RAX, RegState::ImplicitDefine);
18822   } else if (Is64Bit) {
18823     BuildMI(mallocMBB, DL, TII->get(X86::MOV32rr), X86::EDI)
18824       .addReg(sizeVReg);
18825     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
18826       .addExternalSymbol("__morestack_allocate_stack_space")
18827       .addRegMask(RegMask)
18828       .addReg(X86::EDI, RegState::Implicit)
18829       .addReg(X86::EAX, RegState::ImplicitDefine);
18830   } else {
18831     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
18832       .addImm(12);
18833     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
18834     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
18835       .addExternalSymbol("__morestack_allocate_stack_space")
18836       .addRegMask(RegMask)
18837       .addReg(X86::EAX, RegState::ImplicitDefine);
18838   }
18839
18840   if (!Is64Bit)
18841     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
18842       .addImm(16);
18843
18844   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
18845     .addReg(IsLP64 ? X86::RAX : X86::EAX);
18846   BuildMI(mallocMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
18847
18848   // Set up the CFG correctly.
18849   BB->addSuccessor(bumpMBB);
18850   BB->addSuccessor(mallocMBB);
18851   mallocMBB->addSuccessor(continueMBB);
18852   bumpMBB->addSuccessor(continueMBB);
18853
18854   // Take care of the PHI nodes.
18855   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
18856           MI->getOperand(0).getReg())
18857     .addReg(mallocPtrVReg).addMBB(mallocMBB)
18858     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
18859
18860   // Delete the original pseudo instruction.
18861   MI->eraseFromParent();
18862
18863   // And we're done.
18864   return continueMBB;
18865 }
18866
18867 MachineBasicBlock *
18868 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
18869                                         MachineBasicBlock *BB) const {
18870   DebugLoc DL = MI->getDebugLoc();
18871
18872   assert(!Subtarget->isTargetMachO());
18873
18874   X86FrameLowering::emitStackProbeCall(*BB->getParent(), *BB, MI, DL);
18875
18876   MI->eraseFromParent();   // The pseudo instruction is gone now.
18877   return BB;
18878 }
18879
18880 MachineBasicBlock *
18881 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
18882                                       MachineBasicBlock *BB) const {
18883   // This is pretty easy.  We're taking the value that we received from
18884   // our load from the relocation, sticking it in either RDI (x86-64)
18885   // or EAX and doing an indirect call.  The return value will then
18886   // be in the normal return register.
18887   MachineFunction *F = BB->getParent();
18888   const X86InstrInfo *TII = Subtarget->getInstrInfo();
18889   DebugLoc DL = MI->getDebugLoc();
18890
18891   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
18892   assert(MI->getOperand(3).isGlobal() && "This should be a global");
18893
18894   // Get a register mask for the lowered call.
18895   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
18896   // proper register mask.
18897   const uint32_t *RegMask =
18898       Subtarget->getRegisterInfo()->getCallPreservedMask(*F, CallingConv::C);
18899   if (Subtarget->is64Bit()) {
18900     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
18901                                       TII->get(X86::MOV64rm), X86::RDI)
18902     .addReg(X86::RIP)
18903     .addImm(0).addReg(0)
18904     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
18905                       MI->getOperand(3).getTargetFlags())
18906     .addReg(0);
18907     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
18908     addDirectMem(MIB, X86::RDI);
18909     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
18910   } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
18911     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
18912                                       TII->get(X86::MOV32rm), X86::EAX)
18913     .addReg(0)
18914     .addImm(0).addReg(0)
18915     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
18916                       MI->getOperand(3).getTargetFlags())
18917     .addReg(0);
18918     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
18919     addDirectMem(MIB, X86::EAX);
18920     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
18921   } else {
18922     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
18923                                       TII->get(X86::MOV32rm), X86::EAX)
18924     .addReg(TII->getGlobalBaseReg(F))
18925     .addImm(0).addReg(0)
18926     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
18927                       MI->getOperand(3).getTargetFlags())
18928     .addReg(0);
18929     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
18930     addDirectMem(MIB, X86::EAX);
18931     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
18932   }
18933
18934   MI->eraseFromParent(); // The pseudo instruction is gone now.
18935   return BB;
18936 }
18937
18938 MachineBasicBlock *
18939 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
18940                                     MachineBasicBlock *MBB) const {
18941   DebugLoc DL = MI->getDebugLoc();
18942   MachineFunction *MF = MBB->getParent();
18943   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18944   MachineRegisterInfo &MRI = MF->getRegInfo();
18945
18946   const BasicBlock *BB = MBB->getBasicBlock();
18947   MachineFunction::iterator I = MBB;
18948   ++I;
18949
18950   // Memory Reference
18951   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
18952   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
18953
18954   unsigned DstReg;
18955   unsigned MemOpndSlot = 0;
18956
18957   unsigned CurOp = 0;
18958
18959   DstReg = MI->getOperand(CurOp++).getReg();
18960   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
18961   assert(RC->hasType(MVT::i32) && "Invalid destination!");
18962   unsigned mainDstReg = MRI.createVirtualRegister(RC);
18963   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
18964
18965   MemOpndSlot = CurOp;
18966
18967   MVT PVT = getPointerTy();
18968   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
18969          "Invalid Pointer Size!");
18970
18971   // For v = setjmp(buf), we generate
18972   //
18973   // thisMBB:
18974   //  buf[LabelOffset] = restoreMBB
18975   //  SjLjSetup restoreMBB
18976   //
18977   // mainMBB:
18978   //  v_main = 0
18979   //
18980   // sinkMBB:
18981   //  v = phi(main, restore)
18982   //
18983   // restoreMBB:
18984   //  if base pointer being used, load it from frame
18985   //  v_restore = 1
18986
18987   MachineBasicBlock *thisMBB = MBB;
18988   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
18989   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
18990   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
18991   MF->insert(I, mainMBB);
18992   MF->insert(I, sinkMBB);
18993   MF->push_back(restoreMBB);
18994
18995   MachineInstrBuilder MIB;
18996
18997   // Transfer the remainder of BB and its successor edges to sinkMBB.
18998   sinkMBB->splice(sinkMBB->begin(), MBB,
18999                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
19000   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
19001
19002   // thisMBB:
19003   unsigned PtrStoreOpc = 0;
19004   unsigned LabelReg = 0;
19005   const int64_t LabelOffset = 1 * PVT.getStoreSize();
19006   Reloc::Model RM = MF->getTarget().getRelocationModel();
19007   bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
19008                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
19009
19010   // Prepare IP either in reg or imm.
19011   if (!UseImmLabel) {
19012     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
19013     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
19014     LabelReg = MRI.createVirtualRegister(PtrRC);
19015     if (Subtarget->is64Bit()) {
19016       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
19017               .addReg(X86::RIP)
19018               .addImm(0)
19019               .addReg(0)
19020               .addMBB(restoreMBB)
19021               .addReg(0);
19022     } else {
19023       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
19024       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
19025               .addReg(XII->getGlobalBaseReg(MF))
19026               .addImm(0)
19027               .addReg(0)
19028               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
19029               .addReg(0);
19030     }
19031   } else
19032     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
19033   // Store IP
19034   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
19035   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
19036     if (i == X86::AddrDisp)
19037       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
19038     else
19039       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
19040   }
19041   if (!UseImmLabel)
19042     MIB.addReg(LabelReg);
19043   else
19044     MIB.addMBB(restoreMBB);
19045   MIB.setMemRefs(MMOBegin, MMOEnd);
19046   // Setup
19047   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
19048           .addMBB(restoreMBB);
19049
19050   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
19051   MIB.addRegMask(RegInfo->getNoPreservedMask());
19052   thisMBB->addSuccessor(mainMBB);
19053   thisMBB->addSuccessor(restoreMBB);
19054
19055   // mainMBB:
19056   //  EAX = 0
19057   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
19058   mainMBB->addSuccessor(sinkMBB);
19059
19060   // sinkMBB:
19061   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
19062           TII->get(X86::PHI), DstReg)
19063     .addReg(mainDstReg).addMBB(mainMBB)
19064     .addReg(restoreDstReg).addMBB(restoreMBB);
19065
19066   // restoreMBB:
19067   if (RegInfo->hasBasePointer(*MF)) {
19068     const bool Uses64BitFramePtr =
19069         Subtarget->isTarget64BitLP64() || Subtarget->isTargetNaCl64();
19070     X86MachineFunctionInfo *X86FI = MF->getInfo<X86MachineFunctionInfo>();
19071     X86FI->setRestoreBasePointer(MF);
19072     unsigned FramePtr = RegInfo->getFrameRegister(*MF);
19073     unsigned BasePtr = RegInfo->getBaseRegister();
19074     unsigned Opm = Uses64BitFramePtr ? X86::MOV64rm : X86::MOV32rm;
19075     addRegOffset(BuildMI(restoreMBB, DL, TII->get(Opm), BasePtr),
19076                  FramePtr, true, X86FI->getRestoreBasePointerOffset())
19077       .setMIFlag(MachineInstr::FrameSetup);
19078   }
19079   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
19080   BuildMI(restoreMBB, DL, TII->get(X86::JMP_1)).addMBB(sinkMBB);
19081   restoreMBB->addSuccessor(sinkMBB);
19082
19083   MI->eraseFromParent();
19084   return sinkMBB;
19085 }
19086
19087 MachineBasicBlock *
19088 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
19089                                      MachineBasicBlock *MBB) const {
19090   DebugLoc DL = MI->getDebugLoc();
19091   MachineFunction *MF = MBB->getParent();
19092   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19093   MachineRegisterInfo &MRI = MF->getRegInfo();
19094
19095   // Memory Reference
19096   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
19097   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
19098
19099   MVT PVT = getPointerTy();
19100   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
19101          "Invalid Pointer Size!");
19102
19103   const TargetRegisterClass *RC =
19104     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
19105   unsigned Tmp = MRI.createVirtualRegister(RC);
19106   // Since FP is only updated here but NOT referenced, it's treated as GPR.
19107   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
19108   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
19109   unsigned SP = RegInfo->getStackRegister();
19110
19111   MachineInstrBuilder MIB;
19112
19113   const int64_t LabelOffset = 1 * PVT.getStoreSize();
19114   const int64_t SPOffset = 2 * PVT.getStoreSize();
19115
19116   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
19117   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
19118
19119   // Reload FP
19120   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
19121   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
19122     MIB.addOperand(MI->getOperand(i));
19123   MIB.setMemRefs(MMOBegin, MMOEnd);
19124   // Reload IP
19125   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
19126   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
19127     if (i == X86::AddrDisp)
19128       MIB.addDisp(MI->getOperand(i), LabelOffset);
19129     else
19130       MIB.addOperand(MI->getOperand(i));
19131   }
19132   MIB.setMemRefs(MMOBegin, MMOEnd);
19133   // Reload SP
19134   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
19135   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
19136     if (i == X86::AddrDisp)
19137       MIB.addDisp(MI->getOperand(i), SPOffset);
19138     else
19139       MIB.addOperand(MI->getOperand(i));
19140   }
19141   MIB.setMemRefs(MMOBegin, MMOEnd);
19142   // Jump
19143   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
19144
19145   MI->eraseFromParent();
19146   return MBB;
19147 }
19148
19149 // Replace 213-type (isel default) FMA3 instructions with 231-type for
19150 // accumulator loops. Writing back to the accumulator allows the coalescer
19151 // to remove extra copies in the loop.
19152 MachineBasicBlock *
19153 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
19154                                  MachineBasicBlock *MBB) const {
19155   MachineOperand &AddendOp = MI->getOperand(3);
19156
19157   // Bail out early if the addend isn't a register - we can't switch these.
19158   if (!AddendOp.isReg())
19159     return MBB;
19160
19161   MachineFunction &MF = *MBB->getParent();
19162   MachineRegisterInfo &MRI = MF.getRegInfo();
19163
19164   // Check whether the addend is defined by a PHI:
19165   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
19166   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
19167   if (!AddendDef.isPHI())
19168     return MBB;
19169
19170   // Look for the following pattern:
19171   // loop:
19172   //   %addend = phi [%entry, 0], [%loop, %result]
19173   //   ...
19174   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
19175
19176   // Replace with:
19177   //   loop:
19178   //   %addend = phi [%entry, 0], [%loop, %result]
19179   //   ...
19180   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
19181
19182   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
19183     assert(AddendDef.getOperand(i).isReg());
19184     MachineOperand PHISrcOp = AddendDef.getOperand(i);
19185     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
19186     if (&PHISrcInst == MI) {
19187       // Found a matching instruction.
19188       unsigned NewFMAOpc = 0;
19189       switch (MI->getOpcode()) {
19190         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
19191         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
19192         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
19193         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
19194         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
19195         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
19196         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
19197         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
19198         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
19199         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
19200         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
19201         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
19202         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
19203         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
19204         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
19205         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
19206         case X86::VFMADDSUBPDr213r: NewFMAOpc = X86::VFMADDSUBPDr231r; break;
19207         case X86::VFMADDSUBPSr213r: NewFMAOpc = X86::VFMADDSUBPSr231r; break;
19208         case X86::VFMSUBADDPDr213r: NewFMAOpc = X86::VFMSUBADDPDr231r; break;
19209         case X86::VFMSUBADDPSr213r: NewFMAOpc = X86::VFMSUBADDPSr231r; break;
19210
19211         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
19212         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
19213         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
19214         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
19215         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
19216         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
19217         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
19218         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
19219         case X86::VFMADDSUBPDr213rY: NewFMAOpc = X86::VFMADDSUBPDr231rY; break;
19220         case X86::VFMADDSUBPSr213rY: NewFMAOpc = X86::VFMADDSUBPSr231rY; break;
19221         case X86::VFMSUBADDPDr213rY: NewFMAOpc = X86::VFMSUBADDPDr231rY; break;
19222         case X86::VFMSUBADDPSr213rY: NewFMAOpc = X86::VFMSUBADDPSr231rY; break;
19223         default: llvm_unreachable("Unrecognized FMA variant.");
19224       }
19225
19226       const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
19227       MachineInstrBuilder MIB =
19228         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
19229         .addOperand(MI->getOperand(0))
19230         .addOperand(MI->getOperand(3))
19231         .addOperand(MI->getOperand(2))
19232         .addOperand(MI->getOperand(1));
19233       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
19234       MI->eraseFromParent();
19235     }
19236   }
19237
19238   return MBB;
19239 }
19240
19241 MachineBasicBlock *
19242 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
19243                                                MachineBasicBlock *BB) const {
19244   switch (MI->getOpcode()) {
19245   default: llvm_unreachable("Unexpected instr type to insert");
19246   case X86::TAILJMPd64:
19247   case X86::TAILJMPr64:
19248   case X86::TAILJMPm64:
19249   case X86::TAILJMPd64_REX:
19250   case X86::TAILJMPr64_REX:
19251   case X86::TAILJMPm64_REX:
19252     llvm_unreachable("TAILJMP64 would not be touched here.");
19253   case X86::TCRETURNdi64:
19254   case X86::TCRETURNri64:
19255   case X86::TCRETURNmi64:
19256     return BB;
19257   case X86::WIN_ALLOCA:
19258     return EmitLoweredWinAlloca(MI, BB);
19259   case X86::SEG_ALLOCA_32:
19260   case X86::SEG_ALLOCA_64:
19261     return EmitLoweredSegAlloca(MI, BB);
19262   case X86::TLSCall_32:
19263   case X86::TLSCall_64:
19264     return EmitLoweredTLSCall(MI, BB);
19265   case X86::CMOV_GR8:
19266   case X86::CMOV_FR32:
19267   case X86::CMOV_FR64:
19268   case X86::CMOV_V4F32:
19269   case X86::CMOV_V2F64:
19270   case X86::CMOV_V2I64:
19271   case X86::CMOV_V8F32:
19272   case X86::CMOV_V4F64:
19273   case X86::CMOV_V4I64:
19274   case X86::CMOV_V16F32:
19275   case X86::CMOV_V8F64:
19276   case X86::CMOV_V8I64:
19277   case X86::CMOV_GR16:
19278   case X86::CMOV_GR32:
19279   case X86::CMOV_RFP32:
19280   case X86::CMOV_RFP64:
19281   case X86::CMOV_RFP80:
19282     return EmitLoweredSelect(MI, BB);
19283
19284   case X86::FP32_TO_INT16_IN_MEM:
19285   case X86::FP32_TO_INT32_IN_MEM:
19286   case X86::FP32_TO_INT64_IN_MEM:
19287   case X86::FP64_TO_INT16_IN_MEM:
19288   case X86::FP64_TO_INT32_IN_MEM:
19289   case X86::FP64_TO_INT64_IN_MEM:
19290   case X86::FP80_TO_INT16_IN_MEM:
19291   case X86::FP80_TO_INT32_IN_MEM:
19292   case X86::FP80_TO_INT64_IN_MEM: {
19293     MachineFunction *F = BB->getParent();
19294     const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19295     DebugLoc DL = MI->getDebugLoc();
19296
19297     // Change the floating point control register to use "round towards zero"
19298     // mode when truncating to an integer value.
19299     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
19300     addFrameReference(BuildMI(*BB, MI, DL,
19301                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
19302
19303     // Load the old value of the high byte of the control word...
19304     unsigned OldCW =
19305       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
19306     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
19307                       CWFrameIdx);
19308
19309     // Set the high part to be round to zero...
19310     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
19311       .addImm(0xC7F);
19312
19313     // Reload the modified control word now...
19314     addFrameReference(BuildMI(*BB, MI, DL,
19315                               TII->get(X86::FLDCW16m)), CWFrameIdx);
19316
19317     // Restore the memory image of control word to original value
19318     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
19319       .addReg(OldCW);
19320
19321     // Get the X86 opcode to use.
19322     unsigned Opc;
19323     switch (MI->getOpcode()) {
19324     default: llvm_unreachable("illegal opcode!");
19325     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
19326     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
19327     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
19328     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
19329     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
19330     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
19331     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
19332     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
19333     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
19334     }
19335
19336     X86AddressMode AM;
19337     MachineOperand &Op = MI->getOperand(0);
19338     if (Op.isReg()) {
19339       AM.BaseType = X86AddressMode::RegBase;
19340       AM.Base.Reg = Op.getReg();
19341     } else {
19342       AM.BaseType = X86AddressMode::FrameIndexBase;
19343       AM.Base.FrameIndex = Op.getIndex();
19344     }
19345     Op = MI->getOperand(1);
19346     if (Op.isImm())
19347       AM.Scale = Op.getImm();
19348     Op = MI->getOperand(2);
19349     if (Op.isImm())
19350       AM.IndexReg = Op.getImm();
19351     Op = MI->getOperand(3);
19352     if (Op.isGlobal()) {
19353       AM.GV = Op.getGlobal();
19354     } else {
19355       AM.Disp = Op.getImm();
19356     }
19357     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
19358                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
19359
19360     // Reload the original control word now.
19361     addFrameReference(BuildMI(*BB, MI, DL,
19362                               TII->get(X86::FLDCW16m)), CWFrameIdx);
19363
19364     MI->eraseFromParent();   // The pseudo instruction is gone now.
19365     return BB;
19366   }
19367     // String/text processing lowering.
19368   case X86::PCMPISTRM128REG:
19369   case X86::VPCMPISTRM128REG:
19370   case X86::PCMPISTRM128MEM:
19371   case X86::VPCMPISTRM128MEM:
19372   case X86::PCMPESTRM128REG:
19373   case X86::VPCMPESTRM128REG:
19374   case X86::PCMPESTRM128MEM:
19375   case X86::VPCMPESTRM128MEM:
19376     assert(Subtarget->hasSSE42() &&
19377            "Target must have SSE4.2 or AVX features enabled");
19378     return EmitPCMPSTRM(MI, BB, Subtarget->getInstrInfo());
19379
19380   // String/text processing lowering.
19381   case X86::PCMPISTRIREG:
19382   case X86::VPCMPISTRIREG:
19383   case X86::PCMPISTRIMEM:
19384   case X86::VPCMPISTRIMEM:
19385   case X86::PCMPESTRIREG:
19386   case X86::VPCMPESTRIREG:
19387   case X86::PCMPESTRIMEM:
19388   case X86::VPCMPESTRIMEM:
19389     assert(Subtarget->hasSSE42() &&
19390            "Target must have SSE4.2 or AVX features enabled");
19391     return EmitPCMPSTRI(MI, BB, Subtarget->getInstrInfo());
19392
19393   // Thread synchronization.
19394   case X86::MONITOR:
19395     return EmitMonitor(MI, BB, Subtarget);
19396
19397   // xbegin
19398   case X86::XBEGIN:
19399     return EmitXBegin(MI, BB, Subtarget->getInstrInfo());
19400
19401   case X86::VASTART_SAVE_XMM_REGS:
19402     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
19403
19404   case X86::VAARG_64:
19405     return EmitVAARG64WithCustomInserter(MI, BB);
19406
19407   case X86::EH_SjLj_SetJmp32:
19408   case X86::EH_SjLj_SetJmp64:
19409     return emitEHSjLjSetJmp(MI, BB);
19410
19411   case X86::EH_SjLj_LongJmp32:
19412   case X86::EH_SjLj_LongJmp64:
19413     return emitEHSjLjLongJmp(MI, BB);
19414
19415   case TargetOpcode::STATEPOINT:
19416     // As an implementation detail, STATEPOINT shares the STACKMAP format at
19417     // this point in the process.  We diverge later.
19418     return emitPatchPoint(MI, BB);
19419
19420   case TargetOpcode::STACKMAP:
19421   case TargetOpcode::PATCHPOINT:
19422     return emitPatchPoint(MI, BB);
19423
19424   case X86::VFMADDPDr213r:
19425   case X86::VFMADDPSr213r:
19426   case X86::VFMADDSDr213r:
19427   case X86::VFMADDSSr213r:
19428   case X86::VFMSUBPDr213r:
19429   case X86::VFMSUBPSr213r:
19430   case X86::VFMSUBSDr213r:
19431   case X86::VFMSUBSSr213r:
19432   case X86::VFNMADDPDr213r:
19433   case X86::VFNMADDPSr213r:
19434   case X86::VFNMADDSDr213r:
19435   case X86::VFNMADDSSr213r:
19436   case X86::VFNMSUBPDr213r:
19437   case X86::VFNMSUBPSr213r:
19438   case X86::VFNMSUBSDr213r:
19439   case X86::VFNMSUBSSr213r:
19440   case X86::VFMADDSUBPDr213r:
19441   case X86::VFMADDSUBPSr213r:
19442   case X86::VFMSUBADDPDr213r:
19443   case X86::VFMSUBADDPSr213r:
19444   case X86::VFMADDPDr213rY:
19445   case X86::VFMADDPSr213rY:
19446   case X86::VFMSUBPDr213rY:
19447   case X86::VFMSUBPSr213rY:
19448   case X86::VFNMADDPDr213rY:
19449   case X86::VFNMADDPSr213rY:
19450   case X86::VFNMSUBPDr213rY:
19451   case X86::VFNMSUBPSr213rY:
19452   case X86::VFMADDSUBPDr213rY:
19453   case X86::VFMADDSUBPSr213rY:
19454   case X86::VFMSUBADDPDr213rY:
19455   case X86::VFMSUBADDPSr213rY:
19456     return emitFMA3Instr(MI, BB);
19457   }
19458 }
19459
19460 //===----------------------------------------------------------------------===//
19461 //                           X86 Optimization Hooks
19462 //===----------------------------------------------------------------------===//
19463
19464 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
19465                                                       APInt &KnownZero,
19466                                                       APInt &KnownOne,
19467                                                       const SelectionDAG &DAG,
19468                                                       unsigned Depth) const {
19469   unsigned BitWidth = KnownZero.getBitWidth();
19470   unsigned Opc = Op.getOpcode();
19471   assert((Opc >= ISD::BUILTIN_OP_END ||
19472           Opc == ISD::INTRINSIC_WO_CHAIN ||
19473           Opc == ISD::INTRINSIC_W_CHAIN ||
19474           Opc == ISD::INTRINSIC_VOID) &&
19475          "Should use MaskedValueIsZero if you don't know whether Op"
19476          " is a target node!");
19477
19478   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
19479   switch (Opc) {
19480   default: break;
19481   case X86ISD::ADD:
19482   case X86ISD::SUB:
19483   case X86ISD::ADC:
19484   case X86ISD::SBB:
19485   case X86ISD::SMUL:
19486   case X86ISD::UMUL:
19487   case X86ISD::INC:
19488   case X86ISD::DEC:
19489   case X86ISD::OR:
19490   case X86ISD::XOR:
19491   case X86ISD::AND:
19492     // These nodes' second result is a boolean.
19493     if (Op.getResNo() == 0)
19494       break;
19495     // Fallthrough
19496   case X86ISD::SETCC:
19497     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
19498     break;
19499   case ISD::INTRINSIC_WO_CHAIN: {
19500     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
19501     unsigned NumLoBits = 0;
19502     switch (IntId) {
19503     default: break;
19504     case Intrinsic::x86_sse_movmsk_ps:
19505     case Intrinsic::x86_avx_movmsk_ps_256:
19506     case Intrinsic::x86_sse2_movmsk_pd:
19507     case Intrinsic::x86_avx_movmsk_pd_256:
19508     case Intrinsic::x86_mmx_pmovmskb:
19509     case Intrinsic::x86_sse2_pmovmskb_128:
19510     case Intrinsic::x86_avx2_pmovmskb: {
19511       // High bits of movmskp{s|d}, pmovmskb are known zero.
19512       switch (IntId) {
19513         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
19514         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
19515         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
19516         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
19517         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
19518         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
19519         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
19520         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
19521       }
19522       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
19523       break;
19524     }
19525     }
19526     break;
19527   }
19528   }
19529 }
19530
19531 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
19532   SDValue Op,
19533   const SelectionDAG &,
19534   unsigned Depth) const {
19535   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
19536   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
19537     return Op.getValueType().getScalarType().getSizeInBits();
19538
19539   // Fallback case.
19540   return 1;
19541 }
19542
19543 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
19544 /// node is a GlobalAddress + offset.
19545 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
19546                                        const GlobalValue* &GA,
19547                                        int64_t &Offset) const {
19548   if (N->getOpcode() == X86ISD::Wrapper) {
19549     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
19550       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
19551       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
19552       return true;
19553     }
19554   }
19555   return TargetLowering::isGAPlusOffset(N, GA, Offset);
19556 }
19557
19558 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
19559 /// same as extracting the high 128-bit part of 256-bit vector and then
19560 /// inserting the result into the low part of a new 256-bit vector
19561 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
19562   EVT VT = SVOp->getValueType(0);
19563   unsigned NumElems = VT.getVectorNumElements();
19564
19565   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
19566   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
19567     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
19568         SVOp->getMaskElt(j) >= 0)
19569       return false;
19570
19571   return true;
19572 }
19573
19574 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
19575 /// same as extracting the low 128-bit part of 256-bit vector and then
19576 /// inserting the result into the high part of a new 256-bit vector
19577 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
19578   EVT VT = SVOp->getValueType(0);
19579   unsigned NumElems = VT.getVectorNumElements();
19580
19581   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
19582   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
19583     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
19584         SVOp->getMaskElt(j) >= 0)
19585       return false;
19586
19587   return true;
19588 }
19589
19590 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
19591 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
19592                                         TargetLowering::DAGCombinerInfo &DCI,
19593                                         const X86Subtarget* Subtarget) {
19594   SDLoc dl(N);
19595   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
19596   SDValue V1 = SVOp->getOperand(0);
19597   SDValue V2 = SVOp->getOperand(1);
19598   EVT VT = SVOp->getValueType(0);
19599   unsigned NumElems = VT.getVectorNumElements();
19600
19601   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
19602       V2.getOpcode() == ISD::CONCAT_VECTORS) {
19603     //
19604     //                   0,0,0,...
19605     //                      |
19606     //    V      UNDEF    BUILD_VECTOR    UNDEF
19607     //     \      /           \           /
19608     //  CONCAT_VECTOR         CONCAT_VECTOR
19609     //         \                  /
19610     //          \                /
19611     //          RESULT: V + zero extended
19612     //
19613     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
19614         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
19615         V1.getOperand(1).getOpcode() != ISD::UNDEF)
19616       return SDValue();
19617
19618     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
19619       return SDValue();
19620
19621     // To match the shuffle mask, the first half of the mask should
19622     // be exactly the first vector, and all the rest a splat with the
19623     // first element of the second one.
19624     for (unsigned i = 0; i != NumElems/2; ++i)
19625       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
19626           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
19627         return SDValue();
19628
19629     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
19630     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
19631       if (Ld->hasNUsesOfValue(1, 0)) {
19632         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
19633         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
19634         SDValue ResNode =
19635           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
19636                                   Ld->getMemoryVT(),
19637                                   Ld->getPointerInfo(),
19638                                   Ld->getAlignment(),
19639                                   false/*isVolatile*/, true/*ReadMem*/,
19640                                   false/*WriteMem*/);
19641
19642         // Make sure the newly-created LOAD is in the same position as Ld in
19643         // terms of dependency. We create a TokenFactor for Ld and ResNode,
19644         // and update uses of Ld's output chain to use the TokenFactor.
19645         if (Ld->hasAnyUseOfValue(1)) {
19646           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
19647                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
19648           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
19649           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
19650                                  SDValue(ResNode.getNode(), 1));
19651         }
19652
19653         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
19654       }
19655     }
19656
19657     // Emit a zeroed vector and insert the desired subvector on its
19658     // first half.
19659     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
19660     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
19661     return DCI.CombineTo(N, InsV);
19662   }
19663
19664   //===--------------------------------------------------------------------===//
19665   // Combine some shuffles into subvector extracts and inserts:
19666   //
19667
19668   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
19669   if (isShuffleHigh128VectorInsertLow(SVOp)) {
19670     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
19671     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
19672     return DCI.CombineTo(N, InsV);
19673   }
19674
19675   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
19676   if (isShuffleLow128VectorInsertHigh(SVOp)) {
19677     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
19678     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
19679     return DCI.CombineTo(N, InsV);
19680   }
19681
19682   return SDValue();
19683 }
19684
19685 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
19686 /// possible.
19687 ///
19688 /// This is the leaf of the recursive combinine below. When we have found some
19689 /// chain of single-use x86 shuffle instructions and accumulated the combined
19690 /// shuffle mask represented by them, this will try to pattern match that mask
19691 /// into either a single instruction if there is a special purpose instruction
19692 /// for this operation, or into a PSHUFB instruction which is a fully general
19693 /// instruction but should only be used to replace chains over a certain depth.
19694 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
19695                                    int Depth, bool HasPSHUFB, SelectionDAG &DAG,
19696                                    TargetLowering::DAGCombinerInfo &DCI,
19697                                    const X86Subtarget *Subtarget) {
19698   assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
19699
19700   // Find the operand that enters the chain. Note that multiple uses are OK
19701   // here, we're not going to remove the operand we find.
19702   SDValue Input = Op.getOperand(0);
19703   while (Input.getOpcode() == ISD::BITCAST)
19704     Input = Input.getOperand(0);
19705
19706   MVT VT = Input.getSimpleValueType();
19707   MVT RootVT = Root.getSimpleValueType();
19708   SDLoc DL(Root);
19709
19710   // Just remove no-op shuffle masks.
19711   if (Mask.size() == 1) {
19712     DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Input),
19713                   /*AddTo*/ true);
19714     return true;
19715   }
19716
19717   // Use the float domain if the operand type is a floating point type.
19718   bool FloatDomain = VT.isFloatingPoint();
19719
19720   // For floating point shuffles, we don't have free copies in the shuffle
19721   // instructions or the ability to load as part of the instruction, so
19722   // canonicalize their shuffles to UNPCK or MOV variants.
19723   //
19724   // Note that even with AVX we prefer the PSHUFD form of shuffle for integer
19725   // vectors because it can have a load folded into it that UNPCK cannot. This
19726   // doesn't preclude something switching to the shorter encoding post-RA.
19727   //
19728   // FIXME: Should teach these routines about AVX vector widths.
19729   if (FloatDomain && VT.getSizeInBits() == 128) {
19730     if (Mask.equals({0, 0}) || Mask.equals({1, 1})) {
19731       bool Lo = Mask.equals({0, 0});
19732       unsigned Shuffle;
19733       MVT ShuffleVT;
19734       // Check if we have SSE3 which will let us use MOVDDUP. That instruction
19735       // is no slower than UNPCKLPD but has the option to fold the input operand
19736       // into even an unaligned memory load.
19737       if (Lo && Subtarget->hasSSE3()) {
19738         Shuffle = X86ISD::MOVDDUP;
19739         ShuffleVT = MVT::v2f64;
19740       } else {
19741         // We have MOVLHPS and MOVHLPS throughout SSE and they encode smaller
19742         // than the UNPCK variants.
19743         Shuffle = Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS;
19744         ShuffleVT = MVT::v4f32;
19745       }
19746       if (Depth == 1 && Root->getOpcode() == Shuffle)
19747         return false; // Nothing to do!
19748       Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19749       DCI.AddToWorklist(Op.getNode());
19750       if (Shuffle == X86ISD::MOVDDUP)
19751         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
19752       else
19753         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
19754       DCI.AddToWorklist(Op.getNode());
19755       DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19756                     /*AddTo*/ true);
19757       return true;
19758     }
19759     if (Subtarget->hasSSE3() &&
19760         (Mask.equals({0, 0, 2, 2}) || Mask.equals({1, 1, 3, 3}))) {
19761       bool Lo = Mask.equals({0, 0, 2, 2});
19762       unsigned Shuffle = Lo ? X86ISD::MOVSLDUP : X86ISD::MOVSHDUP;
19763       MVT ShuffleVT = MVT::v4f32;
19764       if (Depth == 1 && Root->getOpcode() == Shuffle)
19765         return false; // Nothing to do!
19766       Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19767       DCI.AddToWorklist(Op.getNode());
19768       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
19769       DCI.AddToWorklist(Op.getNode());
19770       DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19771                     /*AddTo*/ true);
19772       return true;
19773     }
19774     if (Mask.equals({0, 0, 1, 1}) || Mask.equals({2, 2, 3, 3})) {
19775       bool Lo = Mask.equals({0, 0, 1, 1});
19776       unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
19777       MVT ShuffleVT = MVT::v4f32;
19778       if (Depth == 1 && Root->getOpcode() == Shuffle)
19779         return false; // Nothing to do!
19780       Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19781       DCI.AddToWorklist(Op.getNode());
19782       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
19783       DCI.AddToWorklist(Op.getNode());
19784       DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19785                     /*AddTo*/ true);
19786       return true;
19787     }
19788   }
19789
19790   // We always canonicalize the 8 x i16 and 16 x i8 shuffles into their UNPCK
19791   // variants as none of these have single-instruction variants that are
19792   // superior to the UNPCK formulation.
19793   if (!FloatDomain && VT.getSizeInBits() == 128 &&
19794       (Mask.equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
19795        Mask.equals({4, 4, 5, 5, 6, 6, 7, 7}) ||
19796        Mask.equals({0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7}) ||
19797        Mask.equals(
19798            {8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15}))) {
19799     bool Lo = Mask[0] == 0;
19800     unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
19801     if (Depth == 1 && Root->getOpcode() == Shuffle)
19802       return false; // Nothing to do!
19803     MVT ShuffleVT;
19804     switch (Mask.size()) {
19805     case 8:
19806       ShuffleVT = MVT::v8i16;
19807       break;
19808     case 16:
19809       ShuffleVT = MVT::v16i8;
19810       break;
19811     default:
19812       llvm_unreachable("Impossible mask size!");
19813     };
19814     Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19815     DCI.AddToWorklist(Op.getNode());
19816     Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
19817     DCI.AddToWorklist(Op.getNode());
19818     DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19819                   /*AddTo*/ true);
19820     return true;
19821   }
19822
19823   // Don't try to re-form single instruction chains under any circumstances now
19824   // that we've done encoding canonicalization for them.
19825   if (Depth < 2)
19826     return false;
19827
19828   // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
19829   // can replace them with a single PSHUFB instruction profitably. Intel's
19830   // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
19831   // in practice PSHUFB tends to be *very* fast so we're more aggressive.
19832   if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
19833     SmallVector<SDValue, 16> PSHUFBMask;
19834     int NumBytes = VT.getSizeInBits() / 8;
19835     int Ratio = NumBytes / Mask.size();
19836     for (int i = 0; i < NumBytes; ++i) {
19837       if (Mask[i / Ratio] == SM_SentinelUndef) {
19838         PSHUFBMask.push_back(DAG.getUNDEF(MVT::i8));
19839         continue;
19840       }
19841       int M = Mask[i / Ratio] != SM_SentinelZero
19842                   ? Ratio * Mask[i / Ratio] + i % Ratio
19843                   : 255;
19844       PSHUFBMask.push_back(DAG.getConstant(M, MVT::i8));
19845     }
19846     MVT ByteVT = MVT::getVectorVT(MVT::i8, NumBytes);
19847     Op = DAG.getNode(ISD::BITCAST, DL, ByteVT, Input);
19848     DCI.AddToWorklist(Op.getNode());
19849     SDValue PSHUFBMaskOp =
19850         DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVT, PSHUFBMask);
19851     DCI.AddToWorklist(PSHUFBMaskOp.getNode());
19852     Op = DAG.getNode(X86ISD::PSHUFB, DL, ByteVT, Op, PSHUFBMaskOp);
19853     DCI.AddToWorklist(Op.getNode());
19854     DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19855                   /*AddTo*/ true);
19856     return true;
19857   }
19858
19859   // Failed to find any combines.
19860   return false;
19861 }
19862
19863 /// \brief Fully generic combining of x86 shuffle instructions.
19864 ///
19865 /// This should be the last combine run over the x86 shuffle instructions. Once
19866 /// they have been fully optimized, this will recursively consider all chains
19867 /// of single-use shuffle instructions, build a generic model of the cumulative
19868 /// shuffle operation, and check for simpler instructions which implement this
19869 /// operation. We use this primarily for two purposes:
19870 ///
19871 /// 1) Collapse generic shuffles to specialized single instructions when
19872 ///    equivalent. In most cases, this is just an encoding size win, but
19873 ///    sometimes we will collapse multiple generic shuffles into a single
19874 ///    special-purpose shuffle.
19875 /// 2) Look for sequences of shuffle instructions with 3 or more total
19876 ///    instructions, and replace them with the slightly more expensive SSSE3
19877 ///    PSHUFB instruction if available. We do this as the last combining step
19878 ///    to ensure we avoid using PSHUFB if we can implement the shuffle with
19879 ///    a suitable short sequence of other instructions. The PHUFB will either
19880 ///    use a register or have to read from memory and so is slightly (but only
19881 ///    slightly) more expensive than the other shuffle instructions.
19882 ///
19883 /// Because this is inherently a quadratic operation (for each shuffle in
19884 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
19885 /// This should never be an issue in practice as the shuffle lowering doesn't
19886 /// produce sequences of more than 8 instructions.
19887 ///
19888 /// FIXME: We will currently miss some cases where the redundant shuffling
19889 /// would simplify under the threshold for PSHUFB formation because of
19890 /// combine-ordering. To fix this, we should do the redundant instruction
19891 /// combining in this recursive walk.
19892 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
19893                                           ArrayRef<int> RootMask,
19894                                           int Depth, bool HasPSHUFB,
19895                                           SelectionDAG &DAG,
19896                                           TargetLowering::DAGCombinerInfo &DCI,
19897                                           const X86Subtarget *Subtarget) {
19898   // Bound the depth of our recursive combine because this is ultimately
19899   // quadratic in nature.
19900   if (Depth > 8)
19901     return false;
19902
19903   // Directly rip through bitcasts to find the underlying operand.
19904   while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
19905     Op = Op.getOperand(0);
19906
19907   MVT VT = Op.getSimpleValueType();
19908   if (!VT.isVector())
19909     return false; // Bail if we hit a non-vector.
19910
19911   assert(Root.getSimpleValueType().isVector() &&
19912          "Shuffles operate on vector types!");
19913   assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
19914          "Can only combine shuffles of the same vector register size.");
19915
19916   if (!isTargetShuffle(Op.getOpcode()))
19917     return false;
19918   SmallVector<int, 16> OpMask;
19919   bool IsUnary;
19920   bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, OpMask, IsUnary);
19921   // We only can combine unary shuffles which we can decode the mask for.
19922   if (!HaveMask || !IsUnary)
19923     return false;
19924
19925   assert(VT.getVectorNumElements() == OpMask.size() &&
19926          "Different mask size from vector size!");
19927   assert(((RootMask.size() > OpMask.size() &&
19928            RootMask.size() % OpMask.size() == 0) ||
19929           (OpMask.size() > RootMask.size() &&
19930            OpMask.size() % RootMask.size() == 0) ||
19931           OpMask.size() == RootMask.size()) &&
19932          "The smaller number of elements must divide the larger.");
19933   int RootRatio = std::max<int>(1, OpMask.size() / RootMask.size());
19934   int OpRatio = std::max<int>(1, RootMask.size() / OpMask.size());
19935   assert(((RootRatio == 1 && OpRatio == 1) ||
19936           (RootRatio == 1) != (OpRatio == 1)) &&
19937          "Must not have a ratio for both incoming and op masks!");
19938
19939   SmallVector<int, 16> Mask;
19940   Mask.reserve(std::max(OpMask.size(), RootMask.size()));
19941
19942   // Merge this shuffle operation's mask into our accumulated mask. Note that
19943   // this shuffle's mask will be the first applied to the input, followed by the
19944   // root mask to get us all the way to the root value arrangement. The reason
19945   // for this order is that we are recursing up the operation chain.
19946   for (int i = 0, e = std::max(OpMask.size(), RootMask.size()); i < e; ++i) {
19947     int RootIdx = i / RootRatio;
19948     if (RootMask[RootIdx] < 0) {
19949       // This is a zero or undef lane, we're done.
19950       Mask.push_back(RootMask[RootIdx]);
19951       continue;
19952     }
19953
19954     int RootMaskedIdx = RootMask[RootIdx] * RootRatio + i % RootRatio;
19955     int OpIdx = RootMaskedIdx / OpRatio;
19956     if (OpMask[OpIdx] < 0) {
19957       // The incoming lanes are zero or undef, it doesn't matter which ones we
19958       // are using.
19959       Mask.push_back(OpMask[OpIdx]);
19960       continue;
19961     }
19962
19963     // Ok, we have non-zero lanes, map them through.
19964     Mask.push_back(OpMask[OpIdx] * OpRatio +
19965                    RootMaskedIdx % OpRatio);
19966   }
19967
19968   // See if we can recurse into the operand to combine more things.
19969   switch (Op.getOpcode()) {
19970     case X86ISD::PSHUFB:
19971       HasPSHUFB = true;
19972     case X86ISD::PSHUFD:
19973     case X86ISD::PSHUFHW:
19974     case X86ISD::PSHUFLW:
19975       if (Op.getOperand(0).hasOneUse() &&
19976           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
19977                                         HasPSHUFB, DAG, DCI, Subtarget))
19978         return true;
19979       break;
19980
19981     case X86ISD::UNPCKL:
19982     case X86ISD::UNPCKH:
19983       assert(Op.getOperand(0) == Op.getOperand(1) && "We only combine unary shuffles!");
19984       // We can't check for single use, we have to check that this shuffle is the only user.
19985       if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
19986           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
19987                                         HasPSHUFB, DAG, DCI, Subtarget))
19988           return true;
19989       break;
19990   }
19991
19992   // Minor canonicalization of the accumulated shuffle mask to make it easier
19993   // to match below. All this does is detect masks with squential pairs of
19994   // elements, and shrink them to the half-width mask. It does this in a loop
19995   // so it will reduce the size of the mask to the minimal width mask which
19996   // performs an equivalent shuffle.
19997   SmallVector<int, 16> WidenedMask;
19998   while (Mask.size() > 1 && canWidenShuffleElements(Mask, WidenedMask)) {
19999     Mask = std::move(WidenedMask);
20000     WidenedMask.clear();
20001   }
20002
20003   return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
20004                                 Subtarget);
20005 }
20006
20007 /// \brief Get the PSHUF-style mask from PSHUF node.
20008 ///
20009 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
20010 /// PSHUF-style masks that can be reused with such instructions.
20011 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
20012   MVT VT = N.getSimpleValueType();
20013   SmallVector<int, 4> Mask;
20014   bool IsUnary;
20015   bool HaveMask = getTargetShuffleMask(N.getNode(), VT, Mask, IsUnary);
20016   (void)HaveMask;
20017   assert(HaveMask);
20018
20019   // If we have more than 128-bits, only the low 128-bits of shuffle mask
20020   // matter. Check that the upper masks are repeats and remove them.
20021   if (VT.getSizeInBits() > 128) {
20022     int LaneElts = 128 / VT.getScalarSizeInBits();
20023 #ifndef NDEBUG
20024     for (int i = 1, NumLanes = VT.getSizeInBits() / 128; i < NumLanes; ++i)
20025       for (int j = 0; j < LaneElts; ++j)
20026         assert(Mask[j] == Mask[i * LaneElts + j] - LaneElts &&
20027                "Mask doesn't repeat in high 128-bit lanes!");
20028 #endif
20029     Mask.resize(LaneElts);
20030   }
20031
20032   switch (N.getOpcode()) {
20033   case X86ISD::PSHUFD:
20034     return Mask;
20035   case X86ISD::PSHUFLW:
20036     Mask.resize(4);
20037     return Mask;
20038   case X86ISD::PSHUFHW:
20039     Mask.erase(Mask.begin(), Mask.begin() + 4);
20040     for (int &M : Mask)
20041       M -= 4;
20042     return Mask;
20043   default:
20044     llvm_unreachable("No valid shuffle instruction found!");
20045   }
20046 }
20047
20048 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
20049 ///
20050 /// We walk up the chain and look for a combinable shuffle, skipping over
20051 /// shuffles that we could hoist this shuffle's transformation past without
20052 /// altering anything.
20053 static SDValue
20054 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
20055                              SelectionDAG &DAG,
20056                              TargetLowering::DAGCombinerInfo &DCI) {
20057   assert(N.getOpcode() == X86ISD::PSHUFD &&
20058          "Called with something other than an x86 128-bit half shuffle!");
20059   SDLoc DL(N);
20060
20061   // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
20062   // of the shuffles in the chain so that we can form a fresh chain to replace
20063   // this one.
20064   SmallVector<SDValue, 8> Chain;
20065   SDValue V = N.getOperand(0);
20066   for (; V.hasOneUse(); V = V.getOperand(0)) {
20067     switch (V.getOpcode()) {
20068     default:
20069       return SDValue(); // Nothing combined!
20070
20071     case ISD::BITCAST:
20072       // Skip bitcasts as we always know the type for the target specific
20073       // instructions.
20074       continue;
20075
20076     case X86ISD::PSHUFD:
20077       // Found another dword shuffle.
20078       break;
20079
20080     case X86ISD::PSHUFLW:
20081       // Check that the low words (being shuffled) are the identity in the
20082       // dword shuffle, and the high words are self-contained.
20083       if (Mask[0] != 0 || Mask[1] != 1 ||
20084           !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
20085         return SDValue();
20086
20087       Chain.push_back(V);
20088       continue;
20089
20090     case X86ISD::PSHUFHW:
20091       // Check that the high words (being shuffled) are the identity in the
20092       // dword shuffle, and the low words are self-contained.
20093       if (Mask[2] != 2 || Mask[3] != 3 ||
20094           !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
20095         return SDValue();
20096
20097       Chain.push_back(V);
20098       continue;
20099
20100     case X86ISD::UNPCKL:
20101     case X86ISD::UNPCKH:
20102       // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
20103       // shuffle into a preceding word shuffle.
20104       if (V.getSimpleValueType().getScalarType() != MVT::i8 &&
20105           V.getSimpleValueType().getScalarType() != MVT::i16)
20106         return SDValue();
20107
20108       // Search for a half-shuffle which we can combine with.
20109       unsigned CombineOp =
20110           V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
20111       if (V.getOperand(0) != V.getOperand(1) ||
20112           !V->isOnlyUserOf(V.getOperand(0).getNode()))
20113         return SDValue();
20114       Chain.push_back(V);
20115       V = V.getOperand(0);
20116       do {
20117         switch (V.getOpcode()) {
20118         default:
20119           return SDValue(); // Nothing to combine.
20120
20121         case X86ISD::PSHUFLW:
20122         case X86ISD::PSHUFHW:
20123           if (V.getOpcode() == CombineOp)
20124             break;
20125
20126           Chain.push_back(V);
20127
20128           // Fallthrough!
20129         case ISD::BITCAST:
20130           V = V.getOperand(0);
20131           continue;
20132         }
20133         break;
20134       } while (V.hasOneUse());
20135       break;
20136     }
20137     // Break out of the loop if we break out of the switch.
20138     break;
20139   }
20140
20141   if (!V.hasOneUse())
20142     // We fell out of the loop without finding a viable combining instruction.
20143     return SDValue();
20144
20145   // Merge this node's mask and our incoming mask.
20146   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
20147   for (int &M : Mask)
20148     M = VMask[M];
20149   V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
20150                   getV4X86ShuffleImm8ForMask(Mask, DAG));
20151
20152   // Rebuild the chain around this new shuffle.
20153   while (!Chain.empty()) {
20154     SDValue W = Chain.pop_back_val();
20155
20156     if (V.getValueType() != W.getOperand(0).getValueType())
20157       V = DAG.getNode(ISD::BITCAST, DL, W.getOperand(0).getValueType(), V);
20158
20159     switch (W.getOpcode()) {
20160     default:
20161       llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
20162
20163     case X86ISD::UNPCKL:
20164     case X86ISD::UNPCKH:
20165       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
20166       break;
20167
20168     case X86ISD::PSHUFD:
20169     case X86ISD::PSHUFLW:
20170     case X86ISD::PSHUFHW:
20171       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
20172       break;
20173     }
20174   }
20175   if (V.getValueType() != N.getValueType())
20176     V = DAG.getNode(ISD::BITCAST, DL, N.getValueType(), V);
20177
20178   // Return the new chain to replace N.
20179   return V;
20180 }
20181
20182 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or pshufhw.
20183 ///
20184 /// We walk up the chain, skipping shuffles of the other half and looking
20185 /// through shuffles which switch halves trying to find a shuffle of the same
20186 /// pair of dwords.
20187 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
20188                                         SelectionDAG &DAG,
20189                                         TargetLowering::DAGCombinerInfo &DCI) {
20190   assert(
20191       (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
20192       "Called with something other than an x86 128-bit half shuffle!");
20193   SDLoc DL(N);
20194   unsigned CombineOpcode = N.getOpcode();
20195
20196   // Walk up a single-use chain looking for a combinable shuffle.
20197   SDValue V = N.getOperand(0);
20198   for (; V.hasOneUse(); V = V.getOperand(0)) {
20199     switch (V.getOpcode()) {
20200     default:
20201       return false; // Nothing combined!
20202
20203     case ISD::BITCAST:
20204       // Skip bitcasts as we always know the type for the target specific
20205       // instructions.
20206       continue;
20207
20208     case X86ISD::PSHUFLW:
20209     case X86ISD::PSHUFHW:
20210       if (V.getOpcode() == CombineOpcode)
20211         break;
20212
20213       // Other-half shuffles are no-ops.
20214       continue;
20215     }
20216     // Break out of the loop if we break out of the switch.
20217     break;
20218   }
20219
20220   if (!V.hasOneUse())
20221     // We fell out of the loop without finding a viable combining instruction.
20222     return false;
20223
20224   // Combine away the bottom node as its shuffle will be accumulated into
20225   // a preceding shuffle.
20226   DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
20227
20228   // Record the old value.
20229   SDValue Old = V;
20230
20231   // Merge this node's mask and our incoming mask (adjusted to account for all
20232   // the pshufd instructions encountered).
20233   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
20234   for (int &M : Mask)
20235     M = VMask[M];
20236   V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
20237                   getV4X86ShuffleImm8ForMask(Mask, DAG));
20238
20239   // Check that the shuffles didn't cancel each other out. If not, we need to
20240   // combine to the new one.
20241   if (Old != V)
20242     // Replace the combinable shuffle with the combined one, updating all users
20243     // so that we re-evaluate the chain here.
20244     DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
20245
20246   return true;
20247 }
20248
20249 /// \brief Try to combine x86 target specific shuffles.
20250 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
20251                                            TargetLowering::DAGCombinerInfo &DCI,
20252                                            const X86Subtarget *Subtarget) {
20253   SDLoc DL(N);
20254   MVT VT = N.getSimpleValueType();
20255   SmallVector<int, 4> Mask;
20256
20257   switch (N.getOpcode()) {
20258   case X86ISD::PSHUFD:
20259   case X86ISD::PSHUFLW:
20260   case X86ISD::PSHUFHW:
20261     Mask = getPSHUFShuffleMask(N);
20262     assert(Mask.size() == 4);
20263     break;
20264   default:
20265     return SDValue();
20266   }
20267
20268   // Nuke no-op shuffles that show up after combining.
20269   if (isNoopShuffleMask(Mask))
20270     return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
20271
20272   // Look for simplifications involving one or two shuffle instructions.
20273   SDValue V = N.getOperand(0);
20274   switch (N.getOpcode()) {
20275   default:
20276     break;
20277   case X86ISD::PSHUFLW:
20278   case X86ISD::PSHUFHW:
20279     assert(VT.getScalarType() == MVT::i16 && "Bad word shuffle type!");
20280
20281     if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
20282       return SDValue(); // We combined away this shuffle, so we're done.
20283
20284     // See if this reduces to a PSHUFD which is no more expensive and can
20285     // combine with more operations. Note that it has to at least flip the
20286     // dwords as otherwise it would have been removed as a no-op.
20287     if (makeArrayRef(Mask).equals({2, 3, 0, 1})) {
20288       int DMask[] = {0, 1, 2, 3};
20289       int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
20290       DMask[DOffset + 0] = DOffset + 1;
20291       DMask[DOffset + 1] = DOffset + 0;
20292       MVT DVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
20293       V = DAG.getNode(ISD::BITCAST, DL, DVT, V);
20294       DCI.AddToWorklist(V.getNode());
20295       V = DAG.getNode(X86ISD::PSHUFD, DL, DVT, V,
20296                       getV4X86ShuffleImm8ForMask(DMask, DAG));
20297       DCI.AddToWorklist(V.getNode());
20298       return DAG.getNode(ISD::BITCAST, DL, VT, V);
20299     }
20300
20301     // Look for shuffle patterns which can be implemented as a single unpack.
20302     // FIXME: This doesn't handle the location of the PSHUFD generically, and
20303     // only works when we have a PSHUFD followed by two half-shuffles.
20304     if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
20305         (V.getOpcode() == X86ISD::PSHUFLW ||
20306          V.getOpcode() == X86ISD::PSHUFHW) &&
20307         V.getOpcode() != N.getOpcode() &&
20308         V.hasOneUse()) {
20309       SDValue D = V.getOperand(0);
20310       while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
20311         D = D.getOperand(0);
20312       if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
20313         SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
20314         SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
20315         int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
20316         int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
20317         int WordMask[8];
20318         for (int i = 0; i < 4; ++i) {
20319           WordMask[i + NOffset] = Mask[i] + NOffset;
20320           WordMask[i + VOffset] = VMask[i] + VOffset;
20321         }
20322         // Map the word mask through the DWord mask.
20323         int MappedMask[8];
20324         for (int i = 0; i < 8; ++i)
20325           MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
20326         if (makeArrayRef(MappedMask).equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
20327             makeArrayRef(MappedMask).equals({4, 4, 5, 5, 6, 6, 7, 7})) {
20328           // We can replace all three shuffles with an unpack.
20329           V = DAG.getNode(ISD::BITCAST, DL, VT, D.getOperand(0));
20330           DCI.AddToWorklist(V.getNode());
20331           return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
20332                                                 : X86ISD::UNPCKH,
20333                              DL, VT, V, V);
20334         }
20335       }
20336     }
20337
20338     break;
20339
20340   case X86ISD::PSHUFD:
20341     if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG, DCI))
20342       return NewN;
20343
20344     break;
20345   }
20346
20347   return SDValue();
20348 }
20349
20350 /// \brief Try to combine a shuffle into a target-specific add-sub node.
20351 ///
20352 /// We combine this directly on the abstract vector shuffle nodes so it is
20353 /// easier to generically match. We also insert dummy vector shuffle nodes for
20354 /// the operands which explicitly discard the lanes which are unused by this
20355 /// operation to try to flow through the rest of the combiner the fact that
20356 /// they're unused.
20357 static SDValue combineShuffleToAddSub(SDNode *N, SelectionDAG &DAG) {
20358   SDLoc DL(N);
20359   EVT VT = N->getValueType(0);
20360
20361   // We only handle target-independent shuffles.
20362   // FIXME: It would be easy and harmless to use the target shuffle mask
20363   // extraction tool to support more.
20364   if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
20365     return SDValue();
20366
20367   auto *SVN = cast<ShuffleVectorSDNode>(N);
20368   ArrayRef<int> Mask = SVN->getMask();
20369   SDValue V1 = N->getOperand(0);
20370   SDValue V2 = N->getOperand(1);
20371
20372   // We require the first shuffle operand to be the SUB node, and the second to
20373   // be the ADD node.
20374   // FIXME: We should support the commuted patterns.
20375   if (V1->getOpcode() != ISD::FSUB || V2->getOpcode() != ISD::FADD)
20376     return SDValue();
20377
20378   // If there are other uses of these operations we can't fold them.
20379   if (!V1->hasOneUse() || !V2->hasOneUse())
20380     return SDValue();
20381
20382   // Ensure that both operations have the same operands. Note that we can
20383   // commute the FADD operands.
20384   SDValue LHS = V1->getOperand(0), RHS = V1->getOperand(1);
20385   if ((V2->getOperand(0) != LHS || V2->getOperand(1) != RHS) &&
20386       (V2->getOperand(0) != RHS || V2->getOperand(1) != LHS))
20387     return SDValue();
20388
20389   // We're looking for blends between FADD and FSUB nodes. We insist on these
20390   // nodes being lined up in a specific expected pattern.
20391   if (!(isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
20392         isShuffleEquivalent(V1, V2, Mask, {0, 5, 2, 7}) ||
20393         isShuffleEquivalent(V1, V2, Mask, {0, 9, 2, 11, 4, 13, 6, 15})))
20394     return SDValue();
20395
20396   // Only specific types are legal at this point, assert so we notice if and
20397   // when these change.
20398   assert((VT == MVT::v4f32 || VT == MVT::v2f64 || VT == MVT::v8f32 ||
20399           VT == MVT::v4f64) &&
20400          "Unknown vector type encountered!");
20401
20402   return DAG.getNode(X86ISD::ADDSUB, DL, VT, LHS, RHS);
20403 }
20404
20405 /// PerformShuffleCombine - Performs several different shuffle combines.
20406 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
20407                                      TargetLowering::DAGCombinerInfo &DCI,
20408                                      const X86Subtarget *Subtarget) {
20409   SDLoc dl(N);
20410   SDValue N0 = N->getOperand(0);
20411   SDValue N1 = N->getOperand(1);
20412   EVT VT = N->getValueType(0);
20413
20414   // Don't create instructions with illegal types after legalize types has run.
20415   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20416   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
20417     return SDValue();
20418
20419   // If we have legalized the vector types, look for blends of FADD and FSUB
20420   // nodes that we can fuse into an ADDSUB node.
20421   if (TLI.isTypeLegal(VT) && Subtarget->hasSSE3())
20422     if (SDValue AddSub = combineShuffleToAddSub(N, DAG))
20423       return AddSub;
20424
20425   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
20426   if (Subtarget->hasFp256() && VT.is256BitVector() &&
20427       N->getOpcode() == ISD::VECTOR_SHUFFLE)
20428     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
20429
20430   // During Type Legalization, when promoting illegal vector types,
20431   // the backend might introduce new shuffle dag nodes and bitcasts.
20432   //
20433   // This code performs the following transformation:
20434   // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
20435   //       (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
20436   //
20437   // We do this only if both the bitcast and the BINOP dag nodes have
20438   // one use. Also, perform this transformation only if the new binary
20439   // operation is legal. This is to avoid introducing dag nodes that
20440   // potentially need to be further expanded (or custom lowered) into a
20441   // less optimal sequence of dag nodes.
20442   if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
20443       N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
20444       N0.getOpcode() == ISD::BITCAST) {
20445     SDValue BC0 = N0.getOperand(0);
20446     EVT SVT = BC0.getValueType();
20447     unsigned Opcode = BC0.getOpcode();
20448     unsigned NumElts = VT.getVectorNumElements();
20449
20450     if (BC0.hasOneUse() && SVT.isVector() &&
20451         SVT.getVectorNumElements() * 2 == NumElts &&
20452         TLI.isOperationLegal(Opcode, VT)) {
20453       bool CanFold = false;
20454       switch (Opcode) {
20455       default : break;
20456       case ISD::ADD :
20457       case ISD::FADD :
20458       case ISD::SUB :
20459       case ISD::FSUB :
20460       case ISD::MUL :
20461       case ISD::FMUL :
20462         CanFold = true;
20463       }
20464
20465       unsigned SVTNumElts = SVT.getVectorNumElements();
20466       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
20467       for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
20468         CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
20469       for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
20470         CanFold = SVOp->getMaskElt(i) < 0;
20471
20472       if (CanFold) {
20473         SDValue BC00 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(0));
20474         SDValue BC01 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(1));
20475         SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
20476         return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
20477       }
20478     }
20479   }
20480
20481   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
20482   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
20483   // consecutive, non-overlapping, and in the right order.
20484   SmallVector<SDValue, 16> Elts;
20485   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
20486     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
20487
20488   SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
20489   if (LD.getNode())
20490     return LD;
20491
20492   if (isTargetShuffle(N->getOpcode())) {
20493     SDValue Shuffle =
20494         PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
20495     if (Shuffle.getNode())
20496       return Shuffle;
20497
20498     // Try recursively combining arbitrary sequences of x86 shuffle
20499     // instructions into higher-order shuffles. We do this after combining
20500     // specific PSHUF instruction sequences into their minimal form so that we
20501     // can evaluate how many specialized shuffle instructions are involved in
20502     // a particular chain.
20503     SmallVector<int, 1> NonceMask; // Just a placeholder.
20504     NonceMask.push_back(0);
20505     if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
20506                                       /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
20507                                       DCI, Subtarget))
20508       return SDValue(); // This routine will use CombineTo to replace N.
20509   }
20510
20511   return SDValue();
20512 }
20513
20514 /// PerformTruncateCombine - Converts truncate operation to
20515 /// a sequence of vector shuffle operations.
20516 /// It is possible when we truncate 256-bit vector to 128-bit vector
20517 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
20518                                       TargetLowering::DAGCombinerInfo &DCI,
20519                                       const X86Subtarget *Subtarget)  {
20520   return SDValue();
20521 }
20522
20523 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
20524 /// specific shuffle of a load can be folded into a single element load.
20525 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
20526 /// shuffles have been custom lowered so we need to handle those here.
20527 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
20528                                          TargetLowering::DAGCombinerInfo &DCI) {
20529   if (DCI.isBeforeLegalizeOps())
20530     return SDValue();
20531
20532   SDValue InVec = N->getOperand(0);
20533   SDValue EltNo = N->getOperand(1);
20534
20535   if (!isa<ConstantSDNode>(EltNo))
20536     return SDValue();
20537
20538   EVT OriginalVT = InVec.getValueType();
20539
20540   if (InVec.getOpcode() == ISD::BITCAST) {
20541     // Don't duplicate a load with other uses.
20542     if (!InVec.hasOneUse())
20543       return SDValue();
20544     EVT BCVT = InVec.getOperand(0).getValueType();
20545     if (BCVT.getVectorNumElements() != OriginalVT.getVectorNumElements())
20546       return SDValue();
20547     InVec = InVec.getOperand(0);
20548   }
20549
20550   EVT CurrentVT = InVec.getValueType();
20551
20552   if (!isTargetShuffle(InVec.getOpcode()))
20553     return SDValue();
20554
20555   // Don't duplicate a load with other uses.
20556   if (!InVec.hasOneUse())
20557     return SDValue();
20558
20559   SmallVector<int, 16> ShuffleMask;
20560   bool UnaryShuffle;
20561   if (!getTargetShuffleMask(InVec.getNode(), CurrentVT.getSimpleVT(),
20562                             ShuffleMask, UnaryShuffle))
20563     return SDValue();
20564
20565   // Select the input vector, guarding against out of range extract vector.
20566   unsigned NumElems = CurrentVT.getVectorNumElements();
20567   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
20568   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
20569   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
20570                                          : InVec.getOperand(1);
20571
20572   // If inputs to shuffle are the same for both ops, then allow 2 uses
20573   unsigned AllowedUses = InVec.getNumOperands() > 1 &&
20574                          InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
20575
20576   if (LdNode.getOpcode() == ISD::BITCAST) {
20577     // Don't duplicate a load with other uses.
20578     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
20579       return SDValue();
20580
20581     AllowedUses = 1; // only allow 1 load use if we have a bitcast
20582     LdNode = LdNode.getOperand(0);
20583   }
20584
20585   if (!ISD::isNormalLoad(LdNode.getNode()))
20586     return SDValue();
20587
20588   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
20589
20590   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
20591     return SDValue();
20592
20593   EVT EltVT = N->getValueType(0);
20594   // If there's a bitcast before the shuffle, check if the load type and
20595   // alignment is valid.
20596   unsigned Align = LN0->getAlignment();
20597   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20598   unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
20599       EltVT.getTypeForEVT(*DAG.getContext()));
20600
20601   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, EltVT))
20602     return SDValue();
20603
20604   // All checks match so transform back to vector_shuffle so that DAG combiner
20605   // can finish the job
20606   SDLoc dl(N);
20607
20608   // Create shuffle node taking into account the case that its a unary shuffle
20609   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(CurrentVT)
20610                                    : InVec.getOperand(1);
20611   Shuffle = DAG.getVectorShuffle(CurrentVT, dl,
20612                                  InVec.getOperand(0), Shuffle,
20613                                  &ShuffleMask[0]);
20614   Shuffle = DAG.getNode(ISD::BITCAST, dl, OriginalVT, Shuffle);
20615   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
20616                      EltNo);
20617 }
20618
20619 /// \brief Detect bitcasts between i32 to x86mmx low word. Since MMX types are
20620 /// special and don't usually play with other vector types, it's better to
20621 /// handle them early to be sure we emit efficient code by avoiding
20622 /// store-load conversions.
20623 static SDValue PerformBITCASTCombine(SDNode *N, SelectionDAG &DAG) {
20624   if (N->getValueType(0) != MVT::x86mmx ||
20625       N->getOperand(0)->getOpcode() != ISD::BUILD_VECTOR ||
20626       N->getOperand(0)->getValueType(0) != MVT::v2i32)
20627     return SDValue();
20628
20629   SDValue V = N->getOperand(0);
20630   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V.getOperand(1));
20631   if (C && C->getZExtValue() == 0 && V.getOperand(0).getValueType() == MVT::i32)
20632     return DAG.getNode(X86ISD::MMX_MOVW2D, SDLoc(V.getOperand(0)),
20633                        N->getValueType(0), V.getOperand(0));
20634
20635   return SDValue();
20636 }
20637
20638 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
20639 /// generation and convert it from being a bunch of shuffles and extracts
20640 /// into a somewhat faster sequence. For i686, the best sequence is apparently
20641 /// storing the value and loading scalars back, while for x64 we should
20642 /// use 64-bit extracts and shifts.
20643 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
20644                                          TargetLowering::DAGCombinerInfo &DCI) {
20645   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
20646   if (NewOp.getNode())
20647     return NewOp;
20648
20649   SDValue InputVector = N->getOperand(0);
20650
20651   // Detect mmx to i32 conversion through a v2i32 elt extract.
20652   if (InputVector.getOpcode() == ISD::BITCAST && InputVector.hasOneUse() &&
20653       N->getValueType(0) == MVT::i32 &&
20654       InputVector.getValueType() == MVT::v2i32) {
20655
20656     // The bitcast source is a direct mmx result.
20657     SDValue MMXSrc = InputVector.getNode()->getOperand(0);
20658     if (MMXSrc.getValueType() == MVT::x86mmx)
20659       return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
20660                          N->getValueType(0),
20661                          InputVector.getNode()->getOperand(0));
20662
20663     // The mmx is indirect: (i64 extract_elt (v1i64 bitcast (x86mmx ...))).
20664     SDValue MMXSrcOp = MMXSrc.getOperand(0);
20665     if (MMXSrc.getOpcode() == ISD::EXTRACT_VECTOR_ELT && MMXSrc.hasOneUse() &&
20666         MMXSrc.getValueType() == MVT::i64 && MMXSrcOp.hasOneUse() &&
20667         MMXSrcOp.getOpcode() == ISD::BITCAST &&
20668         MMXSrcOp.getValueType() == MVT::v1i64 &&
20669         MMXSrcOp.getOperand(0).getValueType() == MVT::x86mmx)
20670       return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
20671                          N->getValueType(0),
20672                          MMXSrcOp.getOperand(0));
20673   }
20674
20675   // Only operate on vectors of 4 elements, where the alternative shuffling
20676   // gets to be more expensive.
20677   if (InputVector.getValueType() != MVT::v4i32)
20678     return SDValue();
20679
20680   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
20681   // single use which is a sign-extend or zero-extend, and all elements are
20682   // used.
20683   SmallVector<SDNode *, 4> Uses;
20684   unsigned ExtractedElements = 0;
20685   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
20686        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
20687     if (UI.getUse().getResNo() != InputVector.getResNo())
20688       return SDValue();
20689
20690     SDNode *Extract = *UI;
20691     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
20692       return SDValue();
20693
20694     if (Extract->getValueType(0) != MVT::i32)
20695       return SDValue();
20696     if (!Extract->hasOneUse())
20697       return SDValue();
20698     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
20699         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
20700       return SDValue();
20701     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
20702       return SDValue();
20703
20704     // Record which element was extracted.
20705     ExtractedElements |=
20706       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
20707
20708     Uses.push_back(Extract);
20709   }
20710
20711   // If not all the elements were used, this may not be worthwhile.
20712   if (ExtractedElements != 15)
20713     return SDValue();
20714
20715   // Ok, we've now decided to do the transformation.
20716   // If 64-bit shifts are legal, use the extract-shift sequence,
20717   // otherwise bounce the vector off the cache.
20718   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20719   SDValue Vals[4];
20720   SDLoc dl(InputVector);
20721
20722   if (TLI.isOperationLegal(ISD::SRA, MVT::i64)) {
20723     SDValue Cst = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, InputVector);
20724     EVT VecIdxTy = DAG.getTargetLoweringInfo().getVectorIdxTy();
20725     SDValue BottomHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
20726       DAG.getConstant(0, VecIdxTy));
20727     SDValue TopHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
20728       DAG.getConstant(1, VecIdxTy));
20729
20730     SDValue ShAmt = DAG.getConstant(32,
20731       DAG.getTargetLoweringInfo().getShiftAmountTy(MVT::i64));
20732     Vals[0] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BottomHalf);
20733     Vals[1] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
20734       DAG.getNode(ISD::SRA, dl, MVT::i64, BottomHalf, ShAmt));
20735     Vals[2] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, TopHalf);
20736     Vals[3] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
20737       DAG.getNode(ISD::SRA, dl, MVT::i64, TopHalf, ShAmt));
20738   } else {
20739     // Store the value to a temporary stack slot.
20740     SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
20741     SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
20742       MachinePointerInfo(), false, false, 0);
20743
20744     EVT ElementType = InputVector.getValueType().getVectorElementType();
20745     unsigned EltSize = ElementType.getSizeInBits() / 8;
20746
20747     // Replace each use (extract) with a load of the appropriate element.
20748     for (unsigned i = 0; i < 4; ++i) {
20749       uint64_t Offset = EltSize * i;
20750       SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
20751
20752       SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
20753                                        StackPtr, OffsetVal);
20754
20755       // Load the scalar.
20756       Vals[i] = DAG.getLoad(ElementType, dl, Ch,
20757                             ScalarAddr, MachinePointerInfo(),
20758                             false, false, false, 0);
20759
20760     }
20761   }
20762
20763   // Replace the extracts
20764   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
20765     UE = Uses.end(); UI != UE; ++UI) {
20766     SDNode *Extract = *UI;
20767
20768     SDValue Idx = Extract->getOperand(1);
20769     uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
20770     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), Vals[IdxVal]);
20771   }
20772
20773   // The replacement was made in place; don't return anything.
20774   return SDValue();
20775 }
20776
20777 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
20778 static std::pair<unsigned, bool>
20779 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
20780                    SelectionDAG &DAG, const X86Subtarget *Subtarget) {
20781   if (!VT.isVector())
20782     return std::make_pair(0, false);
20783
20784   bool NeedSplit = false;
20785   switch (VT.getSimpleVT().SimpleTy) {
20786   default: return std::make_pair(0, false);
20787   case MVT::v4i64:
20788   case MVT::v2i64:
20789     if (!Subtarget->hasVLX())
20790       return std::make_pair(0, false);
20791     break;
20792   case MVT::v64i8:
20793   case MVT::v32i16:
20794     if (!Subtarget->hasBWI())
20795       return std::make_pair(0, false);
20796     break;
20797   case MVT::v16i32:
20798   case MVT::v8i64:
20799     if (!Subtarget->hasAVX512())
20800       return std::make_pair(0, false);
20801     break;
20802   case MVT::v32i8:
20803   case MVT::v16i16:
20804   case MVT::v8i32:
20805     if (!Subtarget->hasAVX2())
20806       NeedSplit = true;
20807     if (!Subtarget->hasAVX())
20808       return std::make_pair(0, false);
20809     break;
20810   case MVT::v16i8:
20811   case MVT::v8i16:
20812   case MVT::v4i32:
20813     if (!Subtarget->hasSSE2())
20814       return std::make_pair(0, false);
20815   }
20816
20817   // SSE2 has only a small subset of the operations.
20818   bool hasUnsigned = Subtarget->hasSSE41() ||
20819                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
20820   bool hasSigned = Subtarget->hasSSE41() ||
20821                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
20822
20823   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20824
20825   unsigned Opc = 0;
20826   // Check for x CC y ? x : y.
20827   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
20828       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
20829     switch (CC) {
20830     default: break;
20831     case ISD::SETULT:
20832     case ISD::SETULE:
20833       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
20834     case ISD::SETUGT:
20835     case ISD::SETUGE:
20836       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
20837     case ISD::SETLT:
20838     case ISD::SETLE:
20839       Opc = hasSigned ? X86ISD::SMIN : 0; break;
20840     case ISD::SETGT:
20841     case ISD::SETGE:
20842       Opc = hasSigned ? X86ISD::SMAX : 0; break;
20843     }
20844   // Check for x CC y ? y : x -- a min/max with reversed arms.
20845   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
20846              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
20847     switch (CC) {
20848     default: break;
20849     case ISD::SETULT:
20850     case ISD::SETULE:
20851       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
20852     case ISD::SETUGT:
20853     case ISD::SETUGE:
20854       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
20855     case ISD::SETLT:
20856     case ISD::SETLE:
20857       Opc = hasSigned ? X86ISD::SMAX : 0; break;
20858     case ISD::SETGT:
20859     case ISD::SETGE:
20860       Opc = hasSigned ? X86ISD::SMIN : 0; break;
20861     }
20862   }
20863
20864   return std::make_pair(Opc, NeedSplit);
20865 }
20866
20867 static SDValue
20868 transformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
20869                                       const X86Subtarget *Subtarget) {
20870   SDLoc dl(N);
20871   SDValue Cond = N->getOperand(0);
20872   SDValue LHS = N->getOperand(1);
20873   SDValue RHS = N->getOperand(2);
20874
20875   if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
20876     SDValue CondSrc = Cond->getOperand(0);
20877     if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
20878       Cond = CondSrc->getOperand(0);
20879   }
20880
20881   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
20882     return SDValue();
20883
20884   // A vselect where all conditions and data are constants can be optimized into
20885   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
20886   if (ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
20887       ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
20888     return SDValue();
20889
20890   unsigned MaskValue = 0;
20891   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
20892     return SDValue();
20893
20894   MVT VT = N->getSimpleValueType(0);
20895   unsigned NumElems = VT.getVectorNumElements();
20896   SmallVector<int, 8> ShuffleMask(NumElems, -1);
20897   for (unsigned i = 0; i < NumElems; ++i) {
20898     // Be sure we emit undef where we can.
20899     if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
20900       ShuffleMask[i] = -1;
20901     else
20902       ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
20903   }
20904
20905   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20906   if (!TLI.isShuffleMaskLegal(ShuffleMask, VT))
20907     return SDValue();
20908   return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
20909 }
20910
20911 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
20912 /// nodes.
20913 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
20914                                     TargetLowering::DAGCombinerInfo &DCI,
20915                                     const X86Subtarget *Subtarget) {
20916   SDLoc DL(N);
20917   SDValue Cond = N->getOperand(0);
20918   // Get the LHS/RHS of the select.
20919   SDValue LHS = N->getOperand(1);
20920   SDValue RHS = N->getOperand(2);
20921   EVT VT = LHS.getValueType();
20922   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20923
20924   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
20925   // instructions match the semantics of the common C idiom x<y?x:y but not
20926   // x<=y?x:y, because of how they handle negative zero (which can be
20927   // ignored in unsafe-math mode).
20928   // We also try to create v2f32 min/max nodes, which we later widen to v4f32.
20929   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
20930       VT != MVT::f80 && (TLI.isTypeLegal(VT) || VT == MVT::v2f32) &&
20931       (Subtarget->hasSSE2() ||
20932        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
20933     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20934
20935     unsigned Opcode = 0;
20936     // Check for x CC y ? x : y.
20937     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
20938         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
20939       switch (CC) {
20940       default: break;
20941       case ISD::SETULT:
20942         // Converting this to a min would handle NaNs incorrectly, and swapping
20943         // the operands would cause it to handle comparisons between positive
20944         // and negative zero incorrectly.
20945         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
20946           if (!DAG.getTarget().Options.UnsafeFPMath &&
20947               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
20948             break;
20949           std::swap(LHS, RHS);
20950         }
20951         Opcode = X86ISD::FMIN;
20952         break;
20953       case ISD::SETOLE:
20954         // Converting this to a min would handle comparisons between positive
20955         // and negative zero incorrectly.
20956         if (!DAG.getTarget().Options.UnsafeFPMath &&
20957             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
20958           break;
20959         Opcode = X86ISD::FMIN;
20960         break;
20961       case ISD::SETULE:
20962         // Converting this to a min would handle both negative zeros and NaNs
20963         // incorrectly, but we can swap the operands to fix both.
20964         std::swap(LHS, RHS);
20965       case ISD::SETOLT:
20966       case ISD::SETLT:
20967       case ISD::SETLE:
20968         Opcode = X86ISD::FMIN;
20969         break;
20970
20971       case ISD::SETOGE:
20972         // Converting this to a max would handle comparisons between positive
20973         // and negative zero incorrectly.
20974         if (!DAG.getTarget().Options.UnsafeFPMath &&
20975             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
20976           break;
20977         Opcode = X86ISD::FMAX;
20978         break;
20979       case ISD::SETUGT:
20980         // Converting this to a max would handle NaNs incorrectly, and swapping
20981         // the operands would cause it to handle comparisons between positive
20982         // and negative zero incorrectly.
20983         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
20984           if (!DAG.getTarget().Options.UnsafeFPMath &&
20985               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
20986             break;
20987           std::swap(LHS, RHS);
20988         }
20989         Opcode = X86ISD::FMAX;
20990         break;
20991       case ISD::SETUGE:
20992         // Converting this to a max would handle both negative zeros and NaNs
20993         // incorrectly, but we can swap the operands to fix both.
20994         std::swap(LHS, RHS);
20995       case ISD::SETOGT:
20996       case ISD::SETGT:
20997       case ISD::SETGE:
20998         Opcode = X86ISD::FMAX;
20999         break;
21000       }
21001     // Check for x CC y ? y : x -- a min/max with reversed arms.
21002     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
21003                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
21004       switch (CC) {
21005       default: break;
21006       case ISD::SETOGE:
21007         // Converting this to a min would handle comparisons between positive
21008         // and negative zero incorrectly, and swapping the operands would
21009         // cause it to handle NaNs incorrectly.
21010         if (!DAG.getTarget().Options.UnsafeFPMath &&
21011             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
21012           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
21013             break;
21014           std::swap(LHS, RHS);
21015         }
21016         Opcode = X86ISD::FMIN;
21017         break;
21018       case ISD::SETUGT:
21019         // Converting this to a min would handle NaNs incorrectly.
21020         if (!DAG.getTarget().Options.UnsafeFPMath &&
21021             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
21022           break;
21023         Opcode = X86ISD::FMIN;
21024         break;
21025       case ISD::SETUGE:
21026         // Converting this to a min would handle both negative zeros and NaNs
21027         // incorrectly, but we can swap the operands to fix both.
21028         std::swap(LHS, RHS);
21029       case ISD::SETOGT:
21030       case ISD::SETGT:
21031       case ISD::SETGE:
21032         Opcode = X86ISD::FMIN;
21033         break;
21034
21035       case ISD::SETULT:
21036         // Converting this to a max would handle NaNs incorrectly.
21037         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
21038           break;
21039         Opcode = X86ISD::FMAX;
21040         break;
21041       case ISD::SETOLE:
21042         // Converting this to a max would handle comparisons between positive
21043         // and negative zero incorrectly, and swapping the operands would
21044         // cause it to handle NaNs incorrectly.
21045         if (!DAG.getTarget().Options.UnsafeFPMath &&
21046             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
21047           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
21048             break;
21049           std::swap(LHS, RHS);
21050         }
21051         Opcode = X86ISD::FMAX;
21052         break;
21053       case ISD::SETULE:
21054         // Converting this to a max would handle both negative zeros and NaNs
21055         // incorrectly, but we can swap the operands to fix both.
21056         std::swap(LHS, RHS);
21057       case ISD::SETOLT:
21058       case ISD::SETLT:
21059       case ISD::SETLE:
21060         Opcode = X86ISD::FMAX;
21061         break;
21062       }
21063     }
21064
21065     if (Opcode)
21066       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
21067   }
21068
21069   EVT CondVT = Cond.getValueType();
21070   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
21071       CondVT.getVectorElementType() == MVT::i1) {
21072     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
21073     // lowering on KNL. In this case we convert it to
21074     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
21075     // The same situation for all 128 and 256-bit vectors of i8 and i16.
21076     // Since SKX these selects have a proper lowering.
21077     EVT OpVT = LHS.getValueType();
21078     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
21079         (OpVT.getVectorElementType() == MVT::i8 ||
21080          OpVT.getVectorElementType() == MVT::i16) &&
21081         !(Subtarget->hasBWI() && Subtarget->hasVLX())) {
21082       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
21083       DCI.AddToWorklist(Cond.getNode());
21084       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
21085     }
21086   }
21087   // If this is a select between two integer constants, try to do some
21088   // optimizations.
21089   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
21090     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
21091       // Don't do this for crazy integer types.
21092       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
21093         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
21094         // so that TrueC (the true value) is larger than FalseC.
21095         bool NeedsCondInvert = false;
21096
21097         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
21098             // Efficiently invertible.
21099             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
21100              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
21101               isa<ConstantSDNode>(Cond.getOperand(1))))) {
21102           NeedsCondInvert = true;
21103           std::swap(TrueC, FalseC);
21104         }
21105
21106         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
21107         if (FalseC->getAPIntValue() == 0 &&
21108             TrueC->getAPIntValue().isPowerOf2()) {
21109           if (NeedsCondInvert) // Invert the condition if needed.
21110             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
21111                                DAG.getConstant(1, Cond.getValueType()));
21112
21113           // Zero extend the condition if needed.
21114           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
21115
21116           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
21117           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
21118                              DAG.getConstant(ShAmt, MVT::i8));
21119         }
21120
21121         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
21122         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
21123           if (NeedsCondInvert) // Invert the condition if needed.
21124             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
21125                                DAG.getConstant(1, Cond.getValueType()));
21126
21127           // Zero extend the condition if needed.
21128           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
21129                              FalseC->getValueType(0), Cond);
21130           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
21131                              SDValue(FalseC, 0));
21132         }
21133
21134         // Optimize cases that will turn into an LEA instruction.  This requires
21135         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
21136         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
21137           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
21138           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
21139
21140           bool isFastMultiplier = false;
21141           if (Diff < 10) {
21142             switch ((unsigned char)Diff) {
21143               default: break;
21144               case 1:  // result = add base, cond
21145               case 2:  // result = lea base(    , cond*2)
21146               case 3:  // result = lea base(cond, cond*2)
21147               case 4:  // result = lea base(    , cond*4)
21148               case 5:  // result = lea base(cond, cond*4)
21149               case 8:  // result = lea base(    , cond*8)
21150               case 9:  // result = lea base(cond, cond*8)
21151                 isFastMultiplier = true;
21152                 break;
21153             }
21154           }
21155
21156           if (isFastMultiplier) {
21157             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
21158             if (NeedsCondInvert) // Invert the condition if needed.
21159               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
21160                                  DAG.getConstant(1, Cond.getValueType()));
21161
21162             // Zero extend the condition if needed.
21163             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
21164                                Cond);
21165             // Scale the condition by the difference.
21166             if (Diff != 1)
21167               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
21168                                  DAG.getConstant(Diff, Cond.getValueType()));
21169
21170             // Add the base if non-zero.
21171             if (FalseC->getAPIntValue() != 0)
21172               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
21173                                  SDValue(FalseC, 0));
21174             return Cond;
21175           }
21176         }
21177       }
21178   }
21179
21180   // Canonicalize max and min:
21181   // (x > y) ? x : y -> (x >= y) ? x : y
21182   // (x < y) ? x : y -> (x <= y) ? x : y
21183   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
21184   // the need for an extra compare
21185   // against zero. e.g.
21186   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
21187   // subl   %esi, %edi
21188   // testl  %edi, %edi
21189   // movl   $0, %eax
21190   // cmovgl %edi, %eax
21191   // =>
21192   // xorl   %eax, %eax
21193   // subl   %esi, $edi
21194   // cmovsl %eax, %edi
21195   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
21196       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
21197       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
21198     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
21199     switch (CC) {
21200     default: break;
21201     case ISD::SETLT:
21202     case ISD::SETGT: {
21203       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
21204       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
21205                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
21206       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
21207     }
21208     }
21209   }
21210
21211   // Early exit check
21212   if (!TLI.isTypeLegal(VT))
21213     return SDValue();
21214
21215   // Match VSELECTs into subs with unsigned saturation.
21216   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
21217       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
21218       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
21219        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
21220     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
21221
21222     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
21223     // left side invert the predicate to simplify logic below.
21224     SDValue Other;
21225     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
21226       Other = RHS;
21227       CC = ISD::getSetCCInverse(CC, true);
21228     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
21229       Other = LHS;
21230     }
21231
21232     if (Other.getNode() && Other->getNumOperands() == 2 &&
21233         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
21234       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
21235       SDValue CondRHS = Cond->getOperand(1);
21236
21237       // Look for a general sub with unsigned saturation first.
21238       // x >= y ? x-y : 0 --> subus x, y
21239       // x >  y ? x-y : 0 --> subus x, y
21240       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
21241           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
21242         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
21243
21244       if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
21245         if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
21246           if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
21247             if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
21248               // If the RHS is a constant we have to reverse the const
21249               // canonicalization.
21250               // x > C-1 ? x+-C : 0 --> subus x, C
21251               if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
21252                   CondRHSConst->getAPIntValue() ==
21253                       (-OpRHSConst->getAPIntValue() - 1))
21254                 return DAG.getNode(
21255                     X86ISD::SUBUS, DL, VT, OpLHS,
21256                     DAG.getConstant(-OpRHSConst->getAPIntValue(), VT));
21257
21258           // Another special case: If C was a sign bit, the sub has been
21259           // canonicalized into a xor.
21260           // FIXME: Would it be better to use computeKnownBits to determine
21261           //        whether it's safe to decanonicalize the xor?
21262           // x s< 0 ? x^C : 0 --> subus x, C
21263           if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
21264               ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
21265               OpRHSConst->getAPIntValue().isSignBit())
21266             // Note that we have to rebuild the RHS constant here to ensure we
21267             // don't rely on particular values of undef lanes.
21268             return DAG.getNode(
21269                 X86ISD::SUBUS, DL, VT, OpLHS,
21270                 DAG.getConstant(OpRHSConst->getAPIntValue(), VT));
21271         }
21272     }
21273   }
21274
21275   // Try to match a min/max vector operation.
21276   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
21277     std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
21278     unsigned Opc = ret.first;
21279     bool NeedSplit = ret.second;
21280
21281     if (Opc && NeedSplit) {
21282       unsigned NumElems = VT.getVectorNumElements();
21283       // Extract the LHS vectors
21284       SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
21285       SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
21286
21287       // Extract the RHS vectors
21288       SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
21289       SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
21290
21291       // Create min/max for each subvector
21292       LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
21293       RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
21294
21295       // Merge the result
21296       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
21297     } else if (Opc)
21298       return DAG.getNode(Opc, DL, VT, LHS, RHS);
21299   }
21300
21301   // Simplify vector selection if condition value type matches vselect
21302   // operand type
21303   if (N->getOpcode() == ISD::VSELECT && CondVT == VT) {
21304     assert(Cond.getValueType().isVector() &&
21305            "vector select expects a vector selector!");
21306
21307     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
21308     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
21309
21310     // Try invert the condition if true value is not all 1s and false value
21311     // is not all 0s.
21312     if (!TValIsAllOnes && !FValIsAllZeros &&
21313         // Check if the selector will be produced by CMPP*/PCMP*
21314         Cond.getOpcode() == ISD::SETCC &&
21315         // Check if SETCC has already been promoted
21316         TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT) {
21317       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
21318       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
21319
21320       if (TValIsAllZeros || FValIsAllOnes) {
21321         SDValue CC = Cond.getOperand(2);
21322         ISD::CondCode NewCC =
21323           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
21324                                Cond.getOperand(0).getValueType().isInteger());
21325         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
21326         std::swap(LHS, RHS);
21327         TValIsAllOnes = FValIsAllOnes;
21328         FValIsAllZeros = TValIsAllZeros;
21329       }
21330     }
21331
21332     if (TValIsAllOnes || FValIsAllZeros) {
21333       SDValue Ret;
21334
21335       if (TValIsAllOnes && FValIsAllZeros)
21336         Ret = Cond;
21337       else if (TValIsAllOnes)
21338         Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
21339                           DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
21340       else if (FValIsAllZeros)
21341         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
21342                           DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
21343
21344       return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
21345     }
21346   }
21347
21348   // We should generate an X86ISD::BLENDI from a vselect if its argument
21349   // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
21350   // constants. This specific pattern gets generated when we split a
21351   // selector for a 512 bit vector in a machine without AVX512 (but with
21352   // 256-bit vectors), during legalization:
21353   //
21354   // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
21355   //
21356   // Iff we find this pattern and the build_vectors are built from
21357   // constants, we translate the vselect into a shuffle_vector that we
21358   // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
21359   if ((N->getOpcode() == ISD::VSELECT ||
21360        N->getOpcode() == X86ISD::SHRUNKBLEND) &&
21361       !DCI.isBeforeLegalize()) {
21362     SDValue Shuffle = transformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
21363     if (Shuffle.getNode())
21364       return Shuffle;
21365   }
21366
21367   // If this is a *dynamic* select (non-constant condition) and we can match
21368   // this node with one of the variable blend instructions, restructure the
21369   // condition so that the blends can use the high bit of each element and use
21370   // SimplifyDemandedBits to simplify the condition operand.
21371   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
21372       !DCI.isBeforeLegalize() &&
21373       !ISD::isBuildVectorOfConstantSDNodes(Cond.getNode())) {
21374     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
21375
21376     // Don't optimize vector selects that map to mask-registers.
21377     if (BitWidth == 1)
21378       return SDValue();
21379
21380     // We can only handle the cases where VSELECT is directly legal on the
21381     // subtarget. We custom lower VSELECT nodes with constant conditions and
21382     // this makes it hard to see whether a dynamic VSELECT will correctly
21383     // lower, so we both check the operation's status and explicitly handle the
21384     // cases where a *dynamic* blend will fail even though a constant-condition
21385     // blend could be custom lowered.
21386     // FIXME: We should find a better way to handle this class of problems.
21387     // Potentially, we should combine constant-condition vselect nodes
21388     // pre-legalization into shuffles and not mark as many types as custom
21389     // lowered.
21390     if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
21391       return SDValue();
21392     // FIXME: We don't support i16-element blends currently. We could and
21393     // should support them by making *all* the bits in the condition be set
21394     // rather than just the high bit and using an i8-element blend.
21395     if (VT.getScalarType() == MVT::i16)
21396       return SDValue();
21397     // Dynamic blending was only available from SSE4.1 onward.
21398     if (VT.getSizeInBits() == 128 && !Subtarget->hasSSE41())
21399       return SDValue();
21400     // Byte blends are only available in AVX2
21401     if (VT.getSizeInBits() == 256 && VT.getScalarType() == MVT::i8 &&
21402         !Subtarget->hasAVX2())
21403       return SDValue();
21404
21405     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
21406     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
21407
21408     APInt KnownZero, KnownOne;
21409     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
21410                                           DCI.isBeforeLegalizeOps());
21411     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
21412         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne,
21413                                  TLO)) {
21414       // If we changed the computation somewhere in the DAG, this change
21415       // will affect all users of Cond.
21416       // Make sure it is fine and update all the nodes so that we do not
21417       // use the generic VSELECT anymore. Otherwise, we may perform
21418       // wrong optimizations as we messed up with the actual expectation
21419       // for the vector boolean values.
21420       if (Cond != TLO.Old) {
21421         // Check all uses of that condition operand to check whether it will be
21422         // consumed by non-BLEND instructions, which may depend on all bits are
21423         // set properly.
21424         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
21425              I != E; ++I)
21426           if (I->getOpcode() != ISD::VSELECT)
21427             // TODO: Add other opcodes eventually lowered into BLEND.
21428             return SDValue();
21429
21430         // Update all the users of the condition, before committing the change,
21431         // so that the VSELECT optimizations that expect the correct vector
21432         // boolean value will not be triggered.
21433         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
21434              I != E; ++I)
21435           DAG.ReplaceAllUsesOfValueWith(
21436               SDValue(*I, 0),
21437               DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(*I), I->getValueType(0),
21438                           Cond, I->getOperand(1), I->getOperand(2)));
21439         DCI.CommitTargetLoweringOpt(TLO);
21440         return SDValue();
21441       }
21442       // At this point, only Cond is changed. Change the condition
21443       // just for N to keep the opportunity to optimize all other
21444       // users their own way.
21445       DAG.ReplaceAllUsesOfValueWith(
21446           SDValue(N, 0),
21447           DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(N), N->getValueType(0),
21448                       TLO.New, N->getOperand(1), N->getOperand(2)));
21449       return SDValue();
21450     }
21451   }
21452
21453   return SDValue();
21454 }
21455
21456 // Check whether a boolean test is testing a boolean value generated by
21457 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
21458 // code.
21459 //
21460 // Simplify the following patterns:
21461 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
21462 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
21463 // to (Op EFLAGS Cond)
21464 //
21465 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
21466 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
21467 // to (Op EFLAGS !Cond)
21468 //
21469 // where Op could be BRCOND or CMOV.
21470 //
21471 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
21472   // Quit if not CMP and SUB with its value result used.
21473   if (Cmp.getOpcode() != X86ISD::CMP &&
21474       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
21475       return SDValue();
21476
21477   // Quit if not used as a boolean value.
21478   if (CC != X86::COND_E && CC != X86::COND_NE)
21479     return SDValue();
21480
21481   // Check CMP operands. One of them should be 0 or 1 and the other should be
21482   // an SetCC or extended from it.
21483   SDValue Op1 = Cmp.getOperand(0);
21484   SDValue Op2 = Cmp.getOperand(1);
21485
21486   SDValue SetCC;
21487   const ConstantSDNode* C = nullptr;
21488   bool needOppositeCond = (CC == X86::COND_E);
21489   bool checkAgainstTrue = false; // Is it a comparison against 1?
21490
21491   if ((C = dyn_cast<ConstantSDNode>(Op1)))
21492     SetCC = Op2;
21493   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
21494     SetCC = Op1;
21495   else // Quit if all operands are not constants.
21496     return SDValue();
21497
21498   if (C->getZExtValue() == 1) {
21499     needOppositeCond = !needOppositeCond;
21500     checkAgainstTrue = true;
21501   } else if (C->getZExtValue() != 0)
21502     // Quit if the constant is neither 0 or 1.
21503     return SDValue();
21504
21505   bool truncatedToBoolWithAnd = false;
21506   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
21507   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
21508          SetCC.getOpcode() == ISD::TRUNCATE ||
21509          SetCC.getOpcode() == ISD::AND) {
21510     if (SetCC.getOpcode() == ISD::AND) {
21511       int OpIdx = -1;
21512       ConstantSDNode *CS;
21513       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
21514           CS->getZExtValue() == 1)
21515         OpIdx = 1;
21516       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
21517           CS->getZExtValue() == 1)
21518         OpIdx = 0;
21519       if (OpIdx == -1)
21520         break;
21521       SetCC = SetCC.getOperand(OpIdx);
21522       truncatedToBoolWithAnd = true;
21523     } else
21524       SetCC = SetCC.getOperand(0);
21525   }
21526
21527   switch (SetCC.getOpcode()) {
21528   case X86ISD::SETCC_CARRY:
21529     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
21530     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
21531     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
21532     // truncated to i1 using 'and'.
21533     if (checkAgainstTrue && !truncatedToBoolWithAnd)
21534       break;
21535     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
21536            "Invalid use of SETCC_CARRY!");
21537     // FALL THROUGH
21538   case X86ISD::SETCC:
21539     // Set the condition code or opposite one if necessary.
21540     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
21541     if (needOppositeCond)
21542       CC = X86::GetOppositeBranchCondition(CC);
21543     return SetCC.getOperand(1);
21544   case X86ISD::CMOV: {
21545     // Check whether false/true value has canonical one, i.e. 0 or 1.
21546     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
21547     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
21548     // Quit if true value is not a constant.
21549     if (!TVal)
21550       return SDValue();
21551     // Quit if false value is not a constant.
21552     if (!FVal) {
21553       SDValue Op = SetCC.getOperand(0);
21554       // Skip 'zext' or 'trunc' node.
21555       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
21556           Op.getOpcode() == ISD::TRUNCATE)
21557         Op = Op.getOperand(0);
21558       // A special case for rdrand/rdseed, where 0 is set if false cond is
21559       // found.
21560       if ((Op.getOpcode() != X86ISD::RDRAND &&
21561            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
21562         return SDValue();
21563     }
21564     // Quit if false value is not the constant 0 or 1.
21565     bool FValIsFalse = true;
21566     if (FVal && FVal->getZExtValue() != 0) {
21567       if (FVal->getZExtValue() != 1)
21568         return SDValue();
21569       // If FVal is 1, opposite cond is needed.
21570       needOppositeCond = !needOppositeCond;
21571       FValIsFalse = false;
21572     }
21573     // Quit if TVal is not the constant opposite of FVal.
21574     if (FValIsFalse && TVal->getZExtValue() != 1)
21575       return SDValue();
21576     if (!FValIsFalse && TVal->getZExtValue() != 0)
21577       return SDValue();
21578     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
21579     if (needOppositeCond)
21580       CC = X86::GetOppositeBranchCondition(CC);
21581     return SetCC.getOperand(3);
21582   }
21583   }
21584
21585   return SDValue();
21586 }
21587
21588 /// Check whether Cond is an AND/OR of SETCCs off of the same EFLAGS.
21589 /// Match:
21590 ///   (X86or (X86setcc) (X86setcc))
21591 ///   (X86cmp (and (X86setcc) (X86setcc)), 0)
21592 static bool checkBoolTestAndOrSetCCCombine(SDValue Cond, X86::CondCode &CC0,
21593                                            X86::CondCode &CC1, SDValue &Flags,
21594                                            bool &isAnd) {
21595   if (Cond->getOpcode() == X86ISD::CMP) {
21596     ConstantSDNode *CondOp1C = dyn_cast<ConstantSDNode>(Cond->getOperand(1));
21597     if (!CondOp1C || !CondOp1C->isNullValue())
21598       return false;
21599
21600     Cond = Cond->getOperand(0);
21601   }
21602
21603   isAnd = false;
21604
21605   SDValue SetCC0, SetCC1;
21606   switch (Cond->getOpcode()) {
21607   default: return false;
21608   case ISD::AND:
21609   case X86ISD::AND:
21610     isAnd = true;
21611     // fallthru
21612   case ISD::OR:
21613   case X86ISD::OR:
21614     SetCC0 = Cond->getOperand(0);
21615     SetCC1 = Cond->getOperand(1);
21616     break;
21617   };
21618
21619   // Make sure we have SETCC nodes, using the same flags value.
21620   if (SetCC0.getOpcode() != X86ISD::SETCC ||
21621       SetCC1.getOpcode() != X86ISD::SETCC ||
21622       SetCC0->getOperand(1) != SetCC1->getOperand(1))
21623     return false;
21624
21625   CC0 = (X86::CondCode)SetCC0->getConstantOperandVal(0);
21626   CC1 = (X86::CondCode)SetCC1->getConstantOperandVal(0);
21627   Flags = SetCC0->getOperand(1);
21628   return true;
21629 }
21630
21631 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
21632 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
21633                                   TargetLowering::DAGCombinerInfo &DCI,
21634                                   const X86Subtarget *Subtarget) {
21635   SDLoc DL(N);
21636
21637   // If the flag operand isn't dead, don't touch this CMOV.
21638   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
21639     return SDValue();
21640
21641   SDValue FalseOp = N->getOperand(0);
21642   SDValue TrueOp = N->getOperand(1);
21643   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
21644   SDValue Cond = N->getOperand(3);
21645
21646   if (CC == X86::COND_E || CC == X86::COND_NE) {
21647     switch (Cond.getOpcode()) {
21648     default: break;
21649     case X86ISD::BSR:
21650     case X86ISD::BSF:
21651       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
21652       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
21653         return (CC == X86::COND_E) ? FalseOp : TrueOp;
21654     }
21655   }
21656
21657   SDValue Flags;
21658
21659   Flags = checkBoolTestSetCCCombine(Cond, CC);
21660   if (Flags.getNode() &&
21661       // Extra check as FCMOV only supports a subset of X86 cond.
21662       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
21663     SDValue Ops[] = { FalseOp, TrueOp,
21664                       DAG.getConstant(CC, MVT::i8), Flags };
21665     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
21666   }
21667
21668   // If this is a select between two integer constants, try to do some
21669   // optimizations.  Note that the operands are ordered the opposite of SELECT
21670   // operands.
21671   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
21672     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
21673       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
21674       // larger than FalseC (the false value).
21675       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
21676         CC = X86::GetOppositeBranchCondition(CC);
21677         std::swap(TrueC, FalseC);
21678         std::swap(TrueOp, FalseOp);
21679       }
21680
21681       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
21682       // This is efficient for any integer data type (including i8/i16) and
21683       // shift amount.
21684       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
21685         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
21686                            DAG.getConstant(CC, MVT::i8), Cond);
21687
21688         // Zero extend the condition if needed.
21689         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
21690
21691         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
21692         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
21693                            DAG.getConstant(ShAmt, MVT::i8));
21694         if (N->getNumValues() == 2)  // Dead flag value?
21695           return DCI.CombineTo(N, Cond, SDValue());
21696         return Cond;
21697       }
21698
21699       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
21700       // for any integer data type, including i8/i16.
21701       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
21702         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
21703                            DAG.getConstant(CC, MVT::i8), Cond);
21704
21705         // Zero extend the condition if needed.
21706         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
21707                            FalseC->getValueType(0), Cond);
21708         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
21709                            SDValue(FalseC, 0));
21710
21711         if (N->getNumValues() == 2)  // Dead flag value?
21712           return DCI.CombineTo(N, Cond, SDValue());
21713         return Cond;
21714       }
21715
21716       // Optimize cases that will turn into an LEA instruction.  This requires
21717       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
21718       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
21719         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
21720         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
21721
21722         bool isFastMultiplier = false;
21723         if (Diff < 10) {
21724           switch ((unsigned char)Diff) {
21725           default: break;
21726           case 1:  // result = add base, cond
21727           case 2:  // result = lea base(    , cond*2)
21728           case 3:  // result = lea base(cond, cond*2)
21729           case 4:  // result = lea base(    , cond*4)
21730           case 5:  // result = lea base(cond, cond*4)
21731           case 8:  // result = lea base(    , cond*8)
21732           case 9:  // result = lea base(cond, cond*8)
21733             isFastMultiplier = true;
21734             break;
21735           }
21736         }
21737
21738         if (isFastMultiplier) {
21739           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
21740           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
21741                              DAG.getConstant(CC, MVT::i8), Cond);
21742           // Zero extend the condition if needed.
21743           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
21744                              Cond);
21745           // Scale the condition by the difference.
21746           if (Diff != 1)
21747             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
21748                                DAG.getConstant(Diff, Cond.getValueType()));
21749
21750           // Add the base if non-zero.
21751           if (FalseC->getAPIntValue() != 0)
21752             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
21753                                SDValue(FalseC, 0));
21754           if (N->getNumValues() == 2)  // Dead flag value?
21755             return DCI.CombineTo(N, Cond, SDValue());
21756           return Cond;
21757         }
21758       }
21759     }
21760   }
21761
21762   // Handle these cases:
21763   //   (select (x != c), e, c) -> select (x != c), e, x),
21764   //   (select (x == c), c, e) -> select (x == c), x, e)
21765   // where the c is an integer constant, and the "select" is the combination
21766   // of CMOV and CMP.
21767   //
21768   // The rationale for this change is that the conditional-move from a constant
21769   // needs two instructions, however, conditional-move from a register needs
21770   // only one instruction.
21771   //
21772   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
21773   //  some instruction-combining opportunities. This opt needs to be
21774   //  postponed as late as possible.
21775   //
21776   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
21777     // the DCI.xxxx conditions are provided to postpone the optimization as
21778     // late as possible.
21779
21780     ConstantSDNode *CmpAgainst = nullptr;
21781     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
21782         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
21783         !isa<ConstantSDNode>(Cond.getOperand(0))) {
21784
21785       if (CC == X86::COND_NE &&
21786           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
21787         CC = X86::GetOppositeBranchCondition(CC);
21788         std::swap(TrueOp, FalseOp);
21789       }
21790
21791       if (CC == X86::COND_E &&
21792           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
21793         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
21794                           DAG.getConstant(CC, MVT::i8), Cond };
21795         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
21796       }
21797     }
21798   }
21799
21800   // Fold and/or of setcc's to double CMOV:
21801   //   (CMOV F, T, ((cc1 | cc2) != 0)) -> (CMOV (CMOV F, T, cc1), T, cc2)
21802   //   (CMOV F, T, ((cc1 & cc2) != 0)) -> (CMOV (CMOV T, F, !cc1), F, !cc2)
21803   //
21804   // This combine lets us generate:
21805   //   cmovcc1 (jcc1 if we don't have CMOV)
21806   //   cmovcc2 (same)
21807   // instead of:
21808   //   setcc1
21809   //   setcc2
21810   //   and/or
21811   //   cmovne (jne if we don't have CMOV)
21812   // When we can't use the CMOV instruction, it might increase branch
21813   // mispredicts.
21814   // When we can use CMOV, or when there is no mispredict, this improves
21815   // throughput and reduces register pressure.
21816   //
21817   if (CC == X86::COND_NE) {
21818     SDValue Flags;
21819     X86::CondCode CC0, CC1;
21820     bool isAndSetCC;
21821     if (checkBoolTestAndOrSetCCCombine(Cond, CC0, CC1, Flags, isAndSetCC)) {
21822       if (isAndSetCC) {
21823         std::swap(FalseOp, TrueOp);
21824         CC0 = X86::GetOppositeBranchCondition(CC0);
21825         CC1 = X86::GetOppositeBranchCondition(CC1);
21826       }
21827
21828       SDValue LOps[] = {FalseOp, TrueOp, DAG.getConstant(CC0, MVT::i8),
21829         Flags};
21830       SDValue LCMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), LOps);
21831       SDValue Ops[] = {LCMOV, TrueOp, DAG.getConstant(CC1, MVT::i8), Flags};
21832       SDValue CMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
21833       DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SDValue(CMOV.getNode(), 1));
21834       return CMOV;
21835     }
21836   }
21837
21838   return SDValue();
21839 }
21840
21841 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
21842                                                 const X86Subtarget *Subtarget) {
21843   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
21844   switch (IntNo) {
21845   default: return SDValue();
21846   // SSE/AVX/AVX2 blend intrinsics.
21847   case Intrinsic::x86_avx2_pblendvb:
21848     // Don't try to simplify this intrinsic if we don't have AVX2.
21849     if (!Subtarget->hasAVX2())
21850       return SDValue();
21851     // FALL-THROUGH
21852   case Intrinsic::x86_avx_blendv_pd_256:
21853   case Intrinsic::x86_avx_blendv_ps_256:
21854     // Don't try to simplify this intrinsic if we don't have AVX.
21855     if (!Subtarget->hasAVX())
21856       return SDValue();
21857     // FALL-THROUGH
21858   case Intrinsic::x86_sse41_blendvps:
21859   case Intrinsic::x86_sse41_blendvpd:
21860   case Intrinsic::x86_sse41_pblendvb: {
21861     SDValue Op0 = N->getOperand(1);
21862     SDValue Op1 = N->getOperand(2);
21863     SDValue Mask = N->getOperand(3);
21864
21865     // Don't try to simplify this intrinsic if we don't have SSE4.1.
21866     if (!Subtarget->hasSSE41())
21867       return SDValue();
21868
21869     // fold (blend A, A, Mask) -> A
21870     if (Op0 == Op1)
21871       return Op0;
21872     // fold (blend A, B, allZeros) -> A
21873     if (ISD::isBuildVectorAllZeros(Mask.getNode()))
21874       return Op0;
21875     // fold (blend A, B, allOnes) -> B
21876     if (ISD::isBuildVectorAllOnes(Mask.getNode()))
21877       return Op1;
21878
21879     // Simplify the case where the mask is a constant i32 value.
21880     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
21881       if (C->isNullValue())
21882         return Op0;
21883       if (C->isAllOnesValue())
21884         return Op1;
21885     }
21886
21887     return SDValue();
21888   }
21889
21890   // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
21891   case Intrinsic::x86_sse2_psrai_w:
21892   case Intrinsic::x86_sse2_psrai_d:
21893   case Intrinsic::x86_avx2_psrai_w:
21894   case Intrinsic::x86_avx2_psrai_d:
21895   case Intrinsic::x86_sse2_psra_w:
21896   case Intrinsic::x86_sse2_psra_d:
21897   case Intrinsic::x86_avx2_psra_w:
21898   case Intrinsic::x86_avx2_psra_d: {
21899     SDValue Op0 = N->getOperand(1);
21900     SDValue Op1 = N->getOperand(2);
21901     EVT VT = Op0.getValueType();
21902     assert(VT.isVector() && "Expected a vector type!");
21903
21904     if (isa<BuildVectorSDNode>(Op1))
21905       Op1 = Op1.getOperand(0);
21906
21907     if (!isa<ConstantSDNode>(Op1))
21908       return SDValue();
21909
21910     EVT SVT = VT.getVectorElementType();
21911     unsigned SVTBits = SVT.getSizeInBits();
21912
21913     ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
21914     const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
21915     uint64_t ShAmt = C.getZExtValue();
21916
21917     // Don't try to convert this shift into a ISD::SRA if the shift
21918     // count is bigger than or equal to the element size.
21919     if (ShAmt >= SVTBits)
21920       return SDValue();
21921
21922     // Trivial case: if the shift count is zero, then fold this
21923     // into the first operand.
21924     if (ShAmt == 0)
21925       return Op0;
21926
21927     // Replace this packed shift intrinsic with a target independent
21928     // shift dag node.
21929     SDValue Splat = DAG.getConstant(C, VT);
21930     return DAG.getNode(ISD::SRA, SDLoc(N), VT, Op0, Splat);
21931   }
21932   }
21933 }
21934
21935 /// PerformMulCombine - Optimize a single multiply with constant into two
21936 /// in order to implement it with two cheaper instructions, e.g.
21937 /// LEA + SHL, LEA + LEA.
21938 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
21939                                  TargetLowering::DAGCombinerInfo &DCI) {
21940   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
21941     return SDValue();
21942
21943   EVT VT = N->getValueType(0);
21944   if (VT != MVT::i64 && VT != MVT::i32)
21945     return SDValue();
21946
21947   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
21948   if (!C)
21949     return SDValue();
21950   uint64_t MulAmt = C->getZExtValue();
21951   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
21952     return SDValue();
21953
21954   uint64_t MulAmt1 = 0;
21955   uint64_t MulAmt2 = 0;
21956   if ((MulAmt % 9) == 0) {
21957     MulAmt1 = 9;
21958     MulAmt2 = MulAmt / 9;
21959   } else if ((MulAmt % 5) == 0) {
21960     MulAmt1 = 5;
21961     MulAmt2 = MulAmt / 5;
21962   } else if ((MulAmt % 3) == 0) {
21963     MulAmt1 = 3;
21964     MulAmt2 = MulAmt / 3;
21965   }
21966   if (MulAmt2 &&
21967       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
21968     SDLoc DL(N);
21969
21970     if (isPowerOf2_64(MulAmt2) &&
21971         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
21972       // If second multiplifer is pow2, issue it first. We want the multiply by
21973       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
21974       // is an add.
21975       std::swap(MulAmt1, MulAmt2);
21976
21977     SDValue NewMul;
21978     if (isPowerOf2_64(MulAmt1))
21979       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
21980                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
21981     else
21982       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
21983                            DAG.getConstant(MulAmt1, VT));
21984
21985     if (isPowerOf2_64(MulAmt2))
21986       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
21987                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
21988     else
21989       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
21990                            DAG.getConstant(MulAmt2, VT));
21991
21992     // Do not add new nodes to DAG combiner worklist.
21993     DCI.CombineTo(N, NewMul, false);
21994   }
21995   return SDValue();
21996 }
21997
21998 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
21999   SDValue N0 = N->getOperand(0);
22000   SDValue N1 = N->getOperand(1);
22001   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
22002   EVT VT = N0.getValueType();
22003
22004   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
22005   // since the result of setcc_c is all zero's or all ones.
22006   if (VT.isInteger() && !VT.isVector() &&
22007       N1C && N0.getOpcode() == ISD::AND &&
22008       N0.getOperand(1).getOpcode() == ISD::Constant) {
22009     SDValue N00 = N0.getOperand(0);
22010     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
22011         ((N00.getOpcode() == ISD::ANY_EXTEND ||
22012           N00.getOpcode() == ISD::ZERO_EXTEND) &&
22013          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
22014       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
22015       APInt ShAmt = N1C->getAPIntValue();
22016       Mask = Mask.shl(ShAmt);
22017       if (Mask != 0)
22018         return DAG.getNode(ISD::AND, SDLoc(N), VT,
22019                            N00, DAG.getConstant(Mask, VT));
22020     }
22021   }
22022
22023   // Hardware support for vector shifts is sparse which makes us scalarize the
22024   // vector operations in many cases. Also, on sandybridge ADD is faster than
22025   // shl.
22026   // (shl V, 1) -> add V,V
22027   if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
22028     if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
22029       assert(N0.getValueType().isVector() && "Invalid vector shift type");
22030       // We shift all of the values by one. In many cases we do not have
22031       // hardware support for this operation. This is better expressed as an ADD
22032       // of two values.
22033       if (N1SplatC->getZExtValue() == 1)
22034         return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
22035     }
22036
22037   return SDValue();
22038 }
22039
22040 /// \brief Returns a vector of 0s if the node in input is a vector logical
22041 /// shift by a constant amount which is known to be bigger than or equal
22042 /// to the vector element size in bits.
22043 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
22044                                       const X86Subtarget *Subtarget) {
22045   EVT VT = N->getValueType(0);
22046
22047   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
22048       (!Subtarget->hasInt256() ||
22049        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
22050     return SDValue();
22051
22052   SDValue Amt = N->getOperand(1);
22053   SDLoc DL(N);
22054   if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
22055     if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
22056       APInt ShiftAmt = AmtSplat->getAPIntValue();
22057       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
22058
22059       // SSE2/AVX2 logical shifts always return a vector of 0s
22060       // if the shift amount is bigger than or equal to
22061       // the element size. The constant shift amount will be
22062       // encoded as a 8-bit immediate.
22063       if (ShiftAmt.trunc(8).uge(MaxAmount))
22064         return getZeroVector(VT, Subtarget, DAG, DL);
22065     }
22066
22067   return SDValue();
22068 }
22069
22070 /// PerformShiftCombine - Combine shifts.
22071 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
22072                                    TargetLowering::DAGCombinerInfo &DCI,
22073                                    const X86Subtarget *Subtarget) {
22074   if (N->getOpcode() == ISD::SHL) {
22075     SDValue V = PerformSHLCombine(N, DAG);
22076     if (V.getNode()) return V;
22077   }
22078
22079   if (N->getOpcode() != ISD::SRA) {
22080     // Try to fold this logical shift into a zero vector.
22081     SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
22082     if (V.getNode()) return V;
22083   }
22084
22085   return SDValue();
22086 }
22087
22088 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
22089 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
22090 // and friends.  Likewise for OR -> CMPNEQSS.
22091 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
22092                             TargetLowering::DAGCombinerInfo &DCI,
22093                             const X86Subtarget *Subtarget) {
22094   unsigned opcode;
22095
22096   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
22097   // we're requiring SSE2 for both.
22098   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
22099     SDValue N0 = N->getOperand(0);
22100     SDValue N1 = N->getOperand(1);
22101     SDValue CMP0 = N0->getOperand(1);
22102     SDValue CMP1 = N1->getOperand(1);
22103     SDLoc DL(N);
22104
22105     // The SETCCs should both refer to the same CMP.
22106     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
22107       return SDValue();
22108
22109     SDValue CMP00 = CMP0->getOperand(0);
22110     SDValue CMP01 = CMP0->getOperand(1);
22111     EVT     VT    = CMP00.getValueType();
22112
22113     if (VT == MVT::f32 || VT == MVT::f64) {
22114       bool ExpectingFlags = false;
22115       // Check for any users that want flags:
22116       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
22117            !ExpectingFlags && UI != UE; ++UI)
22118         switch (UI->getOpcode()) {
22119         default:
22120         case ISD::BR_CC:
22121         case ISD::BRCOND:
22122         case ISD::SELECT:
22123           ExpectingFlags = true;
22124           break;
22125         case ISD::CopyToReg:
22126         case ISD::SIGN_EXTEND:
22127         case ISD::ZERO_EXTEND:
22128         case ISD::ANY_EXTEND:
22129           break;
22130         }
22131
22132       if (!ExpectingFlags) {
22133         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
22134         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
22135
22136         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
22137           X86::CondCode tmp = cc0;
22138           cc0 = cc1;
22139           cc1 = tmp;
22140         }
22141
22142         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
22143             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
22144           // FIXME: need symbolic constants for these magic numbers.
22145           // See X86ATTInstPrinter.cpp:printSSECC().
22146           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
22147           if (Subtarget->hasAVX512()) {
22148             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
22149                                          CMP01, DAG.getConstant(x86cc, MVT::i8));
22150             if (N->getValueType(0) != MVT::i1)
22151               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
22152                                  FSetCC);
22153             return FSetCC;
22154           }
22155           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
22156                                               CMP00.getValueType(), CMP00, CMP01,
22157                                               DAG.getConstant(x86cc, MVT::i8));
22158
22159           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
22160           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
22161
22162           if (is64BitFP && !Subtarget->is64Bit()) {
22163             // On a 32-bit target, we cannot bitcast the 64-bit float to a
22164             // 64-bit integer, since that's not a legal type. Since
22165             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
22166             // bits, but can do this little dance to extract the lowest 32 bits
22167             // and work with those going forward.
22168             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
22169                                            OnesOrZeroesF);
22170             SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
22171                                            Vector64);
22172             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
22173                                         Vector32, DAG.getIntPtrConstant(0));
22174             IntVT = MVT::i32;
22175           }
22176
22177           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT, OnesOrZeroesF);
22178           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
22179                                       DAG.getConstant(1, IntVT));
22180           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
22181           return OneBitOfTruth;
22182         }
22183       }
22184     }
22185   }
22186   return SDValue();
22187 }
22188
22189 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
22190 /// so it can be folded inside ANDNP.
22191 static bool CanFoldXORWithAllOnes(const SDNode *N) {
22192   EVT VT = N->getValueType(0);
22193
22194   // Match direct AllOnes for 128 and 256-bit vectors
22195   if (ISD::isBuildVectorAllOnes(N))
22196     return true;
22197
22198   // Look through a bit convert.
22199   if (N->getOpcode() == ISD::BITCAST)
22200     N = N->getOperand(0).getNode();
22201
22202   // Sometimes the operand may come from a insert_subvector building a 256-bit
22203   // allones vector
22204   if (VT.is256BitVector() &&
22205       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
22206     SDValue V1 = N->getOperand(0);
22207     SDValue V2 = N->getOperand(1);
22208
22209     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
22210         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
22211         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
22212         ISD::isBuildVectorAllOnes(V2.getNode()))
22213       return true;
22214   }
22215
22216   return false;
22217 }
22218
22219 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
22220 // register. In most cases we actually compare or select YMM-sized registers
22221 // and mixing the two types creates horrible code. This method optimizes
22222 // some of the transition sequences.
22223 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
22224                                  TargetLowering::DAGCombinerInfo &DCI,
22225                                  const X86Subtarget *Subtarget) {
22226   EVT VT = N->getValueType(0);
22227   if (!VT.is256BitVector())
22228     return SDValue();
22229
22230   assert((N->getOpcode() == ISD::ANY_EXTEND ||
22231           N->getOpcode() == ISD::ZERO_EXTEND ||
22232           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
22233
22234   SDValue Narrow = N->getOperand(0);
22235   EVT NarrowVT = Narrow->getValueType(0);
22236   if (!NarrowVT.is128BitVector())
22237     return SDValue();
22238
22239   if (Narrow->getOpcode() != ISD::XOR &&
22240       Narrow->getOpcode() != ISD::AND &&
22241       Narrow->getOpcode() != ISD::OR)
22242     return SDValue();
22243
22244   SDValue N0  = Narrow->getOperand(0);
22245   SDValue N1  = Narrow->getOperand(1);
22246   SDLoc DL(Narrow);
22247
22248   // The Left side has to be a trunc.
22249   if (N0.getOpcode() != ISD::TRUNCATE)
22250     return SDValue();
22251
22252   // The type of the truncated inputs.
22253   EVT WideVT = N0->getOperand(0)->getValueType(0);
22254   if (WideVT != VT)
22255     return SDValue();
22256
22257   // The right side has to be a 'trunc' or a constant vector.
22258   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
22259   ConstantSDNode *RHSConstSplat = nullptr;
22260   if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
22261     RHSConstSplat = RHSBV->getConstantSplatNode();
22262   if (!RHSTrunc && !RHSConstSplat)
22263     return SDValue();
22264
22265   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22266
22267   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
22268     return SDValue();
22269
22270   // Set N0 and N1 to hold the inputs to the new wide operation.
22271   N0 = N0->getOperand(0);
22272   if (RHSConstSplat) {
22273     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
22274                      SDValue(RHSConstSplat, 0));
22275     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
22276     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
22277   } else if (RHSTrunc) {
22278     N1 = N1->getOperand(0);
22279   }
22280
22281   // Generate the wide operation.
22282   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
22283   unsigned Opcode = N->getOpcode();
22284   switch (Opcode) {
22285   case ISD::ANY_EXTEND:
22286     return Op;
22287   case ISD::ZERO_EXTEND: {
22288     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
22289     APInt Mask = APInt::getAllOnesValue(InBits);
22290     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
22291     return DAG.getNode(ISD::AND, DL, VT,
22292                        Op, DAG.getConstant(Mask, VT));
22293   }
22294   case ISD::SIGN_EXTEND:
22295     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
22296                        Op, DAG.getValueType(NarrowVT));
22297   default:
22298     llvm_unreachable("Unexpected opcode");
22299   }
22300 }
22301
22302 static SDValue VectorZextCombine(SDNode *N, SelectionDAG &DAG,
22303                                  TargetLowering::DAGCombinerInfo &DCI,
22304                                  const X86Subtarget *Subtarget) {
22305   SDValue N0 = N->getOperand(0);
22306   SDValue N1 = N->getOperand(1);
22307   SDLoc DL(N);
22308
22309   // A vector zext_in_reg may be represented as a shuffle,
22310   // feeding into a bitcast (this represents anyext) feeding into
22311   // an and with a mask.
22312   // We'd like to try to combine that into a shuffle with zero
22313   // plus a bitcast, removing the and.
22314   if (N0.getOpcode() != ISD::BITCAST ||
22315       N0.getOperand(0).getOpcode() != ISD::VECTOR_SHUFFLE)
22316     return SDValue();
22317
22318   // The other side of the AND should be a splat of 2^C, where C
22319   // is the number of bits in the source type.
22320   if (N1.getOpcode() == ISD::BITCAST)
22321     N1 = N1.getOperand(0);
22322   if (N1.getOpcode() != ISD::BUILD_VECTOR)
22323     return SDValue();
22324   BuildVectorSDNode *Vector = cast<BuildVectorSDNode>(N1);
22325
22326   ShuffleVectorSDNode *Shuffle = cast<ShuffleVectorSDNode>(N0.getOperand(0));
22327   EVT SrcType = Shuffle->getValueType(0);
22328
22329   // We expect a single-source shuffle
22330   if (Shuffle->getOperand(1)->getOpcode() != ISD::UNDEF)
22331     return SDValue();
22332
22333   unsigned SrcSize = SrcType.getScalarSizeInBits();
22334
22335   APInt SplatValue, SplatUndef;
22336   unsigned SplatBitSize;
22337   bool HasAnyUndefs;
22338   if (!Vector->isConstantSplat(SplatValue, SplatUndef,
22339                                 SplatBitSize, HasAnyUndefs))
22340     return SDValue();
22341
22342   unsigned ResSize = N1.getValueType().getScalarSizeInBits();
22343   // Make sure the splat matches the mask we expect
22344   if (SplatBitSize > ResSize ||
22345       (SplatValue + 1).exactLogBase2() != (int)SrcSize)
22346     return SDValue();
22347
22348   // Make sure the input and output size make sense
22349   if (SrcSize >= ResSize || ResSize % SrcSize)
22350     return SDValue();
22351
22352   // We expect a shuffle of the form <0, u, u, u, 1, u, u, u...>
22353   // The number of u's between each two values depends on the ratio between
22354   // the source and dest type.
22355   unsigned ZextRatio = ResSize / SrcSize;
22356   bool IsZext = true;
22357   for (unsigned i = 0; i < SrcType.getVectorNumElements(); ++i) {
22358     if (i % ZextRatio) {
22359       if (Shuffle->getMaskElt(i) > 0) {
22360         // Expected undef
22361         IsZext = false;
22362         break;
22363       }
22364     } else {
22365       if (Shuffle->getMaskElt(i) != (int)(i / ZextRatio)) {
22366         // Expected element number
22367         IsZext = false;
22368         break;
22369       }
22370     }
22371   }
22372
22373   if (!IsZext)
22374     return SDValue();
22375
22376   // Ok, perform the transformation - replace the shuffle with
22377   // a shuffle of the form <0, k, k, k, 1, k, k, k> with zero
22378   // (instead of undef) where the k elements come from the zero vector.
22379   SmallVector<int, 8> Mask;
22380   unsigned NumElems = SrcType.getVectorNumElements();
22381   for (unsigned i = 0; i < NumElems; ++i)
22382     if (i % ZextRatio)
22383       Mask.push_back(NumElems);
22384     else
22385       Mask.push_back(i / ZextRatio);
22386
22387   SDValue NewShuffle = DAG.getVectorShuffle(Shuffle->getValueType(0), DL,
22388     Shuffle->getOperand(0), DAG.getConstant(0, SrcType), Mask);
22389   return DAG.getNode(ISD::BITCAST, DL,  N0.getValueType(), NewShuffle);
22390 }
22391
22392 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
22393                                  TargetLowering::DAGCombinerInfo &DCI,
22394                                  const X86Subtarget *Subtarget) {
22395   if (DCI.isBeforeLegalizeOps())
22396     return SDValue();
22397
22398   if (SDValue Zext = VectorZextCombine(N, DAG, DCI, Subtarget))
22399     return Zext;
22400
22401   if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
22402     return R;
22403
22404   EVT VT = N->getValueType(0);
22405   SDValue N0 = N->getOperand(0);
22406   SDValue N1 = N->getOperand(1);
22407   SDLoc DL(N);
22408
22409   // Create BEXTR instructions
22410   // BEXTR is ((X >> imm) & (2**size-1))
22411   if (VT == MVT::i32 || VT == MVT::i64) {
22412     // Check for BEXTR.
22413     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
22414         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
22415       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
22416       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
22417       if (MaskNode && ShiftNode) {
22418         uint64_t Mask = MaskNode->getZExtValue();
22419         uint64_t Shift = ShiftNode->getZExtValue();
22420         if (isMask_64(Mask)) {
22421           uint64_t MaskSize = countPopulation(Mask);
22422           if (Shift + MaskSize <= VT.getSizeInBits())
22423             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
22424                                DAG.getConstant(Shift | (MaskSize << 8), VT));
22425         }
22426       }
22427     } // BEXTR
22428
22429     return SDValue();
22430   }
22431
22432   // Want to form ANDNP nodes:
22433   // 1) In the hopes of then easily combining them with OR and AND nodes
22434   //    to form PBLEND/PSIGN.
22435   // 2) To match ANDN packed intrinsics
22436   if (VT != MVT::v2i64 && VT != MVT::v4i64)
22437     return SDValue();
22438
22439   // Check LHS for vnot
22440   if (N0.getOpcode() == ISD::XOR &&
22441       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
22442       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
22443     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
22444
22445   // Check RHS for vnot
22446   if (N1.getOpcode() == ISD::XOR &&
22447       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
22448       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
22449     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
22450
22451   return SDValue();
22452 }
22453
22454 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
22455                                 TargetLowering::DAGCombinerInfo &DCI,
22456                                 const X86Subtarget *Subtarget) {
22457   if (DCI.isBeforeLegalizeOps())
22458     return SDValue();
22459
22460   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
22461   if (R.getNode())
22462     return R;
22463
22464   SDValue N0 = N->getOperand(0);
22465   SDValue N1 = N->getOperand(1);
22466   EVT VT = N->getValueType(0);
22467
22468   // look for psign/blend
22469   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
22470     if (!Subtarget->hasSSSE3() ||
22471         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
22472       return SDValue();
22473
22474     // Canonicalize pandn to RHS
22475     if (N0.getOpcode() == X86ISD::ANDNP)
22476       std::swap(N0, N1);
22477     // or (and (m, y), (pandn m, x))
22478     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
22479       SDValue Mask = N1.getOperand(0);
22480       SDValue X    = N1.getOperand(1);
22481       SDValue Y;
22482       if (N0.getOperand(0) == Mask)
22483         Y = N0.getOperand(1);
22484       if (N0.getOperand(1) == Mask)
22485         Y = N0.getOperand(0);
22486
22487       // Check to see if the mask appeared in both the AND and ANDNP and
22488       if (!Y.getNode())
22489         return SDValue();
22490
22491       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
22492       // Look through mask bitcast.
22493       if (Mask.getOpcode() == ISD::BITCAST)
22494         Mask = Mask.getOperand(0);
22495       if (X.getOpcode() == ISD::BITCAST)
22496         X = X.getOperand(0);
22497       if (Y.getOpcode() == ISD::BITCAST)
22498         Y = Y.getOperand(0);
22499
22500       EVT MaskVT = Mask.getValueType();
22501
22502       // Validate that the Mask operand is a vector sra node.
22503       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
22504       // there is no psrai.b
22505       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
22506       unsigned SraAmt = ~0;
22507       if (Mask.getOpcode() == ISD::SRA) {
22508         if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
22509           if (auto *AmtConst = AmtBV->getConstantSplatNode())
22510             SraAmt = AmtConst->getZExtValue();
22511       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
22512         SDValue SraC = Mask.getOperand(1);
22513         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
22514       }
22515       if ((SraAmt + 1) != EltBits)
22516         return SDValue();
22517
22518       SDLoc DL(N);
22519
22520       // Now we know we at least have a plendvb with the mask val.  See if
22521       // we can form a psignb/w/d.
22522       // psign = x.type == y.type == mask.type && y = sub(0, x);
22523       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
22524           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
22525           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
22526         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
22527                "Unsupported VT for PSIGN");
22528         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
22529         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
22530       }
22531       // PBLENDVB only available on SSE 4.1
22532       if (!Subtarget->hasSSE41())
22533         return SDValue();
22534
22535       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
22536
22537       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
22538       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
22539       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
22540       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
22541       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
22542     }
22543   }
22544
22545   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
22546     return SDValue();
22547
22548   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
22549   MachineFunction &MF = DAG.getMachineFunction();
22550   bool OptForSize =
22551       MF.getFunction()->hasFnAttribute(Attribute::OptimizeForSize);
22552
22553   // SHLD/SHRD instructions have lower register pressure, but on some
22554   // platforms they have higher latency than the equivalent
22555   // series of shifts/or that would otherwise be generated.
22556   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
22557   // have higher latencies and we are not optimizing for size.
22558   if (!OptForSize && Subtarget->isSHLDSlow())
22559     return SDValue();
22560
22561   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
22562     std::swap(N0, N1);
22563   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
22564     return SDValue();
22565   if (!N0.hasOneUse() || !N1.hasOneUse())
22566     return SDValue();
22567
22568   SDValue ShAmt0 = N0.getOperand(1);
22569   if (ShAmt0.getValueType() != MVT::i8)
22570     return SDValue();
22571   SDValue ShAmt1 = N1.getOperand(1);
22572   if (ShAmt1.getValueType() != MVT::i8)
22573     return SDValue();
22574   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
22575     ShAmt0 = ShAmt0.getOperand(0);
22576   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
22577     ShAmt1 = ShAmt1.getOperand(0);
22578
22579   SDLoc DL(N);
22580   unsigned Opc = X86ISD::SHLD;
22581   SDValue Op0 = N0.getOperand(0);
22582   SDValue Op1 = N1.getOperand(0);
22583   if (ShAmt0.getOpcode() == ISD::SUB) {
22584     Opc = X86ISD::SHRD;
22585     std::swap(Op0, Op1);
22586     std::swap(ShAmt0, ShAmt1);
22587   }
22588
22589   unsigned Bits = VT.getSizeInBits();
22590   if (ShAmt1.getOpcode() == ISD::SUB) {
22591     SDValue Sum = ShAmt1.getOperand(0);
22592     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
22593       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
22594       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
22595         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
22596       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
22597         return DAG.getNode(Opc, DL, VT,
22598                            Op0, Op1,
22599                            DAG.getNode(ISD::TRUNCATE, DL,
22600                                        MVT::i8, ShAmt0));
22601     }
22602   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
22603     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
22604     if (ShAmt0C &&
22605         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
22606       return DAG.getNode(Opc, DL, VT,
22607                          N0.getOperand(0), N1.getOperand(0),
22608                          DAG.getNode(ISD::TRUNCATE, DL,
22609                                        MVT::i8, ShAmt0));
22610   }
22611
22612   return SDValue();
22613 }
22614
22615 // Generate NEG and CMOV for integer abs.
22616 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
22617   EVT VT = N->getValueType(0);
22618
22619   // Since X86 does not have CMOV for 8-bit integer, we don't convert
22620   // 8-bit integer abs to NEG and CMOV.
22621   if (VT.isInteger() && VT.getSizeInBits() == 8)
22622     return SDValue();
22623
22624   SDValue N0 = N->getOperand(0);
22625   SDValue N1 = N->getOperand(1);
22626   SDLoc DL(N);
22627
22628   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
22629   // and change it to SUB and CMOV.
22630   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
22631       N0.getOpcode() == ISD::ADD &&
22632       N0.getOperand(1) == N1 &&
22633       N1.getOpcode() == ISD::SRA &&
22634       N1.getOperand(0) == N0.getOperand(0))
22635     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
22636       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
22637         // Generate SUB & CMOV.
22638         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
22639                                   DAG.getConstant(0, VT), N0.getOperand(0));
22640
22641         SDValue Ops[] = { N0.getOperand(0), Neg,
22642                           DAG.getConstant(X86::COND_GE, MVT::i8),
22643                           SDValue(Neg.getNode(), 1) };
22644         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
22645       }
22646   return SDValue();
22647 }
22648
22649 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
22650 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
22651                                  TargetLowering::DAGCombinerInfo &DCI,
22652                                  const X86Subtarget *Subtarget) {
22653   if (DCI.isBeforeLegalizeOps())
22654     return SDValue();
22655
22656   if (Subtarget->hasCMov()) {
22657     SDValue RV = performIntegerAbsCombine(N, DAG);
22658     if (RV.getNode())
22659       return RV;
22660   }
22661
22662   return SDValue();
22663 }
22664
22665 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
22666 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
22667                                   TargetLowering::DAGCombinerInfo &DCI,
22668                                   const X86Subtarget *Subtarget) {
22669   LoadSDNode *Ld = cast<LoadSDNode>(N);
22670   EVT RegVT = Ld->getValueType(0);
22671   EVT MemVT = Ld->getMemoryVT();
22672   SDLoc dl(Ld);
22673   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22674
22675   // For chips with slow 32-byte unaligned loads, break the 32-byte operation
22676   // into two 16-byte operations.
22677   ISD::LoadExtType Ext = Ld->getExtensionType();
22678   unsigned Alignment = Ld->getAlignment();
22679   bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
22680   if (RegVT.is256BitVector() && Subtarget->isUnalignedMem32Slow() &&
22681       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
22682     unsigned NumElems = RegVT.getVectorNumElements();
22683     if (NumElems < 2)
22684       return SDValue();
22685
22686     SDValue Ptr = Ld->getBasePtr();
22687     SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
22688
22689     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
22690                                   NumElems/2);
22691     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
22692                                 Ld->getPointerInfo(), Ld->isVolatile(),
22693                                 Ld->isNonTemporal(), Ld->isInvariant(),
22694                                 Alignment);
22695     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
22696     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
22697                                 Ld->getPointerInfo(), Ld->isVolatile(),
22698                                 Ld->isNonTemporal(), Ld->isInvariant(),
22699                                 std::min(16U, Alignment));
22700     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
22701                              Load1.getValue(1),
22702                              Load2.getValue(1));
22703
22704     SDValue NewVec = DAG.getUNDEF(RegVT);
22705     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
22706     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
22707     return DCI.CombineTo(N, NewVec, TF, true);
22708   }
22709
22710   return SDValue();
22711 }
22712
22713 /// PerformMLOADCombine - Resolve extending loads
22714 static SDValue PerformMLOADCombine(SDNode *N, SelectionDAG &DAG,
22715                                    TargetLowering::DAGCombinerInfo &DCI,
22716                                    const X86Subtarget *Subtarget) {
22717   MaskedLoadSDNode *Mld = cast<MaskedLoadSDNode>(N);
22718   if (Mld->getExtensionType() != ISD::SEXTLOAD)
22719     return SDValue();
22720
22721   EVT VT = Mld->getValueType(0);
22722   unsigned NumElems = VT.getVectorNumElements();
22723   EVT LdVT = Mld->getMemoryVT();
22724   SDLoc dl(Mld);
22725
22726   assert(LdVT != VT && "Cannot extend to the same type");
22727   unsigned ToSz = VT.getVectorElementType().getSizeInBits();
22728   unsigned FromSz = LdVT.getVectorElementType().getSizeInBits();
22729   // From, To sizes and ElemCount must be pow of two
22730   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
22731     "Unexpected size for extending masked load");
22732
22733   unsigned SizeRatio  = ToSz / FromSz;
22734   assert(SizeRatio * NumElems * FromSz == VT.getSizeInBits());
22735
22736   // Create a type on which we perform the shuffle
22737   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
22738           LdVT.getScalarType(), NumElems*SizeRatio);
22739   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
22740
22741   // Convert Src0 value
22742   SDValue WideSrc0 = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mld->getSrc0());
22743   if (Mld->getSrc0().getOpcode() != ISD::UNDEF) {
22744     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
22745     for (unsigned i = 0; i != NumElems; ++i)
22746       ShuffleVec[i] = i * SizeRatio;
22747
22748     // Can't shuffle using an illegal type.
22749     assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
22750             && "WideVecVT should be legal");
22751     WideSrc0 = DAG.getVectorShuffle(WideVecVT, dl, WideSrc0,
22752                                     DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
22753   }
22754   // Prepare the new mask
22755   SDValue NewMask;
22756   SDValue Mask = Mld->getMask();
22757   if (Mask.getValueType() == VT) {
22758     // Mask and original value have the same type
22759     NewMask = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mask);
22760     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
22761     for (unsigned i = 0; i != NumElems; ++i)
22762       ShuffleVec[i] = i * SizeRatio;
22763     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
22764       ShuffleVec[i] = NumElems*SizeRatio;
22765     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
22766                                    DAG.getConstant(0, WideVecVT),
22767                                    &ShuffleVec[0]);
22768   }
22769   else {
22770     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
22771     unsigned WidenNumElts = NumElems*SizeRatio;
22772     unsigned MaskNumElts = VT.getVectorNumElements();
22773     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
22774                                      WidenNumElts);
22775
22776     unsigned NumConcat = WidenNumElts / MaskNumElts;
22777     SmallVector<SDValue, 16> Ops(NumConcat);
22778     SDValue ZeroVal = DAG.getConstant(0, Mask.getValueType());
22779     Ops[0] = Mask;
22780     for (unsigned i = 1; i != NumConcat; ++i)
22781       Ops[i] = ZeroVal;
22782
22783     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
22784   }
22785
22786   SDValue WideLd = DAG.getMaskedLoad(WideVecVT, dl, Mld->getChain(),
22787                                      Mld->getBasePtr(), NewMask, WideSrc0,
22788                                      Mld->getMemoryVT(), Mld->getMemOperand(),
22789                                      ISD::NON_EXTLOAD);
22790   SDValue NewVec = DAG.getNode(X86ISD::VSEXT, dl, VT, WideLd);
22791   return DCI.CombineTo(N, NewVec, WideLd.getValue(1), true);
22792
22793 }
22794 /// PerformMSTORECombine - Resolve truncating stores
22795 static SDValue PerformMSTORECombine(SDNode *N, SelectionDAG &DAG,
22796                                     const X86Subtarget *Subtarget) {
22797   MaskedStoreSDNode *Mst = cast<MaskedStoreSDNode>(N);
22798   if (!Mst->isTruncatingStore())
22799     return SDValue();
22800
22801   EVT VT = Mst->getValue().getValueType();
22802   unsigned NumElems = VT.getVectorNumElements();
22803   EVT StVT = Mst->getMemoryVT();
22804   SDLoc dl(Mst);
22805
22806   assert(StVT != VT && "Cannot truncate to the same type");
22807   unsigned FromSz = VT.getVectorElementType().getSizeInBits();
22808   unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
22809
22810   // From, To sizes and ElemCount must be pow of two
22811   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
22812     "Unexpected size for truncating masked store");
22813   // We are going to use the original vector elt for storing.
22814   // Accumulated smaller vector elements must be a multiple of the store size.
22815   assert (((NumElems * FromSz) % ToSz) == 0 &&
22816           "Unexpected ratio for truncating masked store");
22817
22818   unsigned SizeRatio  = FromSz / ToSz;
22819   assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
22820
22821   // Create a type on which we perform the shuffle
22822   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
22823           StVT.getScalarType(), NumElems*SizeRatio);
22824
22825   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
22826
22827   SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mst->getValue());
22828   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
22829   for (unsigned i = 0; i != NumElems; ++i)
22830     ShuffleVec[i] = i * SizeRatio;
22831
22832   // Can't shuffle using an illegal type.
22833   assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
22834           && "WideVecVT should be legal");
22835
22836   SDValue TruncatedVal = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
22837                                         DAG.getUNDEF(WideVecVT),
22838                                         &ShuffleVec[0]);
22839
22840   SDValue NewMask;
22841   SDValue Mask = Mst->getMask();
22842   if (Mask.getValueType() == VT) {
22843     // Mask and original value have the same type
22844     NewMask = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mask);
22845     for (unsigned i = 0; i != NumElems; ++i)
22846       ShuffleVec[i] = i * SizeRatio;
22847     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
22848       ShuffleVec[i] = NumElems*SizeRatio;
22849     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
22850                                    DAG.getConstant(0, WideVecVT),
22851                                    &ShuffleVec[0]);
22852   }
22853   else {
22854     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
22855     unsigned WidenNumElts = NumElems*SizeRatio;
22856     unsigned MaskNumElts = VT.getVectorNumElements();
22857     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
22858                                      WidenNumElts);
22859
22860     unsigned NumConcat = WidenNumElts / MaskNumElts;
22861     SmallVector<SDValue, 16> Ops(NumConcat);
22862     SDValue ZeroVal = DAG.getConstant(0, Mask.getValueType());
22863     Ops[0] = Mask;
22864     for (unsigned i = 1; i != NumConcat; ++i)
22865       Ops[i] = ZeroVal;
22866
22867     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
22868   }
22869
22870   return DAG.getMaskedStore(Mst->getChain(), dl, TruncatedVal, Mst->getBasePtr(),
22871                             NewMask, StVT, Mst->getMemOperand(), false);
22872 }
22873 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
22874 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
22875                                    const X86Subtarget *Subtarget) {
22876   StoreSDNode *St = cast<StoreSDNode>(N);
22877   EVT VT = St->getValue().getValueType();
22878   EVT StVT = St->getMemoryVT();
22879   SDLoc dl(St);
22880   SDValue StoredVal = St->getOperand(1);
22881   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22882
22883   // If we are saving a concatenation of two XMM registers and 32-byte stores
22884   // are slow, such as on Sandy Bridge, perform two 16-byte stores.
22885   unsigned Alignment = St->getAlignment();
22886   bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
22887   if (VT.is256BitVector() && Subtarget->isUnalignedMem32Slow() &&
22888       StVT == VT && !IsAligned) {
22889     unsigned NumElems = VT.getVectorNumElements();
22890     if (NumElems < 2)
22891       return SDValue();
22892
22893     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
22894     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
22895
22896     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
22897     SDValue Ptr0 = St->getBasePtr();
22898     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
22899
22900     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
22901                                 St->getPointerInfo(), St->isVolatile(),
22902                                 St->isNonTemporal(), Alignment);
22903     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
22904                                 St->getPointerInfo(), St->isVolatile(),
22905                                 St->isNonTemporal(),
22906                                 std::min(16U, Alignment));
22907     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
22908   }
22909
22910   // Optimize trunc store (of multiple scalars) to shuffle and store.
22911   // First, pack all of the elements in one place. Next, store to memory
22912   // in fewer chunks.
22913   if (St->isTruncatingStore() && VT.isVector()) {
22914     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22915     unsigned NumElems = VT.getVectorNumElements();
22916     assert(StVT != VT && "Cannot truncate to the same type");
22917     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
22918     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
22919
22920     // From, To sizes and ElemCount must be pow of two
22921     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
22922     // We are going to use the original vector elt for storing.
22923     // Accumulated smaller vector elements must be a multiple of the store size.
22924     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
22925
22926     unsigned SizeRatio  = FromSz / ToSz;
22927
22928     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
22929
22930     // Create a type on which we perform the shuffle
22931     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
22932             StVT.getScalarType(), NumElems*SizeRatio);
22933
22934     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
22935
22936     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
22937     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
22938     for (unsigned i = 0; i != NumElems; ++i)
22939       ShuffleVec[i] = i * SizeRatio;
22940
22941     // Can't shuffle using an illegal type.
22942     if (!TLI.isTypeLegal(WideVecVT))
22943       return SDValue();
22944
22945     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
22946                                          DAG.getUNDEF(WideVecVT),
22947                                          &ShuffleVec[0]);
22948     // At this point all of the data is stored at the bottom of the
22949     // register. We now need to save it to mem.
22950
22951     // Find the largest store unit
22952     MVT StoreType = MVT::i8;
22953     for (MVT Tp : MVT::integer_valuetypes()) {
22954       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
22955         StoreType = Tp;
22956     }
22957
22958     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
22959     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
22960         (64 <= NumElems * ToSz))
22961       StoreType = MVT::f64;
22962
22963     // Bitcast the original vector into a vector of store-size units
22964     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
22965             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
22966     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
22967     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
22968     SmallVector<SDValue, 8> Chains;
22969     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
22970                                         TLI.getPointerTy());
22971     SDValue Ptr = St->getBasePtr();
22972
22973     // Perform one or more big stores into memory.
22974     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
22975       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
22976                                    StoreType, ShuffWide,
22977                                    DAG.getIntPtrConstant(i));
22978       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
22979                                 St->getPointerInfo(), St->isVolatile(),
22980                                 St->isNonTemporal(), St->getAlignment());
22981       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
22982       Chains.push_back(Ch);
22983     }
22984
22985     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
22986   }
22987
22988   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
22989   // the FP state in cases where an emms may be missing.
22990   // A preferable solution to the general problem is to figure out the right
22991   // places to insert EMMS.  This qualifies as a quick hack.
22992
22993   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
22994   if (VT.getSizeInBits() != 64)
22995     return SDValue();
22996
22997   const Function *F = DAG.getMachineFunction().getFunction();
22998   bool NoImplicitFloatOps = F->hasFnAttribute(Attribute::NoImplicitFloat);
22999   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
23000                      && Subtarget->hasSSE2();
23001   if ((VT.isVector() ||
23002        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
23003       isa<LoadSDNode>(St->getValue()) &&
23004       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
23005       St->getChain().hasOneUse() && !St->isVolatile()) {
23006     SDNode* LdVal = St->getValue().getNode();
23007     LoadSDNode *Ld = nullptr;
23008     int TokenFactorIndex = -1;
23009     SmallVector<SDValue, 8> Ops;
23010     SDNode* ChainVal = St->getChain().getNode();
23011     // Must be a store of a load.  We currently handle two cases:  the load
23012     // is a direct child, and it's under an intervening TokenFactor.  It is
23013     // possible to dig deeper under nested TokenFactors.
23014     if (ChainVal == LdVal)
23015       Ld = cast<LoadSDNode>(St->getChain());
23016     else if (St->getValue().hasOneUse() &&
23017              ChainVal->getOpcode() == ISD::TokenFactor) {
23018       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
23019         if (ChainVal->getOperand(i).getNode() == LdVal) {
23020           TokenFactorIndex = i;
23021           Ld = cast<LoadSDNode>(St->getValue());
23022         } else
23023           Ops.push_back(ChainVal->getOperand(i));
23024       }
23025     }
23026
23027     if (!Ld || !ISD::isNormalLoad(Ld))
23028       return SDValue();
23029
23030     // If this is not the MMX case, i.e. we are just turning i64 load/store
23031     // into f64 load/store, avoid the transformation if there are multiple
23032     // uses of the loaded value.
23033     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
23034       return SDValue();
23035
23036     SDLoc LdDL(Ld);
23037     SDLoc StDL(N);
23038     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
23039     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
23040     // pair instead.
23041     if (Subtarget->is64Bit() || F64IsLegal) {
23042       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
23043       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
23044                                   Ld->getPointerInfo(), Ld->isVolatile(),
23045                                   Ld->isNonTemporal(), Ld->isInvariant(),
23046                                   Ld->getAlignment());
23047       SDValue NewChain = NewLd.getValue(1);
23048       if (TokenFactorIndex != -1) {
23049         Ops.push_back(NewChain);
23050         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
23051       }
23052       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
23053                           St->getPointerInfo(),
23054                           St->isVolatile(), St->isNonTemporal(),
23055                           St->getAlignment());
23056     }
23057
23058     // Otherwise, lower to two pairs of 32-bit loads / stores.
23059     SDValue LoAddr = Ld->getBasePtr();
23060     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
23061                                  DAG.getConstant(4, MVT::i32));
23062
23063     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
23064                                Ld->getPointerInfo(),
23065                                Ld->isVolatile(), Ld->isNonTemporal(),
23066                                Ld->isInvariant(), Ld->getAlignment());
23067     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
23068                                Ld->getPointerInfo().getWithOffset(4),
23069                                Ld->isVolatile(), Ld->isNonTemporal(),
23070                                Ld->isInvariant(),
23071                                MinAlign(Ld->getAlignment(), 4));
23072
23073     SDValue NewChain = LoLd.getValue(1);
23074     if (TokenFactorIndex != -1) {
23075       Ops.push_back(LoLd);
23076       Ops.push_back(HiLd);
23077       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
23078     }
23079
23080     LoAddr = St->getBasePtr();
23081     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
23082                          DAG.getConstant(4, MVT::i32));
23083
23084     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
23085                                 St->getPointerInfo(),
23086                                 St->isVolatile(), St->isNonTemporal(),
23087                                 St->getAlignment());
23088     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
23089                                 St->getPointerInfo().getWithOffset(4),
23090                                 St->isVolatile(),
23091                                 St->isNonTemporal(),
23092                                 MinAlign(St->getAlignment(), 4));
23093     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
23094   }
23095
23096   // This is similar to the above case, but here we handle a scalar 64-bit
23097   // integer store that is extracted from a vector on a 32-bit target.
23098   // If we have SSE2, then we can treat it like a floating-point double
23099   // to get past legalization. The execution dependencies fixup pass will
23100   // choose the optimal machine instruction for the store if this really is
23101   // an integer or v2f32 rather than an f64.
23102   if (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit() &&
23103       St->getOperand(1).getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
23104     SDValue OldExtract = St->getOperand(1);
23105     SDValue ExtOp0 = OldExtract.getOperand(0);
23106     unsigned VecSize = ExtOp0.getValueSizeInBits();
23107     MVT VecVT = MVT::getVectorVT(MVT::f64, VecSize / 64);
23108     SDValue BitCast = DAG.getNode(ISD::BITCAST, dl, VecVT, ExtOp0);
23109     SDValue NewExtract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
23110                                      BitCast, OldExtract.getOperand(1));
23111     return DAG.getStore(St->getChain(), dl, NewExtract, St->getBasePtr(),
23112                         St->getPointerInfo(), St->isVolatile(),
23113                         St->isNonTemporal(), St->getAlignment());
23114   }
23115
23116   return SDValue();
23117 }
23118
23119 /// Return 'true' if this vector operation is "horizontal"
23120 /// and return the operands for the horizontal operation in LHS and RHS.  A
23121 /// horizontal operation performs the binary operation on successive elements
23122 /// of its first operand, then on successive elements of its second operand,
23123 /// returning the resulting values in a vector.  For example, if
23124 ///   A = < float a0, float a1, float a2, float a3 >
23125 /// and
23126 ///   B = < float b0, float b1, float b2, float b3 >
23127 /// then the result of doing a horizontal operation on A and B is
23128 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
23129 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
23130 /// A horizontal-op B, for some already available A and B, and if so then LHS is
23131 /// set to A, RHS to B, and the routine returns 'true'.
23132 /// Note that the binary operation should have the property that if one of the
23133 /// operands is UNDEF then the result is UNDEF.
23134 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
23135   // Look for the following pattern: if
23136   //   A = < float a0, float a1, float a2, float a3 >
23137   //   B = < float b0, float b1, float b2, float b3 >
23138   // and
23139   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
23140   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
23141   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
23142   // which is A horizontal-op B.
23143
23144   // At least one of the operands should be a vector shuffle.
23145   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
23146       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
23147     return false;
23148
23149   MVT VT = LHS.getSimpleValueType();
23150
23151   assert((VT.is128BitVector() || VT.is256BitVector()) &&
23152          "Unsupported vector type for horizontal add/sub");
23153
23154   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
23155   // operate independently on 128-bit lanes.
23156   unsigned NumElts = VT.getVectorNumElements();
23157   unsigned NumLanes = VT.getSizeInBits()/128;
23158   unsigned NumLaneElts = NumElts / NumLanes;
23159   assert((NumLaneElts % 2 == 0) &&
23160          "Vector type should have an even number of elements in each lane");
23161   unsigned HalfLaneElts = NumLaneElts/2;
23162
23163   // View LHS in the form
23164   //   LHS = VECTOR_SHUFFLE A, B, LMask
23165   // If LHS is not a shuffle then pretend it is the shuffle
23166   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
23167   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
23168   // type VT.
23169   SDValue A, B;
23170   SmallVector<int, 16> LMask(NumElts);
23171   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
23172     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
23173       A = LHS.getOperand(0);
23174     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
23175       B = LHS.getOperand(1);
23176     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
23177     std::copy(Mask.begin(), Mask.end(), LMask.begin());
23178   } else {
23179     if (LHS.getOpcode() != ISD::UNDEF)
23180       A = LHS;
23181     for (unsigned i = 0; i != NumElts; ++i)
23182       LMask[i] = i;
23183   }
23184
23185   // Likewise, view RHS in the form
23186   //   RHS = VECTOR_SHUFFLE C, D, RMask
23187   SDValue C, D;
23188   SmallVector<int, 16> RMask(NumElts);
23189   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
23190     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
23191       C = RHS.getOperand(0);
23192     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
23193       D = RHS.getOperand(1);
23194     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
23195     std::copy(Mask.begin(), Mask.end(), RMask.begin());
23196   } else {
23197     if (RHS.getOpcode() != ISD::UNDEF)
23198       C = RHS;
23199     for (unsigned i = 0; i != NumElts; ++i)
23200       RMask[i] = i;
23201   }
23202
23203   // Check that the shuffles are both shuffling the same vectors.
23204   if (!(A == C && B == D) && !(A == D && B == C))
23205     return false;
23206
23207   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
23208   if (!A.getNode() && !B.getNode())
23209     return false;
23210
23211   // If A and B occur in reverse order in RHS, then "swap" them (which means
23212   // rewriting the mask).
23213   if (A != C)
23214     ShuffleVectorSDNode::commuteMask(RMask);
23215
23216   // At this point LHS and RHS are equivalent to
23217   //   LHS = VECTOR_SHUFFLE A, B, LMask
23218   //   RHS = VECTOR_SHUFFLE A, B, RMask
23219   // Check that the masks correspond to performing a horizontal operation.
23220   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
23221     for (unsigned i = 0; i != NumLaneElts; ++i) {
23222       int LIdx = LMask[i+l], RIdx = RMask[i+l];
23223
23224       // Ignore any UNDEF components.
23225       if (LIdx < 0 || RIdx < 0 ||
23226           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
23227           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
23228         continue;
23229
23230       // Check that successive elements are being operated on.  If not, this is
23231       // not a horizontal operation.
23232       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
23233       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
23234       if (!(LIdx == Index && RIdx == Index + 1) &&
23235           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
23236         return false;
23237     }
23238   }
23239
23240   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
23241   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
23242   return true;
23243 }
23244
23245 /// Do target-specific dag combines on floating point adds.
23246 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
23247                                   const X86Subtarget *Subtarget) {
23248   EVT VT = N->getValueType(0);
23249   SDValue LHS = N->getOperand(0);
23250   SDValue RHS = N->getOperand(1);
23251
23252   // Try to synthesize horizontal adds from adds of shuffles.
23253   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
23254        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
23255       isHorizontalBinOp(LHS, RHS, true))
23256     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
23257   return SDValue();
23258 }
23259
23260 /// Do target-specific dag combines on floating point subs.
23261 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
23262                                   const X86Subtarget *Subtarget) {
23263   EVT VT = N->getValueType(0);
23264   SDValue LHS = N->getOperand(0);
23265   SDValue RHS = N->getOperand(1);
23266
23267   // Try to synthesize horizontal subs from subs of shuffles.
23268   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
23269        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
23270       isHorizontalBinOp(LHS, RHS, false))
23271     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
23272   return SDValue();
23273 }
23274
23275 /// Do target-specific dag combines on X86ISD::FOR and X86ISD::FXOR nodes.
23276 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
23277   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
23278
23279   // F[X]OR(0.0, x) -> x
23280   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
23281     if (C->getValueAPF().isPosZero())
23282       return N->getOperand(1);
23283
23284   // F[X]OR(x, 0.0) -> x
23285   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
23286     if (C->getValueAPF().isPosZero())
23287       return N->getOperand(0);
23288   return SDValue();
23289 }
23290
23291 /// Do target-specific dag combines on X86ISD::FMIN and X86ISD::FMAX nodes.
23292 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
23293   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
23294
23295   // Only perform optimizations if UnsafeMath is used.
23296   if (!DAG.getTarget().Options.UnsafeFPMath)
23297     return SDValue();
23298
23299   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
23300   // into FMINC and FMAXC, which are Commutative operations.
23301   unsigned NewOp = 0;
23302   switch (N->getOpcode()) {
23303     default: llvm_unreachable("unknown opcode");
23304     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
23305     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
23306   }
23307
23308   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
23309                      N->getOperand(0), N->getOperand(1));
23310 }
23311
23312 /// Do target-specific dag combines on X86ISD::FAND nodes.
23313 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
23314   // FAND(0.0, x) -> 0.0
23315   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
23316     if (C->getValueAPF().isPosZero())
23317       return N->getOperand(0);
23318
23319   // FAND(x, 0.0) -> 0.0
23320   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
23321     if (C->getValueAPF().isPosZero())
23322       return N->getOperand(1);
23323
23324   return SDValue();
23325 }
23326
23327 /// Do target-specific dag combines on X86ISD::FANDN nodes
23328 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
23329   // FANDN(0.0, x) -> x
23330   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
23331     if (C->getValueAPF().isPosZero())
23332       return N->getOperand(1);
23333
23334   // FANDN(x, 0.0) -> 0.0
23335   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
23336     if (C->getValueAPF().isPosZero())
23337       return N->getOperand(1);
23338
23339   return SDValue();
23340 }
23341
23342 static SDValue PerformBTCombine(SDNode *N,
23343                                 SelectionDAG &DAG,
23344                                 TargetLowering::DAGCombinerInfo &DCI) {
23345   // BT ignores high bits in the bit index operand.
23346   SDValue Op1 = N->getOperand(1);
23347   if (Op1.hasOneUse()) {
23348     unsigned BitWidth = Op1.getValueSizeInBits();
23349     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
23350     APInt KnownZero, KnownOne;
23351     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
23352                                           !DCI.isBeforeLegalizeOps());
23353     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23354     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
23355         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
23356       DCI.CommitTargetLoweringOpt(TLO);
23357   }
23358   return SDValue();
23359 }
23360
23361 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
23362   SDValue Op = N->getOperand(0);
23363   if (Op.getOpcode() == ISD::BITCAST)
23364     Op = Op.getOperand(0);
23365   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
23366   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
23367       VT.getVectorElementType().getSizeInBits() ==
23368       OpVT.getVectorElementType().getSizeInBits()) {
23369     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
23370   }
23371   return SDValue();
23372 }
23373
23374 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
23375                                                const X86Subtarget *Subtarget) {
23376   EVT VT = N->getValueType(0);
23377   if (!VT.isVector())
23378     return SDValue();
23379
23380   SDValue N0 = N->getOperand(0);
23381   SDValue N1 = N->getOperand(1);
23382   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
23383   SDLoc dl(N);
23384
23385   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
23386   // both SSE and AVX2 since there is no sign-extended shift right
23387   // operation on a vector with 64-bit elements.
23388   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
23389   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
23390   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
23391       N0.getOpcode() == ISD::SIGN_EXTEND)) {
23392     SDValue N00 = N0.getOperand(0);
23393
23394     // EXTLOAD has a better solution on AVX2,
23395     // it may be replaced with X86ISD::VSEXT node.
23396     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
23397       if (!ISD::isNormalLoad(N00.getNode()))
23398         return SDValue();
23399
23400     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
23401         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
23402                                   N00, N1);
23403       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
23404     }
23405   }
23406   return SDValue();
23407 }
23408
23409 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
23410                                   TargetLowering::DAGCombinerInfo &DCI,
23411                                   const X86Subtarget *Subtarget) {
23412   SDValue N0 = N->getOperand(0);
23413   EVT VT = N->getValueType(0);
23414
23415   // (i8,i32 sext (sdivrem (i8 x, i8 y)) ->
23416   // (i8,i32 (sdivrem_sext_hreg (i8 x, i8 y)
23417   // This exposes the sext to the sdivrem lowering, so that it directly extends
23418   // from AH (which we otherwise need to do contortions to access).
23419   if (N0.getOpcode() == ISD::SDIVREM && N0.getResNo() == 1 &&
23420       N0.getValueType() == MVT::i8 && VT == MVT::i32) {
23421     SDLoc dl(N);
23422     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
23423     SDValue R = DAG.getNode(X86ISD::SDIVREM8_SEXT_HREG, dl, NodeTys,
23424                             N0.getOperand(0), N0.getOperand(1));
23425     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
23426     return R.getValue(1);
23427   }
23428
23429   if (!DCI.isBeforeLegalizeOps())
23430     return SDValue();
23431
23432   if (!Subtarget->hasFp256())
23433     return SDValue();
23434
23435   if (VT.isVector() && VT.getSizeInBits() == 256) {
23436     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
23437     if (R.getNode())
23438       return R;
23439   }
23440
23441   return SDValue();
23442 }
23443
23444 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
23445                                  const X86Subtarget* Subtarget) {
23446   SDLoc dl(N);
23447   EVT VT = N->getValueType(0);
23448
23449   // Let legalize expand this if it isn't a legal type yet.
23450   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
23451     return SDValue();
23452
23453   EVT ScalarVT = VT.getScalarType();
23454   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
23455       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
23456     return SDValue();
23457
23458   SDValue A = N->getOperand(0);
23459   SDValue B = N->getOperand(1);
23460   SDValue C = N->getOperand(2);
23461
23462   bool NegA = (A.getOpcode() == ISD::FNEG);
23463   bool NegB = (B.getOpcode() == ISD::FNEG);
23464   bool NegC = (C.getOpcode() == ISD::FNEG);
23465
23466   // Negative multiplication when NegA xor NegB
23467   bool NegMul = (NegA != NegB);
23468   if (NegA)
23469     A = A.getOperand(0);
23470   if (NegB)
23471     B = B.getOperand(0);
23472   if (NegC)
23473     C = C.getOperand(0);
23474
23475   unsigned Opcode;
23476   if (!NegMul)
23477     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
23478   else
23479     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
23480
23481   return DAG.getNode(Opcode, dl, VT, A, B, C);
23482 }
23483
23484 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
23485                                   TargetLowering::DAGCombinerInfo &DCI,
23486                                   const X86Subtarget *Subtarget) {
23487   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
23488   //           (and (i32 x86isd::setcc_carry), 1)
23489   // This eliminates the zext. This transformation is necessary because
23490   // ISD::SETCC is always legalized to i8.
23491   SDLoc dl(N);
23492   SDValue N0 = N->getOperand(0);
23493   EVT VT = N->getValueType(0);
23494
23495   if (N0.getOpcode() == ISD::AND &&
23496       N0.hasOneUse() &&
23497       N0.getOperand(0).hasOneUse()) {
23498     SDValue N00 = N0.getOperand(0);
23499     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
23500       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
23501       if (!C || C->getZExtValue() != 1)
23502         return SDValue();
23503       return DAG.getNode(ISD::AND, dl, VT,
23504                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
23505                                      N00.getOperand(0), N00.getOperand(1)),
23506                          DAG.getConstant(1, VT));
23507     }
23508   }
23509
23510   if (N0.getOpcode() == ISD::TRUNCATE &&
23511       N0.hasOneUse() &&
23512       N0.getOperand(0).hasOneUse()) {
23513     SDValue N00 = N0.getOperand(0);
23514     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
23515       return DAG.getNode(ISD::AND, dl, VT,
23516                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
23517                                      N00.getOperand(0), N00.getOperand(1)),
23518                          DAG.getConstant(1, VT));
23519     }
23520   }
23521   if (VT.is256BitVector()) {
23522     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
23523     if (R.getNode())
23524       return R;
23525   }
23526
23527   // (i8,i32 zext (udivrem (i8 x, i8 y)) ->
23528   // (i8,i32 (udivrem_zext_hreg (i8 x, i8 y)
23529   // This exposes the zext to the udivrem lowering, so that it directly extends
23530   // from AH (which we otherwise need to do contortions to access).
23531   if (N0.getOpcode() == ISD::UDIVREM &&
23532       N0.getResNo() == 1 && N0.getValueType() == MVT::i8 &&
23533       (VT == MVT::i32 || VT == MVT::i64)) {
23534     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
23535     SDValue R = DAG.getNode(X86ISD::UDIVREM8_ZEXT_HREG, dl, NodeTys,
23536                             N0.getOperand(0), N0.getOperand(1));
23537     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
23538     return R.getValue(1);
23539   }
23540
23541   return SDValue();
23542 }
23543
23544 // Optimize x == -y --> x+y == 0
23545 //          x != -y --> x+y != 0
23546 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
23547                                       const X86Subtarget* Subtarget) {
23548   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
23549   SDValue LHS = N->getOperand(0);
23550   SDValue RHS = N->getOperand(1);
23551   EVT VT = N->getValueType(0);
23552   SDLoc DL(N);
23553
23554   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
23555     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
23556       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
23557         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N), LHS.getValueType(), RHS,
23558                                    LHS.getOperand(1));
23559         return DAG.getSetCC(SDLoc(N), N->getValueType(0), addV,
23560                             DAG.getConstant(0, addV.getValueType()), CC);
23561       }
23562   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
23563     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
23564       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
23565         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N), RHS.getValueType(), LHS,
23566                                    RHS.getOperand(1));
23567         return DAG.getSetCC(SDLoc(N), N->getValueType(0), addV,
23568                             DAG.getConstant(0, addV.getValueType()), CC);
23569       }
23570
23571   if (VT.getScalarType() == MVT::i1 &&
23572       (CC == ISD::SETNE || CC == ISD::SETEQ || ISD::isSignedIntSetCC(CC))) {
23573     bool IsSEXT0 =
23574         (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
23575         (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
23576     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
23577
23578     if (!IsSEXT0 || !IsVZero1) {
23579       // Swap the operands and update the condition code.
23580       std::swap(LHS, RHS);
23581       CC = ISD::getSetCCSwappedOperands(CC);
23582
23583       IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
23584                 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
23585       IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
23586     }
23587
23588     if (IsSEXT0 && IsVZero1) {
23589       assert(VT == LHS.getOperand(0).getValueType() &&
23590              "Uexpected operand type");
23591       if (CC == ISD::SETGT)
23592         return DAG.getConstant(0, VT);
23593       if (CC == ISD::SETLE)
23594         return DAG.getConstant(1, VT);
23595       if (CC == ISD::SETEQ || CC == ISD::SETGE)
23596         return DAG.getNOT(DL, LHS.getOperand(0), VT);
23597
23598       assert((CC == ISD::SETNE || CC == ISD::SETLT) &&
23599              "Unexpected condition code!");
23600       return LHS.getOperand(0);
23601     }
23602   }
23603
23604   return SDValue();
23605 }
23606
23607 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
23608                                          SelectionDAG &DAG) {
23609   SDLoc dl(Load);
23610   MVT VT = Load->getSimpleValueType(0);
23611   MVT EVT = VT.getVectorElementType();
23612   SDValue Addr = Load->getOperand(1);
23613   SDValue NewAddr = DAG.getNode(
23614       ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
23615       DAG.getConstant(Index * EVT.getStoreSize(), Addr.getSimpleValueType()));
23616
23617   SDValue NewLoad =
23618       DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
23619                   DAG.getMachineFunction().getMachineMemOperand(
23620                       Load->getMemOperand(), 0, EVT.getStoreSize()));
23621   return NewLoad;
23622 }
23623
23624 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
23625                                       const X86Subtarget *Subtarget) {
23626   SDLoc dl(N);
23627   MVT VT = N->getOperand(1)->getSimpleValueType(0);
23628   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
23629          "X86insertps is only defined for v4x32");
23630
23631   SDValue Ld = N->getOperand(1);
23632   if (MayFoldLoad(Ld)) {
23633     // Extract the countS bits from the immediate so we can get the proper
23634     // address when narrowing the vector load to a specific element.
23635     // When the second source op is a memory address, insertps doesn't use
23636     // countS and just gets an f32 from that address.
23637     unsigned DestIndex =
23638         cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
23639
23640     Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
23641
23642     // Create this as a scalar to vector to match the instruction pattern.
23643     SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
23644     // countS bits are ignored when loading from memory on insertps, which
23645     // means we don't need to explicitly set them to 0.
23646     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
23647                        LoadScalarToVector, N->getOperand(2));
23648   }
23649   return SDValue();
23650 }
23651
23652 static SDValue PerformBLENDICombine(SDNode *N, SelectionDAG &DAG) {
23653   SDValue V0 = N->getOperand(0);
23654   SDValue V1 = N->getOperand(1);
23655   SDLoc DL(N);
23656   EVT VT = N->getValueType(0);
23657
23658   // Canonicalize a v2f64 blend with a mask of 2 by swapping the vector
23659   // operands and changing the mask to 1. This saves us a bunch of
23660   // pattern-matching possibilities related to scalar math ops in SSE/AVX.
23661   // x86InstrInfo knows how to commute this back after instruction selection
23662   // if it would help register allocation.
23663
23664   // TODO: If optimizing for size or a processor that doesn't suffer from
23665   // partial register update stalls, this should be transformed into a MOVSD
23666   // instruction because a MOVSD is 1-2 bytes smaller than a BLENDPD.
23667
23668   if (VT == MVT::v2f64)
23669     if (auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(2)))
23670       if (Mask->getZExtValue() == 2 && !isShuffleFoldableLoad(V0)) {
23671         SDValue NewMask = DAG.getConstant(1, MVT::i8);
23672         return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V0, NewMask);
23673       }
23674
23675   return SDValue();
23676 }
23677
23678 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
23679 // as "sbb reg,reg", since it can be extended without zext and produces
23680 // an all-ones bit which is more useful than 0/1 in some cases.
23681 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
23682                                MVT VT) {
23683   if (VT == MVT::i8)
23684     return DAG.getNode(ISD::AND, DL, VT,
23685                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
23686                                    DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
23687                        DAG.getConstant(1, VT));
23688   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
23689   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
23690                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
23691                                  DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
23692 }
23693
23694 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
23695 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
23696                                    TargetLowering::DAGCombinerInfo &DCI,
23697                                    const X86Subtarget *Subtarget) {
23698   SDLoc DL(N);
23699   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
23700   SDValue EFLAGS = N->getOperand(1);
23701
23702   if (CC == X86::COND_A) {
23703     // Try to convert COND_A into COND_B in an attempt to facilitate
23704     // materializing "setb reg".
23705     //
23706     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
23707     // cannot take an immediate as its first operand.
23708     //
23709     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
23710         EFLAGS.getValueType().isInteger() &&
23711         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
23712       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
23713                                    EFLAGS.getNode()->getVTList(),
23714                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
23715       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
23716       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
23717     }
23718   }
23719
23720   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
23721   // a zext and produces an all-ones bit which is more useful than 0/1 in some
23722   // cases.
23723   if (CC == X86::COND_B)
23724     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
23725
23726   SDValue Flags;
23727
23728   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
23729   if (Flags.getNode()) {
23730     SDValue Cond = DAG.getConstant(CC, MVT::i8);
23731     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
23732   }
23733
23734   return SDValue();
23735 }
23736
23737 // Optimize branch condition evaluation.
23738 //
23739 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
23740                                     TargetLowering::DAGCombinerInfo &DCI,
23741                                     const X86Subtarget *Subtarget) {
23742   SDLoc DL(N);
23743   SDValue Chain = N->getOperand(0);
23744   SDValue Dest = N->getOperand(1);
23745   SDValue EFLAGS = N->getOperand(3);
23746   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
23747
23748   SDValue Flags;
23749
23750   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
23751   if (Flags.getNode()) {
23752     SDValue Cond = DAG.getConstant(CC, MVT::i8);
23753     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
23754                        Flags);
23755   }
23756
23757   return SDValue();
23758 }
23759
23760 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
23761                                                          SelectionDAG &DAG) {
23762   // Take advantage of vector comparisons producing 0 or -1 in each lane to
23763   // optimize away operation when it's from a constant.
23764   //
23765   // The general transformation is:
23766   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
23767   //       AND(VECTOR_CMP(x,y), constant2)
23768   //    constant2 = UNARYOP(constant)
23769
23770   // Early exit if this isn't a vector operation, the operand of the
23771   // unary operation isn't a bitwise AND, or if the sizes of the operations
23772   // aren't the same.
23773   EVT VT = N->getValueType(0);
23774   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
23775       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
23776       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
23777     return SDValue();
23778
23779   // Now check that the other operand of the AND is a constant. We could
23780   // make the transformation for non-constant splats as well, but it's unclear
23781   // that would be a benefit as it would not eliminate any operations, just
23782   // perform one more step in scalar code before moving to the vector unit.
23783   if (BuildVectorSDNode *BV =
23784           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
23785     // Bail out if the vector isn't a constant.
23786     if (!BV->isConstant())
23787       return SDValue();
23788
23789     // Everything checks out. Build up the new and improved node.
23790     SDLoc DL(N);
23791     EVT IntVT = BV->getValueType(0);
23792     // Create a new constant of the appropriate type for the transformed
23793     // DAG.
23794     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
23795     // The AND node needs bitcasts to/from an integer vector type around it.
23796     SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
23797     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
23798                                  N->getOperand(0)->getOperand(0), MaskConst);
23799     SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
23800     return Res;
23801   }
23802
23803   return SDValue();
23804 }
23805
23806 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
23807                                         const X86Subtarget *Subtarget) {
23808   // First try to optimize away the conversion entirely when it's
23809   // conditionally from a constant. Vectors only.
23810   SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG);
23811   if (Res != SDValue())
23812     return Res;
23813
23814   // Now move on to more general possibilities.
23815   SDValue Op0 = N->getOperand(0);
23816   EVT InVT = Op0->getValueType(0);
23817
23818   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
23819   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
23820     SDLoc dl(N);
23821     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
23822     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
23823     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
23824   }
23825
23826   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
23827   // a 32-bit target where SSE doesn't support i64->FP operations.
23828   if (Op0.getOpcode() == ISD::LOAD) {
23829     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
23830     EVT VT = Ld->getValueType(0);
23831     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
23832         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
23833         !Subtarget->is64Bit() && VT == MVT::i64) {
23834       SDValue FILDChain = Subtarget->getTargetLowering()->BuildFILD(
23835           SDValue(N, 0), Ld->getValueType(0), Ld->getChain(), Op0, DAG);
23836       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
23837       return FILDChain;
23838     }
23839   }
23840   return SDValue();
23841 }
23842
23843 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
23844 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
23845                                  X86TargetLowering::DAGCombinerInfo &DCI) {
23846   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
23847   // the result is either zero or one (depending on the input carry bit).
23848   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
23849   if (X86::isZeroNode(N->getOperand(0)) &&
23850       X86::isZeroNode(N->getOperand(1)) &&
23851       // We don't have a good way to replace an EFLAGS use, so only do this when
23852       // dead right now.
23853       SDValue(N, 1).use_empty()) {
23854     SDLoc DL(N);
23855     EVT VT = N->getValueType(0);
23856     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
23857     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
23858                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
23859                                            DAG.getConstant(X86::COND_B,MVT::i8),
23860                                            N->getOperand(2)),
23861                                DAG.getConstant(1, VT));
23862     return DCI.CombineTo(N, Res1, CarryOut);
23863   }
23864
23865   return SDValue();
23866 }
23867
23868 // fold (add Y, (sete  X, 0)) -> adc  0, Y
23869 //      (add Y, (setne X, 0)) -> sbb -1, Y
23870 //      (sub (sete  X, 0), Y) -> sbb  0, Y
23871 //      (sub (setne X, 0), Y) -> adc -1, Y
23872 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
23873   SDLoc DL(N);
23874
23875   // Look through ZExts.
23876   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
23877   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
23878     return SDValue();
23879
23880   SDValue SetCC = Ext.getOperand(0);
23881   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
23882     return SDValue();
23883
23884   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
23885   if (CC != X86::COND_E && CC != X86::COND_NE)
23886     return SDValue();
23887
23888   SDValue Cmp = SetCC.getOperand(1);
23889   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
23890       !X86::isZeroNode(Cmp.getOperand(1)) ||
23891       !Cmp.getOperand(0).getValueType().isInteger())
23892     return SDValue();
23893
23894   SDValue CmpOp0 = Cmp.getOperand(0);
23895   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
23896                                DAG.getConstant(1, CmpOp0.getValueType()));
23897
23898   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
23899   if (CC == X86::COND_NE)
23900     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
23901                        DL, OtherVal.getValueType(), OtherVal,
23902                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
23903   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
23904                      DL, OtherVal.getValueType(), OtherVal,
23905                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
23906 }
23907
23908 /// PerformADDCombine - Do target-specific dag combines on integer adds.
23909 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
23910                                  const X86Subtarget *Subtarget) {
23911   EVT VT = N->getValueType(0);
23912   SDValue Op0 = N->getOperand(0);
23913   SDValue Op1 = N->getOperand(1);
23914
23915   // Try to synthesize horizontal adds from adds of shuffles.
23916   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
23917        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
23918       isHorizontalBinOp(Op0, Op1, true))
23919     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
23920
23921   return OptimizeConditionalInDecrement(N, DAG);
23922 }
23923
23924 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
23925                                  const X86Subtarget *Subtarget) {
23926   SDValue Op0 = N->getOperand(0);
23927   SDValue Op1 = N->getOperand(1);
23928
23929   // X86 can't encode an immediate LHS of a sub. See if we can push the
23930   // negation into a preceding instruction.
23931   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
23932     // If the RHS of the sub is a XOR with one use and a constant, invert the
23933     // immediate. Then add one to the LHS of the sub so we can turn
23934     // X-Y -> X+~Y+1, saving one register.
23935     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
23936         isa<ConstantSDNode>(Op1.getOperand(1))) {
23937       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
23938       EVT VT = Op0.getValueType();
23939       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
23940                                    Op1.getOperand(0),
23941                                    DAG.getConstant(~XorC, VT));
23942       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
23943                          DAG.getConstant(C->getAPIntValue()+1, VT));
23944     }
23945   }
23946
23947   // Try to synthesize horizontal adds from adds of shuffles.
23948   EVT VT = N->getValueType(0);
23949   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
23950        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
23951       isHorizontalBinOp(Op0, Op1, true))
23952     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
23953
23954   return OptimizeConditionalInDecrement(N, DAG);
23955 }
23956
23957 /// performVZEXTCombine - Performs build vector combines
23958 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
23959                                    TargetLowering::DAGCombinerInfo &DCI,
23960                                    const X86Subtarget *Subtarget) {
23961   SDLoc DL(N);
23962   MVT VT = N->getSimpleValueType(0);
23963   SDValue Op = N->getOperand(0);
23964   MVT OpVT = Op.getSimpleValueType();
23965   MVT OpEltVT = OpVT.getVectorElementType();
23966   unsigned InputBits = OpEltVT.getSizeInBits() * VT.getVectorNumElements();
23967
23968   // (vzext (bitcast (vzext (x)) -> (vzext x)
23969   SDValue V = Op;
23970   while (V.getOpcode() == ISD::BITCAST)
23971     V = V.getOperand(0);
23972
23973   if (V != Op && V.getOpcode() == X86ISD::VZEXT) {
23974     MVT InnerVT = V.getSimpleValueType();
23975     MVT InnerEltVT = InnerVT.getVectorElementType();
23976
23977     // If the element sizes match exactly, we can just do one larger vzext. This
23978     // is always an exact type match as vzext operates on integer types.
23979     if (OpEltVT == InnerEltVT) {
23980       assert(OpVT == InnerVT && "Types must match for vzext!");
23981       return DAG.getNode(X86ISD::VZEXT, DL, VT, V.getOperand(0));
23982     }
23983
23984     // The only other way we can combine them is if only a single element of the
23985     // inner vzext is used in the input to the outer vzext.
23986     if (InnerEltVT.getSizeInBits() < InputBits)
23987       return SDValue();
23988
23989     // In this case, the inner vzext is completely dead because we're going to
23990     // only look at bits inside of the low element. Just do the outer vzext on
23991     // a bitcast of the input to the inner.
23992     return DAG.getNode(X86ISD::VZEXT, DL, VT,
23993                        DAG.getNode(ISD::BITCAST, DL, OpVT, V));
23994   }
23995
23996   // Check if we can bypass extracting and re-inserting an element of an input
23997   // vector. Essentialy:
23998   // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
23999   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR &&
24000       V.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
24001       V.getOperand(0).getSimpleValueType().getSizeInBits() == InputBits) {
24002     SDValue ExtractedV = V.getOperand(0);
24003     SDValue OrigV = ExtractedV.getOperand(0);
24004     if (auto *ExtractIdx = dyn_cast<ConstantSDNode>(ExtractedV.getOperand(1)))
24005       if (ExtractIdx->getZExtValue() == 0) {
24006         MVT OrigVT = OrigV.getSimpleValueType();
24007         // Extract a subvector if necessary...
24008         if (OrigVT.getSizeInBits() > OpVT.getSizeInBits()) {
24009           int Ratio = OrigVT.getSizeInBits() / OpVT.getSizeInBits();
24010           OrigVT = MVT::getVectorVT(OrigVT.getVectorElementType(),
24011                                     OrigVT.getVectorNumElements() / Ratio);
24012           OrigV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigVT, OrigV,
24013                               DAG.getIntPtrConstant(0));
24014         }
24015         Op = DAG.getNode(ISD::BITCAST, DL, OpVT, OrigV);
24016         return DAG.getNode(X86ISD::VZEXT, DL, VT, Op);
24017       }
24018   }
24019
24020   return SDValue();
24021 }
24022
24023 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
24024                                              DAGCombinerInfo &DCI) const {
24025   SelectionDAG &DAG = DCI.DAG;
24026   switch (N->getOpcode()) {
24027   default: break;
24028   case ISD::EXTRACT_VECTOR_ELT:
24029     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
24030   case ISD::VSELECT:
24031   case ISD::SELECT:
24032   case X86ISD::SHRUNKBLEND:
24033     return PerformSELECTCombine(N, DAG, DCI, Subtarget);
24034   case ISD::BITCAST:        return PerformBITCASTCombine(N, DAG);
24035   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
24036   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
24037   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
24038   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
24039   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
24040   case ISD::SHL:
24041   case ISD::SRA:
24042   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
24043   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
24044   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
24045   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
24046   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
24047   case ISD::MLOAD:          return PerformMLOADCombine(N, DAG, DCI, Subtarget);
24048   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
24049   case ISD::MSTORE:         return PerformMSTORECombine(N, DAG, Subtarget);
24050   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, Subtarget);
24051   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
24052   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
24053   case X86ISD::FXOR:
24054   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
24055   case X86ISD::FMIN:
24056   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
24057   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
24058   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
24059   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
24060   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
24061   case ISD::ANY_EXTEND:
24062   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
24063   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
24064   case ISD::SIGN_EXTEND_INREG:
24065     return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
24066   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG,DCI,Subtarget);
24067   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
24068   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
24069   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
24070   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
24071   case X86ISD::SHUFP:       // Handle all target specific shuffles
24072   case X86ISD::PALIGNR:
24073   case X86ISD::UNPCKH:
24074   case X86ISD::UNPCKL:
24075   case X86ISD::MOVHLPS:
24076   case X86ISD::MOVLHPS:
24077   case X86ISD::PSHUFB:
24078   case X86ISD::PSHUFD:
24079   case X86ISD::PSHUFHW:
24080   case X86ISD::PSHUFLW:
24081   case X86ISD::MOVSS:
24082   case X86ISD::MOVSD:
24083   case X86ISD::VPERMILPI:
24084   case X86ISD::VPERM2X128:
24085   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
24086   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
24087   case ISD::INTRINSIC_WO_CHAIN:
24088     return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
24089   case X86ISD::INSERTPS: {
24090     if (getTargetMachine().getOptLevel() > CodeGenOpt::None)
24091       return PerformINSERTPSCombine(N, DAG, Subtarget);
24092     break;
24093   }
24094   case X86ISD::BLENDI:    return PerformBLENDICombine(N, DAG);
24095   }
24096
24097   return SDValue();
24098 }
24099
24100 /// isTypeDesirableForOp - Return true if the target has native support for
24101 /// the specified value type and it is 'desirable' to use the type for the
24102 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
24103 /// instruction encodings are longer and some i16 instructions are slow.
24104 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
24105   if (!isTypeLegal(VT))
24106     return false;
24107   if (VT != MVT::i16)
24108     return true;
24109
24110   switch (Opc) {
24111   default:
24112     return true;
24113   case ISD::LOAD:
24114   case ISD::SIGN_EXTEND:
24115   case ISD::ZERO_EXTEND:
24116   case ISD::ANY_EXTEND:
24117   case ISD::SHL:
24118   case ISD::SRL:
24119   case ISD::SUB:
24120   case ISD::ADD:
24121   case ISD::MUL:
24122   case ISD::AND:
24123   case ISD::OR:
24124   case ISD::XOR:
24125     return false;
24126   }
24127 }
24128
24129 /// IsDesirableToPromoteOp - This method query the target whether it is
24130 /// beneficial for dag combiner to promote the specified node. If true, it
24131 /// should return the desired promotion type by reference.
24132 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
24133   EVT VT = Op.getValueType();
24134   if (VT != MVT::i16)
24135     return false;
24136
24137   bool Promote = false;
24138   bool Commute = false;
24139   switch (Op.getOpcode()) {
24140   default: break;
24141   case ISD::LOAD: {
24142     LoadSDNode *LD = cast<LoadSDNode>(Op);
24143     // If the non-extending load has a single use and it's not live out, then it
24144     // might be folded.
24145     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
24146                                                      Op.hasOneUse()*/) {
24147       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
24148              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
24149         // The only case where we'd want to promote LOAD (rather then it being
24150         // promoted as an operand is when it's only use is liveout.
24151         if (UI->getOpcode() != ISD::CopyToReg)
24152           return false;
24153       }
24154     }
24155     Promote = true;
24156     break;
24157   }
24158   case ISD::SIGN_EXTEND:
24159   case ISD::ZERO_EXTEND:
24160   case ISD::ANY_EXTEND:
24161     Promote = true;
24162     break;
24163   case ISD::SHL:
24164   case ISD::SRL: {
24165     SDValue N0 = Op.getOperand(0);
24166     // Look out for (store (shl (load), x)).
24167     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
24168       return false;
24169     Promote = true;
24170     break;
24171   }
24172   case ISD::ADD:
24173   case ISD::MUL:
24174   case ISD::AND:
24175   case ISD::OR:
24176   case ISD::XOR:
24177     Commute = true;
24178     // fallthrough
24179   case ISD::SUB: {
24180     SDValue N0 = Op.getOperand(0);
24181     SDValue N1 = Op.getOperand(1);
24182     if (!Commute && MayFoldLoad(N1))
24183       return false;
24184     // Avoid disabling potential load folding opportunities.
24185     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
24186       return false;
24187     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
24188       return false;
24189     Promote = true;
24190   }
24191   }
24192
24193   PVT = MVT::i32;
24194   return Promote;
24195 }
24196
24197 //===----------------------------------------------------------------------===//
24198 //                           X86 Inline Assembly Support
24199 //===----------------------------------------------------------------------===//
24200
24201 // Helper to match a string separated by whitespace.
24202 static bool matchAsm(StringRef S, ArrayRef<const char *> Pieces) {
24203   S = S.substr(S.find_first_not_of(" \t")); // Skip leading whitespace.
24204
24205   for (StringRef Piece : Pieces) {
24206     if (!S.startswith(Piece)) // Check if the piece matches.
24207       return false;
24208
24209     S = S.substr(Piece.size());
24210     StringRef::size_type Pos = S.find_first_not_of(" \t");
24211     if (Pos == 0) // We matched a prefix.
24212       return false;
24213
24214     S = S.substr(Pos);
24215   }
24216
24217   return S.empty();
24218 }
24219
24220 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
24221
24222   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
24223     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
24224         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
24225         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
24226
24227       if (AsmPieces.size() == 3)
24228         return true;
24229       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
24230         return true;
24231     }
24232   }
24233   return false;
24234 }
24235
24236 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
24237   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
24238
24239   std::string AsmStr = IA->getAsmString();
24240
24241   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
24242   if (!Ty || Ty->getBitWidth() % 16 != 0)
24243     return false;
24244
24245   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
24246   SmallVector<StringRef, 4> AsmPieces;
24247   SplitString(AsmStr, AsmPieces, ";\n");
24248
24249   switch (AsmPieces.size()) {
24250   default: return false;
24251   case 1:
24252     // FIXME: this should verify that we are targeting a 486 or better.  If not,
24253     // we will turn this bswap into something that will be lowered to logical
24254     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
24255     // lower so don't worry about this.
24256     // bswap $0
24257     if (matchAsm(AsmPieces[0], {"bswap", "$0"}) ||
24258         matchAsm(AsmPieces[0], {"bswapl", "$0"}) ||
24259         matchAsm(AsmPieces[0], {"bswapq", "$0"}) ||
24260         matchAsm(AsmPieces[0], {"bswap", "${0:q}"}) ||
24261         matchAsm(AsmPieces[0], {"bswapl", "${0:q}"}) ||
24262         matchAsm(AsmPieces[0], {"bswapq", "${0:q}"})) {
24263       // No need to check constraints, nothing other than the equivalent of
24264       // "=r,0" would be valid here.
24265       return IntrinsicLowering::LowerToByteSwap(CI);
24266     }
24267
24268     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
24269     if (CI->getType()->isIntegerTy(16) &&
24270         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
24271         (matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) ||
24272          matchAsm(AsmPieces[0], {"rolw", "$$8,", "${0:w}"}))) {
24273       AsmPieces.clear();
24274       const std::string &ConstraintsStr = IA->getConstraintString();
24275       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
24276       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
24277       if (clobbersFlagRegisters(AsmPieces))
24278         return IntrinsicLowering::LowerToByteSwap(CI);
24279     }
24280     break;
24281   case 3:
24282     if (CI->getType()->isIntegerTy(32) &&
24283         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
24284         matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) &&
24285         matchAsm(AsmPieces[1], {"rorl", "$$16,", "$0"}) &&
24286         matchAsm(AsmPieces[2], {"rorw", "$$8,", "${0:w}"})) {
24287       AsmPieces.clear();
24288       const std::string &ConstraintsStr = IA->getConstraintString();
24289       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
24290       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
24291       if (clobbersFlagRegisters(AsmPieces))
24292         return IntrinsicLowering::LowerToByteSwap(CI);
24293     }
24294
24295     if (CI->getType()->isIntegerTy(64)) {
24296       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
24297       if (Constraints.size() >= 2 &&
24298           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
24299           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
24300         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
24301         if (matchAsm(AsmPieces[0], {"bswap", "%eax"}) &&
24302             matchAsm(AsmPieces[1], {"bswap", "%edx"}) &&
24303             matchAsm(AsmPieces[2], {"xchgl", "%eax,", "%edx"}))
24304           return IntrinsicLowering::LowerToByteSwap(CI);
24305       }
24306     }
24307     break;
24308   }
24309   return false;
24310 }
24311
24312 /// getConstraintType - Given a constraint letter, return the type of
24313 /// constraint it is for this target.
24314 X86TargetLowering::ConstraintType
24315 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
24316   if (Constraint.size() == 1) {
24317     switch (Constraint[0]) {
24318     case 'R':
24319     case 'q':
24320     case 'Q':
24321     case 'f':
24322     case 't':
24323     case 'u':
24324     case 'y':
24325     case 'x':
24326     case 'Y':
24327     case 'l':
24328       return C_RegisterClass;
24329     case 'a':
24330     case 'b':
24331     case 'c':
24332     case 'd':
24333     case 'S':
24334     case 'D':
24335     case 'A':
24336       return C_Register;
24337     case 'I':
24338     case 'J':
24339     case 'K':
24340     case 'L':
24341     case 'M':
24342     case 'N':
24343     case 'G':
24344     case 'C':
24345     case 'e':
24346     case 'Z':
24347       return C_Other;
24348     default:
24349       break;
24350     }
24351   }
24352   return TargetLowering::getConstraintType(Constraint);
24353 }
24354
24355 /// Examine constraint type and operand type and determine a weight value.
24356 /// This object must already have been set up with the operand type
24357 /// and the current alternative constraint selected.
24358 TargetLowering::ConstraintWeight
24359   X86TargetLowering::getSingleConstraintMatchWeight(
24360     AsmOperandInfo &info, const char *constraint) const {
24361   ConstraintWeight weight = CW_Invalid;
24362   Value *CallOperandVal = info.CallOperandVal;
24363     // If we don't have a value, we can't do a match,
24364     // but allow it at the lowest weight.
24365   if (!CallOperandVal)
24366     return CW_Default;
24367   Type *type = CallOperandVal->getType();
24368   // Look at the constraint type.
24369   switch (*constraint) {
24370   default:
24371     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
24372   case 'R':
24373   case 'q':
24374   case 'Q':
24375   case 'a':
24376   case 'b':
24377   case 'c':
24378   case 'd':
24379   case 'S':
24380   case 'D':
24381   case 'A':
24382     if (CallOperandVal->getType()->isIntegerTy())
24383       weight = CW_SpecificReg;
24384     break;
24385   case 'f':
24386   case 't':
24387   case 'u':
24388     if (type->isFloatingPointTy())
24389       weight = CW_SpecificReg;
24390     break;
24391   case 'y':
24392     if (type->isX86_MMXTy() && Subtarget->hasMMX())
24393       weight = CW_SpecificReg;
24394     break;
24395   case 'x':
24396   case 'Y':
24397     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
24398         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
24399       weight = CW_Register;
24400     break;
24401   case 'I':
24402     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
24403       if (C->getZExtValue() <= 31)
24404         weight = CW_Constant;
24405     }
24406     break;
24407   case 'J':
24408     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24409       if (C->getZExtValue() <= 63)
24410         weight = CW_Constant;
24411     }
24412     break;
24413   case 'K':
24414     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24415       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
24416         weight = CW_Constant;
24417     }
24418     break;
24419   case 'L':
24420     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24421       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
24422         weight = CW_Constant;
24423     }
24424     break;
24425   case 'M':
24426     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24427       if (C->getZExtValue() <= 3)
24428         weight = CW_Constant;
24429     }
24430     break;
24431   case 'N':
24432     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24433       if (C->getZExtValue() <= 0xff)
24434         weight = CW_Constant;
24435     }
24436     break;
24437   case 'G':
24438   case 'C':
24439     if (isa<ConstantFP>(CallOperandVal)) {
24440       weight = CW_Constant;
24441     }
24442     break;
24443   case 'e':
24444     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24445       if ((C->getSExtValue() >= -0x80000000LL) &&
24446           (C->getSExtValue() <= 0x7fffffffLL))
24447         weight = CW_Constant;
24448     }
24449     break;
24450   case 'Z':
24451     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24452       if (C->getZExtValue() <= 0xffffffff)
24453         weight = CW_Constant;
24454     }
24455     break;
24456   }
24457   return weight;
24458 }
24459
24460 /// LowerXConstraint - try to replace an X constraint, which matches anything,
24461 /// with another that has more specific requirements based on the type of the
24462 /// corresponding operand.
24463 const char *X86TargetLowering::
24464 LowerXConstraint(EVT ConstraintVT) const {
24465   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
24466   // 'f' like normal targets.
24467   if (ConstraintVT.isFloatingPoint()) {
24468     if (Subtarget->hasSSE2())
24469       return "Y";
24470     if (Subtarget->hasSSE1())
24471       return "x";
24472   }
24473
24474   return TargetLowering::LowerXConstraint(ConstraintVT);
24475 }
24476
24477 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
24478 /// vector.  If it is invalid, don't add anything to Ops.
24479 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
24480                                                      std::string &Constraint,
24481                                                      std::vector<SDValue>&Ops,
24482                                                      SelectionDAG &DAG) const {
24483   SDValue Result;
24484
24485   // Only support length 1 constraints for now.
24486   if (Constraint.length() > 1) return;
24487
24488   char ConstraintLetter = Constraint[0];
24489   switch (ConstraintLetter) {
24490   default: break;
24491   case 'I':
24492     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24493       if (C->getZExtValue() <= 31) {
24494         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
24495         break;
24496       }
24497     }
24498     return;
24499   case 'J':
24500     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24501       if (C->getZExtValue() <= 63) {
24502         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
24503         break;
24504       }
24505     }
24506     return;
24507   case 'K':
24508     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24509       if (isInt<8>(C->getSExtValue())) {
24510         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
24511         break;
24512       }
24513     }
24514     return;
24515   case 'L':
24516     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24517       if (C->getZExtValue() == 0xff || C->getZExtValue() == 0xffff ||
24518           (Subtarget->is64Bit() && C->getZExtValue() == 0xffffffff)) {
24519         Result = DAG.getTargetConstant(C->getSExtValue(), Op.getValueType());
24520         break;
24521       }
24522     }
24523     return;
24524   case 'M':
24525     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24526       if (C->getZExtValue() <= 3) {
24527         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
24528         break;
24529       }
24530     }
24531     return;
24532   case 'N':
24533     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24534       if (C->getZExtValue() <= 255) {
24535         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
24536         break;
24537       }
24538     }
24539     return;
24540   case 'O':
24541     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24542       if (C->getZExtValue() <= 127) {
24543         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
24544         break;
24545       }
24546     }
24547     return;
24548   case 'e': {
24549     // 32-bit signed value
24550     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24551       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
24552                                            C->getSExtValue())) {
24553         // Widen to 64 bits here to get it sign extended.
24554         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
24555         break;
24556       }
24557     // FIXME gcc accepts some relocatable values here too, but only in certain
24558     // memory models; it's complicated.
24559     }
24560     return;
24561   }
24562   case 'Z': {
24563     // 32-bit unsigned value
24564     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24565       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
24566                                            C->getZExtValue())) {
24567         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
24568         break;
24569       }
24570     }
24571     // FIXME gcc accepts some relocatable values here too, but only in certain
24572     // memory models; it's complicated.
24573     return;
24574   }
24575   case 'i': {
24576     // Literal immediates are always ok.
24577     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
24578       // Widen to 64 bits here to get it sign extended.
24579       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
24580       break;
24581     }
24582
24583     // In any sort of PIC mode addresses need to be computed at runtime by
24584     // adding in a register or some sort of table lookup.  These can't
24585     // be used as immediates.
24586     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
24587       return;
24588
24589     // If we are in non-pic codegen mode, we allow the address of a global (with
24590     // an optional displacement) to be used with 'i'.
24591     GlobalAddressSDNode *GA = nullptr;
24592     int64_t Offset = 0;
24593
24594     // Match either (GA), (GA+C), (GA+C1+C2), etc.
24595     while (1) {
24596       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
24597         Offset += GA->getOffset();
24598         break;
24599       } else if (Op.getOpcode() == ISD::ADD) {
24600         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
24601           Offset += C->getZExtValue();
24602           Op = Op.getOperand(0);
24603           continue;
24604         }
24605       } else if (Op.getOpcode() == ISD::SUB) {
24606         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
24607           Offset += -C->getZExtValue();
24608           Op = Op.getOperand(0);
24609           continue;
24610         }
24611       }
24612
24613       // Otherwise, this isn't something we can handle, reject it.
24614       return;
24615     }
24616
24617     const GlobalValue *GV = GA->getGlobal();
24618     // If we require an extra load to get this address, as in PIC mode, we
24619     // can't accept it.
24620     if (isGlobalStubReference(
24621             Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
24622       return;
24623
24624     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
24625                                         GA->getValueType(0), Offset);
24626     break;
24627   }
24628   }
24629
24630   if (Result.getNode()) {
24631     Ops.push_back(Result);
24632     return;
24633   }
24634   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
24635 }
24636
24637 std::pair<unsigned, const TargetRegisterClass *>
24638 X86TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
24639                                                 const std::string &Constraint,
24640                                                 MVT VT) const {
24641   // First, see if this is a constraint that directly corresponds to an LLVM
24642   // register class.
24643   if (Constraint.size() == 1) {
24644     // GCC Constraint Letters
24645     switch (Constraint[0]) {
24646     default: break;
24647       // TODO: Slight differences here in allocation order and leaving
24648       // RIP in the class. Do they matter any more here than they do
24649       // in the normal allocation?
24650     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
24651       if (Subtarget->is64Bit()) {
24652         if (VT == MVT::i32 || VT == MVT::f32)
24653           return std::make_pair(0U, &X86::GR32RegClass);
24654         if (VT == MVT::i16)
24655           return std::make_pair(0U, &X86::GR16RegClass);
24656         if (VT == MVT::i8 || VT == MVT::i1)
24657           return std::make_pair(0U, &X86::GR8RegClass);
24658         if (VT == MVT::i64 || VT == MVT::f64)
24659           return std::make_pair(0U, &X86::GR64RegClass);
24660         break;
24661       }
24662       // 32-bit fallthrough
24663     case 'Q':   // Q_REGS
24664       if (VT == MVT::i32 || VT == MVT::f32)
24665         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
24666       if (VT == MVT::i16)
24667         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
24668       if (VT == MVT::i8 || VT == MVT::i1)
24669         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
24670       if (VT == MVT::i64)
24671         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
24672       break;
24673     case 'r':   // GENERAL_REGS
24674     case 'l':   // INDEX_REGS
24675       if (VT == MVT::i8 || VT == MVT::i1)
24676         return std::make_pair(0U, &X86::GR8RegClass);
24677       if (VT == MVT::i16)
24678         return std::make_pair(0U, &X86::GR16RegClass);
24679       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
24680         return std::make_pair(0U, &X86::GR32RegClass);
24681       return std::make_pair(0U, &X86::GR64RegClass);
24682     case 'R':   // LEGACY_REGS
24683       if (VT == MVT::i8 || VT == MVT::i1)
24684         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
24685       if (VT == MVT::i16)
24686         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
24687       if (VT == MVT::i32 || !Subtarget->is64Bit())
24688         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
24689       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
24690     case 'f':  // FP Stack registers.
24691       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
24692       // value to the correct fpstack register class.
24693       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
24694         return std::make_pair(0U, &X86::RFP32RegClass);
24695       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
24696         return std::make_pair(0U, &X86::RFP64RegClass);
24697       return std::make_pair(0U, &X86::RFP80RegClass);
24698     case 'y':   // MMX_REGS if MMX allowed.
24699       if (!Subtarget->hasMMX()) break;
24700       return std::make_pair(0U, &X86::VR64RegClass);
24701     case 'Y':   // SSE_REGS if SSE2 allowed
24702       if (!Subtarget->hasSSE2()) break;
24703       // FALL THROUGH.
24704     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
24705       if (!Subtarget->hasSSE1()) break;
24706
24707       switch (VT.SimpleTy) {
24708       default: break;
24709       // Scalar SSE types.
24710       case MVT::f32:
24711       case MVT::i32:
24712         return std::make_pair(0U, &X86::FR32RegClass);
24713       case MVT::f64:
24714       case MVT::i64:
24715         return std::make_pair(0U, &X86::FR64RegClass);
24716       // Vector types.
24717       case MVT::v16i8:
24718       case MVT::v8i16:
24719       case MVT::v4i32:
24720       case MVT::v2i64:
24721       case MVT::v4f32:
24722       case MVT::v2f64:
24723         return std::make_pair(0U, &X86::VR128RegClass);
24724       // AVX types.
24725       case MVT::v32i8:
24726       case MVT::v16i16:
24727       case MVT::v8i32:
24728       case MVT::v4i64:
24729       case MVT::v8f32:
24730       case MVT::v4f64:
24731         return std::make_pair(0U, &X86::VR256RegClass);
24732       case MVT::v8f64:
24733       case MVT::v16f32:
24734       case MVT::v16i32:
24735       case MVT::v8i64:
24736         return std::make_pair(0U, &X86::VR512RegClass);
24737       }
24738       break;
24739     }
24740   }
24741
24742   // Use the default implementation in TargetLowering to convert the register
24743   // constraint into a member of a register class.
24744   std::pair<unsigned, const TargetRegisterClass*> Res;
24745   Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
24746
24747   // Not found as a standard register?
24748   if (!Res.second) {
24749     // Map st(0) -> st(7) -> ST0
24750     if (Constraint.size() == 7 && Constraint[0] == '{' &&
24751         tolower(Constraint[1]) == 's' &&
24752         tolower(Constraint[2]) == 't' &&
24753         Constraint[3] == '(' &&
24754         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
24755         Constraint[5] == ')' &&
24756         Constraint[6] == '}') {
24757
24758       Res.first = X86::FP0+Constraint[4]-'0';
24759       Res.second = &X86::RFP80RegClass;
24760       return Res;
24761     }
24762
24763     // GCC allows "st(0)" to be called just plain "st".
24764     if (StringRef("{st}").equals_lower(Constraint)) {
24765       Res.first = X86::FP0;
24766       Res.second = &X86::RFP80RegClass;
24767       return Res;
24768     }
24769
24770     // flags -> EFLAGS
24771     if (StringRef("{flags}").equals_lower(Constraint)) {
24772       Res.first = X86::EFLAGS;
24773       Res.second = &X86::CCRRegClass;
24774       return Res;
24775     }
24776
24777     // 'A' means EAX + EDX.
24778     if (Constraint == "A") {
24779       Res.first = X86::EAX;
24780       Res.second = &X86::GR32_ADRegClass;
24781       return Res;
24782     }
24783     return Res;
24784   }
24785
24786   // Otherwise, check to see if this is a register class of the wrong value
24787   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
24788   // turn into {ax},{dx}.
24789   if (Res.second->hasType(VT))
24790     return Res;   // Correct type already, nothing to do.
24791
24792   // All of the single-register GCC register classes map their values onto
24793   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
24794   // really want an 8-bit or 32-bit register, map to the appropriate register
24795   // class and return the appropriate register.
24796   if (Res.second == &X86::GR16RegClass) {
24797     if (VT == MVT::i8 || VT == MVT::i1) {
24798       unsigned DestReg = 0;
24799       switch (Res.first) {
24800       default: break;
24801       case X86::AX: DestReg = X86::AL; break;
24802       case X86::DX: DestReg = X86::DL; break;
24803       case X86::CX: DestReg = X86::CL; break;
24804       case X86::BX: DestReg = X86::BL; break;
24805       }
24806       if (DestReg) {
24807         Res.first = DestReg;
24808         Res.second = &X86::GR8RegClass;
24809       }
24810     } else if (VT == MVT::i32 || VT == MVT::f32) {
24811       unsigned DestReg = 0;
24812       switch (Res.first) {
24813       default: break;
24814       case X86::AX: DestReg = X86::EAX; break;
24815       case X86::DX: DestReg = X86::EDX; break;
24816       case X86::CX: DestReg = X86::ECX; break;
24817       case X86::BX: DestReg = X86::EBX; break;
24818       case X86::SI: DestReg = X86::ESI; break;
24819       case X86::DI: DestReg = X86::EDI; break;
24820       case X86::BP: DestReg = X86::EBP; break;
24821       case X86::SP: DestReg = X86::ESP; break;
24822       }
24823       if (DestReg) {
24824         Res.first = DestReg;
24825         Res.second = &X86::GR32RegClass;
24826       }
24827     } else if (VT == MVT::i64 || VT == MVT::f64) {
24828       unsigned DestReg = 0;
24829       switch (Res.first) {
24830       default: break;
24831       case X86::AX: DestReg = X86::RAX; break;
24832       case X86::DX: DestReg = X86::RDX; break;
24833       case X86::CX: DestReg = X86::RCX; break;
24834       case X86::BX: DestReg = X86::RBX; break;
24835       case X86::SI: DestReg = X86::RSI; break;
24836       case X86::DI: DestReg = X86::RDI; break;
24837       case X86::BP: DestReg = X86::RBP; break;
24838       case X86::SP: DestReg = X86::RSP; break;
24839       }
24840       if (DestReg) {
24841         Res.first = DestReg;
24842         Res.second = &X86::GR64RegClass;
24843       }
24844     }
24845   } else if (Res.second == &X86::FR32RegClass ||
24846              Res.second == &X86::FR64RegClass ||
24847              Res.second == &X86::VR128RegClass ||
24848              Res.second == &X86::VR256RegClass ||
24849              Res.second == &X86::FR32XRegClass ||
24850              Res.second == &X86::FR64XRegClass ||
24851              Res.second == &X86::VR128XRegClass ||
24852              Res.second == &X86::VR256XRegClass ||
24853              Res.second == &X86::VR512RegClass) {
24854     // Handle references to XMM physical registers that got mapped into the
24855     // wrong class.  This can happen with constraints like {xmm0} where the
24856     // target independent register mapper will just pick the first match it can
24857     // find, ignoring the required type.
24858
24859     if (VT == MVT::f32 || VT == MVT::i32)
24860       Res.second = &X86::FR32RegClass;
24861     else if (VT == MVT::f64 || VT == MVT::i64)
24862       Res.second = &X86::FR64RegClass;
24863     else if (X86::VR128RegClass.hasType(VT))
24864       Res.second = &X86::VR128RegClass;
24865     else if (X86::VR256RegClass.hasType(VT))
24866       Res.second = &X86::VR256RegClass;
24867     else if (X86::VR512RegClass.hasType(VT))
24868       Res.second = &X86::VR512RegClass;
24869   }
24870
24871   return Res;
24872 }
24873
24874 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
24875                                             Type *Ty) const {
24876   // Scaling factors are not free at all.
24877   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
24878   // will take 2 allocations in the out of order engine instead of 1
24879   // for plain addressing mode, i.e. inst (reg1).
24880   // E.g.,
24881   // vaddps (%rsi,%drx), %ymm0, %ymm1
24882   // Requires two allocations (one for the load, one for the computation)
24883   // whereas:
24884   // vaddps (%rsi), %ymm0, %ymm1
24885   // Requires just 1 allocation, i.e., freeing allocations for other operations
24886   // and having less micro operations to execute.
24887   //
24888   // For some X86 architectures, this is even worse because for instance for
24889   // stores, the complex addressing mode forces the instruction to use the
24890   // "load" ports instead of the dedicated "store" port.
24891   // E.g., on Haswell:
24892   // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
24893   // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
24894   if (isLegalAddressingMode(AM, Ty))
24895     // Scale represents reg2 * scale, thus account for 1
24896     // as soon as we use a second register.
24897     return AM.Scale != 0;
24898   return -1;
24899 }
24900
24901 bool X86TargetLowering::isTargetFTOL() const {
24902   return Subtarget->isTargetKnownWindowsMSVC() && !Subtarget->is64Bit();
24903 }