[X86] Remove unused node after morphing it from shr to and.
[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 (!Subtarget->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 (!Subtarget->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 (!Subtarget->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 (Subtarget->useSoftFloat() || !Subtarget->hasF16C()) {
372     setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
373     setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
374   }
375
376   // There's never any support for operations beyond MVT::f32.
377   setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
378   setOperationAction(ISD::FP16_TO_FP, MVT::f80, Expand);
379   setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
380   setOperationAction(ISD::FP_TO_FP16, MVT::f80, Expand);
381
382   setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
383   setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
384   setLoadExtAction(ISD::EXTLOAD, MVT::f80, MVT::f16, Expand);
385   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
386   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
387   setTruncStoreAction(MVT::f80, MVT::f16, Expand);
388
389   if (Subtarget->hasPOPCNT()) {
390     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
391   } else {
392     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
393     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
394     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
395     if (Subtarget->is64Bit())
396       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
397   }
398
399   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
400
401   if (!Subtarget->hasMOVBE())
402     setOperationAction(ISD::BSWAP          , MVT::i16  , Expand);
403
404   // These should be promoted to a larger select which is supported.
405   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
406   // X86 wants to expand cmov itself.
407   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
408   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
409   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
410   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
411   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
412   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
413   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
414   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
415   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
416   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
417   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
418   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
419   if (Subtarget->is64Bit()) {
420     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
421     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
422   }
423   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
424   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
425   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
426   // support continuation, user-level threading, and etc.. As a result, no
427   // other SjLj exception interfaces are implemented and please don't build
428   // your own exception handling based on them.
429   // LLVM/Clang supports zero-cost DWARF exception handling.
430   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
431   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
432
433   // Darwin ABI issue.
434   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
435   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
436   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
437   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
438   if (Subtarget->is64Bit())
439     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
440   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
441   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
442   if (Subtarget->is64Bit()) {
443     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
444     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
445     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
446     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
447     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
448   }
449   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
450   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
451   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
452   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
453   if (Subtarget->is64Bit()) {
454     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
455     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
456     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
457   }
458
459   if (Subtarget->hasSSE1())
460     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
461
462   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
463
464   // Expand certain atomics
465   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
466     MVT VT = IntVTs[i];
467     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
468     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
469     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
470   }
471
472   if (Subtarget->hasCmpxchg16b()) {
473     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
474   }
475
476   // FIXME - use subtarget debug flags
477   if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetELF() &&
478       !Subtarget->isTargetCygMing() && !Subtarget->isTargetWin64()) {
479     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
480   }
481
482   if (Subtarget->is64Bit()) {
483     setExceptionPointerRegister(X86::RAX);
484     setExceptionSelectorRegister(X86::RDX);
485   } else {
486     setExceptionPointerRegister(X86::EAX);
487     setExceptionSelectorRegister(X86::EDX);
488   }
489   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
490   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
491
492   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
493   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
494
495   setOperationAction(ISD::TRAP, MVT::Other, Legal);
496   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
497
498   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
499   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
500   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
501   if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
502     // TargetInfo::X86_64ABIBuiltinVaList
503     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
504     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
505   } else {
506     // TargetInfo::CharPtrBuiltinVaList
507     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
508     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
509   }
510
511   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
512   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
513
514   setOperationAction(ISD::DYNAMIC_STACKALLOC, getPointerTy(), Custom);
515
516   // GC_TRANSITION_START and GC_TRANSITION_END need custom lowering.
517   setOperationAction(ISD::GC_TRANSITION_START, MVT::Other, Custom);
518   setOperationAction(ISD::GC_TRANSITION_END, MVT::Other, Custom);
519
520   if (!Subtarget->useSoftFloat() && X86ScalarSSEf64) {
521     // f32 and f64 use SSE.
522     // Set up the FP register classes.
523     addRegisterClass(MVT::f32, &X86::FR32RegClass);
524     addRegisterClass(MVT::f64, &X86::FR64RegClass);
525
526     // Use ANDPD to simulate FABS.
527     setOperationAction(ISD::FABS , MVT::f64, Custom);
528     setOperationAction(ISD::FABS , MVT::f32, Custom);
529
530     // Use XORP to simulate FNEG.
531     setOperationAction(ISD::FNEG , MVT::f64, Custom);
532     setOperationAction(ISD::FNEG , MVT::f32, Custom);
533
534     // Use ANDPD and ORPD to simulate FCOPYSIGN.
535     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
536     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
537
538     // Lower this to FGETSIGNx86 plus an AND.
539     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
540     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
541
542     // We don't support sin/cos/fmod
543     setOperationAction(ISD::FSIN   , MVT::f64, Expand);
544     setOperationAction(ISD::FCOS   , MVT::f64, Expand);
545     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
546     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
547     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
548     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
549
550     // Expand FP immediates into loads from the stack, except for the special
551     // cases we handle.
552     addLegalFPImmediate(APFloat(+0.0)); // xorpd
553     addLegalFPImmediate(APFloat(+0.0f)); // xorps
554   } else if (!Subtarget->useSoftFloat() && X86ScalarSSEf32) {
555     // Use SSE for f32, x87 for f64.
556     // Set up the FP register classes.
557     addRegisterClass(MVT::f32, &X86::FR32RegClass);
558     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
559
560     // Use ANDPS to simulate FABS.
561     setOperationAction(ISD::FABS , MVT::f32, Custom);
562
563     // Use XORP to simulate FNEG.
564     setOperationAction(ISD::FNEG , MVT::f32, Custom);
565
566     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
567
568     // Use ANDPS and ORPS to simulate FCOPYSIGN.
569     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
570     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
571
572     // We don't support sin/cos/fmod
573     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
574     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
575     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
576
577     // Special cases we handle for FP constants.
578     addLegalFPImmediate(APFloat(+0.0f)); // xorps
579     addLegalFPImmediate(APFloat(+0.0)); // FLD0
580     addLegalFPImmediate(APFloat(+1.0)); // FLD1
581     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
582     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
583
584     if (!TM.Options.UnsafeFPMath) {
585       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
586       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
587       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
588     }
589   } else if (!Subtarget->useSoftFloat()) {
590     // f32 and f64 in x87.
591     // Set up the FP register classes.
592     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
593     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
594
595     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
596     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
597     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
598     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
599
600     if (!TM.Options.UnsafeFPMath) {
601       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
602       setOperationAction(ISD::FSIN   , MVT::f32, Expand);
603       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
604       setOperationAction(ISD::FCOS   , MVT::f32, Expand);
605       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
606       setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
607     }
608     addLegalFPImmediate(APFloat(+0.0)); // FLD0
609     addLegalFPImmediate(APFloat(+1.0)); // FLD1
610     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
611     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
612     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
613     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
614     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
615     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
616   }
617
618   // We don't support FMA.
619   setOperationAction(ISD::FMA, MVT::f64, Expand);
620   setOperationAction(ISD::FMA, MVT::f32, Expand);
621
622   // Long double always uses X87.
623   if (!Subtarget->useSoftFloat()) {
624     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
625     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
626     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
627     {
628       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
629       addLegalFPImmediate(TmpFlt);  // FLD0
630       TmpFlt.changeSign();
631       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
632
633       bool ignored;
634       APFloat TmpFlt2(+1.0);
635       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
636                       &ignored);
637       addLegalFPImmediate(TmpFlt2);  // FLD1
638       TmpFlt2.changeSign();
639       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
640     }
641
642     if (!TM.Options.UnsafeFPMath) {
643       setOperationAction(ISD::FSIN   , MVT::f80, Expand);
644       setOperationAction(ISD::FCOS   , MVT::f80, Expand);
645       setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
646     }
647
648     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
649     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
650     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
651     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
652     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
653     setOperationAction(ISD::FMA, MVT::f80, Expand);
654   }
655
656   // Always use a library call for pow.
657   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
658   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
659   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
660
661   setOperationAction(ISD::FLOG, MVT::f80, Expand);
662   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
663   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
664   setOperationAction(ISD::FEXP, MVT::f80, Expand);
665   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
666   setOperationAction(ISD::FMINNUM, MVT::f80, Expand);
667   setOperationAction(ISD::FMAXNUM, MVT::f80, Expand);
668
669   // First set operation action for all vector types to either promote
670   // (for widening) or expand (for scalarization). Then we will selectively
671   // turn on ones that can be effectively codegen'd.
672   for (MVT VT : MVT::vector_valuetypes()) {
673     setOperationAction(ISD::ADD , VT, Expand);
674     setOperationAction(ISD::SUB , VT, Expand);
675     setOperationAction(ISD::FADD, VT, Expand);
676     setOperationAction(ISD::FNEG, VT, Expand);
677     setOperationAction(ISD::FSUB, VT, Expand);
678     setOperationAction(ISD::MUL , VT, Expand);
679     setOperationAction(ISD::FMUL, VT, Expand);
680     setOperationAction(ISD::SDIV, VT, Expand);
681     setOperationAction(ISD::UDIV, VT, Expand);
682     setOperationAction(ISD::FDIV, VT, Expand);
683     setOperationAction(ISD::SREM, VT, Expand);
684     setOperationAction(ISD::UREM, VT, Expand);
685     setOperationAction(ISD::LOAD, VT, Expand);
686     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
687     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
688     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
689     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
690     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
691     setOperationAction(ISD::FABS, VT, Expand);
692     setOperationAction(ISD::FSIN, VT, Expand);
693     setOperationAction(ISD::FSINCOS, VT, Expand);
694     setOperationAction(ISD::FCOS, VT, Expand);
695     setOperationAction(ISD::FSINCOS, VT, Expand);
696     setOperationAction(ISD::FREM, VT, Expand);
697     setOperationAction(ISD::FMA,  VT, Expand);
698     setOperationAction(ISD::FPOWI, VT, Expand);
699     setOperationAction(ISD::FSQRT, VT, Expand);
700     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
701     setOperationAction(ISD::FFLOOR, VT, Expand);
702     setOperationAction(ISD::FCEIL, VT, Expand);
703     setOperationAction(ISD::FTRUNC, VT, Expand);
704     setOperationAction(ISD::FRINT, VT, Expand);
705     setOperationAction(ISD::FNEARBYINT, VT, Expand);
706     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
707     setOperationAction(ISD::MULHS, VT, Expand);
708     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
709     setOperationAction(ISD::MULHU, VT, Expand);
710     setOperationAction(ISD::SDIVREM, VT, Expand);
711     setOperationAction(ISD::UDIVREM, VT, Expand);
712     setOperationAction(ISD::FPOW, VT, Expand);
713     setOperationAction(ISD::CTPOP, VT, Expand);
714     setOperationAction(ISD::CTTZ, VT, Expand);
715     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
716     setOperationAction(ISD::CTLZ, VT, Expand);
717     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
718     setOperationAction(ISD::SHL, VT, Expand);
719     setOperationAction(ISD::SRA, VT, Expand);
720     setOperationAction(ISD::SRL, VT, Expand);
721     setOperationAction(ISD::ROTL, VT, Expand);
722     setOperationAction(ISD::ROTR, VT, Expand);
723     setOperationAction(ISD::BSWAP, VT, Expand);
724     setOperationAction(ISD::SETCC, VT, Expand);
725     setOperationAction(ISD::FLOG, VT, Expand);
726     setOperationAction(ISD::FLOG2, VT, Expand);
727     setOperationAction(ISD::FLOG10, VT, Expand);
728     setOperationAction(ISD::FEXP, VT, Expand);
729     setOperationAction(ISD::FEXP2, VT, Expand);
730     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
731     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
732     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
733     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
734     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
735     setOperationAction(ISD::TRUNCATE, VT, Expand);
736     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
737     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
738     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
739     setOperationAction(ISD::VSELECT, VT, Expand);
740     setOperationAction(ISD::SELECT_CC, VT, Expand);
741     for (MVT InnerVT : MVT::vector_valuetypes()) {
742       setTruncStoreAction(InnerVT, VT, Expand);
743
744       setLoadExtAction(ISD::SEXTLOAD, InnerVT, VT, Expand);
745       setLoadExtAction(ISD::ZEXTLOAD, InnerVT, VT, Expand);
746
747       // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like
748       // types, we have to deal with them whether we ask for Expansion or not.
749       // Setting Expand causes its own optimisation problems though, so leave
750       // them legal.
751       if (VT.getVectorElementType() == MVT::i1)
752         setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
753
754       // EXTLOAD for MVT::f16 vectors is not legal because f16 vectors are
755       // split/scalarized right now.
756       if (VT.getVectorElementType() == MVT::f16)
757         setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
758     }
759   }
760
761   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
762   // with -msoft-float, disable use of MMX as well.
763   if (!Subtarget->useSoftFloat() && Subtarget->hasMMX()) {
764     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
765     // No operations on x86mmx supported, everything uses intrinsics.
766   }
767
768   // MMX-sized vectors (other than x86mmx) are expected to be expanded
769   // into smaller operations.
770   for (MVT MMXTy : {MVT::v8i8, MVT::v4i16, MVT::v2i32, MVT::v1i64}) {
771     setOperationAction(ISD::MULHS,              MMXTy,      Expand);
772     setOperationAction(ISD::AND,                MMXTy,      Expand);
773     setOperationAction(ISD::OR,                 MMXTy,      Expand);
774     setOperationAction(ISD::XOR,                MMXTy,      Expand);
775     setOperationAction(ISD::SCALAR_TO_VECTOR,   MMXTy,      Expand);
776     setOperationAction(ISD::SELECT,             MMXTy,      Expand);
777     setOperationAction(ISD::BITCAST,            MMXTy,      Expand);
778   }
779   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
780
781   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE1()) {
782     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
783
784     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
785     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
786     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
787     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
788     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
789     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
790     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
791     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
792     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
793     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
794     setOperationAction(ISD::VSELECT,            MVT::v4f32, Custom);
795     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
796     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
797     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Custom);
798   }
799
800   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE2()) {
801     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
802
803     // FIXME: Unfortunately, -soft-float and -no-implicit-float mean XMM
804     // registers cannot be used even for integer operations.
805     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
806     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
807     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
808     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
809
810     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
811     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
812     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
813     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
814     setOperationAction(ISD::MUL,                MVT::v16i8, Custom);
815     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
816     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
817     setOperationAction(ISD::UMUL_LOHI,          MVT::v4i32, Custom);
818     setOperationAction(ISD::SMUL_LOHI,          MVT::v4i32, Custom);
819     setOperationAction(ISD::MULHU,              MVT::v8i16, Legal);
820     setOperationAction(ISD::MULHS,              MVT::v8i16, Legal);
821     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
822     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
823     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
824     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
825     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
826     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
827     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
828     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
829     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
830     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
831     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
832     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
833
834     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
835     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
836     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
837     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
838
839     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
840     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
841     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
842     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
843     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
844
845     // Only provide customized ctpop vector bit twiddling for vector types we
846     // know to perform better than using the popcnt instructions on each vector
847     // element. If popcnt isn't supported, always provide the custom version.
848     if (!Subtarget->hasPOPCNT()) {
849       setOperationAction(ISD::CTPOP,            MVT::v4i32, Custom);
850       setOperationAction(ISD::CTPOP,            MVT::v2i64, Custom);
851     }
852
853     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
854     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
855       MVT VT = (MVT::SimpleValueType)i;
856       // Do not attempt to custom lower non-power-of-2 vectors
857       if (!isPowerOf2_32(VT.getVectorNumElements()))
858         continue;
859       // Do not attempt to custom lower non-128-bit vectors
860       if (!VT.is128BitVector())
861         continue;
862       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
863       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
864       setOperationAction(ISD::VSELECT,            VT, Custom);
865       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
866     }
867
868     // We support custom legalizing of sext and anyext loads for specific
869     // memory vector types which we can load as a scalar (or sequence of
870     // scalars) and extend in-register to a legal 128-bit vector type. For sext
871     // loads these must work with a single scalar load.
872     for (MVT VT : MVT::integer_vector_valuetypes()) {
873       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i8, Custom);
874       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i16, Custom);
875       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v8i8, Custom);
876       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i8, Custom);
877       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i16, Custom);
878       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i32, Custom);
879       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i8, Custom);
880       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i16, Custom);
881       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8i8, Custom);
882     }
883
884     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
885     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
886     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
887     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
888     setOperationAction(ISD::VSELECT,            MVT::v2f64, Custom);
889     setOperationAction(ISD::VSELECT,            MVT::v2i64, Custom);
890     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
891     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
892
893     if (Subtarget->is64Bit()) {
894       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
895       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
896     }
897
898     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
899     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
900       MVT VT = (MVT::SimpleValueType)i;
901
902       // Do not attempt to promote non-128-bit vectors
903       if (!VT.is128BitVector())
904         continue;
905
906       setOperationAction(ISD::AND,    VT, Promote);
907       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
908       setOperationAction(ISD::OR,     VT, Promote);
909       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
910       setOperationAction(ISD::XOR,    VT, Promote);
911       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
912       setOperationAction(ISD::LOAD,   VT, Promote);
913       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
914       setOperationAction(ISD::SELECT, VT, Promote);
915       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
916     }
917
918     // Custom lower v2i64 and v2f64 selects.
919     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
920     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
921     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
922     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
923
924     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
925     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
926
927     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
928     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
929     // As there is no 64-bit GPR available, we need build a special custom
930     // sequence to convert from v2i32 to v2f32.
931     if (!Subtarget->is64Bit())
932       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
933
934     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
935     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
936
937     for (MVT VT : MVT::fp_vector_valuetypes())
938       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2f32, Legal);
939
940     setOperationAction(ISD::BITCAST,            MVT::v2i32, Custom);
941     setOperationAction(ISD::BITCAST,            MVT::v4i16, Custom);
942     setOperationAction(ISD::BITCAST,            MVT::v8i8,  Custom);
943   }
944
945   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE41()) {
946     for (MVT RoundedTy : {MVT::f32, MVT::f64, MVT::v4f32, MVT::v2f64}) {
947       setOperationAction(ISD::FFLOOR,           RoundedTy,  Legal);
948       setOperationAction(ISD::FCEIL,            RoundedTy,  Legal);
949       setOperationAction(ISD::FTRUNC,           RoundedTy,  Legal);
950       setOperationAction(ISD::FRINT,            RoundedTy,  Legal);
951       setOperationAction(ISD::FNEARBYINT,       RoundedTy,  Legal);
952     }
953
954     // FIXME: Do we need to handle scalar-to-vector here?
955     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
956
957     // We directly match byte blends in the backend as they match the VSELECT
958     // condition form.
959     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
960
961     // SSE41 brings specific instructions for doing vector sign extend even in
962     // cases where we don't have SRA.
963     for (MVT VT : MVT::integer_vector_valuetypes()) {
964       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i8, Custom);
965       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i16, Custom);
966       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i32, Custom);
967     }
968
969     // SSE41 also has vector sign/zero extending loads, PMOV[SZ]X
970     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i16, MVT::v8i8,  Legal);
971     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i8,  Legal);
972     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i8,  Legal);
973     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
974     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
975     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
976
977     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i16, MVT::v8i8,  Legal);
978     setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i8,  Legal);
979     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i8,  Legal);
980     setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
981     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
982     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
983
984     // i8 and i16 vectors are custom because the source register and source
985     // source memory operand types are not the same width.  f32 vectors are
986     // custom since the immediate controlling the insert encodes additional
987     // information.
988     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
989     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
990     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
991     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
992
993     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
994     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
995     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
996     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
997
998     // FIXME: these should be Legal, but that's only for the case where
999     // the index is constant.  For now custom expand to deal with that.
1000     if (Subtarget->is64Bit()) {
1001       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1002       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1003     }
1004   }
1005
1006   if (Subtarget->hasSSE2()) {
1007     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1008     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1009
1010     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1011     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1012
1013     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1014     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1015
1016     // In the customized shift lowering, the legal cases in AVX2 will be
1017     // recognized.
1018     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1019     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1020
1021     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1022     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1023
1024     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1025   }
1026
1027   if (!Subtarget->useSoftFloat() && Subtarget->hasFp256()) {
1028     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1029     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1030     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1031     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1032     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1033     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1034
1035     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1036     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1037     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1038
1039     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1040     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1041     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1042     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1043     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1044     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1045     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1046     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1047     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1048     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1049     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1050     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1051
1052     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1053     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1054     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1055     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1056     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1057     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1058     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1059     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1060     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1061     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1062     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1063     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1064
1065     // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1066     // even though v8i16 is a legal type.
1067     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Promote);
1068     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i16, Promote);
1069     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1070
1071     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1072     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1073     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1074
1075     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1076     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1077
1078     for (MVT VT : MVT::fp_vector_valuetypes())
1079       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4f32, Legal);
1080
1081     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1082     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1083
1084     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1085     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1086
1087     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1088     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1089
1090     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1091     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1092     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1093     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1094
1095     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1096     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1097     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1098
1099     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1100     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1101     setOperationAction(ISD::SIGN_EXTEND,       MVT::v16i16, Custom);
1102     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1103     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1104     setOperationAction(ISD::ZERO_EXTEND,       MVT::v16i16, Custom);
1105     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1106     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1107     setOperationAction(ISD::ANY_EXTEND,        MVT::v16i16, Custom);
1108     setOperationAction(ISD::TRUNCATE,          MVT::v16i8, Custom);
1109     setOperationAction(ISD::TRUNCATE,          MVT::v8i16, Custom);
1110     setOperationAction(ISD::TRUNCATE,          MVT::v4i32, Custom);
1111
1112     if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1113       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1114       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1115       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1116       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1117       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1118       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1119     }
1120
1121     if (Subtarget->hasInt256()) {
1122       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1123       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1124       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1125       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1126
1127       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1128       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1129       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1130       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1131
1132       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1133       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1134       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1135       setOperationAction(ISD::MUL,             MVT::v32i8, Custom);
1136
1137       setOperationAction(ISD::UMUL_LOHI,       MVT::v8i32, Custom);
1138       setOperationAction(ISD::SMUL_LOHI,       MVT::v8i32, Custom);
1139       setOperationAction(ISD::MULHU,           MVT::v16i16, Legal);
1140       setOperationAction(ISD::MULHS,           MVT::v16i16, Legal);
1141
1142       // The custom lowering for UINT_TO_FP for v8i32 becomes interesting
1143       // when we have a 256bit-wide blend with immediate.
1144       setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Custom);
1145
1146       // Only provide customized ctpop vector bit twiddling for vector types we
1147       // know to perform better than using the popcnt instructions on each
1148       // vector element. If popcnt isn't supported, always provide the custom
1149       // version.
1150       if (!Subtarget->hasPOPCNT())
1151         setOperationAction(ISD::CTPOP,           MVT::v4i64, Custom);
1152
1153       // Custom CTPOP always performs better on natively supported v8i32
1154       setOperationAction(ISD::CTPOP,             MVT::v8i32, Custom);
1155
1156       // AVX2 also has wider vector sign/zero extending loads, VPMOV[SZ]X
1157       setLoadExtAction(ISD::SEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1158       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32,  MVT::v8i8,  Legal);
1159       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i8,  Legal);
1160       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32,  MVT::v8i16, Legal);
1161       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i16, Legal);
1162       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i32, Legal);
1163
1164       setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1165       setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32,  MVT::v8i8,  Legal);
1166       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i8,  Legal);
1167       setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32,  MVT::v8i16, Legal);
1168       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i16, Legal);
1169       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i32, Legal);
1170     } else {
1171       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1172       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1173       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1174       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1175
1176       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1177       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1178       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1179       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1180
1181       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1182       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1183       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1184       setOperationAction(ISD::MUL,             MVT::v32i8, Custom);
1185     }
1186
1187     // In the customized shift lowering, the legal cases in AVX2 will be
1188     // recognized.
1189     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1190     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1191
1192     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1193     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1194
1195     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1196
1197     // Custom lower several nodes for 256-bit types.
1198     for (MVT VT : MVT::vector_valuetypes()) {
1199       if (VT.getScalarSizeInBits() >= 32) {
1200         setOperationAction(ISD::MLOAD,  VT, Legal);
1201         setOperationAction(ISD::MSTORE, VT, Legal);
1202       }
1203       // Extract subvector is special because the value type
1204       // (result) is 128-bit but the source is 256-bit wide.
1205       if (VT.is128BitVector()) {
1206         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1207       }
1208       // Do not attempt to custom lower other non-256-bit vectors
1209       if (!VT.is256BitVector())
1210         continue;
1211
1212       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1213       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1214       setOperationAction(ISD::VSELECT,            VT, Custom);
1215       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1216       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1217       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1218       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1219       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1220     }
1221
1222     if (Subtarget->hasInt256())
1223       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1224
1225
1226     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1227     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1228       MVT VT = (MVT::SimpleValueType)i;
1229
1230       // Do not attempt to promote non-256-bit vectors
1231       if (!VT.is256BitVector())
1232         continue;
1233
1234       setOperationAction(ISD::AND,    VT, Promote);
1235       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1236       setOperationAction(ISD::OR,     VT, Promote);
1237       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1238       setOperationAction(ISD::XOR,    VT, Promote);
1239       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1240       setOperationAction(ISD::LOAD,   VT, Promote);
1241       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1242       setOperationAction(ISD::SELECT, VT, Promote);
1243       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1244     }
1245   }
1246
1247   if (!Subtarget->useSoftFloat() && Subtarget->hasAVX512()) {
1248     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1249     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1250     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1251     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1252
1253     addRegisterClass(MVT::i1,     &X86::VK1RegClass);
1254     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1255     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1256
1257     for (MVT VT : MVT::fp_vector_valuetypes())
1258       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8f32, Legal);
1259
1260     setOperationAction(ISD::BR_CC,              MVT::i1,    Expand);
1261     setOperationAction(ISD::SETCC,              MVT::i1,    Custom);
1262     setOperationAction(ISD::XOR,                MVT::i1,    Legal);
1263     setOperationAction(ISD::OR,                 MVT::i1,    Legal);
1264     setOperationAction(ISD::AND,                MVT::i1,    Legal);
1265     setOperationAction(ISD::LOAD,               MVT::v16f32, Legal);
1266     setOperationAction(ISD::LOAD,               MVT::v8f64, Legal);
1267     setOperationAction(ISD::LOAD,               MVT::v8i64, Legal);
1268     setOperationAction(ISD::LOAD,               MVT::v16i32, Legal);
1269     setOperationAction(ISD::LOAD,               MVT::v16i1, Legal);
1270
1271     setOperationAction(ISD::FADD,               MVT::v16f32, Legal);
1272     setOperationAction(ISD::FSUB,               MVT::v16f32, Legal);
1273     setOperationAction(ISD::FMUL,               MVT::v16f32, Legal);
1274     setOperationAction(ISD::FDIV,               MVT::v16f32, Legal);
1275     setOperationAction(ISD::FSQRT,              MVT::v16f32, Legal);
1276     setOperationAction(ISD::FNEG,               MVT::v16f32, Custom);
1277
1278     setOperationAction(ISD::FADD,               MVT::v8f64, Legal);
1279     setOperationAction(ISD::FSUB,               MVT::v8f64, Legal);
1280     setOperationAction(ISD::FMUL,               MVT::v8f64, Legal);
1281     setOperationAction(ISD::FDIV,               MVT::v8f64, Legal);
1282     setOperationAction(ISD::FSQRT,              MVT::v8f64, Legal);
1283     setOperationAction(ISD::FNEG,               MVT::v8f64, Custom);
1284     setOperationAction(ISD::FMA,                MVT::v8f64, Legal);
1285     setOperationAction(ISD::FMA,                MVT::v16f32, Legal);
1286
1287     setOperationAction(ISD::FP_TO_SINT,         MVT::i32, Legal);
1288     setOperationAction(ISD::FP_TO_UINT,         MVT::i32, Legal);
1289     setOperationAction(ISD::SINT_TO_FP,         MVT::i32, Legal);
1290     setOperationAction(ISD::UINT_TO_FP,         MVT::i32, Legal);
1291     if (Subtarget->is64Bit()) {
1292       setOperationAction(ISD::FP_TO_UINT,       MVT::i64, Legal);
1293       setOperationAction(ISD::FP_TO_SINT,       MVT::i64, Legal);
1294       setOperationAction(ISD::SINT_TO_FP,       MVT::i64, Legal);
1295       setOperationAction(ISD::UINT_TO_FP,       MVT::i64, Legal);
1296     }
1297     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1298     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1299     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1300     setOperationAction(ISD::FP_TO_UINT,         MVT::v4i32, Legal);
1301     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1302     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i1,   Custom);
1303     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i1,  Custom);
1304     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i8,  Promote);
1305     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i16, Promote);
1306     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1307     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1308     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Legal);
1309     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i8, Custom);
1310     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i16, Custom);
1311     setOperationAction(ISD::FP_ROUND,           MVT::v8f32, Legal);
1312     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Legal);
1313
1314     setOperationAction(ISD::TRUNCATE,           MVT::i1, Custom);
1315     setOperationAction(ISD::TRUNCATE,           MVT::v16i8, Custom);
1316     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1317     if (Subtarget->hasDQI()) {
1318       setOperationAction(ISD::TRUNCATE,           MVT::v2i1, Custom);
1319       setOperationAction(ISD::TRUNCATE,           MVT::v4i1, Custom);
1320     }
1321     setOperationAction(ISD::TRUNCATE,           MVT::v8i1, Custom);
1322     setOperationAction(ISD::TRUNCATE,           MVT::v16i1, Custom);
1323     setOperationAction(ISD::TRUNCATE,           MVT::v16i16, Custom);
1324     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1325     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1326     setOperationAction(ISD::ANY_EXTEND,         MVT::v16i32, Custom);
1327     setOperationAction(ISD::ANY_EXTEND,         MVT::v8i64, Custom);
1328     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1329     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1330     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i8, Custom);
1331     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i16, Custom);
1332     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i16, Custom);
1333     if (Subtarget->hasDQI()) {
1334       setOperationAction(ISD::SIGN_EXTEND,        MVT::v4i32, Custom);
1335       setOperationAction(ISD::SIGN_EXTEND,        MVT::v2i64, Custom);
1336     }
1337     setOperationAction(ISD::FFLOOR,             MVT::v16f32, Legal);
1338     setOperationAction(ISD::FFLOOR,             MVT::v8f64, Legal);
1339     setOperationAction(ISD::FCEIL,              MVT::v16f32, Legal);
1340     setOperationAction(ISD::FCEIL,              MVT::v8f64, Legal);
1341     setOperationAction(ISD::FTRUNC,             MVT::v16f32, Legal);
1342     setOperationAction(ISD::FTRUNC,             MVT::v8f64, Legal);
1343     setOperationAction(ISD::FRINT,              MVT::v16f32, Legal);
1344     setOperationAction(ISD::FRINT,              MVT::v8f64, Legal);
1345     setOperationAction(ISD::FNEARBYINT,         MVT::v16f32, Legal);
1346     setOperationAction(ISD::FNEARBYINT,         MVT::v8f64, Legal);
1347
1348     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1349     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1350     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1351     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1352     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i1, Legal);
1353
1354     setOperationAction(ISD::SETCC,              MVT::v16i1, Custom);
1355     setOperationAction(ISD::SETCC,              MVT::v8i1, Custom);
1356
1357     setOperationAction(ISD::MUL,              MVT::v8i64, Custom);
1358
1359     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1,  Custom);
1360     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1361     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i1, Custom);
1362     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i1, Custom);
1363     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i1, Custom);
1364     setOperationAction(ISD::BUILD_VECTOR,       MVT::v16i1, Custom);
1365     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1366     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1367     setOperationAction(ISD::SELECT,             MVT::v16f32, Custom);
1368     setOperationAction(ISD::SELECT,             MVT::v16i1, Custom);
1369     setOperationAction(ISD::SELECT,             MVT::v8i1,  Custom);
1370
1371     setOperationAction(ISD::ADD,                MVT::v8i64, Legal);
1372     setOperationAction(ISD::ADD,                MVT::v16i32, Legal);
1373
1374     setOperationAction(ISD::SUB,                MVT::v8i64, Legal);
1375     setOperationAction(ISD::SUB,                MVT::v16i32, Legal);
1376
1377     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1378
1379     setOperationAction(ISD::SRL,                MVT::v8i64, Custom);
1380     setOperationAction(ISD::SRL,                MVT::v16i32, Custom);
1381
1382     setOperationAction(ISD::SHL,                MVT::v8i64, Custom);
1383     setOperationAction(ISD::SHL,                MVT::v16i32, Custom);
1384
1385     setOperationAction(ISD::SRA,                MVT::v8i64, Custom);
1386     setOperationAction(ISD::SRA,                MVT::v16i32, Custom);
1387
1388     setOperationAction(ISD::AND,                MVT::v8i64, Legal);
1389     setOperationAction(ISD::OR,                 MVT::v8i64, Legal);
1390     setOperationAction(ISD::XOR,                MVT::v8i64, Legal);
1391     setOperationAction(ISD::AND,                MVT::v16i32, Legal);
1392     setOperationAction(ISD::OR,                 MVT::v16i32, Legal);
1393     setOperationAction(ISD::XOR,                MVT::v16i32, Legal);
1394
1395     if (Subtarget->hasCDI()) {
1396       setOperationAction(ISD::CTLZ,             MVT::v8i64, Legal);
1397       setOperationAction(ISD::CTLZ,             MVT::v16i32, Legal);
1398     }
1399     if (Subtarget->hasDQI()) {
1400       setOperationAction(ISD::MUL,             MVT::v2i64, Legal);
1401       setOperationAction(ISD::MUL,             MVT::v4i64, Legal);
1402       setOperationAction(ISD::MUL,             MVT::v8i64, Legal);
1403     }
1404     // Custom lower several nodes.
1405     for (MVT VT : MVT::vector_valuetypes()) {
1406       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1407       if (EltSize == 1) {
1408         setOperationAction(ISD::AND, VT, Legal);
1409         setOperationAction(ISD::OR,  VT, Legal);
1410         setOperationAction(ISD::XOR,  VT, Legal);
1411       }
1412       if (EltSize >= 32 && VT.getSizeInBits() <= 512) {
1413         setOperationAction(ISD::MGATHER,  VT, Custom);
1414         setOperationAction(ISD::MSCATTER, VT, Custom);
1415       }
1416       // Extract subvector is special because the value type
1417       // (result) is 256/128-bit but the source is 512-bit wide.
1418       if (VT.is128BitVector() || VT.is256BitVector()) {
1419         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1420       }
1421       if (VT.getVectorElementType() == MVT::i1)
1422         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1423
1424       // Do not attempt to custom lower other non-512-bit vectors
1425       if (!VT.is512BitVector())
1426         continue;
1427
1428       if (EltSize >= 32) {
1429         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1430         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1431         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1432         setOperationAction(ISD::VSELECT,             VT, Legal);
1433         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1434         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1435         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1436         setOperationAction(ISD::MLOAD,               VT, Legal);
1437         setOperationAction(ISD::MSTORE,              VT, Legal);
1438       }
1439     }
1440     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1441       MVT VT = (MVT::SimpleValueType)i;
1442
1443       // Do not attempt to promote non-512-bit vectors.
1444       if (!VT.is512BitVector())
1445         continue;
1446
1447       setOperationAction(ISD::SELECT, VT, Promote);
1448       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1449     }
1450   }// has  AVX-512
1451
1452   if (!Subtarget->useSoftFloat() && Subtarget->hasBWI()) {
1453     addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1454     addRegisterClass(MVT::v64i8,  &X86::VR512RegClass);
1455
1456     addRegisterClass(MVT::v32i1,  &X86::VK32RegClass);
1457     addRegisterClass(MVT::v64i1,  &X86::VK64RegClass);
1458
1459     setOperationAction(ISD::LOAD,               MVT::v32i16, Legal);
1460     setOperationAction(ISD::LOAD,               MVT::v64i8, Legal);
1461     setOperationAction(ISD::SETCC,              MVT::v32i1, Custom);
1462     setOperationAction(ISD::SETCC,              MVT::v64i1, Custom);
1463     setOperationAction(ISD::ADD,                MVT::v32i16, Legal);
1464     setOperationAction(ISD::ADD,                MVT::v64i8, Legal);
1465     setOperationAction(ISD::SUB,                MVT::v32i16, Legal);
1466     setOperationAction(ISD::SUB,                MVT::v64i8, Legal);
1467     setOperationAction(ISD::MUL,                MVT::v32i16, Legal);
1468     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v32i1, Custom);
1469     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v64i1, Custom);
1470     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v32i1, Custom);
1471     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v64i1, Custom);
1472     setOperationAction(ISD::SELECT,             MVT::v32i1, Custom);
1473     setOperationAction(ISD::SELECT,             MVT::v64i1, Custom);
1474     setOperationAction(ISD::SIGN_EXTEND,        MVT::v32i8, Custom);
1475     setOperationAction(ISD::SIGN_EXTEND,        MVT::v64i8, Custom);
1476     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v32i1, Custom);
1477     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v64i1, Custom);
1478
1479     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1480       const MVT VT = (MVT::SimpleValueType)i;
1481
1482       const unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1483
1484       // Do not attempt to promote non-512-bit vectors.
1485       if (!VT.is512BitVector())
1486         continue;
1487
1488       if (EltSize < 32) {
1489         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1490         setOperationAction(ISD::VSELECT,             VT, Legal);
1491       }
1492     }
1493   }
1494
1495   if (!Subtarget->useSoftFloat() && Subtarget->hasVLX()) {
1496     addRegisterClass(MVT::v4i1,   &X86::VK4RegClass);
1497     addRegisterClass(MVT::v2i1,   &X86::VK2RegClass);
1498
1499     setOperationAction(ISD::SETCC,              MVT::v4i1, Custom);
1500     setOperationAction(ISD::SETCC,              MVT::v2i1, Custom);
1501     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i1, Custom);
1502     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1, Custom);
1503     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v8i1, Custom);
1504     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v4i1, Custom);
1505     setOperationAction(ISD::SELECT,             MVT::v4i1, Custom);
1506     setOperationAction(ISD::SELECT,             MVT::v2i1, Custom);
1507     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4i1, Custom);
1508     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i1, Custom);
1509
1510     setOperationAction(ISD::AND,                MVT::v8i32, Legal);
1511     setOperationAction(ISD::OR,                 MVT::v8i32, Legal);
1512     setOperationAction(ISD::XOR,                MVT::v8i32, Legal);
1513     setOperationAction(ISD::AND,                MVT::v4i32, Legal);
1514     setOperationAction(ISD::OR,                 MVT::v4i32, Legal);
1515     setOperationAction(ISD::XOR,                MVT::v4i32, Legal);
1516     setOperationAction(ISD::SRA,                MVT::v2i64, Custom);
1517     setOperationAction(ISD::SRA,                MVT::v4i64, Custom);
1518   }
1519
1520   // We want to custom lower some of our intrinsics.
1521   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1522   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1523   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1524   if (!Subtarget->is64Bit())
1525     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1526
1527   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1528   // handle type legalization for these operations here.
1529   //
1530   // FIXME: We really should do custom legalization for addition and
1531   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1532   // than generic legalization for 64-bit multiplication-with-overflow, though.
1533   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1534     // Add/Sub/Mul with overflow operations are custom lowered.
1535     MVT VT = IntVTs[i];
1536     setOperationAction(ISD::SADDO, VT, Custom);
1537     setOperationAction(ISD::UADDO, VT, Custom);
1538     setOperationAction(ISD::SSUBO, VT, Custom);
1539     setOperationAction(ISD::USUBO, VT, Custom);
1540     setOperationAction(ISD::SMULO, VT, Custom);
1541     setOperationAction(ISD::UMULO, VT, Custom);
1542   }
1543
1544
1545   if (!Subtarget->is64Bit()) {
1546     // These libcalls are not available in 32-bit.
1547     setLibcallName(RTLIB::SHL_I128, nullptr);
1548     setLibcallName(RTLIB::SRL_I128, nullptr);
1549     setLibcallName(RTLIB::SRA_I128, nullptr);
1550   }
1551
1552   // Combine sin / cos into one node or libcall if possible.
1553   if (Subtarget->hasSinCos()) {
1554     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1555     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1556     if (Subtarget->isTargetDarwin()) {
1557       // For MacOSX, we don't want the normal expansion of a libcall to sincos.
1558       // We want to issue a libcall to __sincos_stret to avoid memory traffic.
1559       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1560       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1561     }
1562   }
1563
1564   if (Subtarget->isTargetWin64()) {
1565     setOperationAction(ISD::SDIV, MVT::i128, Custom);
1566     setOperationAction(ISD::UDIV, MVT::i128, Custom);
1567     setOperationAction(ISD::SREM, MVT::i128, Custom);
1568     setOperationAction(ISD::UREM, MVT::i128, Custom);
1569     setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1570     setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1571   }
1572
1573   // We have target-specific dag combine patterns for the following nodes:
1574   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1575   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1576   setTargetDAGCombine(ISD::BITCAST);
1577   setTargetDAGCombine(ISD::VSELECT);
1578   setTargetDAGCombine(ISD::SELECT);
1579   setTargetDAGCombine(ISD::SHL);
1580   setTargetDAGCombine(ISD::SRA);
1581   setTargetDAGCombine(ISD::SRL);
1582   setTargetDAGCombine(ISD::OR);
1583   setTargetDAGCombine(ISD::AND);
1584   setTargetDAGCombine(ISD::ADD);
1585   setTargetDAGCombine(ISD::FADD);
1586   setTargetDAGCombine(ISD::FSUB);
1587   setTargetDAGCombine(ISD::FMA);
1588   setTargetDAGCombine(ISD::SUB);
1589   setTargetDAGCombine(ISD::LOAD);
1590   setTargetDAGCombine(ISD::MLOAD);
1591   setTargetDAGCombine(ISD::STORE);
1592   setTargetDAGCombine(ISD::MSTORE);
1593   setTargetDAGCombine(ISD::ZERO_EXTEND);
1594   setTargetDAGCombine(ISD::ANY_EXTEND);
1595   setTargetDAGCombine(ISD::SIGN_EXTEND);
1596   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1597   setTargetDAGCombine(ISD::SINT_TO_FP);
1598   setTargetDAGCombine(ISD::SETCC);
1599   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1600   setTargetDAGCombine(ISD::BUILD_VECTOR);
1601   setTargetDAGCombine(ISD::MUL);
1602   setTargetDAGCombine(ISD::XOR);
1603
1604   computeRegisterProperties(Subtarget->getRegisterInfo());
1605
1606   // On Darwin, -Os means optimize for size without hurting performance,
1607   // do not reduce the limit.
1608   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1609   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1610   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1611   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1612   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1613   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1614   setPrefLoopAlignment(4); // 2^4 bytes.
1615
1616   // Predictable cmov don't hurt on atom because it's in-order.
1617   PredictableSelectIsExpensive = !Subtarget->isAtom();
1618   EnableExtLdPromotion = true;
1619   setPrefFunctionAlignment(4); // 2^4 bytes.
1620
1621   verifyIntrinsicTables();
1622 }
1623
1624 // This has so far only been implemented for 64-bit MachO.
1625 bool X86TargetLowering::useLoadStackGuardNode() const {
1626   return Subtarget->isTargetMachO() && Subtarget->is64Bit();
1627 }
1628
1629 TargetLoweringBase::LegalizeTypeAction
1630 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1631   if (ExperimentalVectorWideningLegalization &&
1632       VT.getVectorNumElements() != 1 &&
1633       VT.getVectorElementType().getSimpleVT() != MVT::i1)
1634     return TypeWidenVector;
1635
1636   return TargetLoweringBase::getPreferredVectorAction(VT);
1637 }
1638
1639 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1640   if (!VT.isVector())
1641     return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1642
1643   const unsigned NumElts = VT.getVectorNumElements();
1644   const EVT EltVT = VT.getVectorElementType();
1645   if (VT.is512BitVector()) {
1646     if (Subtarget->hasAVX512())
1647       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1648           EltVT == MVT::f32 || EltVT == MVT::f64)
1649         switch(NumElts) {
1650         case  8: return MVT::v8i1;
1651         case 16: return MVT::v16i1;
1652       }
1653     if (Subtarget->hasBWI())
1654       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1655         switch(NumElts) {
1656         case 32: return MVT::v32i1;
1657         case 64: return MVT::v64i1;
1658       }
1659   }
1660
1661   if (VT.is256BitVector() || VT.is128BitVector()) {
1662     if (Subtarget->hasVLX())
1663       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1664           EltVT == MVT::f32 || EltVT == MVT::f64)
1665         switch(NumElts) {
1666         case 2: return MVT::v2i1;
1667         case 4: return MVT::v4i1;
1668         case 8: return MVT::v8i1;
1669       }
1670     if (Subtarget->hasBWI() && Subtarget->hasVLX())
1671       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1672         switch(NumElts) {
1673         case  8: return MVT::v8i1;
1674         case 16: return MVT::v16i1;
1675         case 32: return MVT::v32i1;
1676       }
1677   }
1678
1679   return VT.changeVectorElementTypeToInteger();
1680 }
1681
1682 /// Helper for getByValTypeAlignment to determine
1683 /// the desired ByVal argument alignment.
1684 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1685   if (MaxAlign == 16)
1686     return;
1687   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1688     if (VTy->getBitWidth() == 128)
1689       MaxAlign = 16;
1690   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1691     unsigned EltAlign = 0;
1692     getMaxByValAlign(ATy->getElementType(), EltAlign);
1693     if (EltAlign > MaxAlign)
1694       MaxAlign = EltAlign;
1695   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1696     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1697       unsigned EltAlign = 0;
1698       getMaxByValAlign(STy->getElementType(i), EltAlign);
1699       if (EltAlign > MaxAlign)
1700         MaxAlign = EltAlign;
1701       if (MaxAlign == 16)
1702         break;
1703     }
1704   }
1705 }
1706
1707 /// Return the desired alignment for ByVal aggregate
1708 /// function arguments in the caller parameter area. For X86, aggregates
1709 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1710 /// are at 4-byte boundaries.
1711 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1712   if (Subtarget->is64Bit()) {
1713     // Max of 8 and alignment of type.
1714     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1715     if (TyAlign > 8)
1716       return TyAlign;
1717     return 8;
1718   }
1719
1720   unsigned Align = 4;
1721   if (Subtarget->hasSSE1())
1722     getMaxByValAlign(Ty, Align);
1723   return Align;
1724 }
1725
1726 /// Returns the target specific optimal type for load
1727 /// and store operations as a result of memset, memcpy, and memmove
1728 /// lowering. If DstAlign is zero that means it's safe to destination
1729 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1730 /// means there isn't a need to check it against alignment requirement,
1731 /// probably because the source does not need to be loaded. If 'IsMemset' is
1732 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1733 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1734 /// source is constant so it does not need to be loaded.
1735 /// It returns EVT::Other if the type should be determined using generic
1736 /// target-independent logic.
1737 EVT
1738 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1739                                        unsigned DstAlign, unsigned SrcAlign,
1740                                        bool IsMemset, bool ZeroMemset,
1741                                        bool MemcpyStrSrc,
1742                                        MachineFunction &MF) const {
1743   const Function *F = MF.getFunction();
1744   if ((!IsMemset || ZeroMemset) &&
1745       !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1746     if (Size >= 16 &&
1747         (Subtarget->isUnalignedMemAccessFast() ||
1748          ((DstAlign == 0 || DstAlign >= 16) &&
1749           (SrcAlign == 0 || SrcAlign >= 16)))) {
1750       if (Size >= 32) {
1751         if (Subtarget->hasInt256())
1752           return MVT::v8i32;
1753         if (Subtarget->hasFp256())
1754           return MVT::v8f32;
1755       }
1756       if (Subtarget->hasSSE2())
1757         return MVT::v4i32;
1758       if (Subtarget->hasSSE1())
1759         return MVT::v4f32;
1760     } else if (!MemcpyStrSrc && Size >= 8 &&
1761                !Subtarget->is64Bit() &&
1762                Subtarget->hasSSE2()) {
1763       // Do not use f64 to lower memcpy if source is string constant. It's
1764       // better to use i32 to avoid the loads.
1765       return MVT::f64;
1766     }
1767   }
1768   if (Subtarget->is64Bit() && Size >= 8)
1769     return MVT::i64;
1770   return MVT::i32;
1771 }
1772
1773 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1774   if (VT == MVT::f32)
1775     return X86ScalarSSEf32;
1776   else if (VT == MVT::f64)
1777     return X86ScalarSSEf64;
1778   return true;
1779 }
1780
1781 bool
1782 X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1783                                                   unsigned,
1784                                                   unsigned,
1785                                                   bool *Fast) const {
1786   if (Fast)
1787     *Fast = Subtarget->isUnalignedMemAccessFast();
1788   return true;
1789 }
1790
1791 /// Return the entry encoding for a jump table in the
1792 /// current function.  The returned value is a member of the
1793 /// MachineJumpTableInfo::JTEntryKind enum.
1794 unsigned X86TargetLowering::getJumpTableEncoding() const {
1795   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1796   // symbol.
1797   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1798       Subtarget->isPICStyleGOT())
1799     return MachineJumpTableInfo::EK_Custom32;
1800
1801   // Otherwise, use the normal jump table encoding heuristics.
1802   return TargetLowering::getJumpTableEncoding();
1803 }
1804
1805 bool X86TargetLowering::useSoftFloat() const {
1806   return Subtarget->useSoftFloat();
1807 }
1808
1809 const MCExpr *
1810 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1811                                              const MachineBasicBlock *MBB,
1812                                              unsigned uid,MCContext &Ctx) const{
1813   assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
1814          Subtarget->isPICStyleGOT());
1815   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1816   // entries.
1817   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1818                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1819 }
1820
1821 /// Returns relocation base for the given PIC jumptable.
1822 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1823                                                     SelectionDAG &DAG) const {
1824   if (!Subtarget->is64Bit())
1825     // This doesn't have SDLoc associated with it, but is not really the
1826     // same as a Register.
1827     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1828   return Table;
1829 }
1830
1831 /// This returns the relocation base for the given PIC jumptable,
1832 /// the same as getPICJumpTableRelocBase, but as an MCExpr.
1833 const MCExpr *X86TargetLowering::
1834 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1835                              MCContext &Ctx) const {
1836   // X86-64 uses RIP relative addressing based on the jump table label.
1837   if (Subtarget->isPICStyleRIPRel())
1838     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1839
1840   // Otherwise, the reference is relative to the PIC base.
1841   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1842 }
1843
1844 std::pair<const TargetRegisterClass *, uint8_t>
1845 X86TargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1846                                            MVT VT) const {
1847   const TargetRegisterClass *RRC = nullptr;
1848   uint8_t Cost = 1;
1849   switch (VT.SimpleTy) {
1850   default:
1851     return TargetLowering::findRepresentativeClass(TRI, VT);
1852   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1853     RRC = Subtarget->is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
1854     break;
1855   case MVT::x86mmx:
1856     RRC = &X86::VR64RegClass;
1857     break;
1858   case MVT::f32: case MVT::f64:
1859   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1860   case MVT::v4f32: case MVT::v2f64:
1861   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1862   case MVT::v4f64:
1863     RRC = &X86::VR128RegClass;
1864     break;
1865   }
1866   return std::make_pair(RRC, Cost);
1867 }
1868
1869 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1870                                                unsigned &Offset) const {
1871   if (!Subtarget->isTargetLinux())
1872     return false;
1873
1874   if (Subtarget->is64Bit()) {
1875     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1876     Offset = 0x28;
1877     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1878       AddressSpace = 256;
1879     else
1880       AddressSpace = 257;
1881   } else {
1882     // %gs:0x14 on i386
1883     Offset = 0x14;
1884     AddressSpace = 256;
1885   }
1886   return true;
1887 }
1888
1889 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1890                                             unsigned DestAS) const {
1891   assert(SrcAS != DestAS && "Expected different address spaces!");
1892
1893   return SrcAS < 256 && DestAS < 256;
1894 }
1895
1896 //===----------------------------------------------------------------------===//
1897 //               Return Value Calling Convention Implementation
1898 //===----------------------------------------------------------------------===//
1899
1900 #include "X86GenCallingConv.inc"
1901
1902 bool
1903 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1904                                   MachineFunction &MF, bool isVarArg,
1905                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1906                         LLVMContext &Context) const {
1907   SmallVector<CCValAssign, 16> RVLocs;
1908   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
1909   return CCInfo.CheckReturn(Outs, RetCC_X86);
1910 }
1911
1912 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1913   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1914   return ScratchRegs;
1915 }
1916
1917 SDValue
1918 X86TargetLowering::LowerReturn(SDValue Chain,
1919                                CallingConv::ID CallConv, bool isVarArg,
1920                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1921                                const SmallVectorImpl<SDValue> &OutVals,
1922                                SDLoc dl, SelectionDAG &DAG) const {
1923   MachineFunction &MF = DAG.getMachineFunction();
1924   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1925
1926   SmallVector<CCValAssign, 16> RVLocs;
1927   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
1928   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1929
1930   SDValue Flag;
1931   SmallVector<SDValue, 6> RetOps;
1932   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1933   // Operand #1 = Bytes To Pop
1934   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(), dl,
1935                    MVT::i16));
1936
1937   // Copy the result values into the output registers.
1938   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1939     CCValAssign &VA = RVLocs[i];
1940     assert(VA.isRegLoc() && "Can only return in registers!");
1941     SDValue ValToCopy = OutVals[i];
1942     EVT ValVT = ValToCopy.getValueType();
1943
1944     // Promote values to the appropriate types.
1945     if (VA.getLocInfo() == CCValAssign::SExt)
1946       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1947     else if (VA.getLocInfo() == CCValAssign::ZExt)
1948       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1949     else if (VA.getLocInfo() == CCValAssign::AExt) {
1950       if (ValVT.isVector() && ValVT.getScalarType() == MVT::i1)
1951         ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1952       else
1953         ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1954     }
1955     else if (VA.getLocInfo() == CCValAssign::BCvt)
1956       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1957
1958     assert(VA.getLocInfo() != CCValAssign::FPExt &&
1959            "Unexpected FP-extend for return value.");
1960
1961     // If this is x86-64, and we disabled SSE, we can't return FP values,
1962     // or SSE or MMX vectors.
1963     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1964          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1965           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1966       report_fatal_error("SSE register return with SSE disabled");
1967     }
1968     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1969     // llvm-gcc has never done it right and no one has noticed, so this
1970     // should be OK for now.
1971     if (ValVT == MVT::f64 &&
1972         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1973       report_fatal_error("SSE2 register return with SSE2 disabled");
1974
1975     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1976     // the RET instruction and handled by the FP Stackifier.
1977     if (VA.getLocReg() == X86::FP0 ||
1978         VA.getLocReg() == X86::FP1) {
1979       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1980       // change the value to the FP stack register class.
1981       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1982         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1983       RetOps.push_back(ValToCopy);
1984       // Don't emit a copytoreg.
1985       continue;
1986     }
1987
1988     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1989     // which is returned in RAX / RDX.
1990     if (Subtarget->is64Bit()) {
1991       if (ValVT == MVT::x86mmx) {
1992         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1993           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1994           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1995                                   ValToCopy);
1996           // If we don't have SSE2 available, convert to v4f32 so the generated
1997           // register is legal.
1998           if (!Subtarget->hasSSE2())
1999             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
2000         }
2001       }
2002     }
2003
2004     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
2005     Flag = Chain.getValue(1);
2006     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2007   }
2008
2009   // All x86 ABIs require that for returning structs by value we copy
2010   // the sret argument into %rax/%eax (depending on ABI) for the return.
2011   // We saved the argument into a virtual register in the entry block,
2012   // so now we copy the value out and into %rax/%eax.
2013   //
2014   // Checking Function.hasStructRetAttr() here is insufficient because the IR
2015   // may not have an explicit sret argument. If FuncInfo.CanLowerReturn is
2016   // false, then an sret argument may be implicitly inserted in the SelDAG. In
2017   // either case FuncInfo->setSRetReturnReg() will have been called.
2018   if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
2019     SDValue Val = DAG.getCopyFromReg(Chain, dl, SRetReg, getPointerTy());
2020
2021     unsigned RetValReg
2022         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
2023           X86::RAX : X86::EAX;
2024     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2025     Flag = Chain.getValue(1);
2026
2027     // RAX/EAX now acts like a return value.
2028     RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
2029   }
2030
2031   RetOps[0] = Chain;  // Update chain.
2032
2033   // Add the flag if we have it.
2034   if (Flag.getNode())
2035     RetOps.push_back(Flag);
2036
2037   return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
2038 }
2039
2040 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2041   if (N->getNumValues() != 1)
2042     return false;
2043   if (!N->hasNUsesOfValue(1, 0))
2044     return false;
2045
2046   SDValue TCChain = Chain;
2047   SDNode *Copy = *N->use_begin();
2048   if (Copy->getOpcode() == ISD::CopyToReg) {
2049     // If the copy has a glue operand, we conservatively assume it isn't safe to
2050     // perform a tail call.
2051     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2052       return false;
2053     TCChain = Copy->getOperand(0);
2054   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2055     return false;
2056
2057   bool HasRet = false;
2058   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2059        UI != UE; ++UI) {
2060     if (UI->getOpcode() != X86ISD::RET_FLAG)
2061       return false;
2062     // If we are returning more than one value, we can definitely
2063     // not make a tail call see PR19530
2064     if (UI->getNumOperands() > 4)
2065       return false;
2066     if (UI->getNumOperands() == 4 &&
2067         UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2068       return false;
2069     HasRet = true;
2070   }
2071
2072   if (!HasRet)
2073     return false;
2074
2075   Chain = TCChain;
2076   return true;
2077 }
2078
2079 EVT
2080 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
2081                                             ISD::NodeType ExtendKind) const {
2082   MVT ReturnMVT;
2083   // TODO: Is this also valid on 32-bit?
2084   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2085     ReturnMVT = MVT::i8;
2086   else
2087     ReturnMVT = MVT::i32;
2088
2089   EVT MinVT = getRegisterType(Context, ReturnMVT);
2090   return VT.bitsLT(MinVT) ? MinVT : VT;
2091 }
2092
2093 /// Lower the result values of a call into the
2094 /// appropriate copies out of appropriate physical registers.
2095 ///
2096 SDValue
2097 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2098                                    CallingConv::ID CallConv, bool isVarArg,
2099                                    const SmallVectorImpl<ISD::InputArg> &Ins,
2100                                    SDLoc dl, SelectionDAG &DAG,
2101                                    SmallVectorImpl<SDValue> &InVals) const {
2102
2103   // Assign locations to each value returned by this call.
2104   SmallVector<CCValAssign, 16> RVLocs;
2105   bool Is64Bit = Subtarget->is64Bit();
2106   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2107                  *DAG.getContext());
2108   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2109
2110   // Copy all of the result registers out of their specified physreg.
2111   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2112     CCValAssign &VA = RVLocs[i];
2113     EVT CopyVT = VA.getLocVT();
2114
2115     // If this is x86-64, and we disabled SSE, we can't return FP values
2116     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2117         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2118       report_fatal_error("SSE register return with SSE disabled");
2119     }
2120
2121     // If we prefer to use the value in xmm registers, copy it out as f80 and
2122     // use a truncate to move it from fp stack reg to xmm reg.
2123     bool RoundAfterCopy = false;
2124     if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2125         isScalarFPTypeInSSEReg(VA.getValVT())) {
2126       CopyVT = MVT::f80;
2127       RoundAfterCopy = (CopyVT != VA.getLocVT());
2128     }
2129
2130     Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2131                                CopyVT, InFlag).getValue(1);
2132     SDValue Val = Chain.getValue(0);
2133
2134     if (RoundAfterCopy)
2135       Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2136                         // This truncation won't change the value.
2137                         DAG.getIntPtrConstant(1, dl));
2138
2139     if (VA.isExtInLoc() && VA.getValVT().getScalarType() == MVT::i1)
2140       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
2141
2142     InFlag = Chain.getValue(2);
2143     InVals.push_back(Val);
2144   }
2145
2146   return Chain;
2147 }
2148
2149 //===----------------------------------------------------------------------===//
2150 //                C & StdCall & Fast Calling Convention implementation
2151 //===----------------------------------------------------------------------===//
2152 //  StdCall calling convention seems to be standard for many Windows' API
2153 //  routines and around. It differs from C calling convention just a little:
2154 //  callee should clean up the stack, not caller. Symbols should be also
2155 //  decorated in some fancy way :) It doesn't support any vector arguments.
2156 //  For info on fast calling convention see Fast Calling Convention (tail call)
2157 //  implementation LowerX86_32FastCCCallTo.
2158
2159 /// CallIsStructReturn - Determines whether a call uses struct return
2160 /// semantics.
2161 enum StructReturnType {
2162   NotStructReturn,
2163   RegStructReturn,
2164   StackStructReturn
2165 };
2166 static StructReturnType
2167 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2168   if (Outs.empty())
2169     return NotStructReturn;
2170
2171   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2172   if (!Flags.isSRet())
2173     return NotStructReturn;
2174   if (Flags.isInReg())
2175     return RegStructReturn;
2176   return StackStructReturn;
2177 }
2178
2179 /// Determines whether a function uses struct return semantics.
2180 static StructReturnType
2181 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2182   if (Ins.empty())
2183     return NotStructReturn;
2184
2185   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2186   if (!Flags.isSRet())
2187     return NotStructReturn;
2188   if (Flags.isInReg())
2189     return RegStructReturn;
2190   return StackStructReturn;
2191 }
2192
2193 /// Make a copy of an aggregate at address specified by "Src" to address
2194 /// "Dst" with size and alignment information specified by the specific
2195 /// parameter attribute. The copy will be passed as a byval function parameter.
2196 static SDValue
2197 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2198                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2199                           SDLoc dl) {
2200   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
2201
2202   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2203                        /*isVolatile*/false, /*AlwaysInline=*/true,
2204                        /*isTailCall*/false,
2205                        MachinePointerInfo(), MachinePointerInfo());
2206 }
2207
2208 /// Return true if the calling convention is one that
2209 /// supports tail call optimization.
2210 static bool IsTailCallConvention(CallingConv::ID CC) {
2211   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2212           CC == CallingConv::HiPE);
2213 }
2214
2215 /// \brief Return true if the calling convention is a C calling convention.
2216 static bool IsCCallConvention(CallingConv::ID CC) {
2217   return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2218           CC == CallingConv::X86_64_SysV);
2219 }
2220
2221 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2222   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2223     return false;
2224
2225   CallSite CS(CI);
2226   CallingConv::ID CalleeCC = CS.getCallingConv();
2227   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2228     return false;
2229
2230   return true;
2231 }
2232
2233 /// Return true if the function is being made into
2234 /// a tailcall target by changing its ABI.
2235 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2236                                    bool GuaranteedTailCallOpt) {
2237   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2238 }
2239
2240 SDValue
2241 X86TargetLowering::LowerMemArgument(SDValue Chain,
2242                                     CallingConv::ID CallConv,
2243                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2244                                     SDLoc dl, SelectionDAG &DAG,
2245                                     const CCValAssign &VA,
2246                                     MachineFrameInfo *MFI,
2247                                     unsigned i) const {
2248   // Create the nodes corresponding to a load from this parameter slot.
2249   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2250   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2251       CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2252   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2253   EVT ValVT;
2254
2255   // If value is passed by pointer we have address passed instead of the value
2256   // itself.
2257   bool ExtendedInMem = VA.isExtInLoc() &&
2258     VA.getValVT().getScalarType() == MVT::i1;
2259
2260   if (VA.getLocInfo() == CCValAssign::Indirect || ExtendedInMem)
2261     ValVT = VA.getLocVT();
2262   else
2263     ValVT = VA.getValVT();
2264
2265   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2266   // changed with more analysis.
2267   // In case of tail call optimization mark all arguments mutable. Since they
2268   // could be overwritten by lowering of arguments in case of a tail call.
2269   if (Flags.isByVal()) {
2270     unsigned Bytes = Flags.getByValSize();
2271     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2272     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2273     return DAG.getFrameIndex(FI, getPointerTy());
2274   } else {
2275     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2276                                     VA.getLocMemOffset(), isImmutable);
2277     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2278     SDValue Val =  DAG.getLoad(ValVT, dl, Chain, FIN,
2279                                MachinePointerInfo::getFixedStack(FI),
2280                                false, false, false, 0);
2281     return ExtendedInMem ?
2282       DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val) : Val;
2283   }
2284 }
2285
2286 // FIXME: Get this from tablegen.
2287 static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
2288                                                 const X86Subtarget *Subtarget) {
2289   assert(Subtarget->is64Bit());
2290
2291   if (Subtarget->isCallingConvWin64(CallConv)) {
2292     static const MCPhysReg GPR64ArgRegsWin64[] = {
2293       X86::RCX, X86::RDX, X86::R8,  X86::R9
2294     };
2295     return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
2296   }
2297
2298   static const MCPhysReg GPR64ArgRegs64Bit[] = {
2299     X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2300   };
2301   return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
2302 }
2303
2304 // FIXME: Get this from tablegen.
2305 static ArrayRef<MCPhysReg> get64BitArgumentXMMs(MachineFunction &MF,
2306                                                 CallingConv::ID CallConv,
2307                                                 const X86Subtarget *Subtarget) {
2308   assert(Subtarget->is64Bit());
2309   if (Subtarget->isCallingConvWin64(CallConv)) {
2310     // The XMM registers which might contain var arg parameters are shadowed
2311     // in their paired GPR.  So we only need to save the GPR to their home
2312     // slots.
2313     // TODO: __vectorcall will change this.
2314     return None;
2315   }
2316
2317   const Function *Fn = MF.getFunction();
2318   bool NoImplicitFloatOps = Fn->hasFnAttribute(Attribute::NoImplicitFloat);
2319   bool isSoftFloat = Subtarget->useSoftFloat();
2320   assert(!(isSoftFloat && NoImplicitFloatOps) &&
2321          "SSE register cannot be used when SSE is disabled!");
2322   if (isSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
2323     // Kernel mode asks for SSE to be disabled, so there are no XMM argument
2324     // registers.
2325     return None;
2326
2327   static const MCPhysReg XMMArgRegs64Bit[] = {
2328     X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2329     X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2330   };
2331   return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
2332 }
2333
2334 SDValue
2335 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2336                                         CallingConv::ID CallConv,
2337                                         bool isVarArg,
2338                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2339                                         SDLoc dl,
2340                                         SelectionDAG &DAG,
2341                                         SmallVectorImpl<SDValue> &InVals)
2342                                           const {
2343   MachineFunction &MF = DAG.getMachineFunction();
2344   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2345   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
2346
2347   const Function* Fn = MF.getFunction();
2348   if (Fn->hasExternalLinkage() &&
2349       Subtarget->isTargetCygMing() &&
2350       Fn->getName() == "main")
2351     FuncInfo->setForceFramePointer(true);
2352
2353   MachineFrameInfo *MFI = MF.getFrameInfo();
2354   bool Is64Bit = Subtarget->is64Bit();
2355   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2356
2357   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2358          "Var args not supported with calling convention fastcc, ghc or hipe");
2359
2360   // Assign locations to all of the incoming arguments.
2361   SmallVector<CCValAssign, 16> ArgLocs;
2362   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2363
2364   // Allocate shadow area for Win64
2365   if (IsWin64)
2366     CCInfo.AllocateStack(32, 8);
2367
2368   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2369
2370   unsigned LastVal = ~0U;
2371   SDValue ArgValue;
2372   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2373     CCValAssign &VA = ArgLocs[i];
2374     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2375     // places.
2376     assert(VA.getValNo() != LastVal &&
2377            "Don't support value assigned to multiple locs yet");
2378     (void)LastVal;
2379     LastVal = VA.getValNo();
2380
2381     if (VA.isRegLoc()) {
2382       EVT RegVT = VA.getLocVT();
2383       const TargetRegisterClass *RC;
2384       if (RegVT == MVT::i32)
2385         RC = &X86::GR32RegClass;
2386       else if (Is64Bit && RegVT == MVT::i64)
2387         RC = &X86::GR64RegClass;
2388       else if (RegVT == MVT::f32)
2389         RC = &X86::FR32RegClass;
2390       else if (RegVT == MVT::f64)
2391         RC = &X86::FR64RegClass;
2392       else if (RegVT.is512BitVector())
2393         RC = &X86::VR512RegClass;
2394       else if (RegVT.is256BitVector())
2395         RC = &X86::VR256RegClass;
2396       else if (RegVT.is128BitVector())
2397         RC = &X86::VR128RegClass;
2398       else if (RegVT == MVT::x86mmx)
2399         RC = &X86::VR64RegClass;
2400       else if (RegVT == MVT::i1)
2401         RC = &X86::VK1RegClass;
2402       else if (RegVT == MVT::v8i1)
2403         RC = &X86::VK8RegClass;
2404       else if (RegVT == MVT::v16i1)
2405         RC = &X86::VK16RegClass;
2406       else if (RegVT == MVT::v32i1)
2407         RC = &X86::VK32RegClass;
2408       else if (RegVT == MVT::v64i1)
2409         RC = &X86::VK64RegClass;
2410       else
2411         llvm_unreachable("Unknown argument type!");
2412
2413       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2414       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2415
2416       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2417       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2418       // right size.
2419       if (VA.getLocInfo() == CCValAssign::SExt)
2420         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2421                                DAG.getValueType(VA.getValVT()));
2422       else if (VA.getLocInfo() == CCValAssign::ZExt)
2423         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2424                                DAG.getValueType(VA.getValVT()));
2425       else if (VA.getLocInfo() == CCValAssign::BCvt)
2426         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2427
2428       if (VA.isExtInLoc()) {
2429         // Handle MMX values passed in XMM regs.
2430         if (RegVT.isVector() && VA.getValVT().getScalarType() != MVT::i1)
2431           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2432         else
2433           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2434       }
2435     } else {
2436       assert(VA.isMemLoc());
2437       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2438     }
2439
2440     // If value is passed via pointer - do a load.
2441     if (VA.getLocInfo() == CCValAssign::Indirect)
2442       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2443                              MachinePointerInfo(), false, false, false, 0);
2444
2445     InVals.push_back(ArgValue);
2446   }
2447
2448   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2449     // All x86 ABIs require that for returning structs by value we copy the
2450     // sret argument into %rax/%eax (depending on ABI) for the return. Save
2451     // the argument into a virtual register so that we can access it from the
2452     // return points.
2453     if (Ins[i].Flags.isSRet()) {
2454       unsigned Reg = FuncInfo->getSRetReturnReg();
2455       if (!Reg) {
2456         MVT PtrTy = getPointerTy();
2457         Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2458         FuncInfo->setSRetReturnReg(Reg);
2459       }
2460       SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2461       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2462       break;
2463     }
2464   }
2465
2466   unsigned StackSize = CCInfo.getNextStackOffset();
2467   // Align stack specially for tail calls.
2468   if (FuncIsMadeTailCallSafe(CallConv,
2469                              MF.getTarget().Options.GuaranteedTailCallOpt))
2470     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2471
2472   // If the function takes variable number of arguments, make a frame index for
2473   // the start of the first vararg value... for expansion of llvm.va_start. We
2474   // can skip this if there are no va_start calls.
2475   if (MFI->hasVAStart() &&
2476       (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2477                    CallConv != CallingConv::X86_ThisCall))) {
2478     FuncInfo->setVarArgsFrameIndex(
2479         MFI->CreateFixedObject(1, StackSize, true));
2480   }
2481
2482   MachineModuleInfo &MMI = MF.getMMI();
2483   const Function *WinEHParent = nullptr;
2484   if (IsWin64 && MMI.hasWinEHFuncInfo(Fn))
2485     WinEHParent = MMI.getWinEHParent(Fn);
2486   bool IsWinEHOutlined = WinEHParent && WinEHParent != Fn;
2487   bool IsWinEHParent = WinEHParent && WinEHParent == Fn;
2488
2489   // Figure out if XMM registers are in use.
2490   assert(!(Subtarget->useSoftFloat() &&
2491            Fn->hasFnAttribute(Attribute::NoImplicitFloat)) &&
2492          "SSE register cannot be used when SSE is disabled!");
2493
2494   // 64-bit calling conventions support varargs and register parameters, so we
2495   // have to do extra work to spill them in the prologue.
2496   if (Is64Bit && isVarArg && MFI->hasVAStart()) {
2497     // Find the first unallocated argument registers.
2498     ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
2499     ArrayRef<MCPhysReg> ArgXMMs = get64BitArgumentXMMs(MF, CallConv, Subtarget);
2500     unsigned NumIntRegs = CCInfo.getFirstUnallocated(ArgGPRs);
2501     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(ArgXMMs);
2502     assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2503            "SSE register cannot be used when SSE is disabled!");
2504
2505     // Gather all the live in physical registers.
2506     SmallVector<SDValue, 6> LiveGPRs;
2507     SmallVector<SDValue, 8> LiveXMMRegs;
2508     SDValue ALVal;
2509     for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
2510       unsigned GPR = MF.addLiveIn(Reg, &X86::GR64RegClass);
2511       LiveGPRs.push_back(
2512           DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64));
2513     }
2514     if (!ArgXMMs.empty()) {
2515       unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2516       ALVal = DAG.getCopyFromReg(Chain, dl, AL, MVT::i8);
2517       for (MCPhysReg Reg : ArgXMMs.slice(NumXMMRegs)) {
2518         unsigned XMMReg = MF.addLiveIn(Reg, &X86::VR128RegClass);
2519         LiveXMMRegs.push_back(
2520             DAG.getCopyFromReg(Chain, dl, XMMReg, MVT::v4f32));
2521       }
2522     }
2523
2524     if (IsWin64) {
2525       // Get to the caller-allocated home save location.  Add 8 to account
2526       // for the return address.
2527       int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2528       FuncInfo->setRegSaveFrameIndex(
2529           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2530       // Fixup to set vararg frame on shadow area (4 x i64).
2531       if (NumIntRegs < 4)
2532         FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2533     } else {
2534       // For X86-64, if there are vararg parameters that are passed via
2535       // registers, then we must store them to their spots on the stack so
2536       // they may be loaded by deferencing the result of va_next.
2537       FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2538       FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
2539       FuncInfo->setRegSaveFrameIndex(MFI->CreateStackObject(
2540           ArgGPRs.size() * 8 + ArgXMMs.size() * 16, 16, false));
2541     }
2542
2543     // Store the integer parameter registers.
2544     SmallVector<SDValue, 8> MemOps;
2545     SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2546                                       getPointerTy());
2547     unsigned Offset = FuncInfo->getVarArgsGPOffset();
2548     for (SDValue Val : LiveGPRs) {
2549       SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2550                                 DAG.getIntPtrConstant(Offset, dl));
2551       SDValue Store =
2552         DAG.getStore(Val.getValue(1), dl, Val, FIN,
2553                      MachinePointerInfo::getFixedStack(
2554                        FuncInfo->getRegSaveFrameIndex(), Offset),
2555                      false, false, 0);
2556       MemOps.push_back(Store);
2557       Offset += 8;
2558     }
2559
2560     if (!ArgXMMs.empty() && NumXMMRegs != ArgXMMs.size()) {
2561       // Now store the XMM (fp + vector) parameter registers.
2562       SmallVector<SDValue, 12> SaveXMMOps;
2563       SaveXMMOps.push_back(Chain);
2564       SaveXMMOps.push_back(ALVal);
2565       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2566                              FuncInfo->getRegSaveFrameIndex(), dl));
2567       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2568                              FuncInfo->getVarArgsFPOffset(), dl));
2569       SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
2570                         LiveXMMRegs.end());
2571       MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2572                                    MVT::Other, SaveXMMOps));
2573     }
2574
2575     if (!MemOps.empty())
2576       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2577   } else if (IsWinEHOutlined) {
2578     // Get to the caller-allocated home save location.  Add 8 to account
2579     // for the return address.
2580     int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2581     FuncInfo->setRegSaveFrameIndex(MFI->CreateFixedObject(
2582         /*Size=*/1, /*SPOffset=*/HomeOffset + 8, /*Immutable=*/false));
2583
2584     MMI.getWinEHFuncInfo(Fn)
2585         .CatchHandlerParentFrameObjIdx[const_cast<Function *>(Fn)] =
2586         FuncInfo->getRegSaveFrameIndex();
2587
2588     // Store the second integer parameter (rdx) into rsp+16 relative to the
2589     // stack pointer at the entry of the function.
2590     SDValue RSFIN =
2591         DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), getPointerTy());
2592     unsigned GPR = MF.addLiveIn(X86::RDX, &X86::GR64RegClass);
2593     SDValue Val = DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64);
2594     Chain = DAG.getStore(
2595         Val.getValue(1), dl, Val, RSFIN,
2596         MachinePointerInfo::getFixedStack(FuncInfo->getRegSaveFrameIndex()),
2597         /*isVolatile=*/true, /*isNonTemporal=*/false, /*Alignment=*/0);
2598   }
2599
2600   if (isVarArg && MFI->hasMustTailInVarArgFunc()) {
2601     // Find the largest legal vector type.
2602     MVT VecVT = MVT::Other;
2603     // FIXME: Only some x86_32 calling conventions support AVX512.
2604     if (Subtarget->hasAVX512() &&
2605         (Is64Bit || (CallConv == CallingConv::X86_VectorCall ||
2606                      CallConv == CallingConv::Intel_OCL_BI)))
2607       VecVT = MVT::v16f32;
2608     else if (Subtarget->hasAVX())
2609       VecVT = MVT::v8f32;
2610     else if (Subtarget->hasSSE2())
2611       VecVT = MVT::v4f32;
2612
2613     // We forward some GPRs and some vector types.
2614     SmallVector<MVT, 2> RegParmTypes;
2615     MVT IntVT = Is64Bit ? MVT::i64 : MVT::i32;
2616     RegParmTypes.push_back(IntVT);
2617     if (VecVT != MVT::Other)
2618       RegParmTypes.push_back(VecVT);
2619
2620     // Compute the set of forwarded registers. The rest are scratch.
2621     SmallVectorImpl<ForwardedRegister> &Forwards =
2622         FuncInfo->getForwardedMustTailRegParms();
2623     CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, CC_X86);
2624
2625     // Conservatively forward AL on x86_64, since it might be used for varargs.
2626     if (Is64Bit && !CCInfo.isAllocated(X86::AL)) {
2627       unsigned ALVReg = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2628       Forwards.push_back(ForwardedRegister(ALVReg, X86::AL, MVT::i8));
2629     }
2630
2631     // Copy all forwards from physical to virtual registers.
2632     for (ForwardedRegister &F : Forwards) {
2633       // FIXME: Can we use a less constrained schedule?
2634       SDValue RegVal = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2635       F.VReg = MF.getRegInfo().createVirtualRegister(getRegClassFor(F.VT));
2636       Chain = DAG.getCopyToReg(Chain, dl, F.VReg, RegVal);
2637     }
2638   }
2639
2640   // Some CCs need callee pop.
2641   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2642                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2643     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2644   } else {
2645     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2646     // If this is an sret function, the return should pop the hidden pointer.
2647     if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2648         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2649         argsAreStructReturn(Ins) == StackStructReturn)
2650       FuncInfo->setBytesToPopOnReturn(4);
2651   }
2652
2653   if (!Is64Bit) {
2654     // RegSaveFrameIndex is X86-64 only.
2655     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2656     if (CallConv == CallingConv::X86_FastCall ||
2657         CallConv == CallingConv::X86_ThisCall)
2658       // fastcc functions can't have varargs.
2659       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2660   }
2661
2662   FuncInfo->setArgumentStackSize(StackSize);
2663
2664   if (IsWinEHParent) {
2665     int UnwindHelpFI = MFI->CreateStackObject(8, 8, /*isSS=*/false);
2666     SDValue StackSlot = DAG.getFrameIndex(UnwindHelpFI, MVT::i64);
2667     MMI.getWinEHFuncInfo(MF.getFunction()).UnwindHelpFrameIdx = UnwindHelpFI;
2668     SDValue Neg2 = DAG.getConstant(-2, dl, MVT::i64);
2669     Chain = DAG.getStore(Chain, dl, Neg2, StackSlot,
2670                          MachinePointerInfo::getFixedStack(UnwindHelpFI),
2671                          /*isVolatile=*/true,
2672                          /*isNonTemporal=*/false, /*Alignment=*/0);
2673   }
2674
2675   return Chain;
2676 }
2677
2678 SDValue
2679 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2680                                     SDValue StackPtr, SDValue Arg,
2681                                     SDLoc dl, SelectionDAG &DAG,
2682                                     const CCValAssign &VA,
2683                                     ISD::ArgFlagsTy Flags) const {
2684   unsigned LocMemOffset = VA.getLocMemOffset();
2685   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
2686   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2687   if (Flags.isByVal())
2688     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2689
2690   return DAG.getStore(Chain, dl, Arg, PtrOff,
2691                       MachinePointerInfo::getStack(LocMemOffset),
2692                       false, false, 0);
2693 }
2694
2695 /// Emit a load of return address if tail call
2696 /// optimization is performed and it is required.
2697 SDValue
2698 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2699                                            SDValue &OutRetAddr, SDValue Chain,
2700                                            bool IsTailCall, bool Is64Bit,
2701                                            int FPDiff, SDLoc dl) const {
2702   // Adjust the Return address stack slot.
2703   EVT VT = getPointerTy();
2704   OutRetAddr = getReturnAddressFrameIndex(DAG);
2705
2706   // Load the "old" Return address.
2707   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2708                            false, false, false, 0);
2709   return SDValue(OutRetAddr.getNode(), 1);
2710 }
2711
2712 /// Emit a store of the return address if tail call
2713 /// optimization is performed and it is required (FPDiff!=0).
2714 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2715                                         SDValue Chain, SDValue RetAddrFrIdx,
2716                                         EVT PtrVT, unsigned SlotSize,
2717                                         int FPDiff, SDLoc dl) {
2718   // Store the return address to the appropriate stack slot.
2719   if (!FPDiff) return Chain;
2720   // Calculate the new stack slot for the return address.
2721   int NewReturnAddrFI =
2722     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2723                                          false);
2724   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2725   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2726                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2727                        false, false, 0);
2728   return Chain;
2729 }
2730
2731 SDValue
2732 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2733                              SmallVectorImpl<SDValue> &InVals) const {
2734   SelectionDAG &DAG                     = CLI.DAG;
2735   SDLoc &dl                             = CLI.DL;
2736   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2737   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2738   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2739   SDValue Chain                         = CLI.Chain;
2740   SDValue Callee                        = CLI.Callee;
2741   CallingConv::ID CallConv              = CLI.CallConv;
2742   bool &isTailCall                      = CLI.IsTailCall;
2743   bool isVarArg                         = CLI.IsVarArg;
2744
2745   MachineFunction &MF = DAG.getMachineFunction();
2746   bool Is64Bit        = Subtarget->is64Bit();
2747   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2748   StructReturnType SR = callIsStructReturn(Outs);
2749   bool IsSibcall      = false;
2750   X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2751
2752   if (MF.getTarget().Options.DisableTailCalls)
2753     isTailCall = false;
2754
2755   bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2756   if (IsMustTail) {
2757     // Force this to be a tail call.  The verifier rules are enough to ensure
2758     // that we can lower this successfully without moving the return address
2759     // around.
2760     isTailCall = true;
2761   } else if (isTailCall) {
2762     // Check if it's really possible to do a tail call.
2763     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2764                     isVarArg, SR != NotStructReturn,
2765                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2766                     Outs, OutVals, Ins, DAG);
2767
2768     // Sibcalls are automatically detected tailcalls which do not require
2769     // ABI changes.
2770     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2771       IsSibcall = true;
2772
2773     if (isTailCall)
2774       ++NumTailCalls;
2775   }
2776
2777   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2778          "Var args not supported with calling convention fastcc, ghc or hipe");
2779
2780   // Analyze operands of the call, assigning locations to each operand.
2781   SmallVector<CCValAssign, 16> ArgLocs;
2782   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2783
2784   // Allocate shadow area for Win64
2785   if (IsWin64)
2786     CCInfo.AllocateStack(32, 8);
2787
2788   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2789
2790   // Get a count of how many bytes are to be pushed on the stack.
2791   unsigned NumBytes = CCInfo.getNextStackOffset();
2792   if (IsSibcall)
2793     // This is a sibcall. The memory operands are available in caller's
2794     // own caller's stack.
2795     NumBytes = 0;
2796   else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
2797            IsTailCallConvention(CallConv))
2798     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2799
2800   int FPDiff = 0;
2801   if (isTailCall && !IsSibcall && !IsMustTail) {
2802     // Lower arguments at fp - stackoffset + fpdiff.
2803     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2804
2805     FPDiff = NumBytesCallerPushed - NumBytes;
2806
2807     // Set the delta of movement of the returnaddr stackslot.
2808     // But only set if delta is greater than previous delta.
2809     if (FPDiff < X86Info->getTCReturnAddrDelta())
2810       X86Info->setTCReturnAddrDelta(FPDiff);
2811   }
2812
2813   unsigned NumBytesToPush = NumBytes;
2814   unsigned NumBytesToPop = NumBytes;
2815
2816   // If we have an inalloca argument, all stack space has already been allocated
2817   // for us and be right at the top of the stack.  We don't support multiple
2818   // arguments passed in memory when using inalloca.
2819   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2820     NumBytesToPush = 0;
2821     if (!ArgLocs.back().isMemLoc())
2822       report_fatal_error("cannot use inalloca attribute on a register "
2823                          "parameter");
2824     if (ArgLocs.back().getLocMemOffset() != 0)
2825       report_fatal_error("any parameter with the inalloca attribute must be "
2826                          "the only memory argument");
2827   }
2828
2829   if (!IsSibcall)
2830     Chain = DAG.getCALLSEQ_START(
2831         Chain, DAG.getIntPtrConstant(NumBytesToPush, dl, true), dl);
2832
2833   SDValue RetAddrFrIdx;
2834   // Load return address for tail calls.
2835   if (isTailCall && FPDiff)
2836     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2837                                     Is64Bit, FPDiff, dl);
2838
2839   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2840   SmallVector<SDValue, 8> MemOpChains;
2841   SDValue StackPtr;
2842
2843   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2844   // of tail call optimization arguments are handle later.
2845   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
2846   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2847     // Skip inalloca arguments, they have already been written.
2848     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2849     if (Flags.isInAlloca())
2850       continue;
2851
2852     CCValAssign &VA = ArgLocs[i];
2853     EVT RegVT = VA.getLocVT();
2854     SDValue Arg = OutVals[i];
2855     bool isByVal = Flags.isByVal();
2856
2857     // Promote the value if needed.
2858     switch (VA.getLocInfo()) {
2859     default: llvm_unreachable("Unknown loc info!");
2860     case CCValAssign::Full: break;
2861     case CCValAssign::SExt:
2862       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2863       break;
2864     case CCValAssign::ZExt:
2865       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2866       break;
2867     case CCValAssign::AExt:
2868       if (Arg.getValueType().isVector() &&
2869           Arg.getValueType().getScalarType() == MVT::i1)
2870         Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2871       else if (RegVT.is128BitVector()) {
2872         // Special case: passing MMX values in XMM registers.
2873         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2874         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2875         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2876       } else
2877         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2878       break;
2879     case CCValAssign::BCvt:
2880       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2881       break;
2882     case CCValAssign::Indirect: {
2883       // Store the argument.
2884       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2885       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2886       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2887                            MachinePointerInfo::getFixedStack(FI),
2888                            false, false, 0);
2889       Arg = SpillSlot;
2890       break;
2891     }
2892     }
2893
2894     if (VA.isRegLoc()) {
2895       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2896       if (isVarArg && IsWin64) {
2897         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2898         // shadow reg if callee is a varargs function.
2899         unsigned ShadowReg = 0;
2900         switch (VA.getLocReg()) {
2901         case X86::XMM0: ShadowReg = X86::RCX; break;
2902         case X86::XMM1: ShadowReg = X86::RDX; break;
2903         case X86::XMM2: ShadowReg = X86::R8; break;
2904         case X86::XMM3: ShadowReg = X86::R9; break;
2905         }
2906         if (ShadowReg)
2907           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2908       }
2909     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2910       assert(VA.isMemLoc());
2911       if (!StackPtr.getNode())
2912         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2913                                       getPointerTy());
2914       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2915                                              dl, DAG, VA, Flags));
2916     }
2917   }
2918
2919   if (!MemOpChains.empty())
2920     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2921
2922   if (Subtarget->isPICStyleGOT()) {
2923     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2924     // GOT pointer.
2925     if (!isTailCall) {
2926       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2927                DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2928     } else {
2929       // If we are tail calling and generating PIC/GOT style code load the
2930       // address of the callee into ECX. The value in ecx is used as target of
2931       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2932       // for tail calls on PIC/GOT architectures. Normally we would just put the
2933       // address of GOT into ebx and then call target@PLT. But for tail calls
2934       // ebx would be restored (since ebx is callee saved) before jumping to the
2935       // target@PLT.
2936
2937       // Note: The actual moving to ECX is done further down.
2938       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2939       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2940           !G->getGlobal()->hasProtectedVisibility())
2941         Callee = LowerGlobalAddress(Callee, DAG);
2942       else if (isa<ExternalSymbolSDNode>(Callee))
2943         Callee = LowerExternalSymbol(Callee, DAG);
2944     }
2945   }
2946
2947   if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail) {
2948     // From AMD64 ABI document:
2949     // For calls that may call functions that use varargs or stdargs
2950     // (prototype-less calls or calls to functions containing ellipsis (...) in
2951     // the declaration) %al is used as hidden argument to specify the number
2952     // of SSE registers used. The contents of %al do not need to match exactly
2953     // the number of registers, but must be an ubound on the number of SSE
2954     // registers used and is in the range 0 - 8 inclusive.
2955
2956     // Count the number of XMM registers allocated.
2957     static const MCPhysReg XMMArgRegs[] = {
2958       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2959       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2960     };
2961     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
2962     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2963            && "SSE registers cannot be used when SSE is disabled");
2964
2965     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2966                                         DAG.getConstant(NumXMMRegs, dl,
2967                                                         MVT::i8)));
2968   }
2969
2970   if (isVarArg && IsMustTail) {
2971     const auto &Forwards = X86Info->getForwardedMustTailRegParms();
2972     for (const auto &F : Forwards) {
2973       SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2974       RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
2975     }
2976   }
2977
2978   // For tail calls lower the arguments to the 'real' stack slots.  Sibcalls
2979   // don't need this because the eligibility check rejects calls that require
2980   // shuffling arguments passed in memory.
2981   if (!IsSibcall && isTailCall) {
2982     // Force all the incoming stack arguments to be loaded from the stack
2983     // before any new outgoing arguments are stored to the stack, because the
2984     // outgoing stack slots may alias the incoming argument stack slots, and
2985     // the alias isn't otherwise explicit. This is slightly more conservative
2986     // than necessary, because it means that each store effectively depends
2987     // on every argument instead of just those arguments it would clobber.
2988     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2989
2990     SmallVector<SDValue, 8> MemOpChains2;
2991     SDValue FIN;
2992     int FI = 0;
2993     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2994       CCValAssign &VA = ArgLocs[i];
2995       if (VA.isRegLoc())
2996         continue;
2997       assert(VA.isMemLoc());
2998       SDValue Arg = OutVals[i];
2999       ISD::ArgFlagsTy Flags = Outs[i].Flags;
3000       // Skip inalloca arguments.  They don't require any work.
3001       if (Flags.isInAlloca())
3002         continue;
3003       // Create frame index.
3004       int32_t Offset = VA.getLocMemOffset()+FPDiff;
3005       uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
3006       FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3007       FIN = DAG.getFrameIndex(FI, getPointerTy());
3008
3009       if (Flags.isByVal()) {
3010         // Copy relative to framepointer.
3011         SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset(), dl);
3012         if (!StackPtr.getNode())
3013           StackPtr = DAG.getCopyFromReg(Chain, dl,
3014                                         RegInfo->getStackRegister(),
3015                                         getPointerTy());
3016         Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
3017
3018         MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
3019                                                          ArgChain,
3020                                                          Flags, DAG, dl));
3021       } else {
3022         // Store relative to framepointer.
3023         MemOpChains2.push_back(
3024           DAG.getStore(ArgChain, dl, Arg, FIN,
3025                        MachinePointerInfo::getFixedStack(FI),
3026                        false, false, 0));
3027       }
3028     }
3029
3030     if (!MemOpChains2.empty())
3031       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3032
3033     // Store the return address to the appropriate stack slot.
3034     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
3035                                      getPointerTy(), RegInfo->getSlotSize(),
3036                                      FPDiff, dl);
3037   }
3038
3039   // Build a sequence of copy-to-reg nodes chained together with token chain
3040   // and flag operands which copy the outgoing args into registers.
3041   SDValue InFlag;
3042   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3043     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3044                              RegsToPass[i].second, InFlag);
3045     InFlag = Chain.getValue(1);
3046   }
3047
3048   if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
3049     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
3050     // In the 64-bit large code model, we have to make all calls
3051     // through a register, since the call instruction's 32-bit
3052     // pc-relative offset may not be large enough to hold the whole
3053     // address.
3054   } else if (Callee->getOpcode() == ISD::GlobalAddress) {
3055     // If the callee is a GlobalAddress node (quite common, every direct call
3056     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
3057     // it.
3058     GlobalAddressSDNode* G = cast<GlobalAddressSDNode>(Callee);
3059
3060     // We should use extra load for direct calls to dllimported functions in
3061     // non-JIT mode.
3062     const GlobalValue *GV = G->getGlobal();
3063     if (!GV->hasDLLImportStorageClass()) {
3064       unsigned char OpFlags = 0;
3065       bool ExtraLoad = false;
3066       unsigned WrapperKind = ISD::DELETED_NODE;
3067
3068       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
3069       // external symbols most go through the PLT in PIC mode.  If the symbol
3070       // has hidden or protected visibility, or if it is static or local, then
3071       // we don't need to use the PLT - we can directly call it.
3072       if (Subtarget->isTargetELF() &&
3073           DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
3074           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
3075         OpFlags = X86II::MO_PLT;
3076       } else if (Subtarget->isPICStyleStubAny() &&
3077                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
3078                  (!Subtarget->getTargetTriple().isMacOSX() ||
3079                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3080         // PC-relative references to external symbols should go through $stub,
3081         // unless we're building with the leopard linker or later, which
3082         // automatically synthesizes these stubs.
3083         OpFlags = X86II::MO_DARWIN_STUB;
3084       } else if (Subtarget->isPICStyleRIPRel() && isa<Function>(GV) &&
3085                  cast<Function>(GV)->hasFnAttribute(Attribute::NonLazyBind)) {
3086         // If the function is marked as non-lazy, generate an indirect call
3087         // which loads from the GOT directly. This avoids runtime overhead
3088         // at the cost of eager binding (and one extra byte of encoding).
3089         OpFlags = X86II::MO_GOTPCREL;
3090         WrapperKind = X86ISD::WrapperRIP;
3091         ExtraLoad = true;
3092       }
3093
3094       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
3095                                           G->getOffset(), OpFlags);
3096
3097       // Add a wrapper if needed.
3098       if (WrapperKind != ISD::DELETED_NODE)
3099         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
3100       // Add extra indirection if needed.
3101       if (ExtraLoad)
3102         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
3103                              MachinePointerInfo::getGOT(),
3104                              false, false, false, 0);
3105     }
3106   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3107     unsigned char OpFlags = 0;
3108
3109     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
3110     // external symbols should go through the PLT.
3111     if (Subtarget->isTargetELF() &&
3112         DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
3113       OpFlags = X86II::MO_PLT;
3114     } else if (Subtarget->isPICStyleStubAny() &&
3115                (!Subtarget->getTargetTriple().isMacOSX() ||
3116                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3117       // PC-relative references to external symbols should go through $stub,
3118       // unless we're building with the leopard linker or later, which
3119       // automatically synthesizes these stubs.
3120       OpFlags = X86II::MO_DARWIN_STUB;
3121     }
3122
3123     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
3124                                          OpFlags);
3125   } else if (Subtarget->isTarget64BitILP32() &&
3126              Callee->getValueType(0) == MVT::i32) {
3127     // Zero-extend the 32-bit Callee address into a 64-bit according to x32 ABI
3128     Callee = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Callee);
3129   }
3130
3131   // Returns a chain & a flag for retval copy to use.
3132   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3133   SmallVector<SDValue, 8> Ops;
3134
3135   if (!IsSibcall && isTailCall) {
3136     Chain = DAG.getCALLSEQ_END(Chain,
3137                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3138                                DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
3139     InFlag = Chain.getValue(1);
3140   }
3141
3142   Ops.push_back(Chain);
3143   Ops.push_back(Callee);
3144
3145   if (isTailCall)
3146     Ops.push_back(DAG.getConstant(FPDiff, dl, MVT::i32));
3147
3148   // Add argument registers to the end of the list so that they are known live
3149   // into the call.
3150   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3151     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3152                                   RegsToPass[i].second.getValueType()));
3153
3154   // Add a register mask operand representing the call-preserved registers.
3155   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
3156   const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
3157   assert(Mask && "Missing call preserved mask for calling convention");
3158   Ops.push_back(DAG.getRegisterMask(Mask));
3159
3160   if (InFlag.getNode())
3161     Ops.push_back(InFlag);
3162
3163   if (isTailCall) {
3164     // We used to do:
3165     //// If this is the first return lowered for this function, add the regs
3166     //// to the liveout set for the function.
3167     // This isn't right, although it's probably harmless on x86; liveouts
3168     // should be computed from returns not tail calls.  Consider a void
3169     // function making a tail call to a function returning int.
3170     MF.getFrameInfo()->setHasTailCall();
3171     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3172   }
3173
3174   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3175   InFlag = Chain.getValue(1);
3176
3177   // Create the CALLSEQ_END node.
3178   unsigned NumBytesForCalleeToPop;
3179   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3180                        DAG.getTarget().Options.GuaranteedTailCallOpt))
3181     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
3182   else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
3183            !Subtarget->getTargetTriple().isOSMSVCRT() &&
3184            SR == StackStructReturn)
3185     // If this is a call to a struct-return function, the callee
3186     // pops the hidden struct pointer, so we have to push it back.
3187     // This is common for Darwin/X86, Linux & Mingw32 targets.
3188     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3189     NumBytesForCalleeToPop = 4;
3190   else
3191     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
3192
3193   // Returns a flag for retval copy to use.
3194   if (!IsSibcall) {
3195     Chain = DAG.getCALLSEQ_END(Chain,
3196                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3197                                DAG.getIntPtrConstant(NumBytesForCalleeToPop, dl,
3198                                                      true),
3199                                InFlag, dl);
3200     InFlag = Chain.getValue(1);
3201   }
3202
3203   // Handle result values, copying them out of physregs into vregs that we
3204   // return.
3205   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3206                          Ins, dl, DAG, InVals);
3207 }
3208
3209 //===----------------------------------------------------------------------===//
3210 //                Fast Calling Convention (tail call) implementation
3211 //===----------------------------------------------------------------------===//
3212
3213 //  Like std call, callee cleans arguments, convention except that ECX is
3214 //  reserved for storing the tail called function address. Only 2 registers are
3215 //  free for argument passing (inreg). Tail call optimization is performed
3216 //  provided:
3217 //                * tailcallopt is enabled
3218 //                * caller/callee are fastcc
3219 //  On X86_64 architecture with GOT-style position independent code only local
3220 //  (within module) calls are supported at the moment.
3221 //  To keep the stack aligned according to platform abi the function
3222 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
3223 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3224 //  If a tail called function callee has more arguments than the caller the
3225 //  caller needs to make sure that there is room to move the RETADDR to. This is
3226 //  achieved by reserving an area the size of the argument delta right after the
3227 //  original RETADDR, but before the saved framepointer or the spilled registers
3228 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3229 //  stack layout:
3230 //    arg1
3231 //    arg2
3232 //    RETADDR
3233 //    [ new RETADDR
3234 //      move area ]
3235 //    (possible EBP)
3236 //    ESI
3237 //    EDI
3238 //    local1 ..
3239
3240 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3241 /// for a 16 byte align requirement.
3242 unsigned
3243 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3244                                                SelectionDAG& DAG) const {
3245   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3246   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
3247   unsigned StackAlignment = TFI.getStackAlignment();
3248   uint64_t AlignMask = StackAlignment - 1;
3249   int64_t Offset = StackSize;
3250   unsigned SlotSize = RegInfo->getSlotSize();
3251   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3252     // Number smaller than 12 so just add the difference.
3253     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3254   } else {
3255     // Mask out lower bits, add stackalignment once plus the 12 bytes.
3256     Offset = ((~AlignMask) & Offset) + StackAlignment +
3257       (StackAlignment-SlotSize);
3258   }
3259   return Offset;
3260 }
3261
3262 /// MatchingStackOffset - Return true if the given stack call argument is
3263 /// already available in the same position (relatively) of the caller's
3264 /// incoming argument stack.
3265 static
3266 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3267                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3268                          const X86InstrInfo *TII) {
3269   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3270   int FI = INT_MAX;
3271   if (Arg.getOpcode() == ISD::CopyFromReg) {
3272     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3273     if (!TargetRegisterInfo::isVirtualRegister(VR))
3274       return false;
3275     MachineInstr *Def = MRI->getVRegDef(VR);
3276     if (!Def)
3277       return false;
3278     if (!Flags.isByVal()) {
3279       if (!TII->isLoadFromStackSlot(Def, FI))
3280         return false;
3281     } else {
3282       unsigned Opcode = Def->getOpcode();
3283       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r ||
3284            Opcode == X86::LEA64_32r) &&
3285           Def->getOperand(1).isFI()) {
3286         FI = Def->getOperand(1).getIndex();
3287         Bytes = Flags.getByValSize();
3288       } else
3289         return false;
3290     }
3291   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3292     if (Flags.isByVal())
3293       // ByVal argument is passed in as a pointer but it's now being
3294       // dereferenced. e.g.
3295       // define @foo(%struct.X* %A) {
3296       //   tail call @bar(%struct.X* byval %A)
3297       // }
3298       return false;
3299     SDValue Ptr = Ld->getBasePtr();
3300     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3301     if (!FINode)
3302       return false;
3303     FI = FINode->getIndex();
3304   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3305     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3306     FI = FINode->getIndex();
3307     Bytes = Flags.getByValSize();
3308   } else
3309     return false;
3310
3311   assert(FI != INT_MAX);
3312   if (!MFI->isFixedObjectIndex(FI))
3313     return false;
3314   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3315 }
3316
3317 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3318 /// for tail call optimization. Targets which want to do tail call
3319 /// optimization should implement this function.
3320 bool
3321 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3322                                                      CallingConv::ID CalleeCC,
3323                                                      bool isVarArg,
3324                                                      bool isCalleeStructRet,
3325                                                      bool isCallerStructRet,
3326                                                      Type *RetTy,
3327                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3328                                     const SmallVectorImpl<SDValue> &OutVals,
3329                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3330                                                      SelectionDAG &DAG) const {
3331   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3332     return false;
3333
3334   // If -tailcallopt is specified, make fastcc functions tail-callable.
3335   const MachineFunction &MF = DAG.getMachineFunction();
3336   const Function *CallerF = MF.getFunction();
3337
3338   // If the function return type is x86_fp80 and the callee return type is not,
3339   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3340   // perform a tailcall optimization here.
3341   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3342     return false;
3343
3344   CallingConv::ID CallerCC = CallerF->getCallingConv();
3345   bool CCMatch = CallerCC == CalleeCC;
3346   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3347   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3348
3349   // Win64 functions have extra shadow space for argument homing. Don't do the
3350   // sibcall if the caller and callee have mismatched expectations for this
3351   // space.
3352   if (IsCalleeWin64 != IsCallerWin64)
3353     return false;
3354
3355   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3356     if (IsTailCallConvention(CalleeCC) && CCMatch)
3357       return true;
3358     return false;
3359   }
3360
3361   // Look for obvious safe cases to perform tail call optimization that do not
3362   // require ABI changes. This is what gcc calls sibcall.
3363
3364   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3365   // emit a special epilogue.
3366   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3367   if (RegInfo->needsStackRealignment(MF))
3368     return false;
3369
3370   // Also avoid sibcall optimization if either caller or callee uses struct
3371   // return semantics.
3372   if (isCalleeStructRet || isCallerStructRet)
3373     return false;
3374
3375   // An stdcall/thiscall caller is expected to clean up its arguments; the
3376   // callee isn't going to do that.
3377   // FIXME: this is more restrictive than needed. We could produce a tailcall
3378   // when the stack adjustment matches. For example, with a thiscall that takes
3379   // only one argument.
3380   if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3381                    CallerCC == CallingConv::X86_ThisCall))
3382     return false;
3383
3384   // Do not sibcall optimize vararg calls unless all arguments are passed via
3385   // registers.
3386   if (isVarArg && !Outs.empty()) {
3387
3388     // Optimizing for varargs on Win64 is unlikely to be safe without
3389     // additional testing.
3390     if (IsCalleeWin64 || IsCallerWin64)
3391       return false;
3392
3393     SmallVector<CCValAssign, 16> ArgLocs;
3394     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3395                    *DAG.getContext());
3396
3397     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3398     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3399       if (!ArgLocs[i].isRegLoc())
3400         return false;
3401   }
3402
3403   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3404   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3405   // this into a sibcall.
3406   bool Unused = false;
3407   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3408     if (!Ins[i].Used) {
3409       Unused = true;
3410       break;
3411     }
3412   }
3413   if (Unused) {
3414     SmallVector<CCValAssign, 16> RVLocs;
3415     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), RVLocs,
3416                    *DAG.getContext());
3417     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3418     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3419       CCValAssign &VA = RVLocs[i];
3420       if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3421         return false;
3422     }
3423   }
3424
3425   // If the calling conventions do not match, then we'd better make sure the
3426   // results are returned in the same way as what the caller expects.
3427   if (!CCMatch) {
3428     SmallVector<CCValAssign, 16> RVLocs1;
3429     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
3430                     *DAG.getContext());
3431     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3432
3433     SmallVector<CCValAssign, 16> RVLocs2;
3434     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
3435                     *DAG.getContext());
3436     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3437
3438     if (RVLocs1.size() != RVLocs2.size())
3439       return false;
3440     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3441       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3442         return false;
3443       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3444         return false;
3445       if (RVLocs1[i].isRegLoc()) {
3446         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3447           return false;
3448       } else {
3449         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3450           return false;
3451       }
3452     }
3453   }
3454
3455   // If the callee takes no arguments then go on to check the results of the
3456   // call.
3457   if (!Outs.empty()) {
3458     // Check if stack adjustment is needed. For now, do not do this if any
3459     // argument is passed on the stack.
3460     SmallVector<CCValAssign, 16> ArgLocs;
3461     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3462                    *DAG.getContext());
3463
3464     // Allocate shadow area for Win64
3465     if (IsCalleeWin64)
3466       CCInfo.AllocateStack(32, 8);
3467
3468     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3469     if (CCInfo.getNextStackOffset()) {
3470       MachineFunction &MF = DAG.getMachineFunction();
3471       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3472         return false;
3473
3474       // Check if the arguments are already laid out in the right way as
3475       // the caller's fixed stack objects.
3476       MachineFrameInfo *MFI = MF.getFrameInfo();
3477       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3478       const X86InstrInfo *TII = Subtarget->getInstrInfo();
3479       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3480         CCValAssign &VA = ArgLocs[i];
3481         SDValue Arg = OutVals[i];
3482         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3483         if (VA.getLocInfo() == CCValAssign::Indirect)
3484           return false;
3485         if (!VA.isRegLoc()) {
3486           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3487                                    MFI, MRI, TII))
3488             return false;
3489         }
3490       }
3491     }
3492
3493     // If the tailcall address may be in a register, then make sure it's
3494     // possible to register allocate for it. In 32-bit, the call address can
3495     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3496     // callee-saved registers are restored. These happen to be the same
3497     // registers used to pass 'inreg' arguments so watch out for those.
3498     if (!Subtarget->is64Bit() &&
3499         ((!isa<GlobalAddressSDNode>(Callee) &&
3500           !isa<ExternalSymbolSDNode>(Callee)) ||
3501          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3502       unsigned NumInRegs = 0;
3503       // In PIC we need an extra register to formulate the address computation
3504       // for the callee.
3505       unsigned MaxInRegs =
3506         (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3507
3508       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3509         CCValAssign &VA = ArgLocs[i];
3510         if (!VA.isRegLoc())
3511           continue;
3512         unsigned Reg = VA.getLocReg();
3513         switch (Reg) {
3514         default: break;
3515         case X86::EAX: case X86::EDX: case X86::ECX:
3516           if (++NumInRegs == MaxInRegs)
3517             return false;
3518           break;
3519         }
3520       }
3521     }
3522   }
3523
3524   return true;
3525 }
3526
3527 FastISel *
3528 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3529                                   const TargetLibraryInfo *libInfo) const {
3530   return X86::createFastISel(funcInfo, libInfo);
3531 }
3532
3533 //===----------------------------------------------------------------------===//
3534 //                           Other Lowering Hooks
3535 //===----------------------------------------------------------------------===//
3536
3537 static bool MayFoldLoad(SDValue Op) {
3538   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3539 }
3540
3541 static bool MayFoldIntoStore(SDValue Op) {
3542   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3543 }
3544
3545 static bool isTargetShuffle(unsigned Opcode) {
3546   switch(Opcode) {
3547   default: return false;
3548   case X86ISD::BLENDI:
3549   case X86ISD::PSHUFB:
3550   case X86ISD::PSHUFD:
3551   case X86ISD::PSHUFHW:
3552   case X86ISD::PSHUFLW:
3553   case X86ISD::SHUFP:
3554   case X86ISD::PALIGNR:
3555   case X86ISD::MOVLHPS:
3556   case X86ISD::MOVLHPD:
3557   case X86ISD::MOVHLPS:
3558   case X86ISD::MOVLPS:
3559   case X86ISD::MOVLPD:
3560   case X86ISD::MOVSHDUP:
3561   case X86ISD::MOVSLDUP:
3562   case X86ISD::MOVDDUP:
3563   case X86ISD::MOVSS:
3564   case X86ISD::MOVSD:
3565   case X86ISD::UNPCKL:
3566   case X86ISD::UNPCKH:
3567   case X86ISD::VPERMILPI:
3568   case X86ISD::VPERM2X128:
3569   case X86ISD::VPERMI:
3570     return true;
3571   }
3572 }
3573
3574 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3575                                     SDValue V1, unsigned TargetMask,
3576                                     SelectionDAG &DAG) {
3577   switch(Opc) {
3578   default: llvm_unreachable("Unknown x86 shuffle node");
3579   case X86ISD::PSHUFD:
3580   case X86ISD::PSHUFHW:
3581   case X86ISD::PSHUFLW:
3582   case X86ISD::VPERMILPI:
3583   case X86ISD::VPERMI:
3584     return DAG.getNode(Opc, dl, VT, V1,
3585                        DAG.getConstant(TargetMask, dl, MVT::i8));
3586   }
3587 }
3588
3589 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3590                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3591   switch(Opc) {
3592   default: llvm_unreachable("Unknown x86 shuffle node");
3593   case X86ISD::MOVLHPS:
3594   case X86ISD::MOVLHPD:
3595   case X86ISD::MOVHLPS:
3596   case X86ISD::MOVLPS:
3597   case X86ISD::MOVLPD:
3598   case X86ISD::MOVSS:
3599   case X86ISD::MOVSD:
3600   case X86ISD::UNPCKL:
3601   case X86ISD::UNPCKH:
3602     return DAG.getNode(Opc, dl, VT, V1, V2);
3603   }
3604 }
3605
3606 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3607   MachineFunction &MF = DAG.getMachineFunction();
3608   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3609   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3610   int ReturnAddrIndex = FuncInfo->getRAIndex();
3611
3612   if (ReturnAddrIndex == 0) {
3613     // Set up a frame object for the return address.
3614     unsigned SlotSize = RegInfo->getSlotSize();
3615     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3616                                                            -(int64_t)SlotSize,
3617                                                            false);
3618     FuncInfo->setRAIndex(ReturnAddrIndex);
3619   }
3620
3621   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3622 }
3623
3624 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3625                                        bool hasSymbolicDisplacement) {
3626   // Offset should fit into 32 bit immediate field.
3627   if (!isInt<32>(Offset))
3628     return false;
3629
3630   // If we don't have a symbolic displacement - we don't have any extra
3631   // restrictions.
3632   if (!hasSymbolicDisplacement)
3633     return true;
3634
3635   // FIXME: Some tweaks might be needed for medium code model.
3636   if (M != CodeModel::Small && M != CodeModel::Kernel)
3637     return false;
3638
3639   // For small code model we assume that latest object is 16MB before end of 31
3640   // bits boundary. We may also accept pretty large negative constants knowing
3641   // that all objects are in the positive half of address space.
3642   if (M == CodeModel::Small && Offset < 16*1024*1024)
3643     return true;
3644
3645   // For kernel code model we know that all object resist in the negative half
3646   // of 32bits address space. We may not accept negative offsets, since they may
3647   // be just off and we may accept pretty large positive ones.
3648   if (M == CodeModel::Kernel && Offset >= 0)
3649     return true;
3650
3651   return false;
3652 }
3653
3654 /// isCalleePop - Determines whether the callee is required to pop its
3655 /// own arguments. Callee pop is necessary to support tail calls.
3656 bool X86::isCalleePop(CallingConv::ID CallingConv,
3657                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3658   switch (CallingConv) {
3659   default:
3660     return false;
3661   case CallingConv::X86_StdCall:
3662   case CallingConv::X86_FastCall:
3663   case CallingConv::X86_ThisCall:
3664     return !is64Bit;
3665   case CallingConv::Fast:
3666   case CallingConv::GHC:
3667   case CallingConv::HiPE:
3668     if (IsVarArg)
3669       return false;
3670     return TailCallOpt;
3671   }
3672 }
3673
3674 /// \brief Return true if the condition is an unsigned comparison operation.
3675 static bool isX86CCUnsigned(unsigned X86CC) {
3676   switch (X86CC) {
3677   default: llvm_unreachable("Invalid integer condition!");
3678   case X86::COND_E:     return true;
3679   case X86::COND_G:     return false;
3680   case X86::COND_GE:    return false;
3681   case X86::COND_L:     return false;
3682   case X86::COND_LE:    return false;
3683   case X86::COND_NE:    return true;
3684   case X86::COND_B:     return true;
3685   case X86::COND_A:     return true;
3686   case X86::COND_BE:    return true;
3687   case X86::COND_AE:    return true;
3688   }
3689   llvm_unreachable("covered switch fell through?!");
3690 }
3691
3692 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3693 /// specific condition code, returning the condition code and the LHS/RHS of the
3694 /// comparison to make.
3695 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, SDLoc DL, bool isFP,
3696                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3697   if (!isFP) {
3698     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3699       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3700         // X > -1   -> X == 0, jump !sign.
3701         RHS = DAG.getConstant(0, DL, RHS.getValueType());
3702         return X86::COND_NS;
3703       }
3704       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3705         // X < 0   -> X == 0, jump on sign.
3706         return X86::COND_S;
3707       }
3708       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3709         // X < 1   -> X <= 0
3710         RHS = DAG.getConstant(0, DL, RHS.getValueType());
3711         return X86::COND_LE;
3712       }
3713     }
3714
3715     switch (SetCCOpcode) {
3716     default: llvm_unreachable("Invalid integer condition!");
3717     case ISD::SETEQ:  return X86::COND_E;
3718     case ISD::SETGT:  return X86::COND_G;
3719     case ISD::SETGE:  return X86::COND_GE;
3720     case ISD::SETLT:  return X86::COND_L;
3721     case ISD::SETLE:  return X86::COND_LE;
3722     case ISD::SETNE:  return X86::COND_NE;
3723     case ISD::SETULT: return X86::COND_B;
3724     case ISD::SETUGT: return X86::COND_A;
3725     case ISD::SETULE: return X86::COND_BE;
3726     case ISD::SETUGE: return X86::COND_AE;
3727     }
3728   }
3729
3730   // First determine if it is required or is profitable to flip the operands.
3731
3732   // If LHS is a foldable load, but RHS is not, flip the condition.
3733   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3734       !ISD::isNON_EXTLoad(RHS.getNode())) {
3735     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3736     std::swap(LHS, RHS);
3737   }
3738
3739   switch (SetCCOpcode) {
3740   default: break;
3741   case ISD::SETOLT:
3742   case ISD::SETOLE:
3743   case ISD::SETUGT:
3744   case ISD::SETUGE:
3745     std::swap(LHS, RHS);
3746     break;
3747   }
3748
3749   // On a floating point condition, the flags are set as follows:
3750   // ZF  PF  CF   op
3751   //  0 | 0 | 0 | X > Y
3752   //  0 | 0 | 1 | X < Y
3753   //  1 | 0 | 0 | X == Y
3754   //  1 | 1 | 1 | unordered
3755   switch (SetCCOpcode) {
3756   default: llvm_unreachable("Condcode should be pre-legalized away");
3757   case ISD::SETUEQ:
3758   case ISD::SETEQ:   return X86::COND_E;
3759   case ISD::SETOLT:              // flipped
3760   case ISD::SETOGT:
3761   case ISD::SETGT:   return X86::COND_A;
3762   case ISD::SETOLE:              // flipped
3763   case ISD::SETOGE:
3764   case ISD::SETGE:   return X86::COND_AE;
3765   case ISD::SETUGT:              // flipped
3766   case ISD::SETULT:
3767   case ISD::SETLT:   return X86::COND_B;
3768   case ISD::SETUGE:              // flipped
3769   case ISD::SETULE:
3770   case ISD::SETLE:   return X86::COND_BE;
3771   case ISD::SETONE:
3772   case ISD::SETNE:   return X86::COND_NE;
3773   case ISD::SETUO:   return X86::COND_P;
3774   case ISD::SETO:    return X86::COND_NP;
3775   case ISD::SETOEQ:
3776   case ISD::SETUNE:  return X86::COND_INVALID;
3777   }
3778 }
3779
3780 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3781 /// code. Current x86 isa includes the following FP cmov instructions:
3782 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3783 static bool hasFPCMov(unsigned X86CC) {
3784   switch (X86CC) {
3785   default:
3786     return false;
3787   case X86::COND_B:
3788   case X86::COND_BE:
3789   case X86::COND_E:
3790   case X86::COND_P:
3791   case X86::COND_A:
3792   case X86::COND_AE:
3793   case X86::COND_NE:
3794   case X86::COND_NP:
3795     return true;
3796   }
3797 }
3798
3799 /// isFPImmLegal - Returns true if the target can instruction select the
3800 /// specified FP immediate natively. If false, the legalizer will
3801 /// materialize the FP immediate as a load from a constant pool.
3802 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3803   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3804     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3805       return true;
3806   }
3807   return false;
3808 }
3809
3810 bool X86TargetLowering::shouldReduceLoadWidth(SDNode *Load,
3811                                               ISD::LoadExtType ExtTy,
3812                                               EVT NewVT) const {
3813   // "ELF Handling for Thread-Local Storage" specifies that R_X86_64_GOTTPOFF
3814   // relocation target a movq or addq instruction: don't let the load shrink.
3815   SDValue BasePtr = cast<LoadSDNode>(Load)->getBasePtr();
3816   if (BasePtr.getOpcode() == X86ISD::WrapperRIP)
3817     if (const auto *GA = dyn_cast<GlobalAddressSDNode>(BasePtr.getOperand(0)))
3818       return GA->getTargetFlags() != X86II::MO_GOTTPOFF;
3819   return true;
3820 }
3821
3822 /// \brief Returns true if it is beneficial to convert a load of a constant
3823 /// to just the constant itself.
3824 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3825                                                           Type *Ty) const {
3826   assert(Ty->isIntegerTy());
3827
3828   unsigned BitSize = Ty->getPrimitiveSizeInBits();
3829   if (BitSize == 0 || BitSize > 64)
3830     return false;
3831   return true;
3832 }
3833
3834 bool X86TargetLowering::isExtractSubvectorCheap(EVT ResVT,
3835                                                 unsigned Index) const {
3836   if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
3837     return false;
3838
3839   return (Index == 0 || Index == ResVT.getVectorNumElements());
3840 }
3841
3842 bool X86TargetLowering::isCheapToSpeculateCttz() const {
3843   // Speculate cttz only if we can directly use TZCNT.
3844   return Subtarget->hasBMI();
3845 }
3846
3847 bool X86TargetLowering::isCheapToSpeculateCtlz() const {
3848   // Speculate ctlz only if we can directly use LZCNT.
3849   return Subtarget->hasLZCNT();
3850 }
3851
3852 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3853 /// the specified range (L, H].
3854 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3855   return (Val < 0) || (Val >= Low && Val < Hi);
3856 }
3857
3858 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3859 /// specified value.
3860 static bool isUndefOrEqual(int Val, int CmpVal) {
3861   return (Val < 0 || Val == CmpVal);
3862 }
3863
3864 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3865 /// from position Pos and ending in Pos+Size, falls within the specified
3866 /// sequential range (Low, Low+Size]. or is undef.
3867 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3868                                        unsigned Pos, unsigned Size, int Low) {
3869   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3870     if (!isUndefOrEqual(Mask[i], Low))
3871       return false;
3872   return true;
3873 }
3874
3875 /// isVEXTRACTIndex - Return true if the specified
3876 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3877 /// suitable for instruction that extract 128 or 256 bit vectors
3878 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
3879   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
3880   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3881     return false;
3882
3883   // The index should be aligned on a vecWidth-bit boundary.
3884   uint64_t Index =
3885     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3886
3887   MVT VT = N->getSimpleValueType(0);
3888   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
3889   bool Result = (Index * ElSize) % vecWidth == 0;
3890
3891   return Result;
3892 }
3893
3894 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
3895 /// operand specifies a subvector insert that is suitable for input to
3896 /// insertion of 128 or 256-bit subvectors
3897 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
3898   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
3899   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3900     return false;
3901   // The index should be aligned on a vecWidth-bit boundary.
3902   uint64_t Index =
3903     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3904
3905   MVT VT = N->getSimpleValueType(0);
3906   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
3907   bool Result = (Index * ElSize) % vecWidth == 0;
3908
3909   return Result;
3910 }
3911
3912 bool X86::isVINSERT128Index(SDNode *N) {
3913   return isVINSERTIndex(N, 128);
3914 }
3915
3916 bool X86::isVINSERT256Index(SDNode *N) {
3917   return isVINSERTIndex(N, 256);
3918 }
3919
3920 bool X86::isVEXTRACT128Index(SDNode *N) {
3921   return isVEXTRACTIndex(N, 128);
3922 }
3923
3924 bool X86::isVEXTRACT256Index(SDNode *N) {
3925   return isVEXTRACTIndex(N, 256);
3926 }
3927
3928 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
3929   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
3930   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3931     llvm_unreachable("Illegal extract subvector for VEXTRACT");
3932
3933   uint64_t Index =
3934     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3935
3936   MVT VecVT = N->getOperand(0).getSimpleValueType();
3937   MVT ElVT = VecVT.getVectorElementType();
3938
3939   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
3940   return Index / NumElemsPerChunk;
3941 }
3942
3943 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
3944   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
3945   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3946     llvm_unreachable("Illegal insert subvector for VINSERT");
3947
3948   uint64_t Index =
3949     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3950
3951   MVT VecVT = N->getSimpleValueType(0);
3952   MVT ElVT = VecVT.getVectorElementType();
3953
3954   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
3955   return Index / NumElemsPerChunk;
3956 }
3957
3958 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
3959 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
3960 /// and VINSERTI128 instructions.
3961 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
3962   return getExtractVEXTRACTImmediate(N, 128);
3963 }
3964
3965 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
3966 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
3967 /// and VINSERTI64x4 instructions.
3968 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
3969   return getExtractVEXTRACTImmediate(N, 256);
3970 }
3971
3972 /// getInsertVINSERT128Immediate - Return the appropriate immediate
3973 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
3974 /// and VINSERTI128 instructions.
3975 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
3976   return getInsertVINSERTImmediate(N, 128);
3977 }
3978
3979 /// getInsertVINSERT256Immediate - Return the appropriate immediate
3980 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
3981 /// and VINSERTI64x4 instructions.
3982 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
3983   return getInsertVINSERTImmediate(N, 256);
3984 }
3985
3986 /// isZero - Returns true if Elt is a constant integer zero
3987 static bool isZero(SDValue V) {
3988   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
3989   return C && C->isNullValue();
3990 }
3991
3992 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
3993 /// constant +0.0.
3994 bool X86::isZeroNode(SDValue Elt) {
3995   if (isZero(Elt))
3996     return true;
3997   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
3998     return CFP->getValueAPF().isPosZero();
3999   return false;
4000 }
4001
4002 /// getZeroVector - Returns a vector of specified type with all zero elements.
4003 ///
4004 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4005                              SelectionDAG &DAG, SDLoc dl) {
4006   assert(VT.isVector() && "Expected a vector type");
4007
4008   // Always build SSE zero vectors as <4 x i32> bitcasted
4009   // to their dest type. This ensures they get CSE'd.
4010   SDValue Vec;
4011   if (VT.is128BitVector()) {  // SSE
4012     if (Subtarget->hasSSE2()) {  // SSE2
4013       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4014       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4015     } else { // SSE1
4016       SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4017       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4018     }
4019   } else if (VT.is256BitVector()) { // AVX
4020     if (Subtarget->hasInt256()) { // AVX2
4021       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4022       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4023       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4024     } else {
4025       // 256-bit logic and arithmetic instructions in AVX are all
4026       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4027       SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4028       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4029       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4030     }
4031   } else if (VT.is512BitVector()) { // AVX-512
4032       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4033       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4034                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4035       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4036   } else if (VT.getScalarType() == MVT::i1) {
4037
4038     assert((Subtarget->hasBWI() || VT.getVectorNumElements() <= 16)
4039             && "Unexpected vector type");
4040     assert((Subtarget->hasVLX() || VT.getVectorNumElements() >= 8)
4041             && "Unexpected vector type");
4042     SDValue Cst = DAG.getConstant(0, dl, MVT::i1);
4043     SmallVector<SDValue, 64> Ops(VT.getVectorNumElements(), Cst);
4044     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4045   } else
4046     llvm_unreachable("Unexpected vector type");
4047
4048   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4049 }
4050
4051 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
4052                                 SelectionDAG &DAG, SDLoc dl,
4053                                 unsigned vectorWidth) {
4054   assert((vectorWidth == 128 || vectorWidth == 256) &&
4055          "Unsupported vector width");
4056   EVT VT = Vec.getValueType();
4057   EVT ElVT = VT.getVectorElementType();
4058   unsigned Factor = VT.getSizeInBits()/vectorWidth;
4059   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
4060                                   VT.getVectorNumElements()/Factor);
4061
4062   // Extract from UNDEF is UNDEF.
4063   if (Vec.getOpcode() == ISD::UNDEF)
4064     return DAG.getUNDEF(ResultVT);
4065
4066   // Extract the relevant vectorWidth bits.  Generate an EXTRACT_SUBVECTOR
4067   unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
4068
4069   // This is the index of the first element of the vectorWidth-bit chunk
4070   // we want.
4071   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
4072                                * ElemsPerChunk);
4073
4074   // If the input is a buildvector just emit a smaller one.
4075   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
4076     return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
4077                        makeArrayRef(Vec->op_begin() + NormalizedIdxVal,
4078                                     ElemsPerChunk));
4079
4080   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4081   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec, VecIdx);
4082 }
4083
4084 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
4085 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
4086 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
4087 /// instructions or a simple subregister reference. Idx is an index in the
4088 /// 128 bits we want.  It need not be aligned to a 128-bit boundary.  That makes
4089 /// lowering EXTRACT_VECTOR_ELT operations easier.
4090 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
4091                                    SelectionDAG &DAG, SDLoc dl) {
4092   assert((Vec.getValueType().is256BitVector() ||
4093           Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
4094   return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
4095 }
4096
4097 /// Generate a DAG to grab 256-bits from a 512-bit vector.
4098 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
4099                                    SelectionDAG &DAG, SDLoc dl) {
4100   assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
4101   return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
4102 }
4103
4104 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
4105                                unsigned IdxVal, SelectionDAG &DAG,
4106                                SDLoc dl, unsigned vectorWidth) {
4107   assert((vectorWidth == 128 || vectorWidth == 256) &&
4108          "Unsupported vector width");
4109   // Inserting UNDEF is Result
4110   if (Vec.getOpcode() == ISD::UNDEF)
4111     return Result;
4112   EVT VT = Vec.getValueType();
4113   EVT ElVT = VT.getVectorElementType();
4114   EVT ResultVT = Result.getValueType();
4115
4116   // Insert the relevant vectorWidth bits.
4117   unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
4118
4119   // This is the index of the first element of the vectorWidth-bit chunk
4120   // we want.
4121   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
4122                                * ElemsPerChunk);
4123
4124   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4125   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec, VecIdx);
4126 }
4127
4128 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
4129 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
4130 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
4131 /// simple superregister reference.  Idx is an index in the 128 bits
4132 /// we want.  It need not be aligned to a 128-bit boundary.  That makes
4133 /// lowering INSERT_VECTOR_ELT operations easier.
4134 static SDValue Insert128BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4135                                   SelectionDAG &DAG, SDLoc dl) {
4136   assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
4137
4138   // For insertion into the zero index (low half) of a 256-bit vector, it is
4139   // more efficient to generate a blend with immediate instead of an insert*128.
4140   // We are still creating an INSERT_SUBVECTOR below with an undef node to
4141   // extend the subvector to the size of the result vector. Make sure that
4142   // we are not recursing on that node by checking for undef here.
4143   if (IdxVal == 0 && Result.getValueType().is256BitVector() &&
4144       Result.getOpcode() != ISD::UNDEF) {
4145     EVT ResultVT = Result.getValueType();
4146     SDValue ZeroIndex = DAG.getIntPtrConstant(0, dl);
4147     SDValue Undef = DAG.getUNDEF(ResultVT);
4148     SDValue Vec256 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Undef,
4149                                  Vec, ZeroIndex);
4150
4151     // The blend instruction, and therefore its mask, depend on the data type.
4152     MVT ScalarType = ResultVT.getScalarType().getSimpleVT();
4153     if (ScalarType.isFloatingPoint()) {
4154       // Choose either vblendps (float) or vblendpd (double).
4155       unsigned ScalarSize = ScalarType.getSizeInBits();
4156       assert((ScalarSize == 64 || ScalarSize == 32) && "Unknown float type");
4157       unsigned MaskVal = (ScalarSize == 64) ? 0x03 : 0x0f;
4158       SDValue Mask = DAG.getConstant(MaskVal, dl, MVT::i8);
4159       return DAG.getNode(X86ISD::BLENDI, dl, ResultVT, Result, Vec256, Mask);
4160     }
4161
4162     const X86Subtarget &Subtarget =
4163     static_cast<const X86Subtarget &>(DAG.getSubtarget());
4164
4165     // AVX2 is needed for 256-bit integer blend support.
4166     // Integers must be cast to 32-bit because there is only vpblendd;
4167     // vpblendw can't be used for this because it has a handicapped mask.
4168
4169     // If we don't have AVX2, then cast to float. Using a wrong domain blend
4170     // is still more efficient than using the wrong domain vinsertf128 that
4171     // will be created by InsertSubVector().
4172     MVT CastVT = Subtarget.hasAVX2() ? MVT::v8i32 : MVT::v8f32;
4173
4174     SDValue Mask = DAG.getConstant(0x0f, dl, MVT::i8);
4175     Vec256 = DAG.getNode(ISD::BITCAST, dl, CastVT, Vec256);
4176     Vec256 = DAG.getNode(X86ISD::BLENDI, dl, CastVT, Result, Vec256, Mask);
4177     return DAG.getNode(ISD::BITCAST, dl, ResultVT, Vec256);
4178   }
4179
4180   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
4181 }
4182
4183 static SDValue Insert256BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4184                                   SelectionDAG &DAG, SDLoc dl) {
4185   assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
4186   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
4187 }
4188
4189 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
4190 /// instructions. This is used because creating CONCAT_VECTOR nodes of
4191 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
4192 /// large BUILD_VECTORS.
4193 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
4194                                    unsigned NumElems, SelectionDAG &DAG,
4195                                    SDLoc dl) {
4196   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4197   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
4198 }
4199
4200 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
4201                                    unsigned NumElems, SelectionDAG &DAG,
4202                                    SDLoc dl) {
4203   SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4204   return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
4205 }
4206
4207 /// getOnesVector - Returns a vector of specified type with all bits set.
4208 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4209 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4210 /// Then bitcast to their original type, ensuring they get CSE'd.
4211 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4212                              SDLoc dl) {
4213   assert(VT.isVector() && "Expected a vector type");
4214
4215   SDValue Cst = DAG.getConstant(~0U, dl, MVT::i32);
4216   SDValue Vec;
4217   if (VT.is256BitVector()) {
4218     if (HasInt256) { // AVX2
4219       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4220       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4221     } else { // AVX
4222       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4223       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4224     }
4225   } else if (VT.is128BitVector()) {
4226     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4227   } else
4228     llvm_unreachable("Unexpected vector type");
4229
4230   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4231 }
4232
4233 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4234 /// operation of specified width.
4235 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4236                        SDValue V2) {
4237   unsigned NumElems = VT.getVectorNumElements();
4238   SmallVector<int, 8> Mask;
4239   Mask.push_back(NumElems);
4240   for (unsigned i = 1; i != NumElems; ++i)
4241     Mask.push_back(i);
4242   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4243 }
4244
4245 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4246 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4247                           SDValue V2) {
4248   unsigned NumElems = VT.getVectorNumElements();
4249   SmallVector<int, 8> Mask;
4250   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4251     Mask.push_back(i);
4252     Mask.push_back(i + NumElems);
4253   }
4254   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4255 }
4256
4257 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4258 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4259                           SDValue V2) {
4260   unsigned NumElems = VT.getVectorNumElements();
4261   SmallVector<int, 8> Mask;
4262   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4263     Mask.push_back(i + Half);
4264     Mask.push_back(i + NumElems + Half);
4265   }
4266   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4267 }
4268
4269 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4270 /// vector of zero or undef vector.  This produces a shuffle where the low
4271 /// element of V2 is swizzled into the zero/undef vector, landing at element
4272 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4273 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4274                                            bool IsZero,
4275                                            const X86Subtarget *Subtarget,
4276                                            SelectionDAG &DAG) {
4277   MVT VT = V2.getSimpleValueType();
4278   SDValue V1 = IsZero
4279     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
4280   unsigned NumElems = VT.getVectorNumElements();
4281   SmallVector<int, 16> MaskVec;
4282   for (unsigned i = 0; i != NumElems; ++i)
4283     // If this is the insertion idx, put the low elt of V2 here.
4284     MaskVec.push_back(i == Idx ? NumElems : i);
4285   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
4286 }
4287
4288 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4289 /// target specific opcode. Returns true if the Mask could be calculated. Sets
4290 /// IsUnary to true if only uses one source. Note that this will set IsUnary for
4291 /// shuffles which use a single input multiple times, and in those cases it will
4292 /// adjust the mask to only have indices within that single input.
4293 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4294                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
4295   unsigned NumElems = VT.getVectorNumElements();
4296   SDValue ImmN;
4297
4298   IsUnary = false;
4299   bool IsFakeUnary = false;
4300   switch(N->getOpcode()) {
4301   case X86ISD::BLENDI:
4302     ImmN = N->getOperand(N->getNumOperands()-1);
4303     DecodeBLENDMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4304     break;
4305   case X86ISD::SHUFP:
4306     ImmN = N->getOperand(N->getNumOperands()-1);
4307     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4308     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4309     break;
4310   case X86ISD::UNPCKH:
4311     DecodeUNPCKHMask(VT, Mask);
4312     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4313     break;
4314   case X86ISD::UNPCKL:
4315     DecodeUNPCKLMask(VT, Mask);
4316     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4317     break;
4318   case X86ISD::MOVHLPS:
4319     DecodeMOVHLPSMask(NumElems, Mask);
4320     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4321     break;
4322   case X86ISD::MOVLHPS:
4323     DecodeMOVLHPSMask(NumElems, Mask);
4324     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4325     break;
4326   case X86ISD::PALIGNR:
4327     ImmN = N->getOperand(N->getNumOperands()-1);
4328     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4329     break;
4330   case X86ISD::PSHUFD:
4331   case X86ISD::VPERMILPI:
4332     ImmN = N->getOperand(N->getNumOperands()-1);
4333     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4334     IsUnary = true;
4335     break;
4336   case X86ISD::PSHUFHW:
4337     ImmN = N->getOperand(N->getNumOperands()-1);
4338     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4339     IsUnary = true;
4340     break;
4341   case X86ISD::PSHUFLW:
4342     ImmN = N->getOperand(N->getNumOperands()-1);
4343     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4344     IsUnary = true;
4345     break;
4346   case X86ISD::PSHUFB: {
4347     IsUnary = true;
4348     SDValue MaskNode = N->getOperand(1);
4349     while (MaskNode->getOpcode() == ISD::BITCAST)
4350       MaskNode = MaskNode->getOperand(0);
4351
4352     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4353       // If we have a build-vector, then things are easy.
4354       EVT VT = MaskNode.getValueType();
4355       assert(VT.isVector() &&
4356              "Can't produce a non-vector with a build_vector!");
4357       if (!VT.isInteger())
4358         return false;
4359
4360       int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
4361
4362       SmallVector<uint64_t, 32> RawMask;
4363       for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
4364         SDValue Op = MaskNode->getOperand(i);
4365         if (Op->getOpcode() == ISD::UNDEF) {
4366           RawMask.push_back((uint64_t)SM_SentinelUndef);
4367           continue;
4368         }
4369         auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4370         if (!CN)
4371           return false;
4372         APInt MaskElement = CN->getAPIntValue();
4373
4374         // We now have to decode the element which could be any integer size and
4375         // extract each byte of it.
4376         for (int j = 0; j < NumBytesPerElement; ++j) {
4377           // Note that this is x86 and so always little endian: the low byte is
4378           // the first byte of the mask.
4379           RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
4380           MaskElement = MaskElement.lshr(8);
4381         }
4382       }
4383       DecodePSHUFBMask(RawMask, Mask);
4384       break;
4385     }
4386
4387     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4388     if (!MaskLoad)
4389       return false;
4390
4391     SDValue Ptr = MaskLoad->getBasePtr();
4392     if (Ptr->getOpcode() == X86ISD::Wrapper ||
4393         Ptr->getOpcode() == X86ISD::WrapperRIP)
4394       Ptr = Ptr->getOperand(0);
4395
4396     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4397     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4398       return false;
4399
4400     if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
4401       DecodePSHUFBMask(C, Mask);
4402       if (Mask.empty())
4403         return false;
4404       break;
4405     }
4406
4407     return false;
4408   }
4409   case X86ISD::VPERMI:
4410     ImmN = N->getOperand(N->getNumOperands()-1);
4411     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4412     IsUnary = true;
4413     break;
4414   case X86ISD::MOVSS:
4415   case X86ISD::MOVSD:
4416     DecodeScalarMoveMask(VT, /* IsLoad */ false, Mask);
4417     break;
4418   case X86ISD::VPERM2X128:
4419     ImmN = N->getOperand(N->getNumOperands()-1);
4420     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4421     if (Mask.empty()) return false;
4422     break;
4423   case X86ISD::MOVSLDUP:
4424     DecodeMOVSLDUPMask(VT, Mask);
4425     IsUnary = true;
4426     break;
4427   case X86ISD::MOVSHDUP:
4428     DecodeMOVSHDUPMask(VT, Mask);
4429     IsUnary = true;
4430     break;
4431   case X86ISD::MOVDDUP:
4432     DecodeMOVDDUPMask(VT, Mask);
4433     IsUnary = true;
4434     break;
4435   case X86ISD::MOVLHPD:
4436   case X86ISD::MOVLPD:
4437   case X86ISD::MOVLPS:
4438     // Not yet implemented
4439     return false;
4440   default: llvm_unreachable("unknown target shuffle node");
4441   }
4442
4443   // If we have a fake unary shuffle, the shuffle mask is spread across two
4444   // inputs that are actually the same node. Re-map the mask to always point
4445   // into the first input.
4446   if (IsFakeUnary)
4447     for (int &M : Mask)
4448       if (M >= (int)Mask.size())
4449         M -= Mask.size();
4450
4451   return true;
4452 }
4453
4454 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4455 /// element of the result of the vector shuffle.
4456 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4457                                    unsigned Depth) {
4458   if (Depth == 6)
4459     return SDValue();  // Limit search depth.
4460
4461   SDValue V = SDValue(N, 0);
4462   EVT VT = V.getValueType();
4463   unsigned Opcode = V.getOpcode();
4464
4465   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4466   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4467     int Elt = SV->getMaskElt(Index);
4468
4469     if (Elt < 0)
4470       return DAG.getUNDEF(VT.getVectorElementType());
4471
4472     unsigned NumElems = VT.getVectorNumElements();
4473     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4474                                          : SV->getOperand(1);
4475     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4476   }
4477
4478   // Recurse into target specific vector shuffles to find scalars.
4479   if (isTargetShuffle(Opcode)) {
4480     MVT ShufVT = V.getSimpleValueType();
4481     unsigned NumElems = ShufVT.getVectorNumElements();
4482     SmallVector<int, 16> ShuffleMask;
4483     bool IsUnary;
4484
4485     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4486       return SDValue();
4487
4488     int Elt = ShuffleMask[Index];
4489     if (Elt < 0)
4490       return DAG.getUNDEF(ShufVT.getVectorElementType());
4491
4492     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4493                                          : N->getOperand(1);
4494     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4495                                Depth+1);
4496   }
4497
4498   // Actual nodes that may contain scalar elements
4499   if (Opcode == ISD::BITCAST) {
4500     V = V.getOperand(0);
4501     EVT SrcVT = V.getValueType();
4502     unsigned NumElems = VT.getVectorNumElements();
4503
4504     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4505       return SDValue();
4506   }
4507
4508   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4509     return (Index == 0) ? V.getOperand(0)
4510                         : DAG.getUNDEF(VT.getVectorElementType());
4511
4512   if (V.getOpcode() == ISD::BUILD_VECTOR)
4513     return V.getOperand(Index);
4514
4515   return SDValue();
4516 }
4517
4518 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4519 ///
4520 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4521                                        unsigned NumNonZero, unsigned NumZero,
4522                                        SelectionDAG &DAG,
4523                                        const X86Subtarget* Subtarget,
4524                                        const TargetLowering &TLI) {
4525   if (NumNonZero > 8)
4526     return SDValue();
4527
4528   SDLoc dl(Op);
4529   SDValue V;
4530   bool First = true;
4531
4532   // SSE4.1 - use PINSRB to insert each byte directly.
4533   if (Subtarget->hasSSE41()) {
4534     for (unsigned i = 0; i < 16; ++i) {
4535       bool isNonZero = (NonZeros & (1 << i)) != 0;
4536       if (isNonZero) {
4537         if (First) {
4538           if (NumZero)
4539             V = getZeroVector(MVT::v16i8, Subtarget, DAG, dl);
4540           else
4541             V = DAG.getUNDEF(MVT::v16i8);
4542           First = false;
4543         }
4544         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4545                         MVT::v16i8, V, Op.getOperand(i),
4546                         DAG.getIntPtrConstant(i, dl));
4547       }
4548     }
4549
4550     return V;
4551   }
4552
4553   // Pre-SSE4.1 - merge byte pairs and insert with PINSRW.
4554   for (unsigned i = 0; i < 16; ++i) {
4555     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4556     if (ThisIsNonZero && First) {
4557       if (NumZero)
4558         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4559       else
4560         V = DAG.getUNDEF(MVT::v8i16);
4561       First = false;
4562     }
4563
4564     if ((i & 1) != 0) {
4565       SDValue ThisElt, LastElt;
4566       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4567       if (LastIsNonZero) {
4568         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4569                               MVT::i16, Op.getOperand(i-1));
4570       }
4571       if (ThisIsNonZero) {
4572         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4573         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4574                               ThisElt, DAG.getConstant(8, dl, MVT::i8));
4575         if (LastIsNonZero)
4576           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4577       } else
4578         ThisElt = LastElt;
4579
4580       if (ThisElt.getNode())
4581         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4582                         DAG.getIntPtrConstant(i/2, dl));
4583     }
4584   }
4585
4586   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4587 }
4588
4589 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4590 ///
4591 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4592                                      unsigned NumNonZero, unsigned NumZero,
4593                                      SelectionDAG &DAG,
4594                                      const X86Subtarget* Subtarget,
4595                                      const TargetLowering &TLI) {
4596   if (NumNonZero > 4)
4597     return SDValue();
4598
4599   SDLoc dl(Op);
4600   SDValue V;
4601   bool First = true;
4602   for (unsigned i = 0; i < 8; ++i) {
4603     bool isNonZero = (NonZeros & (1 << i)) != 0;
4604     if (isNonZero) {
4605       if (First) {
4606         if (NumZero)
4607           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4608         else
4609           V = DAG.getUNDEF(MVT::v8i16);
4610         First = false;
4611       }
4612       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4613                       MVT::v8i16, V, Op.getOperand(i),
4614                       DAG.getIntPtrConstant(i, dl));
4615     }
4616   }
4617
4618   return V;
4619 }
4620
4621 /// LowerBuildVectorv4x32 - Custom lower build_vector of v4i32 or v4f32.
4622 static SDValue LowerBuildVectorv4x32(SDValue Op, SelectionDAG &DAG,
4623                                      const X86Subtarget *Subtarget,
4624                                      const TargetLowering &TLI) {
4625   // Find all zeroable elements.
4626   std::bitset<4> Zeroable;
4627   for (int i=0; i < 4; ++i) {
4628     SDValue Elt = Op->getOperand(i);
4629     Zeroable[i] = (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt));
4630   }
4631   assert(Zeroable.size() - Zeroable.count() > 1 &&
4632          "We expect at least two non-zero elements!");
4633
4634   // We only know how to deal with build_vector nodes where elements are either
4635   // zeroable or extract_vector_elt with constant index.
4636   SDValue FirstNonZero;
4637   unsigned FirstNonZeroIdx;
4638   for (unsigned i=0; i < 4; ++i) {
4639     if (Zeroable[i])
4640       continue;
4641     SDValue Elt = Op->getOperand(i);
4642     if (Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4643         !isa<ConstantSDNode>(Elt.getOperand(1)))
4644       return SDValue();
4645     // Make sure that this node is extracting from a 128-bit vector.
4646     MVT VT = Elt.getOperand(0).getSimpleValueType();
4647     if (!VT.is128BitVector())
4648       return SDValue();
4649     if (!FirstNonZero.getNode()) {
4650       FirstNonZero = Elt;
4651       FirstNonZeroIdx = i;
4652     }
4653   }
4654
4655   assert(FirstNonZero.getNode() && "Unexpected build vector of all zeros!");
4656   SDValue V1 = FirstNonZero.getOperand(0);
4657   MVT VT = V1.getSimpleValueType();
4658
4659   // See if this build_vector can be lowered as a blend with zero.
4660   SDValue Elt;
4661   unsigned EltMaskIdx, EltIdx;
4662   int Mask[4];
4663   for (EltIdx = 0; EltIdx < 4; ++EltIdx) {
4664     if (Zeroable[EltIdx]) {
4665       // The zero vector will be on the right hand side.
4666       Mask[EltIdx] = EltIdx+4;
4667       continue;
4668     }
4669
4670     Elt = Op->getOperand(EltIdx);
4671     // By construction, Elt is a EXTRACT_VECTOR_ELT with constant index.
4672     EltMaskIdx = cast<ConstantSDNode>(Elt.getOperand(1))->getZExtValue();
4673     if (Elt.getOperand(0) != V1 || EltMaskIdx != EltIdx)
4674       break;
4675     Mask[EltIdx] = EltIdx;
4676   }
4677
4678   if (EltIdx == 4) {
4679     // Let the shuffle legalizer deal with blend operations.
4680     SDValue VZero = getZeroVector(VT, Subtarget, DAG, SDLoc(Op));
4681     if (V1.getSimpleValueType() != VT)
4682       V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), VT, V1);
4683     return DAG.getVectorShuffle(VT, SDLoc(V1), V1, VZero, &Mask[0]);
4684   }
4685
4686   // See if we can lower this build_vector to a INSERTPS.
4687   if (!Subtarget->hasSSE41())
4688     return SDValue();
4689
4690   SDValue V2 = Elt.getOperand(0);
4691   if (Elt == FirstNonZero && EltIdx == FirstNonZeroIdx)
4692     V1 = SDValue();
4693
4694   bool CanFold = true;
4695   for (unsigned i = EltIdx + 1; i < 4 && CanFold; ++i) {
4696     if (Zeroable[i])
4697       continue;
4698
4699     SDValue Current = Op->getOperand(i);
4700     SDValue SrcVector = Current->getOperand(0);
4701     if (!V1.getNode())
4702       V1 = SrcVector;
4703     CanFold = SrcVector == V1 &&
4704       cast<ConstantSDNode>(Current.getOperand(1))->getZExtValue() == i;
4705   }
4706
4707   if (!CanFold)
4708     return SDValue();
4709
4710   assert(V1.getNode() && "Expected at least two non-zero elements!");
4711   if (V1.getSimpleValueType() != MVT::v4f32)
4712     V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), MVT::v4f32, V1);
4713   if (V2.getSimpleValueType() != MVT::v4f32)
4714     V2 = DAG.getNode(ISD::BITCAST, SDLoc(V2), MVT::v4f32, V2);
4715
4716   // Ok, we can emit an INSERTPS instruction.
4717   unsigned ZMask = Zeroable.to_ulong();
4718
4719   unsigned InsertPSMask = EltMaskIdx << 6 | EltIdx << 4 | ZMask;
4720   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
4721   SDLoc DL(Op);
4722   SDValue Result = DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
4723                                DAG.getIntPtrConstant(InsertPSMask, DL));
4724   return DAG.getNode(ISD::BITCAST, DL, VT, Result);
4725 }
4726
4727 /// Return a vector logical shift node.
4728 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4729                          unsigned NumBits, SelectionDAG &DAG,
4730                          const TargetLowering &TLI, SDLoc dl) {
4731   assert(VT.is128BitVector() && "Unknown type for VShift");
4732   MVT ShVT = MVT::v2i64;
4733   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4734   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4735   MVT ScalarShiftTy = TLI.getScalarShiftAmountTy(SrcOp.getValueType());
4736   assert(NumBits % 8 == 0 && "Only support byte sized shifts");
4737   SDValue ShiftVal = DAG.getConstant(NumBits/8, dl, ScalarShiftTy);
4738   return DAG.getNode(ISD::BITCAST, dl, VT,
4739                      DAG.getNode(Opc, dl, ShVT, SrcOp, ShiftVal));
4740 }
4741
4742 static SDValue
4743 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
4744
4745   // Check if the scalar load can be widened into a vector load. And if
4746   // the address is "base + cst" see if the cst can be "absorbed" into
4747   // the shuffle mask.
4748   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4749     SDValue Ptr = LD->getBasePtr();
4750     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4751       return SDValue();
4752     EVT PVT = LD->getValueType(0);
4753     if (PVT != MVT::i32 && PVT != MVT::f32)
4754       return SDValue();
4755
4756     int FI = -1;
4757     int64_t Offset = 0;
4758     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4759       FI = FINode->getIndex();
4760       Offset = 0;
4761     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4762                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4763       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4764       Offset = Ptr.getConstantOperandVal(1);
4765       Ptr = Ptr.getOperand(0);
4766     } else {
4767       return SDValue();
4768     }
4769
4770     // FIXME: 256-bit vector instructions don't require a strict alignment,
4771     // improve this code to support it better.
4772     unsigned RequiredAlign = VT.getSizeInBits()/8;
4773     SDValue Chain = LD->getChain();
4774     // Make sure the stack object alignment is at least 16 or 32.
4775     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4776     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4777       if (MFI->isFixedObjectIndex(FI)) {
4778         // Can't change the alignment. FIXME: It's possible to compute
4779         // the exact stack offset and reference FI + adjust offset instead.
4780         // If someone *really* cares about this. That's the way to implement it.
4781         return SDValue();
4782       } else {
4783         MFI->setObjectAlignment(FI, RequiredAlign);
4784       }
4785     }
4786
4787     // (Offset % 16 or 32) must be multiple of 4. Then address is then
4788     // Ptr + (Offset & ~15).
4789     if (Offset < 0)
4790       return SDValue();
4791     if ((Offset % RequiredAlign) & 3)
4792       return SDValue();
4793     int64_t StartOffset = Offset & ~(RequiredAlign-1);
4794     if (StartOffset) {
4795       SDLoc DL(Ptr);
4796       Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
4797                         DAG.getConstant(StartOffset, DL, Ptr.getValueType()));
4798     }
4799
4800     int EltNo = (Offset - StartOffset) >> 2;
4801     unsigned NumElems = VT.getVectorNumElements();
4802
4803     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4804     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4805                              LD->getPointerInfo().getWithOffset(StartOffset),
4806                              false, false, false, 0);
4807
4808     SmallVector<int, 8> Mask(NumElems, EltNo);
4809
4810     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
4811   }
4812
4813   return SDValue();
4814 }
4815
4816 /// Given the initializing elements 'Elts' of a vector of type 'VT', see if the
4817 /// elements can be replaced by a single large load which has the same value as
4818 /// a build_vector or insert_subvector whose loaded operands are 'Elts'.
4819 ///
4820 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4821 ///
4822 /// FIXME: we'd also like to handle the case where the last elements are zero
4823 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4824 /// There's even a handy isZeroNode for that purpose.
4825 static SDValue EltsFromConsecutiveLoads(EVT VT, ArrayRef<SDValue> Elts,
4826                                         SDLoc &DL, SelectionDAG &DAG,
4827                                         bool isAfterLegalize) {
4828   unsigned NumElems = Elts.size();
4829
4830   LoadSDNode *LDBase = nullptr;
4831   unsigned LastLoadedElt = -1U;
4832
4833   // For each element in the initializer, see if we've found a load or an undef.
4834   // If we don't find an initial load element, or later load elements are
4835   // non-consecutive, bail out.
4836   for (unsigned i = 0; i < NumElems; ++i) {
4837     SDValue Elt = Elts[i];
4838     // Look through a bitcast.
4839     if (Elt.getNode() && Elt.getOpcode() == ISD::BITCAST)
4840       Elt = Elt.getOperand(0);
4841     if (!Elt.getNode() ||
4842         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4843       return SDValue();
4844     if (!LDBase) {
4845       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4846         return SDValue();
4847       LDBase = cast<LoadSDNode>(Elt.getNode());
4848       LastLoadedElt = i;
4849       continue;
4850     }
4851     if (Elt.getOpcode() == ISD::UNDEF)
4852       continue;
4853
4854     LoadSDNode *LD = cast<LoadSDNode>(Elt);
4855     EVT LdVT = Elt.getValueType();
4856     // Each loaded element must be the correct fractional portion of the
4857     // requested vector load.
4858     if (LdVT.getSizeInBits() != VT.getSizeInBits() / NumElems)
4859       return SDValue();
4860     if (!DAG.isConsecutiveLoad(LD, LDBase, LdVT.getSizeInBits() / 8, i))
4861       return SDValue();
4862     LastLoadedElt = i;
4863   }
4864
4865   // If we have found an entire vector of loads and undefs, then return a large
4866   // load of the entire vector width starting at the base pointer.  If we found
4867   // consecutive loads for the low half, generate a vzext_load node.
4868   if (LastLoadedElt == NumElems - 1) {
4869     assert(LDBase && "Did not find base load for merging consecutive loads");
4870     EVT EltVT = LDBase->getValueType(0);
4871     // Ensure that the input vector size for the merged loads matches the
4872     // cumulative size of the input elements.
4873     if (VT.getSizeInBits() != EltVT.getSizeInBits() * NumElems)
4874       return SDValue();
4875
4876     if (isAfterLegalize &&
4877         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
4878       return SDValue();
4879
4880     SDValue NewLd = SDValue();
4881
4882     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4883                         LDBase->getPointerInfo(), LDBase->isVolatile(),
4884                         LDBase->isNonTemporal(), LDBase->isInvariant(),
4885                         LDBase->getAlignment());
4886
4887     if (LDBase->hasAnyUseOfValue(1)) {
4888       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
4889                                      SDValue(LDBase, 1),
4890                                      SDValue(NewLd.getNode(), 1));
4891       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
4892       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
4893                              SDValue(NewLd.getNode(), 1));
4894     }
4895
4896     return NewLd;
4897   }
4898
4899   //TODO: The code below fires only for for loading the low v2i32 / v2f32
4900   //of a v4i32 / v4f32. It's probably worth generalizing.
4901   EVT EltVT = VT.getVectorElementType();
4902   if (NumElems == 4 && LastLoadedElt == 1 && (EltVT.getSizeInBits() == 32) &&
4903       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
4904     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4905     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4906     SDValue ResNode =
4907         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
4908                                 LDBase->getPointerInfo(),
4909                                 LDBase->getAlignment(),
4910                                 false/*isVolatile*/, true/*ReadMem*/,
4911                                 false/*WriteMem*/);
4912
4913     // Make sure the newly-created LOAD is in the same position as LDBase in
4914     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
4915     // update uses of LDBase's output chain to use the TokenFactor.
4916     if (LDBase->hasAnyUseOfValue(1)) {
4917       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
4918                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
4919       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
4920       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
4921                              SDValue(ResNode.getNode(), 1));
4922     }
4923
4924     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
4925   }
4926   return SDValue();
4927 }
4928
4929 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
4930 /// to generate a splat value for the following cases:
4931 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
4932 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
4933 /// a scalar load, or a constant.
4934 /// The VBROADCAST node is returned when a pattern is found,
4935 /// or SDValue() otherwise.
4936 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
4937                                     SelectionDAG &DAG) {
4938   // VBROADCAST requires AVX.
4939   // TODO: Splats could be generated for non-AVX CPUs using SSE
4940   // instructions, but there's less potential gain for only 128-bit vectors.
4941   if (!Subtarget->hasAVX())
4942     return SDValue();
4943
4944   MVT VT = Op.getSimpleValueType();
4945   SDLoc dl(Op);
4946
4947   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
4948          "Unsupported vector type for broadcast.");
4949
4950   SDValue Ld;
4951   bool ConstSplatVal;
4952
4953   switch (Op.getOpcode()) {
4954     default:
4955       // Unknown pattern found.
4956       return SDValue();
4957
4958     case ISD::BUILD_VECTOR: {
4959       auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
4960       BitVector UndefElements;
4961       SDValue Splat = BVOp->getSplatValue(&UndefElements);
4962
4963       // We need a splat of a single value to use broadcast, and it doesn't
4964       // make any sense if the value is only in one element of the vector.
4965       if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
4966         return SDValue();
4967
4968       Ld = Splat;
4969       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
4970                        Ld.getOpcode() == ISD::ConstantFP);
4971
4972       // Make sure that all of the users of a non-constant load are from the
4973       // BUILD_VECTOR node.
4974       if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
4975         return SDValue();
4976       break;
4977     }
4978
4979     case ISD::VECTOR_SHUFFLE: {
4980       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4981
4982       // Shuffles must have a splat mask where the first element is
4983       // broadcasted.
4984       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
4985         return SDValue();
4986
4987       SDValue Sc = Op.getOperand(0);
4988       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
4989           Sc.getOpcode() != ISD::BUILD_VECTOR) {
4990
4991         if (!Subtarget->hasInt256())
4992           return SDValue();
4993
4994         // Use the register form of the broadcast instruction available on AVX2.
4995         if (VT.getSizeInBits() >= 256)
4996           Sc = Extract128BitVector(Sc, 0, DAG, dl);
4997         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
4998       }
4999
5000       Ld = Sc.getOperand(0);
5001       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5002                        Ld.getOpcode() == ISD::ConstantFP);
5003
5004       // The scalar_to_vector node and the suspected
5005       // load node must have exactly one user.
5006       // Constants may have multiple users.
5007
5008       // AVX-512 has register version of the broadcast
5009       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5010         Ld.getValueType().getSizeInBits() >= 32;
5011       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5012           !hasRegVer))
5013         return SDValue();
5014       break;
5015     }
5016   }
5017
5018   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5019   bool IsGE256 = (VT.getSizeInBits() >= 256);
5020
5021   // When optimizing for size, generate up to 5 extra bytes for a broadcast
5022   // instruction to save 8 or more bytes of constant pool data.
5023   // TODO: If multiple splats are generated to load the same constant,
5024   // it may be detrimental to overall size. There needs to be a way to detect
5025   // that condition to know if this is truly a size win.
5026   const Function *F = DAG.getMachineFunction().getFunction();
5027   bool OptForSize = F->hasFnAttribute(Attribute::OptimizeForSize);
5028
5029   // Handle broadcasting a single constant scalar from the constant pool
5030   // into a vector.
5031   // On Sandybridge (no AVX2), it is still better to load a constant vector
5032   // from the constant pool and not to broadcast it from a scalar.
5033   // But override that restriction when optimizing for size.
5034   // TODO: Check if splatting is recommended for other AVX-capable CPUs.
5035   if (ConstSplatVal && (Subtarget->hasAVX2() || OptForSize)) {
5036     EVT CVT = Ld.getValueType();
5037     assert(!CVT.isVector() && "Must not broadcast a vector type");
5038
5039     // Splat f32, i32, v4f64, v4i64 in all cases with AVX2.
5040     // For size optimization, also splat v2f64 and v2i64, and for size opt
5041     // with AVX2, also splat i8 and i16.
5042     // With pattern matching, the VBROADCAST node may become a VMOVDDUP.
5043     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5044         (OptForSize && (ScalarSize == 64 || Subtarget->hasAVX2()))) {
5045       const Constant *C = nullptr;
5046       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5047         C = CI->getConstantIntValue();
5048       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5049         C = CF->getConstantFPValue();
5050
5051       assert(C && "Invalid constant type");
5052
5053       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5054       SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
5055       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5056       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5057                        MachinePointerInfo::getConstantPool(),
5058                        false, false, false, Alignment);
5059
5060       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5061     }
5062   }
5063
5064   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5065
5066   // Handle AVX2 in-register broadcasts.
5067   if (!IsLoad && Subtarget->hasInt256() &&
5068       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5069     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5070
5071   // The scalar source must be a normal load.
5072   if (!IsLoad)
5073     return SDValue();
5074
5075   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5076       (Subtarget->hasVLX() && ScalarSize == 64))
5077     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5078
5079   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5080   // double since there is no vbroadcastsd xmm
5081   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5082     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5083       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5084   }
5085
5086   // Unsupported broadcast.
5087   return SDValue();
5088 }
5089
5090 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5091 /// underlying vector and index.
5092 ///
5093 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5094 /// index.
5095 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5096                                          SDValue ExtIdx) {
5097   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5098   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5099     return Idx;
5100
5101   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5102   // lowered this:
5103   //   (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5104   // to:
5105   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
5106   //                           (extract_subvector (v8f32 %vreg0), Constant<4>),
5107   //                           undef)
5108   //                       Constant<0>)
5109   // In this case the vector is the extract_subvector expression and the index
5110   // is 2, as specified by the shuffle.
5111   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5112   SDValue ShuffleVec = SVOp->getOperand(0);
5113   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5114   assert(ShuffleVecVT.getVectorElementType() ==
5115          ExtractedFromVec.getSimpleValueType().getVectorElementType());
5116
5117   int ShuffleIdx = SVOp->getMaskElt(Idx);
5118   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5119     ExtractedFromVec = ShuffleVec;
5120     return ShuffleIdx;
5121   }
5122   return Idx;
5123 }
5124
5125 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5126   MVT VT = Op.getSimpleValueType();
5127
5128   // Skip if insert_vec_elt is not supported.
5129   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5130   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5131     return SDValue();
5132
5133   SDLoc DL(Op);
5134   unsigned NumElems = Op.getNumOperands();
5135
5136   SDValue VecIn1;
5137   SDValue VecIn2;
5138   SmallVector<unsigned, 4> InsertIndices;
5139   SmallVector<int, 8> Mask(NumElems, -1);
5140
5141   for (unsigned i = 0; i != NumElems; ++i) {
5142     unsigned Opc = Op.getOperand(i).getOpcode();
5143
5144     if (Opc == ISD::UNDEF)
5145       continue;
5146
5147     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5148       // Quit if more than 1 elements need inserting.
5149       if (InsertIndices.size() > 1)
5150         return SDValue();
5151
5152       InsertIndices.push_back(i);
5153       continue;
5154     }
5155
5156     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5157     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5158     // Quit if non-constant index.
5159     if (!isa<ConstantSDNode>(ExtIdx))
5160       return SDValue();
5161     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5162
5163     // Quit if extracted from vector of different type.
5164     if (ExtractedFromVec.getValueType() != VT)
5165       return SDValue();
5166
5167     if (!VecIn1.getNode())
5168       VecIn1 = ExtractedFromVec;
5169     else if (VecIn1 != ExtractedFromVec) {
5170       if (!VecIn2.getNode())
5171         VecIn2 = ExtractedFromVec;
5172       else if (VecIn2 != ExtractedFromVec)
5173         // Quit if more than 2 vectors to shuffle
5174         return SDValue();
5175     }
5176
5177     if (ExtractedFromVec == VecIn1)
5178       Mask[i] = Idx;
5179     else if (ExtractedFromVec == VecIn2)
5180       Mask[i] = Idx + NumElems;
5181   }
5182
5183   if (!VecIn1.getNode())
5184     return SDValue();
5185
5186   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5187   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5188   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5189     unsigned Idx = InsertIndices[i];
5190     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5191                      DAG.getIntPtrConstant(Idx, DL));
5192   }
5193
5194   return NV;
5195 }
5196
5197 static SDValue ConvertI1VectorToInterger(SDValue Op, SelectionDAG &DAG) {
5198   assert(ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
5199          Op.getScalarValueSizeInBits() == 1 &&
5200          "Can not convert non-constant vector");
5201   uint64_t Immediate = 0;
5202   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5203     SDValue In = Op.getOperand(idx);
5204     if (In.getOpcode() != ISD::UNDEF)
5205       Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5206   }
5207   SDLoc dl(Op);
5208   MVT VT =
5209    MVT::getIntegerVT(std::max((int)Op.getValueType().getSizeInBits(), 8));
5210   return DAG.getConstant(Immediate, dl, VT);
5211 }
5212 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5213 SDValue
5214 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5215
5216   MVT VT = Op.getSimpleValueType();
5217   assert((VT.getVectorElementType() == MVT::i1) &&
5218          "Unexpected type in LowerBUILD_VECTORvXi1!");
5219
5220   SDLoc dl(Op);
5221   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5222     SDValue Cst = DAG.getTargetConstant(0, dl, MVT::i1);
5223     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5224     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5225   }
5226
5227   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5228     SDValue Cst = DAG.getTargetConstant(1, dl, MVT::i1);
5229     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5230     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5231   }
5232
5233   if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
5234     SDValue Imm = ConvertI1VectorToInterger(Op, DAG);
5235     if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5236       return DAG.getNode(ISD::BITCAST, dl, VT, Imm);
5237     SDValue ExtVec = DAG.getNode(ISD::BITCAST, dl, MVT::v8i1, Imm);
5238     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5239                         DAG.getIntPtrConstant(0, dl));
5240   }
5241
5242   // Vector has one or more non-const elements
5243   uint64_t Immediate = 0;
5244   SmallVector<unsigned, 16> NonConstIdx;
5245   bool IsSplat = true;
5246   bool HasConstElts = false;
5247   int SplatIdx = -1;
5248   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5249     SDValue In = Op.getOperand(idx);
5250     if (In.getOpcode() == ISD::UNDEF)
5251       continue;
5252     if (!isa<ConstantSDNode>(In)) 
5253       NonConstIdx.push_back(idx);
5254     else {
5255       Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5256       HasConstElts = true;
5257     }
5258     if (SplatIdx == -1)
5259       SplatIdx = idx;
5260     else if (In != Op.getOperand(SplatIdx))
5261       IsSplat = false;
5262   }
5263
5264   // for splat use " (select i1 splat_elt, all-ones, all-zeroes)"
5265   if (IsSplat)
5266     return DAG.getNode(ISD::SELECT, dl, VT, Op.getOperand(SplatIdx),
5267                        DAG.getConstant(1, dl, VT),
5268                        DAG.getConstant(0, dl, VT));
5269
5270   // insert elements one by one
5271   SDValue DstVec;
5272   SDValue Imm;
5273   if (Immediate) {
5274     MVT ImmVT = MVT::getIntegerVT(std::max((int)VT.getSizeInBits(), 8));
5275     Imm = DAG.getConstant(Immediate, dl, ImmVT);
5276   }
5277   else if (HasConstElts)
5278     Imm = DAG.getConstant(0, dl, VT);
5279   else 
5280     Imm = DAG.getUNDEF(VT);
5281   if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5282     DstVec = DAG.getNode(ISD::BITCAST, dl, VT, Imm);
5283   else {
5284     SDValue ExtVec = DAG.getNode(ISD::BITCAST, dl, MVT::v8i1, Imm);
5285     DstVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5286                          DAG.getIntPtrConstant(0, dl));
5287   }
5288
5289   for (unsigned i = 0; i < NonConstIdx.size(); ++i) {
5290     unsigned InsertIdx = NonConstIdx[i];
5291     DstVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5292                          Op.getOperand(InsertIdx),
5293                          DAG.getIntPtrConstant(InsertIdx, dl));
5294   }
5295   return DstVec;
5296 }
5297
5298 /// \brief Return true if \p N implements a horizontal binop and return the
5299 /// operands for the horizontal binop into V0 and V1.
5300 ///
5301 /// This is a helper function of LowerToHorizontalOp().
5302 /// This function checks that the build_vector \p N in input implements a
5303 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
5304 /// operation to match.
5305 /// For example, if \p Opcode is equal to ISD::ADD, then this function
5306 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
5307 /// is equal to ISD::SUB, then this function checks if this is a horizontal
5308 /// arithmetic sub.
5309 ///
5310 /// This function only analyzes elements of \p N whose indices are
5311 /// in range [BaseIdx, LastIdx).
5312 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
5313                               SelectionDAG &DAG,
5314                               unsigned BaseIdx, unsigned LastIdx,
5315                               SDValue &V0, SDValue &V1) {
5316   EVT VT = N->getValueType(0);
5317
5318   assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
5319   assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
5320          "Invalid Vector in input!");
5321
5322   bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
5323   bool CanFold = true;
5324   unsigned ExpectedVExtractIdx = BaseIdx;
5325   unsigned NumElts = LastIdx - BaseIdx;
5326   V0 = DAG.getUNDEF(VT);
5327   V1 = DAG.getUNDEF(VT);
5328
5329   // Check if N implements a horizontal binop.
5330   for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
5331     SDValue Op = N->getOperand(i + BaseIdx);
5332
5333     // Skip UNDEFs.
5334     if (Op->getOpcode() == ISD::UNDEF) {
5335       // Update the expected vector extract index.
5336       if (i * 2 == NumElts)
5337         ExpectedVExtractIdx = BaseIdx;
5338       ExpectedVExtractIdx += 2;
5339       continue;
5340     }
5341
5342     CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
5343
5344     if (!CanFold)
5345       break;
5346
5347     SDValue Op0 = Op.getOperand(0);
5348     SDValue Op1 = Op.getOperand(1);
5349
5350     // Try to match the following pattern:
5351     // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
5352     CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5353         Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5354         Op0.getOperand(0) == Op1.getOperand(0) &&
5355         isa<ConstantSDNode>(Op0.getOperand(1)) &&
5356         isa<ConstantSDNode>(Op1.getOperand(1)));
5357     if (!CanFold)
5358       break;
5359
5360     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5361     unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
5362
5363     if (i * 2 < NumElts) {
5364       if (V0.getOpcode() == ISD::UNDEF) {
5365         V0 = Op0.getOperand(0);
5366         if (V0.getValueType() != VT)
5367           return false;
5368       }
5369     } else {
5370       if (V1.getOpcode() == ISD::UNDEF) {
5371         V1 = Op0.getOperand(0);
5372         if (V1.getValueType() != VT)
5373           return false;
5374       }
5375       if (i * 2 == NumElts)
5376         ExpectedVExtractIdx = BaseIdx;
5377     }
5378
5379     SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
5380     if (I0 == ExpectedVExtractIdx)
5381       CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
5382     else if (IsCommutable && I1 == ExpectedVExtractIdx) {
5383       // Try to match the following dag sequence:
5384       // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
5385       CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
5386     } else
5387       CanFold = false;
5388
5389     ExpectedVExtractIdx += 2;
5390   }
5391
5392   return CanFold;
5393 }
5394
5395 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
5396 /// a concat_vector.
5397 ///
5398 /// This is a helper function of LowerToHorizontalOp().
5399 /// This function expects two 256-bit vectors called V0 and V1.
5400 /// At first, each vector is split into two separate 128-bit vectors.
5401 /// Then, the resulting 128-bit vectors are used to implement two
5402 /// horizontal binary operations.
5403 ///
5404 /// The kind of horizontal binary operation is defined by \p X86Opcode.
5405 ///
5406 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
5407 /// the two new horizontal binop.
5408 /// When Mode is set, the first horizontal binop dag node would take as input
5409 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
5410 /// horizontal binop dag node would take as input the lower 128-bit of V1
5411 /// and the upper 128-bit of V1.
5412 ///   Example:
5413 ///     HADD V0_LO, V0_HI
5414 ///     HADD V1_LO, V1_HI
5415 ///
5416 /// Otherwise, the first horizontal binop dag node takes as input the lower
5417 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
5418 /// dag node takes the the upper 128-bit of V0 and the upper 128-bit of V1.
5419 ///   Example:
5420 ///     HADD V0_LO, V1_LO
5421 ///     HADD V0_HI, V1_HI
5422 ///
5423 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
5424 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
5425 /// the upper 128-bits of the result.
5426 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
5427                                      SDLoc DL, SelectionDAG &DAG,
5428                                      unsigned X86Opcode, bool Mode,
5429                                      bool isUndefLO, bool isUndefHI) {
5430   EVT VT = V0.getValueType();
5431   assert(VT.is256BitVector() && VT == V1.getValueType() &&
5432          "Invalid nodes in input!");
5433
5434   unsigned NumElts = VT.getVectorNumElements();
5435   SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
5436   SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
5437   SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
5438   SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
5439   EVT NewVT = V0_LO.getValueType();
5440
5441   SDValue LO = DAG.getUNDEF(NewVT);
5442   SDValue HI = DAG.getUNDEF(NewVT);
5443
5444   if (Mode) {
5445     // Don't emit a horizontal binop if the result is expected to be UNDEF.
5446     if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
5447       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
5448     if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
5449       HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
5450   } else {
5451     // Don't emit a horizontal binop if the result is expected to be UNDEF.
5452     if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
5453                        V1_LO->getOpcode() != ISD::UNDEF))
5454       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
5455
5456     if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
5457                        V1_HI->getOpcode() != ISD::UNDEF))
5458       HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
5459   }
5460
5461   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
5462 }
5463
5464 /// Try to fold a build_vector that performs an 'addsub' to an X86ISD::ADDSUB
5465 /// node.
5466 static SDValue LowerToAddSub(const BuildVectorSDNode *BV,
5467                              const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5468   EVT VT = BV->getValueType(0);
5469   if ((!Subtarget->hasSSE3() || (VT != MVT::v4f32 && VT != MVT::v2f64)) &&
5470       (!Subtarget->hasAVX() || (VT != MVT::v8f32 && VT != MVT::v4f64)))
5471     return SDValue();
5472
5473   SDLoc DL(BV);
5474   unsigned NumElts = VT.getVectorNumElements();
5475   SDValue InVec0 = DAG.getUNDEF(VT);
5476   SDValue InVec1 = DAG.getUNDEF(VT);
5477
5478   assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
5479           VT == MVT::v2f64) && "build_vector with an invalid type found!");
5480
5481   // Odd-numbered elements in the input build vector are obtained from
5482   // adding two integer/float elements.
5483   // Even-numbered elements in the input build vector are obtained from
5484   // subtracting two integer/float elements.
5485   unsigned ExpectedOpcode = ISD::FSUB;
5486   unsigned NextExpectedOpcode = ISD::FADD;
5487   bool AddFound = false;
5488   bool SubFound = false;
5489
5490   for (unsigned i = 0, e = NumElts; i != e; ++i) {
5491     SDValue Op = BV->getOperand(i);
5492
5493     // Skip 'undef' values.
5494     unsigned Opcode = Op.getOpcode();
5495     if (Opcode == ISD::UNDEF) {
5496       std::swap(ExpectedOpcode, NextExpectedOpcode);
5497       continue;
5498     }
5499
5500     // Early exit if we found an unexpected opcode.
5501     if (Opcode != ExpectedOpcode)
5502       return SDValue();
5503
5504     SDValue Op0 = Op.getOperand(0);
5505     SDValue Op1 = Op.getOperand(1);
5506
5507     // Try to match the following pattern:
5508     // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
5509     // Early exit if we cannot match that sequence.
5510     if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5511         Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5512         !isa<ConstantSDNode>(Op0.getOperand(1)) ||
5513         !isa<ConstantSDNode>(Op1.getOperand(1)) ||
5514         Op0.getOperand(1) != Op1.getOperand(1))
5515       return SDValue();
5516
5517     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5518     if (I0 != i)
5519       return SDValue();
5520
5521     // We found a valid add/sub node. Update the information accordingly.
5522     if (i & 1)
5523       AddFound = true;
5524     else
5525       SubFound = true;
5526
5527     // Update InVec0 and InVec1.
5528     if (InVec0.getOpcode() == ISD::UNDEF) {
5529       InVec0 = Op0.getOperand(0);
5530       if (InVec0.getValueType() != VT)
5531         return SDValue();
5532     }
5533     if (InVec1.getOpcode() == ISD::UNDEF) {
5534       InVec1 = Op1.getOperand(0);
5535       if (InVec1.getValueType() != VT)
5536         return SDValue();
5537     }
5538
5539     // Make sure that operands in input to each add/sub node always
5540     // come from a same pair of vectors.
5541     if (InVec0 != Op0.getOperand(0)) {
5542       if (ExpectedOpcode == ISD::FSUB)
5543         return SDValue();
5544
5545       // FADD is commutable. Try to commute the operands
5546       // and then test again.
5547       std::swap(Op0, Op1);
5548       if (InVec0 != Op0.getOperand(0))
5549         return SDValue();
5550     }
5551
5552     if (InVec1 != Op1.getOperand(0))
5553       return SDValue();
5554
5555     // Update the pair of expected opcodes.
5556     std::swap(ExpectedOpcode, NextExpectedOpcode);
5557   }
5558
5559   // Don't try to fold this build_vector into an ADDSUB if the inputs are undef.
5560   if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
5561       InVec1.getOpcode() != ISD::UNDEF)
5562     return DAG.getNode(X86ISD::ADDSUB, DL, VT, InVec0, InVec1);
5563
5564   return SDValue();
5565 }
5566
5567 /// Lower BUILD_VECTOR to a horizontal add/sub operation if possible.
5568 static SDValue LowerToHorizontalOp(const BuildVectorSDNode *BV,
5569                                    const X86Subtarget *Subtarget,
5570                                    SelectionDAG &DAG) {
5571   EVT VT = BV->getValueType(0);
5572   unsigned NumElts = VT.getVectorNumElements();
5573   unsigned NumUndefsLO = 0;
5574   unsigned NumUndefsHI = 0;
5575   unsigned Half = NumElts/2;
5576
5577   // Count the number of UNDEF operands in the build_vector in input.
5578   for (unsigned i = 0, e = Half; i != e; ++i)
5579     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5580       NumUndefsLO++;
5581
5582   for (unsigned i = Half, e = NumElts; i != e; ++i)
5583     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5584       NumUndefsHI++;
5585
5586   // Early exit if this is either a build_vector of all UNDEFs or all the
5587   // operands but one are UNDEF.
5588   if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
5589     return SDValue();
5590
5591   SDLoc DL(BV);
5592   SDValue InVec0, InVec1;
5593   if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
5594     // Try to match an SSE3 float HADD/HSUB.
5595     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5596       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5597
5598     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5599       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5600   } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
5601     // Try to match an SSSE3 integer HADD/HSUB.
5602     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5603       return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
5604
5605     if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5606       return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
5607   }
5608
5609   if (!Subtarget->hasAVX())
5610     return SDValue();
5611
5612   if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
5613     // Try to match an AVX horizontal add/sub of packed single/double
5614     // precision floating point values from 256-bit vectors.
5615     SDValue InVec2, InVec3;
5616     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
5617         isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
5618         ((InVec0.getOpcode() == ISD::UNDEF ||
5619           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5620         ((InVec1.getOpcode() == ISD::UNDEF ||
5621           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5622       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5623
5624     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
5625         isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
5626         ((InVec0.getOpcode() == ISD::UNDEF ||
5627           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5628         ((InVec1.getOpcode() == ISD::UNDEF ||
5629           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5630       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5631   } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
5632     // Try to match an AVX2 horizontal add/sub of signed integers.
5633     SDValue InVec2, InVec3;
5634     unsigned X86Opcode;
5635     bool CanFold = true;
5636
5637     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
5638         isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
5639         ((InVec0.getOpcode() == ISD::UNDEF ||
5640           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5641         ((InVec1.getOpcode() == ISD::UNDEF ||
5642           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5643       X86Opcode = X86ISD::HADD;
5644     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
5645         isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
5646         ((InVec0.getOpcode() == ISD::UNDEF ||
5647           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5648         ((InVec1.getOpcode() == ISD::UNDEF ||
5649           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5650       X86Opcode = X86ISD::HSUB;
5651     else
5652       CanFold = false;
5653
5654     if (CanFold) {
5655       // Fold this build_vector into a single horizontal add/sub.
5656       // Do this only if the target has AVX2.
5657       if (Subtarget->hasAVX2())
5658         return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
5659
5660       // Do not try to expand this build_vector into a pair of horizontal
5661       // add/sub if we can emit a pair of scalar add/sub.
5662       if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5663         return SDValue();
5664
5665       // Convert this build_vector into a pair of horizontal binop followed by
5666       // a concat vector.
5667       bool isUndefLO = NumUndefsLO == Half;
5668       bool isUndefHI = NumUndefsHI == Half;
5669       return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
5670                                    isUndefLO, isUndefHI);
5671     }
5672   }
5673
5674   if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
5675        VT == MVT::v16i16) && Subtarget->hasAVX()) {
5676     unsigned X86Opcode;
5677     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5678       X86Opcode = X86ISD::HADD;
5679     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5680       X86Opcode = X86ISD::HSUB;
5681     else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5682       X86Opcode = X86ISD::FHADD;
5683     else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5684       X86Opcode = X86ISD::FHSUB;
5685     else
5686       return SDValue();
5687
5688     // Don't try to expand this build_vector into a pair of horizontal add/sub
5689     // if we can simply emit a pair of scalar add/sub.
5690     if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5691       return SDValue();
5692
5693     // Convert this build_vector into two horizontal add/sub followed by
5694     // a concat vector.
5695     bool isUndefLO = NumUndefsLO == Half;
5696     bool isUndefHI = NumUndefsHI == Half;
5697     return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
5698                                  isUndefLO, isUndefHI);
5699   }
5700
5701   return SDValue();
5702 }
5703
5704 SDValue
5705 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5706   SDLoc dl(Op);
5707
5708   MVT VT = Op.getSimpleValueType();
5709   MVT ExtVT = VT.getVectorElementType();
5710   unsigned NumElems = Op.getNumOperands();
5711
5712   // Generate vectors for predicate vectors.
5713   if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
5714     return LowerBUILD_VECTORvXi1(Op, DAG);
5715
5716   // Vectors containing all zeros can be matched by pxor and xorps later
5717   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5718     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5719     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5720     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
5721       return Op;
5722
5723     return getZeroVector(VT, Subtarget, DAG, dl);
5724   }
5725
5726   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5727   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5728   // vpcmpeqd on 256-bit vectors.
5729   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5730     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5731       return Op;
5732
5733     if (!VT.is512BitVector())
5734       return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5735   }
5736
5737   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(Op.getNode());
5738   if (SDValue AddSub = LowerToAddSub(BV, Subtarget, DAG))
5739     return AddSub;
5740   if (SDValue HorizontalOp = LowerToHorizontalOp(BV, Subtarget, DAG))
5741     return HorizontalOp;
5742   if (SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG))
5743     return Broadcast;
5744
5745   unsigned EVTBits = ExtVT.getSizeInBits();
5746
5747   unsigned NumZero  = 0;
5748   unsigned NumNonZero = 0;
5749   unsigned NonZeros = 0;
5750   bool IsAllConstants = true;
5751   SmallSet<SDValue, 8> Values;
5752   for (unsigned i = 0; i < NumElems; ++i) {
5753     SDValue Elt = Op.getOperand(i);
5754     if (Elt.getOpcode() == ISD::UNDEF)
5755       continue;
5756     Values.insert(Elt);
5757     if (Elt.getOpcode() != ISD::Constant &&
5758         Elt.getOpcode() != ISD::ConstantFP)
5759       IsAllConstants = false;
5760     if (X86::isZeroNode(Elt))
5761       NumZero++;
5762     else {
5763       NonZeros |= (1 << i);
5764       NumNonZero++;
5765     }
5766   }
5767
5768   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5769   if (NumNonZero == 0)
5770     return DAG.getUNDEF(VT);
5771
5772   // Special case for single non-zero, non-undef, element.
5773   if (NumNonZero == 1) {
5774     unsigned Idx = countTrailingZeros(NonZeros);
5775     SDValue Item = Op.getOperand(Idx);
5776
5777     // If this is an insertion of an i64 value on x86-32, and if the top bits of
5778     // the value are obviously zero, truncate the value to i32 and do the
5779     // insertion that way.  Only do this if the value is non-constant or if the
5780     // value is a constant being inserted into element 0.  It is cheaper to do
5781     // a constant pool load than it is to do a movd + shuffle.
5782     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5783         (!IsAllConstants || Idx == 0)) {
5784       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5785         // Handle SSE only.
5786         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5787         EVT VecVT = MVT::v4i32;
5788
5789         // Truncate the value (which may itself be a constant) to i32, and
5790         // convert it to a vector with movd (S2V+shuffle to zero extend).
5791         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5792         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5793         return DAG.getNode(
5794             ISD::BITCAST, dl, VT,
5795             getShuffleVectorZeroOrUndef(Item, Idx * 2, true, Subtarget, DAG));
5796       }
5797     }
5798
5799     // If we have a constant or non-constant insertion into the low element of
5800     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5801     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5802     // depending on what the source datatype is.
5803     if (Idx == 0) {
5804       if (NumZero == 0)
5805         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5806
5807       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5808           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5809         if (VT.is512BitVector()) {
5810           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5811           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5812                              Item, DAG.getIntPtrConstant(0, dl));
5813         }
5814         assert((VT.is128BitVector() || VT.is256BitVector()) &&
5815                "Expected an SSE value type!");
5816         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5817         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5818         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5819       }
5820
5821       // We can't directly insert an i8 or i16 into a vector, so zero extend
5822       // it to i32 first.
5823       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5824         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5825         if (VT.is256BitVector()) {
5826           if (Subtarget->hasAVX()) {
5827             Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v8i32, Item);
5828             Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5829           } else {
5830             // Without AVX, we need to extend to a 128-bit vector and then
5831             // insert into the 256-bit vector.
5832             Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5833             SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5834             Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5835           }
5836         } else {
5837           assert(VT.is128BitVector() && "Expected an SSE value type!");
5838           Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5839           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5840         }
5841         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5842       }
5843     }
5844
5845     // Is it a vector logical left shift?
5846     if (NumElems == 2 && Idx == 1 &&
5847         X86::isZeroNode(Op.getOperand(0)) &&
5848         !X86::isZeroNode(Op.getOperand(1))) {
5849       unsigned NumBits = VT.getSizeInBits();
5850       return getVShift(true, VT,
5851                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5852                                    VT, Op.getOperand(1)),
5853                        NumBits/2, DAG, *this, dl);
5854     }
5855
5856     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5857       return SDValue();
5858
5859     // Otherwise, if this is a vector with i32 or f32 elements, and the element
5860     // is a non-constant being inserted into an element other than the low one,
5861     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
5862     // movd/movss) to move this into the low element, then shuffle it into
5863     // place.
5864     if (EVTBits == 32) {
5865       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5866       return getShuffleVectorZeroOrUndef(Item, Idx, NumZero > 0, Subtarget, DAG);
5867     }
5868   }
5869
5870   // Splat is obviously ok. Let legalizer expand it to a shuffle.
5871   if (Values.size() == 1) {
5872     if (EVTBits == 32) {
5873       // Instead of a shuffle like this:
5874       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5875       // Check if it's possible to issue this instead.
5876       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5877       unsigned Idx = countTrailingZeros(NonZeros);
5878       SDValue Item = Op.getOperand(Idx);
5879       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5880         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5881     }
5882     return SDValue();
5883   }
5884
5885   // A vector full of immediates; various special cases are already
5886   // handled, so this is best done with a single constant-pool load.
5887   if (IsAllConstants)
5888     return SDValue();
5889
5890   // For AVX-length vectors, see if we can use a vector load to get all of the
5891   // elements, otherwise build the individual 128-bit pieces and use
5892   // shuffles to put them in place.
5893   if (VT.is256BitVector() || VT.is512BitVector()) {
5894     SmallVector<SDValue, 64> V(Op->op_begin(), Op->op_begin() + NumElems);
5895
5896     // Check for a build vector of consecutive loads.
5897     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
5898       return LD;
5899
5900     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5901
5902     // Build both the lower and upper subvector.
5903     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
5904                                 makeArrayRef(&V[0], NumElems/2));
5905     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
5906                                 makeArrayRef(&V[NumElems / 2], NumElems/2));
5907
5908     // Recreate the wider vector with the lower and upper part.
5909     if (VT.is256BitVector())
5910       return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5911     return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5912   }
5913
5914   // Let legalizer expand 2-wide build_vectors.
5915   if (EVTBits == 64) {
5916     if (NumNonZero == 1) {
5917       // One half is zero or undef.
5918       unsigned Idx = countTrailingZeros(NonZeros);
5919       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5920                                  Op.getOperand(Idx));
5921       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
5922     }
5923     return SDValue();
5924   }
5925
5926   // If element VT is < 32 bits, convert it to inserts into a zero vector.
5927   if (EVTBits == 8 && NumElems == 16)
5928     if (SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5929                                         Subtarget, *this))
5930       return V;
5931
5932   if (EVTBits == 16 && NumElems == 8)
5933     if (SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5934                                       Subtarget, *this))
5935       return V;
5936
5937   // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
5938   if (EVTBits == 32 && NumElems == 4)
5939     if (SDValue V = LowerBuildVectorv4x32(Op, DAG, Subtarget, *this))
5940       return V;
5941
5942   // If element VT is == 32 bits, turn it into a number of shuffles.
5943   SmallVector<SDValue, 8> V(NumElems);
5944   if (NumElems == 4 && NumZero > 0) {
5945     for (unsigned i = 0; i < 4; ++i) {
5946       bool isZero = !(NonZeros & (1 << i));
5947       if (isZero)
5948         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
5949       else
5950         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5951     }
5952
5953     for (unsigned i = 0; i < 2; ++i) {
5954       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5955         default: break;
5956         case 0:
5957           V[i] = V[i*2];  // Must be a zero vector.
5958           break;
5959         case 1:
5960           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5961           break;
5962         case 2:
5963           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5964           break;
5965         case 3:
5966           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5967           break;
5968       }
5969     }
5970
5971     bool Reverse1 = (NonZeros & 0x3) == 2;
5972     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5973     int MaskVec[] = {
5974       Reverse1 ? 1 : 0,
5975       Reverse1 ? 0 : 1,
5976       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
5977       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
5978     };
5979     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5980   }
5981
5982   if (Values.size() > 1 && VT.is128BitVector()) {
5983     // Check for a build vector of consecutive loads.
5984     for (unsigned i = 0; i < NumElems; ++i)
5985       V[i] = Op.getOperand(i);
5986
5987     // Check for elements which are consecutive loads.
5988     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
5989       return LD;
5990
5991     // Check for a build vector from mostly shuffle plus few inserting.
5992     if (SDValue Sh = buildFromShuffleMostly(Op, DAG))
5993       return Sh;
5994
5995     // For SSE 4.1, use insertps to put the high elements into the low element.
5996     if (Subtarget->hasSSE41()) {
5997       SDValue Result;
5998       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5999         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6000       else
6001         Result = DAG.getUNDEF(VT);
6002
6003       for (unsigned i = 1; i < NumElems; ++i) {
6004         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6005         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6006                              Op.getOperand(i), DAG.getIntPtrConstant(i, dl));
6007       }
6008       return Result;
6009     }
6010
6011     // Otherwise, expand into a number of unpckl*, start by extending each of
6012     // our (non-undef) elements to the full vector width with the element in the
6013     // bottom slot of the vector (which generates no code for SSE).
6014     for (unsigned i = 0; i < NumElems; ++i) {
6015       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6016         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6017       else
6018         V[i] = DAG.getUNDEF(VT);
6019     }
6020
6021     // Next, we iteratively mix elements, e.g. for v4f32:
6022     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6023     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6024     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
6025     unsigned EltStride = NumElems >> 1;
6026     while (EltStride != 0) {
6027       for (unsigned i = 0; i < EltStride; ++i) {
6028         // If V[i+EltStride] is undef and this is the first round of mixing,
6029         // then it is safe to just drop this shuffle: V[i] is already in the
6030         // right place, the one element (since it's the first round) being
6031         // inserted as undef can be dropped.  This isn't safe for successive
6032         // rounds because they will permute elements within both vectors.
6033         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6034             EltStride == NumElems/2)
6035           continue;
6036
6037         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6038       }
6039       EltStride >>= 1;
6040     }
6041     return V[0];
6042   }
6043   return SDValue();
6044 }
6045
6046 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6047 // to create 256-bit vectors from two other 128-bit ones.
6048 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6049   SDLoc dl(Op);
6050   MVT ResVT = Op.getSimpleValueType();
6051
6052   assert((ResVT.is256BitVector() ||
6053           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6054
6055   SDValue V1 = Op.getOperand(0);
6056   SDValue V2 = Op.getOperand(1);
6057   unsigned NumElems = ResVT.getVectorNumElements();
6058   if (ResVT.is256BitVector())
6059     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6060
6061   if (Op.getNumOperands() == 4) {
6062     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6063                                 ResVT.getVectorNumElements()/2);
6064     SDValue V3 = Op.getOperand(2);
6065     SDValue V4 = Op.getOperand(3);
6066     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6067       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6068   }
6069   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6070 }
6071
6072 static SDValue LowerCONCAT_VECTORSvXi1(SDValue Op,
6073                                        const X86Subtarget *Subtarget,
6074                                        SelectionDAG & DAG) {
6075   SDLoc dl(Op);
6076   MVT ResVT = Op.getSimpleValueType();
6077   unsigned NumOfOperands = Op.getNumOperands();
6078
6079   assert(isPowerOf2_32(NumOfOperands) &&
6080          "Unexpected number of operands in CONCAT_VECTORS");
6081
6082   if (NumOfOperands > 2) {
6083     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6084                                   ResVT.getVectorNumElements()/2);
6085     SmallVector<SDValue, 2> Ops;
6086     for (unsigned i = 0; i < NumOfOperands/2; i++)
6087       Ops.push_back(Op.getOperand(i));
6088     SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6089     Ops.clear();
6090     for (unsigned i = NumOfOperands/2; i < NumOfOperands; i++)
6091       Ops.push_back(Op.getOperand(i));
6092     SDValue Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6093     return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Lo, Hi);
6094   }
6095
6096   SDValue V1 = Op.getOperand(0);
6097   SDValue V2 = Op.getOperand(1);
6098   bool IsZeroV1 = ISD::isBuildVectorAllZeros(V1.getNode());
6099   bool IsZeroV2 = ISD::isBuildVectorAllZeros(V2.getNode());
6100
6101   if (IsZeroV1 && IsZeroV2)
6102     return getZeroVector(ResVT, Subtarget, DAG, dl);
6103
6104   SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
6105   SDValue Undef = DAG.getUNDEF(ResVT);
6106   unsigned NumElems = ResVT.getVectorNumElements();
6107   SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
6108
6109   V2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V2, ZeroIdx);
6110   V2 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V2, ShiftBits);
6111   if (IsZeroV1)
6112     return V2;
6113
6114   V1 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V1, ZeroIdx);
6115   // Zero the upper bits of V1
6116   V1 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V1, ShiftBits);
6117   V1 = DAG.getNode(X86ISD::VSRLI, dl, ResVT, V1, ShiftBits);
6118   if (IsZeroV2)
6119     return V1;
6120   return DAG.getNode(ISD::OR, dl, ResVT, V1, V2);
6121 }
6122
6123 static SDValue LowerCONCAT_VECTORS(SDValue Op,
6124                                    const X86Subtarget *Subtarget,
6125                                    SelectionDAG &DAG) {
6126   MVT VT = Op.getSimpleValueType();
6127   if (VT.getVectorElementType() == MVT::i1)
6128     return LowerCONCAT_VECTORSvXi1(Op, Subtarget, DAG);
6129
6130   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6131          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6132           Op.getNumOperands() == 4)));
6133
6134   // AVX can use the vinsertf128 instruction to create 256-bit vectors
6135   // from two other 128-bit ones.
6136
6137   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6138   return LowerAVXCONCAT_VECTORS(Op, DAG);
6139 }
6140
6141
6142 //===----------------------------------------------------------------------===//
6143 // Vector shuffle lowering
6144 //
6145 // This is an experimental code path for lowering vector shuffles on x86. It is
6146 // designed to handle arbitrary vector shuffles and blends, gracefully
6147 // degrading performance as necessary. It works hard to recognize idiomatic
6148 // shuffles and lower them to optimal instruction patterns without leaving
6149 // a framework that allows reasonably efficient handling of all vector shuffle
6150 // patterns.
6151 //===----------------------------------------------------------------------===//
6152
6153 /// \brief Tiny helper function to identify a no-op mask.
6154 ///
6155 /// This is a somewhat boring predicate function. It checks whether the mask
6156 /// array input, which is assumed to be a single-input shuffle mask of the kind
6157 /// used by the X86 shuffle instructions (not a fully general
6158 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
6159 /// in-place shuffle are 'no-op's.
6160 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
6161   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6162     if (Mask[i] != -1 && Mask[i] != i)
6163       return false;
6164   return true;
6165 }
6166
6167 /// \brief Helper function to classify a mask as a single-input mask.
6168 ///
6169 /// This isn't a generic single-input test because in the vector shuffle
6170 /// lowering we canonicalize single inputs to be the first input operand. This
6171 /// means we can more quickly test for a single input by only checking whether
6172 /// an input from the second operand exists. We also assume that the size of
6173 /// mask corresponds to the size of the input vectors which isn't true in the
6174 /// fully general case.
6175 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
6176   for (int M : Mask)
6177     if (M >= (int)Mask.size())
6178       return false;
6179   return true;
6180 }
6181
6182 /// \brief Test whether there are elements crossing 128-bit lanes in this
6183 /// shuffle mask.
6184 ///
6185 /// X86 divides up its shuffles into in-lane and cross-lane shuffle operations
6186 /// and we routinely test for these.
6187 static bool is128BitLaneCrossingShuffleMask(MVT VT, ArrayRef<int> Mask) {
6188   int LaneSize = 128 / VT.getScalarSizeInBits();
6189   int Size = Mask.size();
6190   for (int i = 0; i < Size; ++i)
6191     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
6192       return true;
6193   return false;
6194 }
6195
6196 /// \brief Test whether a shuffle mask is equivalent within each 128-bit lane.
6197 ///
6198 /// This checks a shuffle mask to see if it is performing the same
6199 /// 128-bit lane-relative shuffle in each 128-bit lane. This trivially implies
6200 /// that it is also not lane-crossing. It may however involve a blend from the
6201 /// same lane of a second vector.
6202 ///
6203 /// The specific repeated shuffle mask is populated in \p RepeatedMask, as it is
6204 /// non-trivial to compute in the face of undef lanes. The representation is
6205 /// *not* suitable for use with existing 128-bit shuffles as it will contain
6206 /// entries from both V1 and V2 inputs to the wider mask.
6207 static bool
6208 is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
6209                                 SmallVectorImpl<int> &RepeatedMask) {
6210   int LaneSize = 128 / VT.getScalarSizeInBits();
6211   RepeatedMask.resize(LaneSize, -1);
6212   int Size = Mask.size();
6213   for (int i = 0; i < Size; ++i) {
6214     if (Mask[i] < 0)
6215       continue;
6216     if ((Mask[i] % Size) / LaneSize != i / LaneSize)
6217       // This entry crosses lanes, so there is no way to model this shuffle.
6218       return false;
6219
6220     // Ok, handle the in-lane shuffles by detecting if and when they repeat.
6221     if (RepeatedMask[i % LaneSize] == -1)
6222       // This is the first non-undef entry in this slot of a 128-bit lane.
6223       RepeatedMask[i % LaneSize] =
6224           Mask[i] < Size ? Mask[i] % LaneSize : Mask[i] % LaneSize + Size;
6225     else if (RepeatedMask[i % LaneSize] + (i / LaneSize) * LaneSize != Mask[i])
6226       // Found a mismatch with the repeated mask.
6227       return false;
6228   }
6229   return true;
6230 }
6231
6232 /// \brief Checks whether a shuffle mask is equivalent to an explicit list of
6233 /// arguments.
6234 ///
6235 /// This is a fast way to test a shuffle mask against a fixed pattern:
6236 ///
6237 ///   if (isShuffleEquivalent(Mask, 3, 2, {1, 0})) { ... }
6238 ///
6239 /// It returns true if the mask is exactly as wide as the argument list, and
6240 /// each element of the mask is either -1 (signifying undef) or the value given
6241 /// in the argument.
6242 static bool isShuffleEquivalent(SDValue V1, SDValue V2, ArrayRef<int> Mask,
6243                                 ArrayRef<int> ExpectedMask) {
6244   if (Mask.size() != ExpectedMask.size())
6245     return false;
6246
6247   int Size = Mask.size();
6248
6249   // If the values are build vectors, we can look through them to find
6250   // equivalent inputs that make the shuffles equivalent.
6251   auto *BV1 = dyn_cast<BuildVectorSDNode>(V1);
6252   auto *BV2 = dyn_cast<BuildVectorSDNode>(V2);
6253
6254   for (int i = 0; i < Size; ++i)
6255     if (Mask[i] != -1 && Mask[i] != ExpectedMask[i]) {
6256       auto *MaskBV = Mask[i] < Size ? BV1 : BV2;
6257       auto *ExpectedBV = ExpectedMask[i] < Size ? BV1 : BV2;
6258       if (!MaskBV || !ExpectedBV ||
6259           MaskBV->getOperand(Mask[i] % Size) !=
6260               ExpectedBV->getOperand(ExpectedMask[i] % Size))
6261         return false;
6262     }
6263
6264   return true;
6265 }
6266
6267 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
6268 ///
6269 /// This helper function produces an 8-bit shuffle immediate corresponding to
6270 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
6271 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
6272 /// example.
6273 ///
6274 /// NB: We rely heavily on "undef" masks preserving the input lane.
6275 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask, SDLoc DL,
6276                                           SelectionDAG &DAG) {
6277   assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
6278   assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
6279   assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
6280   assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
6281   assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
6282
6283   unsigned Imm = 0;
6284   Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
6285   Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
6286   Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
6287   Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
6288   return DAG.getConstant(Imm, DL, MVT::i8);
6289 }
6290
6291 /// \brief Try to emit a blend instruction for a shuffle using bit math.
6292 ///
6293 /// This is used as a fallback approach when first class blend instructions are
6294 /// unavailable. Currently it is only suitable for integer vectors, but could
6295 /// be generalized for floating point vectors if desirable.
6296 static SDValue lowerVectorShuffleAsBitBlend(SDLoc DL, MVT VT, SDValue V1,
6297                                             SDValue V2, ArrayRef<int> Mask,
6298                                             SelectionDAG &DAG) {
6299   assert(VT.isInteger() && "Only supports integer vector types!");
6300   MVT EltVT = VT.getScalarType();
6301   int NumEltBits = EltVT.getSizeInBits();
6302   SDValue Zero = DAG.getConstant(0, DL, EltVT);
6303   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6304                                     EltVT);
6305   SmallVector<SDValue, 16> MaskOps;
6306   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6307     if (Mask[i] != -1 && Mask[i] != i && Mask[i] != i + Size)
6308       return SDValue(); // Shuffled input!
6309     MaskOps.push_back(Mask[i] < Size ? AllOnes : Zero);
6310   }
6311
6312   SDValue V1Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, MaskOps);
6313   V1 = DAG.getNode(ISD::AND, DL, VT, V1, V1Mask);
6314   // We have to cast V2 around.
6315   MVT MaskVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
6316   V2 = DAG.getNode(ISD::BITCAST, DL, VT,
6317                    DAG.getNode(X86ISD::ANDNP, DL, MaskVT,
6318                                DAG.getNode(ISD::BITCAST, DL, MaskVT, V1Mask),
6319                                DAG.getNode(ISD::BITCAST, DL, MaskVT, V2)));
6320   return DAG.getNode(ISD::OR, DL, VT, V1, V2);
6321 }
6322
6323 /// \brief Try to emit a blend instruction for a shuffle.
6324 ///
6325 /// This doesn't do any checks for the availability of instructions for blending
6326 /// these values. It relies on the availability of the X86ISD::BLENDI pattern to
6327 /// be matched in the backend with the type given. What it does check for is
6328 /// that the shuffle mask is in fact a blend.
6329 static SDValue lowerVectorShuffleAsBlend(SDLoc DL, MVT VT, SDValue V1,
6330                                          SDValue V2, ArrayRef<int> Mask,
6331                                          const X86Subtarget *Subtarget,
6332                                          SelectionDAG &DAG) {
6333   unsigned BlendMask = 0;
6334   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6335     if (Mask[i] >= Size) {
6336       if (Mask[i] != i + Size)
6337         return SDValue(); // Shuffled V2 input!
6338       BlendMask |= 1u << i;
6339       continue;
6340     }
6341     if (Mask[i] >= 0 && Mask[i] != i)
6342       return SDValue(); // Shuffled V1 input!
6343   }
6344   switch (VT.SimpleTy) {
6345   case MVT::v2f64:
6346   case MVT::v4f32:
6347   case MVT::v4f64:
6348   case MVT::v8f32:
6349     return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V2,
6350                        DAG.getConstant(BlendMask, DL, MVT::i8));
6351
6352   case MVT::v4i64:
6353   case MVT::v8i32:
6354     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6355     // FALLTHROUGH
6356   case MVT::v2i64:
6357   case MVT::v4i32:
6358     // If we have AVX2 it is faster to use VPBLENDD when the shuffle fits into
6359     // that instruction.
6360     if (Subtarget->hasAVX2()) {
6361       // Scale the blend by the number of 32-bit dwords per element.
6362       int Scale =  VT.getScalarSizeInBits() / 32;
6363       BlendMask = 0;
6364       for (int i = 0, Size = Mask.size(); i < Size; ++i)
6365         if (Mask[i] >= Size)
6366           for (int j = 0; j < Scale; ++j)
6367             BlendMask |= 1u << (i * Scale + j);
6368
6369       MVT BlendVT = VT.getSizeInBits() > 128 ? MVT::v8i32 : MVT::v4i32;
6370       V1 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V1);
6371       V2 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V2);
6372       return DAG.getNode(ISD::BITCAST, DL, VT,
6373                          DAG.getNode(X86ISD::BLENDI, DL, BlendVT, V1, V2,
6374                                      DAG.getConstant(BlendMask, DL, MVT::i8)));
6375     }
6376     // FALLTHROUGH
6377   case MVT::v8i16: {
6378     // For integer shuffles we need to expand the mask and cast the inputs to
6379     // v8i16s prior to blending.
6380     int Scale = 8 / VT.getVectorNumElements();
6381     BlendMask = 0;
6382     for (int i = 0, Size = Mask.size(); i < Size; ++i)
6383       if (Mask[i] >= Size)
6384         for (int j = 0; j < Scale; ++j)
6385           BlendMask |= 1u << (i * Scale + j);
6386
6387     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1);
6388     V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V2);
6389     return DAG.getNode(ISD::BITCAST, DL, VT,
6390                        DAG.getNode(X86ISD::BLENDI, DL, MVT::v8i16, V1, V2,
6391                                    DAG.getConstant(BlendMask, DL, MVT::i8)));
6392   }
6393
6394   case MVT::v16i16: {
6395     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6396     SmallVector<int, 8> RepeatedMask;
6397     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
6398       // We can lower these with PBLENDW which is mirrored across 128-bit lanes.
6399       assert(RepeatedMask.size() == 8 && "Repeated mask size doesn't match!");
6400       BlendMask = 0;
6401       for (int i = 0; i < 8; ++i)
6402         if (RepeatedMask[i] >= 16)
6403           BlendMask |= 1u << i;
6404       return DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
6405                          DAG.getConstant(BlendMask, DL, MVT::i8));
6406     }
6407   }
6408     // FALLTHROUGH
6409   case MVT::v16i8:
6410   case MVT::v32i8: {
6411     assert((VT.getSizeInBits() == 128 || Subtarget->hasAVX2()) &&
6412            "256-bit byte-blends require AVX2 support!");
6413
6414     // Scale the blend by the number of bytes per element.
6415     int Scale = VT.getScalarSizeInBits() / 8;
6416
6417     // This form of blend is always done on bytes. Compute the byte vector
6418     // type.
6419     MVT BlendVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
6420
6421     // Compute the VSELECT mask. Note that VSELECT is really confusing in the
6422     // mix of LLVM's code generator and the x86 backend. We tell the code
6423     // generator that boolean values in the elements of an x86 vector register
6424     // are -1 for true and 0 for false. We then use the LLVM semantics of 'true'
6425     // mapping a select to operand #1, and 'false' mapping to operand #2. The
6426     // reality in x86 is that vector masks (pre-AVX-512) use only the high bit
6427     // of the element (the remaining are ignored) and 0 in that high bit would
6428     // mean operand #1 while 1 in the high bit would mean operand #2. So while
6429     // the LLVM model for boolean values in vector elements gets the relevant
6430     // bit set, it is set backwards and over constrained relative to x86's
6431     // actual model.
6432     SmallVector<SDValue, 32> VSELECTMask;
6433     for (int i = 0, Size = Mask.size(); i < Size; ++i)
6434       for (int j = 0; j < Scale; ++j)
6435         VSELECTMask.push_back(
6436             Mask[i] < 0 ? DAG.getUNDEF(MVT::i8)
6437                         : DAG.getConstant(Mask[i] < Size ? -1 : 0, DL,
6438                                           MVT::i8));
6439
6440     V1 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V1);
6441     V2 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V2);
6442     return DAG.getNode(
6443         ISD::BITCAST, DL, VT,
6444         DAG.getNode(ISD::VSELECT, DL, BlendVT,
6445                     DAG.getNode(ISD::BUILD_VECTOR, DL, BlendVT, VSELECTMask),
6446                     V1, V2));
6447   }
6448
6449   default:
6450     llvm_unreachable("Not a supported integer vector type!");
6451   }
6452 }
6453
6454 /// \brief Try to lower as a blend of elements from two inputs followed by
6455 /// a single-input permutation.
6456 ///
6457 /// This matches the pattern where we can blend elements from two inputs and
6458 /// then reduce the shuffle to a single-input permutation.
6459 static SDValue lowerVectorShuffleAsBlendAndPermute(SDLoc DL, MVT VT, SDValue V1,
6460                                                    SDValue V2,
6461                                                    ArrayRef<int> Mask,
6462                                                    SelectionDAG &DAG) {
6463   // We build up the blend mask while checking whether a blend is a viable way
6464   // to reduce the shuffle.
6465   SmallVector<int, 32> BlendMask(Mask.size(), -1);
6466   SmallVector<int, 32> PermuteMask(Mask.size(), -1);
6467
6468   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6469     if (Mask[i] < 0)
6470       continue;
6471
6472     assert(Mask[i] < Size * 2 && "Shuffle input is out of bounds.");
6473
6474     if (BlendMask[Mask[i] % Size] == -1)
6475       BlendMask[Mask[i] % Size] = Mask[i];
6476     else if (BlendMask[Mask[i] % Size] != Mask[i])
6477       return SDValue(); // Can't blend in the needed input!
6478
6479     PermuteMask[i] = Mask[i] % Size;
6480   }
6481
6482   SDValue V = DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6483   return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), PermuteMask);
6484 }
6485
6486 /// \brief Generic routine to decompose a shuffle and blend into indepndent
6487 /// blends and permutes.
6488 ///
6489 /// This matches the extremely common pattern for handling combined
6490 /// shuffle+blend operations on newer X86 ISAs where we have very fast blend
6491 /// operations. It will try to pick the best arrangement of shuffles and
6492 /// blends.
6493 static SDValue lowerVectorShuffleAsDecomposedShuffleBlend(SDLoc DL, MVT VT,
6494                                                           SDValue V1,
6495                                                           SDValue V2,
6496                                                           ArrayRef<int> Mask,
6497                                                           SelectionDAG &DAG) {
6498   // Shuffle the input elements into the desired positions in V1 and V2 and
6499   // blend them together.
6500   SmallVector<int, 32> V1Mask(Mask.size(), -1);
6501   SmallVector<int, 32> V2Mask(Mask.size(), -1);
6502   SmallVector<int, 32> BlendMask(Mask.size(), -1);
6503   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6504     if (Mask[i] >= 0 && Mask[i] < Size) {
6505       V1Mask[i] = Mask[i];
6506       BlendMask[i] = i;
6507     } else if (Mask[i] >= Size) {
6508       V2Mask[i] = Mask[i] - Size;
6509       BlendMask[i] = i + Size;
6510     }
6511
6512   // Try to lower with the simpler initial blend strategy unless one of the
6513   // input shuffles would be a no-op. We prefer to shuffle inputs as the
6514   // shuffle may be able to fold with a load or other benefit. However, when
6515   // we'll have to do 2x as many shuffles in order to achieve this, blending
6516   // first is a better strategy.
6517   if (!isNoopShuffleMask(V1Mask) && !isNoopShuffleMask(V2Mask))
6518     if (SDValue BlendPerm =
6519             lowerVectorShuffleAsBlendAndPermute(DL, VT, V1, V2, Mask, DAG))
6520       return BlendPerm;
6521
6522   V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
6523   V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
6524   return DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6525 }
6526
6527 /// \brief Try to lower a vector shuffle as a byte rotation.
6528 ///
6529 /// SSSE3 has a generic PALIGNR instruction in x86 that will do an arbitrary
6530 /// byte-rotation of the concatenation of two vectors; pre-SSSE3 can use
6531 /// a PSRLDQ/PSLLDQ/POR pattern to get a similar effect. This routine will
6532 /// try to generically lower a vector shuffle through such an pattern. It
6533 /// does not check for the profitability of lowering either as PALIGNR or
6534 /// PSRLDQ/PSLLDQ/POR, only whether the mask is valid to lower in that form.
6535 /// This matches shuffle vectors that look like:
6536 ///
6537 ///   v8i16 [11, 12, 13, 14, 15, 0, 1, 2]
6538 ///
6539 /// Essentially it concatenates V1 and V2, shifts right by some number of
6540 /// elements, and takes the low elements as the result. Note that while this is
6541 /// specified as a *right shift* because x86 is little-endian, it is a *left
6542 /// rotate* of the vector lanes.
6543 static SDValue lowerVectorShuffleAsByteRotate(SDLoc DL, MVT VT, SDValue V1,
6544                                               SDValue V2,
6545                                               ArrayRef<int> Mask,
6546                                               const X86Subtarget *Subtarget,
6547                                               SelectionDAG &DAG) {
6548   assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
6549
6550   int NumElts = Mask.size();
6551   int NumLanes = VT.getSizeInBits() / 128;
6552   int NumLaneElts = NumElts / NumLanes;
6553
6554   // We need to detect various ways of spelling a rotation:
6555   //   [11, 12, 13, 14, 15,  0,  1,  2]
6556   //   [-1, 12, 13, 14, -1, -1,  1, -1]
6557   //   [-1, -1, -1, -1, -1, -1,  1,  2]
6558   //   [ 3,  4,  5,  6,  7,  8,  9, 10]
6559   //   [-1,  4,  5,  6, -1, -1,  9, -1]
6560   //   [-1,  4,  5,  6, -1, -1, -1, -1]
6561   int Rotation = 0;
6562   SDValue Lo, Hi;
6563   for (int l = 0; l < NumElts; l += NumLaneElts) {
6564     for (int i = 0; i < NumLaneElts; ++i) {
6565       if (Mask[l + i] == -1)
6566         continue;
6567       assert(Mask[l + i] >= 0 && "Only -1 is a valid negative mask element!");
6568
6569       // Get the mod-Size index and lane correct it.
6570       int LaneIdx = (Mask[l + i] % NumElts) - l;
6571       // Make sure it was in this lane.
6572       if (LaneIdx < 0 || LaneIdx >= NumLaneElts)
6573         return SDValue();
6574
6575       // Determine where a rotated vector would have started.
6576       int StartIdx = i - LaneIdx;
6577       if (StartIdx == 0)
6578         // The identity rotation isn't interesting, stop.
6579         return SDValue();
6580
6581       // If we found the tail of a vector the rotation must be the missing
6582       // front. If we found the head of a vector, it must be how much of the
6583       // head.
6584       int CandidateRotation = StartIdx < 0 ? -StartIdx : NumLaneElts - StartIdx;
6585
6586       if (Rotation == 0)
6587         Rotation = CandidateRotation;
6588       else if (Rotation != CandidateRotation)
6589         // The rotations don't match, so we can't match this mask.
6590         return SDValue();
6591
6592       // Compute which value this mask is pointing at.
6593       SDValue MaskV = Mask[l + i] < NumElts ? V1 : V2;
6594
6595       // Compute which of the two target values this index should be assigned
6596       // to. This reflects whether the high elements are remaining or the low
6597       // elements are remaining.
6598       SDValue &TargetV = StartIdx < 0 ? Hi : Lo;
6599
6600       // Either set up this value if we've not encountered it before, or check
6601       // that it remains consistent.
6602       if (!TargetV)
6603         TargetV = MaskV;
6604       else if (TargetV != MaskV)
6605         // This may be a rotation, but it pulls from the inputs in some
6606         // unsupported interleaving.
6607         return SDValue();
6608     }
6609   }
6610
6611   // Check that we successfully analyzed the mask, and normalize the results.
6612   assert(Rotation != 0 && "Failed to locate a viable rotation!");
6613   assert((Lo || Hi) && "Failed to find a rotated input vector!");
6614   if (!Lo)
6615     Lo = Hi;
6616   else if (!Hi)
6617     Hi = Lo;
6618
6619   // The actual rotate instruction rotates bytes, so we need to scale the
6620   // rotation based on how many bytes are in the vector lane.
6621   int Scale = 16 / NumLaneElts;
6622
6623   // SSSE3 targets can use the palignr instruction.
6624   if (Subtarget->hasSSSE3()) {
6625     // Cast the inputs to i8 vector of correct length to match PALIGNR.
6626     MVT AlignVT = MVT::getVectorVT(MVT::i8, 16 * NumLanes);
6627     Lo = DAG.getNode(ISD::BITCAST, DL, AlignVT, Lo);
6628     Hi = DAG.getNode(ISD::BITCAST, DL, AlignVT, Hi);
6629
6630     return DAG.getNode(ISD::BITCAST, DL, VT,
6631                        DAG.getNode(X86ISD::PALIGNR, DL, AlignVT, Hi, Lo,
6632                                    DAG.getConstant(Rotation * Scale, DL,
6633                                                    MVT::i8)));
6634   }
6635
6636   assert(VT.getSizeInBits() == 128 &&
6637          "Rotate-based lowering only supports 128-bit lowering!");
6638   assert(Mask.size() <= 16 &&
6639          "Can shuffle at most 16 bytes in a 128-bit vector!");
6640
6641   // Default SSE2 implementation
6642   int LoByteShift = 16 - Rotation * Scale;
6643   int HiByteShift = Rotation * Scale;
6644
6645   // Cast the inputs to v2i64 to match PSLLDQ/PSRLDQ.
6646   Lo = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Lo);
6647   Hi = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Hi);
6648
6649   SDValue LoShift = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v2i64, Lo,
6650                                 DAG.getConstant(LoByteShift, DL, MVT::i8));
6651   SDValue HiShift = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v2i64, Hi,
6652                                 DAG.getConstant(HiByteShift, DL, MVT::i8));
6653   return DAG.getNode(ISD::BITCAST, DL, VT,
6654                      DAG.getNode(ISD::OR, DL, MVT::v2i64, LoShift, HiShift));
6655 }
6656
6657 /// \brief Compute whether each element of a shuffle is zeroable.
6658 ///
6659 /// A "zeroable" vector shuffle element is one which can be lowered to zero.
6660 /// Either it is an undef element in the shuffle mask, the element of the input
6661 /// referenced is undef, or the element of the input referenced is known to be
6662 /// zero. Many x86 shuffles can zero lanes cheaply and we often want to handle
6663 /// as many lanes with this technique as possible to simplify the remaining
6664 /// shuffle.
6665 static SmallBitVector computeZeroableShuffleElements(ArrayRef<int> Mask,
6666                                                      SDValue V1, SDValue V2) {
6667   SmallBitVector Zeroable(Mask.size(), false);
6668
6669   while (V1.getOpcode() == ISD::BITCAST)
6670     V1 = V1->getOperand(0);
6671   while (V2.getOpcode() == ISD::BITCAST)
6672     V2 = V2->getOperand(0);
6673
6674   bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
6675   bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
6676
6677   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6678     int M = Mask[i];
6679     // Handle the easy cases.
6680     if (M < 0 || (M >= 0 && M < Size && V1IsZero) || (M >= Size && V2IsZero)) {
6681       Zeroable[i] = true;
6682       continue;
6683     }
6684
6685     // If this is an index into a build_vector node (which has the same number
6686     // of elements), dig out the input value and use it.
6687     SDValue V = M < Size ? V1 : V2;
6688     if (V.getOpcode() != ISD::BUILD_VECTOR || Size != (int)V.getNumOperands())
6689       continue;
6690
6691     SDValue Input = V.getOperand(M % Size);
6692     // The UNDEF opcode check really should be dead code here, but not quite
6693     // worth asserting on (it isn't invalid, just unexpected).
6694     if (Input.getOpcode() == ISD::UNDEF || X86::isZeroNode(Input))
6695       Zeroable[i] = true;
6696   }
6697
6698   return Zeroable;
6699 }
6700
6701 /// \brief Try to emit a bitmask instruction for a shuffle.
6702 ///
6703 /// This handles cases where we can model a blend exactly as a bitmask due to
6704 /// one of the inputs being zeroable.
6705 static SDValue lowerVectorShuffleAsBitMask(SDLoc DL, MVT VT, SDValue V1,
6706                                            SDValue V2, ArrayRef<int> Mask,
6707                                            SelectionDAG &DAG) {
6708   MVT EltVT = VT.getScalarType();
6709   int NumEltBits = EltVT.getSizeInBits();
6710   MVT IntEltVT = MVT::getIntegerVT(NumEltBits);
6711   SDValue Zero = DAG.getConstant(0, DL, IntEltVT);
6712   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6713                                     IntEltVT);
6714   if (EltVT.isFloatingPoint()) {
6715     Zero = DAG.getNode(ISD::BITCAST, DL, EltVT, Zero);
6716     AllOnes = DAG.getNode(ISD::BITCAST, DL, EltVT, AllOnes);
6717   }
6718   SmallVector<SDValue, 16> VMaskOps(Mask.size(), Zero);
6719   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6720   SDValue V;
6721   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6722     if (Zeroable[i])
6723       continue;
6724     if (Mask[i] % Size != i)
6725       return SDValue(); // Not a blend.
6726     if (!V)
6727       V = Mask[i] < Size ? V1 : V2;
6728     else if (V != (Mask[i] < Size ? V1 : V2))
6729       return SDValue(); // Can only let one input through the mask.
6730
6731     VMaskOps[i] = AllOnes;
6732   }
6733   if (!V)
6734     return SDValue(); // No non-zeroable elements!
6735
6736   SDValue VMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, VMaskOps);
6737   V = DAG.getNode(VT.isFloatingPoint()
6738                   ? (unsigned) X86ISD::FAND : (unsigned) ISD::AND,
6739                   DL, VT, V, VMask);
6740   return V;
6741 }
6742
6743 /// \brief Try to lower a vector shuffle as a bit shift (shifts in zeros).
6744 ///
6745 /// Attempts to match a shuffle mask against the PSLL(W/D/Q/DQ) and
6746 /// PSRL(W/D/Q/DQ) SSE2 and AVX2 logical bit-shift instructions. The function
6747 /// matches elements from one of the input vectors shuffled to the left or
6748 /// right with zeroable elements 'shifted in'. It handles both the strictly
6749 /// bit-wise element shifts and the byte shift across an entire 128-bit double
6750 /// quad word lane.
6751 ///
6752 /// PSHL : (little-endian) left bit shift.
6753 /// [ zz, 0, zz,  2 ]
6754 /// [ -1, 4, zz, -1 ]
6755 /// PSRL : (little-endian) right bit shift.
6756 /// [  1, zz,  3, zz]
6757 /// [ -1, -1,  7, zz]
6758 /// PSLLDQ : (little-endian) left byte shift
6759 /// [ zz,  0,  1,  2,  3,  4,  5,  6]
6760 /// [ zz, zz, -1, -1,  2,  3,  4, -1]
6761 /// [ zz, zz, zz, zz, zz, zz, -1,  1]
6762 /// PSRLDQ : (little-endian) right byte shift
6763 /// [  5, 6,  7, zz, zz, zz, zz, zz]
6764 /// [ -1, 5,  6,  7, zz, zz, zz, zz]
6765 /// [  1, 2, -1, -1, -1, -1, zz, zz]
6766 static SDValue lowerVectorShuffleAsShift(SDLoc DL, MVT VT, SDValue V1,
6767                                          SDValue V2, ArrayRef<int> Mask,
6768                                          SelectionDAG &DAG) {
6769   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6770
6771   int Size = Mask.size();
6772   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
6773
6774   auto CheckZeros = [&](int Shift, int Scale, bool Left) {
6775     for (int i = 0; i < Size; i += Scale)
6776       for (int j = 0; j < Shift; ++j)
6777         if (!Zeroable[i + j + (Left ? 0 : (Scale - Shift))])
6778           return false;
6779
6780     return true;
6781   };
6782
6783   auto MatchShift = [&](int Shift, int Scale, bool Left, SDValue V) {
6784     for (int i = 0; i != Size; i += Scale) {
6785       unsigned Pos = Left ? i + Shift : i;
6786       unsigned Low = Left ? i : i + Shift;
6787       unsigned Len = Scale - Shift;
6788       if (!isSequentialOrUndefInRange(Mask, Pos, Len,
6789                                       Low + (V == V1 ? 0 : Size)))
6790         return SDValue();
6791     }
6792
6793     int ShiftEltBits = VT.getScalarSizeInBits() * Scale;
6794     bool ByteShift = ShiftEltBits > 64;
6795     unsigned OpCode = Left ? (ByteShift ? X86ISD::VSHLDQ : X86ISD::VSHLI)
6796                            : (ByteShift ? X86ISD::VSRLDQ : X86ISD::VSRLI);
6797     int ShiftAmt = Shift * VT.getScalarSizeInBits() / (ByteShift ? 8 : 1);
6798
6799     // Normalize the scale for byte shifts to still produce an i64 element
6800     // type.
6801     Scale = ByteShift ? Scale / 2 : Scale;
6802
6803     // We need to round trip through the appropriate type for the shift.
6804     MVT ShiftSVT = MVT::getIntegerVT(VT.getScalarSizeInBits() * Scale);
6805     MVT ShiftVT = MVT::getVectorVT(ShiftSVT, Size / Scale);
6806     assert(DAG.getTargetLoweringInfo().isTypeLegal(ShiftVT) &&
6807            "Illegal integer vector type");
6808     V = DAG.getNode(ISD::BITCAST, DL, ShiftVT, V);
6809
6810     V = DAG.getNode(OpCode, DL, ShiftVT, V,
6811                     DAG.getConstant(ShiftAmt, DL, MVT::i8));
6812     return DAG.getNode(ISD::BITCAST, DL, VT, V);
6813   };
6814
6815   // SSE/AVX supports logical shifts up to 64-bit integers - so we can just
6816   // keep doubling the size of the integer elements up to that. We can
6817   // then shift the elements of the integer vector by whole multiples of
6818   // their width within the elements of the larger integer vector. Test each
6819   // multiple to see if we can find a match with the moved element indices
6820   // and that the shifted in elements are all zeroable.
6821   for (int Scale = 2; Scale * VT.getScalarSizeInBits() <= 128; Scale *= 2)
6822     for (int Shift = 1; Shift != Scale; ++Shift)
6823       for (bool Left : {true, false})
6824         if (CheckZeros(Shift, Scale, Left))
6825           for (SDValue V : {V1, V2})
6826             if (SDValue Match = MatchShift(Shift, Scale, Left, V))
6827               return Match;
6828
6829   // no match
6830   return SDValue();
6831 }
6832
6833 /// \brief Lower a vector shuffle as a zero or any extension.
6834 ///
6835 /// Given a specific number of elements, element bit width, and extension
6836 /// stride, produce either a zero or any extension based on the available
6837 /// features of the subtarget.
6838 static SDValue lowerVectorShuffleAsSpecificZeroOrAnyExtend(
6839     SDLoc DL, MVT VT, int Scale, bool AnyExt, SDValue InputV,
6840     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6841   assert(Scale > 1 && "Need a scale to extend.");
6842   int NumElements = VT.getVectorNumElements();
6843   int EltBits = VT.getScalarSizeInBits();
6844   assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
6845          "Only 8, 16, and 32 bit elements can be extended.");
6846   assert(Scale * EltBits <= 64 && "Cannot zero extend past 64 bits.");
6847
6848   // Found a valid zext mask! Try various lowering strategies based on the
6849   // input type and available ISA extensions.
6850   if (Subtarget->hasSSE41()) {
6851     MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits * Scale),
6852                                  NumElements / Scale);
6853     return DAG.getNode(ISD::BITCAST, DL, VT,
6854                        DAG.getNode(X86ISD::VZEXT, DL, ExtVT, InputV));
6855   }
6856
6857   // For any extends we can cheat for larger element sizes and use shuffle
6858   // instructions that can fold with a load and/or copy.
6859   if (AnyExt && EltBits == 32) {
6860     int PSHUFDMask[4] = {0, -1, 1, -1};
6861     return DAG.getNode(
6862         ISD::BITCAST, DL, VT,
6863         DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
6864                     DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, InputV),
6865                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
6866   }
6867   if (AnyExt && EltBits == 16 && Scale > 2) {
6868     int PSHUFDMask[4] = {0, -1, 0, -1};
6869     InputV = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
6870                          DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, InputV),
6871                          getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG));
6872     int PSHUFHWMask[4] = {1, -1, -1, -1};
6873     return DAG.getNode(
6874         ISD::BITCAST, DL, VT,
6875         DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16,
6876                     DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, InputV),
6877                     getV4X86ShuffleImm8ForMask(PSHUFHWMask, DL, DAG)));
6878   }
6879
6880   // If this would require more than 2 unpack instructions to expand, use
6881   // pshufb when available. We can only use more than 2 unpack instructions
6882   // when zero extending i8 elements which also makes it easier to use pshufb.
6883   if (Scale > 4 && EltBits == 8 && Subtarget->hasSSSE3()) {
6884     assert(NumElements == 16 && "Unexpected byte vector width!");
6885     SDValue PSHUFBMask[16];
6886     for (int i = 0; i < 16; ++i)
6887       PSHUFBMask[i] =
6888           DAG.getConstant((i % Scale == 0) ? i / Scale : 0x80, DL, MVT::i8);
6889     InputV = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, InputV);
6890     return DAG.getNode(ISD::BITCAST, DL, VT,
6891                        DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, InputV,
6892                                    DAG.getNode(ISD::BUILD_VECTOR, DL,
6893                                                MVT::v16i8, PSHUFBMask)));
6894   }
6895
6896   // Otherwise emit a sequence of unpacks.
6897   do {
6898     MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
6899     SDValue Ext = AnyExt ? DAG.getUNDEF(InputVT)
6900                          : getZeroVector(InputVT, Subtarget, DAG, DL);
6901     InputV = DAG.getNode(ISD::BITCAST, DL, InputVT, InputV);
6902     InputV = DAG.getNode(X86ISD::UNPCKL, DL, InputVT, InputV, Ext);
6903     Scale /= 2;
6904     EltBits *= 2;
6905     NumElements /= 2;
6906   } while (Scale > 1);
6907   return DAG.getNode(ISD::BITCAST, DL, VT, InputV);
6908 }
6909
6910 /// \brief Try to lower a vector shuffle as a zero extension on any microarch.
6911 ///
6912 /// This routine will try to do everything in its power to cleverly lower
6913 /// a shuffle which happens to match the pattern of a zero extend. It doesn't
6914 /// check for the profitability of this lowering,  it tries to aggressively
6915 /// match this pattern. It will use all of the micro-architectural details it
6916 /// can to emit an efficient lowering. It handles both blends with all-zero
6917 /// inputs to explicitly zero-extend and undef-lanes (sometimes undef due to
6918 /// masking out later).
6919 ///
6920 /// The reason we have dedicated lowering for zext-style shuffles is that they
6921 /// are both incredibly common and often quite performance sensitive.
6922 static SDValue lowerVectorShuffleAsZeroOrAnyExtend(
6923     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
6924     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6925   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6926
6927   int Bits = VT.getSizeInBits();
6928   int NumElements = VT.getVectorNumElements();
6929   assert(VT.getScalarSizeInBits() <= 32 &&
6930          "Exceeds 32-bit integer zero extension limit");
6931   assert((int)Mask.size() == NumElements && "Unexpected shuffle mask size");
6932
6933   // Define a helper function to check a particular ext-scale and lower to it if
6934   // valid.
6935   auto Lower = [&](int Scale) -> SDValue {
6936     SDValue InputV;
6937     bool AnyExt = true;
6938     for (int i = 0; i < NumElements; ++i) {
6939       if (Mask[i] == -1)
6940         continue; // Valid anywhere but doesn't tell us anything.
6941       if (i % Scale != 0) {
6942         // Each of the extended elements need to be zeroable.
6943         if (!Zeroable[i])
6944           return SDValue();
6945
6946         // We no longer are in the anyext case.
6947         AnyExt = false;
6948         continue;
6949       }
6950
6951       // Each of the base elements needs to be consecutive indices into the
6952       // same input vector.
6953       SDValue V = Mask[i] < NumElements ? V1 : V2;
6954       if (!InputV)
6955         InputV = V;
6956       else if (InputV != V)
6957         return SDValue(); // Flip-flopping inputs.
6958
6959       if (Mask[i] % NumElements != i / Scale)
6960         return SDValue(); // Non-consecutive strided elements.
6961     }
6962
6963     // If we fail to find an input, we have a zero-shuffle which should always
6964     // have already been handled.
6965     // FIXME: Maybe handle this here in case during blending we end up with one?
6966     if (!InputV)
6967       return SDValue();
6968
6969     return lowerVectorShuffleAsSpecificZeroOrAnyExtend(
6970         DL, VT, Scale, AnyExt, InputV, Subtarget, DAG);
6971   };
6972
6973   // The widest scale possible for extending is to a 64-bit integer.
6974   assert(Bits % 64 == 0 &&
6975          "The number of bits in a vector must be divisible by 64 on x86!");
6976   int NumExtElements = Bits / 64;
6977
6978   // Each iteration, try extending the elements half as much, but into twice as
6979   // many elements.
6980   for (; NumExtElements < NumElements; NumExtElements *= 2) {
6981     assert(NumElements % NumExtElements == 0 &&
6982            "The input vector size must be divisible by the extended size.");
6983     if (SDValue V = Lower(NumElements / NumExtElements))
6984       return V;
6985   }
6986
6987   // General extends failed, but 128-bit vectors may be able to use MOVQ.
6988   if (Bits != 128)
6989     return SDValue();
6990
6991   // Returns one of the source operands if the shuffle can be reduced to a
6992   // MOVQ, copying the lower 64-bits and zero-extending to the upper 64-bits.
6993   auto CanZExtLowHalf = [&]() {
6994     for (int i = NumElements / 2; i != NumElements; ++i)
6995       if (!Zeroable[i])
6996         return SDValue();
6997     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, 0))
6998       return V1;
6999     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, NumElements))
7000       return V2;
7001     return SDValue();
7002   };
7003
7004   if (SDValue V = CanZExtLowHalf()) {
7005     V = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, V);
7006     V = DAG.getNode(X86ISD::VZEXT_MOVL, DL, MVT::v2i64, V);
7007     return DAG.getNode(ISD::BITCAST, DL, VT, V);
7008   }
7009
7010   // No viable ext lowering found.
7011   return SDValue();
7012 }
7013
7014 /// \brief Try to get a scalar value for a specific element of a vector.
7015 ///
7016 /// Looks through BUILD_VECTOR and SCALAR_TO_VECTOR nodes to find a scalar.
7017 static SDValue getScalarValueForVectorElement(SDValue V, int Idx,
7018                                               SelectionDAG &DAG) {
7019   MVT VT = V.getSimpleValueType();
7020   MVT EltVT = VT.getVectorElementType();
7021   while (V.getOpcode() == ISD::BITCAST)
7022     V = V.getOperand(0);
7023   // If the bitcasts shift the element size, we can't extract an equivalent
7024   // element from it.
7025   MVT NewVT = V.getSimpleValueType();
7026   if (!NewVT.isVector() || NewVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
7027     return SDValue();
7028
7029   if (V.getOpcode() == ISD::BUILD_VECTOR ||
7030       (Idx == 0 && V.getOpcode() == ISD::SCALAR_TO_VECTOR)) {
7031     // Ensure the scalar operand is the same size as the destination.
7032     // FIXME: Add support for scalar truncation where possible.
7033     SDValue S = V.getOperand(Idx);
7034     if (EltVT.getSizeInBits() == S.getSimpleValueType().getSizeInBits())
7035       return DAG.getNode(ISD::BITCAST, SDLoc(V), EltVT, S);
7036   }
7037
7038   return SDValue();
7039 }
7040
7041 /// \brief Helper to test for a load that can be folded with x86 shuffles.
7042 ///
7043 /// This is particularly important because the set of instructions varies
7044 /// significantly based on whether the operand is a load or not.
7045 static bool isShuffleFoldableLoad(SDValue V) {
7046   while (V.getOpcode() == ISD::BITCAST)
7047     V = V.getOperand(0);
7048
7049   return ISD::isNON_EXTLoad(V.getNode());
7050 }
7051
7052 /// \brief Try to lower insertion of a single element into a zero vector.
7053 ///
7054 /// This is a common pattern that we have especially efficient patterns to lower
7055 /// across all subtarget feature sets.
7056 static SDValue lowerVectorShuffleAsElementInsertion(
7057     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7058     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7059   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7060   MVT ExtVT = VT;
7061   MVT EltVT = VT.getVectorElementType();
7062
7063   int V2Index = std::find_if(Mask.begin(), Mask.end(),
7064                              [&Mask](int M) { return M >= (int)Mask.size(); }) -
7065                 Mask.begin();
7066   bool IsV1Zeroable = true;
7067   for (int i = 0, Size = Mask.size(); i < Size; ++i)
7068     if (i != V2Index && !Zeroable[i]) {
7069       IsV1Zeroable = false;
7070       break;
7071     }
7072
7073   // Check for a single input from a SCALAR_TO_VECTOR node.
7074   // FIXME: All of this should be canonicalized into INSERT_VECTOR_ELT and
7075   // all the smarts here sunk into that routine. However, the current
7076   // lowering of BUILD_VECTOR makes that nearly impossible until the old
7077   // vector shuffle lowering is dead.
7078   if (SDValue V2S = getScalarValueForVectorElement(
7079           V2, Mask[V2Index] - Mask.size(), DAG)) {
7080     // We need to zext the scalar if it is smaller than an i32.
7081     V2S = DAG.getNode(ISD::BITCAST, DL, EltVT, V2S);
7082     if (EltVT == MVT::i8 || EltVT == MVT::i16) {
7083       // Using zext to expand a narrow element won't work for non-zero
7084       // insertions.
7085       if (!IsV1Zeroable)
7086         return SDValue();
7087
7088       // Zero-extend directly to i32.
7089       ExtVT = MVT::v4i32;
7090       V2S = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, V2S);
7091     }
7092     V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
7093   } else if (Mask[V2Index] != (int)Mask.size() || EltVT == MVT::i8 ||
7094              EltVT == MVT::i16) {
7095     // Either not inserting from the low element of the input or the input
7096     // element size is too small to use VZEXT_MOVL to clear the high bits.
7097     return SDValue();
7098   }
7099
7100   if (!IsV1Zeroable) {
7101     // If V1 can't be treated as a zero vector we have fewer options to lower
7102     // this. We can't support integer vectors or non-zero targets cheaply, and
7103     // the V1 elements can't be permuted in any way.
7104     assert(VT == ExtVT && "Cannot change extended type when non-zeroable!");
7105     if (!VT.isFloatingPoint() || V2Index != 0)
7106       return SDValue();
7107     SmallVector<int, 8> V1Mask(Mask.begin(), Mask.end());
7108     V1Mask[V2Index] = -1;
7109     if (!isNoopShuffleMask(V1Mask))
7110       return SDValue();
7111     // This is essentially a special case blend operation, but if we have
7112     // general purpose blend operations, they are always faster. Bail and let
7113     // the rest of the lowering handle these as blends.
7114     if (Subtarget->hasSSE41())
7115       return SDValue();
7116
7117     // Otherwise, use MOVSD or MOVSS.
7118     assert((EltVT == MVT::f32 || EltVT == MVT::f64) &&
7119            "Only two types of floating point element types to handle!");
7120     return DAG.getNode(EltVT == MVT::f32 ? X86ISD::MOVSS : X86ISD::MOVSD, DL,
7121                        ExtVT, V1, V2);
7122   }
7123
7124   // This lowering only works for the low element with floating point vectors.
7125   if (VT.isFloatingPoint() && V2Index != 0)
7126     return SDValue();
7127
7128   V2 = DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2);
7129   if (ExtVT != VT)
7130     V2 = DAG.getNode(ISD::BITCAST, DL, VT, V2);
7131
7132   if (V2Index != 0) {
7133     // If we have 4 or fewer lanes we can cheaply shuffle the element into
7134     // the desired position. Otherwise it is more efficient to do a vector
7135     // shift left. We know that we can do a vector shift left because all
7136     // the inputs are zero.
7137     if (VT.isFloatingPoint() || VT.getVectorNumElements() <= 4) {
7138       SmallVector<int, 4> V2Shuffle(Mask.size(), 1);
7139       V2Shuffle[V2Index] = 0;
7140       V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Shuffle);
7141     } else {
7142       V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, V2);
7143       V2 = DAG.getNode(
7144           X86ISD::VSHLDQ, DL, MVT::v2i64, V2,
7145           DAG.getConstant(
7146               V2Index * EltVT.getSizeInBits()/8, DL,
7147               DAG.getTargetLoweringInfo().getScalarShiftAmountTy(MVT::v2i64)));
7148       V2 = DAG.getNode(ISD::BITCAST, DL, VT, V2);
7149     }
7150   }
7151   return V2;
7152 }
7153
7154 /// \brief Try to lower broadcast of a single element.
7155 ///
7156 /// For convenience, this code also bundles all of the subtarget feature set
7157 /// filtering. While a little annoying to re-dispatch on type here, there isn't
7158 /// a convenient way to factor it out.
7159 static SDValue lowerVectorShuffleAsBroadcast(SDLoc DL, MVT VT, SDValue V,
7160                                              ArrayRef<int> Mask,
7161                                              const X86Subtarget *Subtarget,
7162                                              SelectionDAG &DAG) {
7163   if (!Subtarget->hasAVX())
7164     return SDValue();
7165   if (VT.isInteger() && !Subtarget->hasAVX2())
7166     return SDValue();
7167
7168   // Check that the mask is a broadcast.
7169   int BroadcastIdx = -1;
7170   for (int M : Mask)
7171     if (M >= 0 && BroadcastIdx == -1)
7172       BroadcastIdx = M;
7173     else if (M >= 0 && M != BroadcastIdx)
7174       return SDValue();
7175
7176   assert(BroadcastIdx < (int)Mask.size() && "We only expect to be called with "
7177                                             "a sorted mask where the broadcast "
7178                                             "comes from V1.");
7179
7180   // Go up the chain of (vector) values to find a scalar load that we can
7181   // combine with the broadcast.
7182   for (;;) {
7183     switch (V.getOpcode()) {
7184     case ISD::CONCAT_VECTORS: {
7185       int OperandSize = Mask.size() / V.getNumOperands();
7186       V = V.getOperand(BroadcastIdx / OperandSize);
7187       BroadcastIdx %= OperandSize;
7188       continue;
7189     }
7190
7191     case ISD::INSERT_SUBVECTOR: {
7192       SDValue VOuter = V.getOperand(0), VInner = V.getOperand(1);
7193       auto ConstantIdx = dyn_cast<ConstantSDNode>(V.getOperand(2));
7194       if (!ConstantIdx)
7195         break;
7196
7197       int BeginIdx = (int)ConstantIdx->getZExtValue();
7198       int EndIdx =
7199           BeginIdx + (int)VInner.getValueType().getVectorNumElements();
7200       if (BroadcastIdx >= BeginIdx && BroadcastIdx < EndIdx) {
7201         BroadcastIdx -= BeginIdx;
7202         V = VInner;
7203       } else {
7204         V = VOuter;
7205       }
7206       continue;
7207     }
7208     }
7209     break;
7210   }
7211
7212   // Check if this is a broadcast of a scalar. We special case lowering
7213   // for scalars so that we can more effectively fold with loads.
7214   if (V.getOpcode() == ISD::BUILD_VECTOR ||
7215       (V.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)) {
7216     V = V.getOperand(BroadcastIdx);
7217
7218     // If the scalar isn't a load, we can't broadcast from it in AVX1.
7219     // Only AVX2 has register broadcasts.
7220     if (!Subtarget->hasAVX2() && !isShuffleFoldableLoad(V))
7221       return SDValue();
7222   } else if (BroadcastIdx != 0 || !Subtarget->hasAVX2()) {
7223     // We can't broadcast from a vector register without AVX2, and we can only
7224     // broadcast from the zero-element of a vector register.
7225     return SDValue();
7226   }
7227
7228   return DAG.getNode(X86ISD::VBROADCAST, DL, VT, V);
7229 }
7230
7231 // Check for whether we can use INSERTPS to perform the shuffle. We only use
7232 // INSERTPS when the V1 elements are already in the correct locations
7233 // because otherwise we can just always use two SHUFPS instructions which
7234 // are much smaller to encode than a SHUFPS and an INSERTPS. We can also
7235 // perform INSERTPS if a single V1 element is out of place and all V2
7236 // elements are zeroable.
7237 static SDValue lowerVectorShuffleAsInsertPS(SDValue Op, SDValue V1, SDValue V2,
7238                                             ArrayRef<int> Mask,
7239                                             SelectionDAG &DAG) {
7240   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7241   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7242   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7243   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7244
7245   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7246
7247   unsigned ZMask = 0;
7248   int V1DstIndex = -1;
7249   int V2DstIndex = -1;
7250   bool V1UsedInPlace = false;
7251
7252   for (int i = 0; i < 4; ++i) {
7253     // Synthesize a zero mask from the zeroable elements (includes undefs).
7254     if (Zeroable[i]) {
7255       ZMask |= 1 << i;
7256       continue;
7257     }
7258
7259     // Flag if we use any V1 inputs in place.
7260     if (i == Mask[i]) {
7261       V1UsedInPlace = true;
7262       continue;
7263     }
7264
7265     // We can only insert a single non-zeroable element.
7266     if (V1DstIndex != -1 || V2DstIndex != -1)
7267       return SDValue();
7268
7269     if (Mask[i] < 4) {
7270       // V1 input out of place for insertion.
7271       V1DstIndex = i;
7272     } else {
7273       // V2 input for insertion.
7274       V2DstIndex = i;
7275     }
7276   }
7277
7278   // Don't bother if we have no (non-zeroable) element for insertion.
7279   if (V1DstIndex == -1 && V2DstIndex == -1)
7280     return SDValue();
7281
7282   // Determine element insertion src/dst indices. The src index is from the
7283   // start of the inserted vector, not the start of the concatenated vector.
7284   unsigned V2SrcIndex = 0;
7285   if (V1DstIndex != -1) {
7286     // If we have a V1 input out of place, we use V1 as the V2 element insertion
7287     // and don't use the original V2 at all.
7288     V2SrcIndex = Mask[V1DstIndex];
7289     V2DstIndex = V1DstIndex;
7290     V2 = V1;
7291   } else {
7292     V2SrcIndex = Mask[V2DstIndex] - 4;
7293   }
7294
7295   // If no V1 inputs are used in place, then the result is created only from
7296   // the zero mask and the V2 insertion - so remove V1 dependency.
7297   if (!V1UsedInPlace)
7298     V1 = DAG.getUNDEF(MVT::v4f32);
7299
7300   unsigned InsertPSMask = V2SrcIndex << 6 | V2DstIndex << 4 | ZMask;
7301   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
7302
7303   // Insert the V2 element into the desired position.
7304   SDLoc DL(Op);
7305   return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
7306                      DAG.getConstant(InsertPSMask, DL, MVT::i8));
7307 }
7308
7309 /// \brief Try to lower a shuffle as a permute of the inputs followed by an
7310 /// UNPCK instruction.
7311 ///
7312 /// This specifically targets cases where we end up with alternating between
7313 /// the two inputs, and so can permute them into something that feeds a single
7314 /// UNPCK instruction. Note that this routine only targets integer vectors
7315 /// because for floating point vectors we have a generalized SHUFPS lowering
7316 /// strategy that handles everything that doesn't *exactly* match an unpack,
7317 /// making this clever lowering unnecessary.
7318 static SDValue lowerVectorShuffleAsUnpack(SDLoc DL, MVT VT, SDValue V1,
7319                                           SDValue V2, ArrayRef<int> Mask,
7320                                           SelectionDAG &DAG) {
7321   assert(!VT.isFloatingPoint() &&
7322          "This routine only supports integer vectors.");
7323   assert(!isSingleInputShuffleMask(Mask) &&
7324          "This routine should only be used when blending two inputs.");
7325   assert(Mask.size() >= 2 && "Single element masks are invalid.");
7326
7327   int Size = Mask.size();
7328
7329   int NumLoInputs = std::count_if(Mask.begin(), Mask.end(), [Size](int M) {
7330     return M >= 0 && M % Size < Size / 2;
7331   });
7332   int NumHiInputs = std::count_if(
7333       Mask.begin(), Mask.end(), [Size](int M) { return M % Size >= Size / 2; });
7334
7335   bool UnpackLo = NumLoInputs >= NumHiInputs;
7336
7337   auto TryUnpack = [&](MVT UnpackVT, int Scale) {
7338     SmallVector<int, 32> V1Mask(Mask.size(), -1);
7339     SmallVector<int, 32> V2Mask(Mask.size(), -1);
7340
7341     for (int i = 0; i < Size; ++i) {
7342       if (Mask[i] < 0)
7343         continue;
7344
7345       // Each element of the unpack contains Scale elements from this mask.
7346       int UnpackIdx = i / Scale;
7347
7348       // We only handle the case where V1 feeds the first slots of the unpack.
7349       // We rely on canonicalization to ensure this is the case.
7350       if ((UnpackIdx % 2 == 0) != (Mask[i] < Size))
7351         return SDValue();
7352
7353       // Setup the mask for this input. The indexing is tricky as we have to
7354       // handle the unpack stride.
7355       SmallVectorImpl<int> &VMask = (UnpackIdx % 2 == 0) ? V1Mask : V2Mask;
7356       VMask[(UnpackIdx / 2) * Scale + i % Scale + (UnpackLo ? 0 : Size / 2)] =
7357           Mask[i] % Size;
7358     }
7359
7360     // If we will have to shuffle both inputs to use the unpack, check whether
7361     // we can just unpack first and shuffle the result. If so, skip this unpack.
7362     if ((NumLoInputs == 0 || NumHiInputs == 0) && !isNoopShuffleMask(V1Mask) &&
7363         !isNoopShuffleMask(V2Mask))
7364       return SDValue();
7365
7366     // Shuffle the inputs into place.
7367     V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
7368     V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
7369
7370     // Cast the inputs to the type we will use to unpack them.
7371     V1 = DAG.getNode(ISD::BITCAST, DL, UnpackVT, V1);
7372     V2 = DAG.getNode(ISD::BITCAST, DL, UnpackVT, V2);
7373
7374     // Unpack the inputs and cast the result back to the desired type.
7375     return DAG.getNode(ISD::BITCAST, DL, VT,
7376                        DAG.getNode(UnpackLo ? X86ISD::UNPCKL : X86ISD::UNPCKH,
7377                                    DL, UnpackVT, V1, V2));
7378   };
7379
7380   // We try each unpack from the largest to the smallest to try and find one
7381   // that fits this mask.
7382   int OrigNumElements = VT.getVectorNumElements();
7383   int OrigScalarSize = VT.getScalarSizeInBits();
7384   for (int ScalarSize = 64; ScalarSize >= OrigScalarSize; ScalarSize /= 2) {
7385     int Scale = ScalarSize / OrigScalarSize;
7386     int NumElements = OrigNumElements / Scale;
7387     MVT UnpackVT = MVT::getVectorVT(MVT::getIntegerVT(ScalarSize), NumElements);
7388     if (SDValue Unpack = TryUnpack(UnpackVT, Scale))
7389       return Unpack;
7390   }
7391
7392   // If none of the unpack-rooted lowerings worked (or were profitable) try an
7393   // initial unpack.
7394   if (NumLoInputs == 0 || NumHiInputs == 0) {
7395     assert((NumLoInputs > 0 || NumHiInputs > 0) &&
7396            "We have to have *some* inputs!");
7397     int HalfOffset = NumLoInputs == 0 ? Size / 2 : 0;
7398
7399     // FIXME: We could consider the total complexity of the permute of each
7400     // possible unpacking. Or at the least we should consider how many
7401     // half-crossings are created.
7402     // FIXME: We could consider commuting the unpacks.
7403
7404     SmallVector<int, 32> PermMask;
7405     PermMask.assign(Size, -1);
7406     for (int i = 0; i < Size; ++i) {
7407       if (Mask[i] < 0)
7408         continue;
7409
7410       assert(Mask[i] % Size >= HalfOffset && "Found input from wrong half!");
7411
7412       PermMask[i] =
7413           2 * ((Mask[i] % Size) - HalfOffset) + (Mask[i] < Size ? 0 : 1);
7414     }
7415     return DAG.getVectorShuffle(
7416         VT, DL, DAG.getNode(NumLoInputs == 0 ? X86ISD::UNPCKH : X86ISD::UNPCKL,
7417                             DL, VT, V1, V2),
7418         DAG.getUNDEF(VT), PermMask);
7419   }
7420
7421   return SDValue();
7422 }
7423
7424 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
7425 ///
7426 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
7427 /// support for floating point shuffles but not integer shuffles. These
7428 /// instructions will incur a domain crossing penalty on some chips though so
7429 /// it is better to avoid lowering through this for integer vectors where
7430 /// possible.
7431 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7432                                        const X86Subtarget *Subtarget,
7433                                        SelectionDAG &DAG) {
7434   SDLoc DL(Op);
7435   assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
7436   assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7437   assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7438   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7439   ArrayRef<int> Mask = SVOp->getMask();
7440   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7441
7442   if (isSingleInputShuffleMask(Mask)) {
7443     // Use low duplicate instructions for masks that match their pattern.
7444     if (Subtarget->hasSSE3())
7445       if (isShuffleEquivalent(V1, V2, Mask, {0, 0}))
7446         return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v2f64, V1);
7447
7448     // Straight shuffle of a single input vector. Simulate this by using the
7449     // single input as both of the "inputs" to this instruction..
7450     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
7451
7452     if (Subtarget->hasAVX()) {
7453       // If we have AVX, we can use VPERMILPS which will allow folding a load
7454       // into the shuffle.
7455       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v2f64, V1,
7456                          DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7457     }
7458
7459     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V1,
7460                        DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7461   }
7462   assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
7463   assert(Mask[1] >= 2 && "Non-canonicalized blend!");
7464
7465   // If we have a single input, insert that into V1 if we can do so cheaply.
7466   if ((Mask[0] >= 2) + (Mask[1] >= 2) == 1) {
7467     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7468             DL, MVT::v2f64, V1, V2, Mask, Subtarget, DAG))
7469       return Insertion;
7470     // Try inverting the insertion since for v2 masks it is easy to do and we
7471     // can't reliably sort the mask one way or the other.
7472     int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
7473                           Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
7474     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7475             DL, MVT::v2f64, V2, V1, InverseMask, Subtarget, DAG))
7476       return Insertion;
7477   }
7478
7479   // Try to use one of the special instruction patterns to handle two common
7480   // blend patterns if a zero-blend above didn't work.
7481   if (isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
7482       isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7483     if (SDValue V1S = getScalarValueForVectorElement(V1, Mask[0], DAG))
7484       // We can either use a special instruction to load over the low double or
7485       // to move just the low double.
7486       return DAG.getNode(
7487           isShuffleFoldableLoad(V1S) ? X86ISD::MOVLPD : X86ISD::MOVSD,
7488           DL, MVT::v2f64, V2,
7489           DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V1S));
7490
7491   if (Subtarget->hasSSE41())
7492     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2f64, V1, V2, Mask,
7493                                                   Subtarget, DAG))
7494       return Blend;
7495
7496   // Use dedicated unpack instructions for masks that match their pattern.
7497   if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7498     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2f64, V1, V2);
7499   if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7500     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2f64, V1, V2);
7501
7502   unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
7503   return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V2,
7504                      DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7505 }
7506
7507 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
7508 ///
7509 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
7510 /// the integer unit to minimize domain crossing penalties. However, for blends
7511 /// it falls back to the floating point shuffle operation with appropriate bit
7512 /// casting.
7513 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7514                                        const X86Subtarget *Subtarget,
7515                                        SelectionDAG &DAG) {
7516   SDLoc DL(Op);
7517   assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
7518   assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7519   assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7520   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7521   ArrayRef<int> Mask = SVOp->getMask();
7522   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7523
7524   if (isSingleInputShuffleMask(Mask)) {
7525     // Check for being able to broadcast a single element.
7526     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v2i64, V1,
7527                                                           Mask, Subtarget, DAG))
7528       return Broadcast;
7529
7530     // Straight shuffle of a single input vector. For everything from SSE2
7531     // onward this has a single fast instruction with no scary immediates.
7532     // We have to map the mask as it is actually a v4i32 shuffle instruction.
7533     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V1);
7534     int WidenedMask[4] = {
7535         std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
7536         std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
7537     return DAG.getNode(
7538         ISD::BITCAST, DL, MVT::v2i64,
7539         DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
7540                     getV4X86ShuffleImm8ForMask(WidenedMask, DL, DAG)));
7541   }
7542   assert(Mask[0] != -1 && "No undef lanes in multi-input v2 shuffles!");
7543   assert(Mask[1] != -1 && "No undef lanes in multi-input v2 shuffles!");
7544   assert(Mask[0] < 2 && "We sort V1 to be the first input.");
7545   assert(Mask[1] >= 2 && "We sort V2 to be the second input.");
7546
7547   // If we have a blend of two PACKUS operations an the blend aligns with the
7548   // low and half halves, we can just merge the PACKUS operations. This is
7549   // particularly important as it lets us merge shuffles that this routine itself
7550   // creates.
7551   auto GetPackNode = [](SDValue V) {
7552     while (V.getOpcode() == ISD::BITCAST)
7553       V = V.getOperand(0);
7554
7555     return V.getOpcode() == X86ISD::PACKUS ? V : SDValue();
7556   };
7557   if (SDValue V1Pack = GetPackNode(V1))
7558     if (SDValue V2Pack = GetPackNode(V2))
7559       return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7560                          DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8,
7561                                      Mask[0] == 0 ? V1Pack.getOperand(0)
7562                                                   : V1Pack.getOperand(1),
7563                                      Mask[1] == 2 ? V2Pack.getOperand(0)
7564                                                   : V2Pack.getOperand(1)));
7565
7566   // Try to use shift instructions.
7567   if (SDValue Shift =
7568           lowerVectorShuffleAsShift(DL, MVT::v2i64, V1, V2, Mask, DAG))
7569     return Shift;
7570
7571   // When loading a scalar and then shuffling it into a vector we can often do
7572   // the insertion cheaply.
7573   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7574           DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
7575     return Insertion;
7576   // Try inverting the insertion since for v2 masks it is easy to do and we
7577   // can't reliably sort the mask one way or the other.
7578   int InverseMask[2] = {Mask[0] ^ 2, Mask[1] ^ 2};
7579   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7580           DL, MVT::v2i64, V2, V1, InverseMask, Subtarget, DAG))
7581     return Insertion;
7582
7583   // We have different paths for blend lowering, but they all must use the
7584   // *exact* same predicate.
7585   bool IsBlendSupported = Subtarget->hasSSE41();
7586   if (IsBlendSupported)
7587     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2i64, V1, V2, Mask,
7588                                                   Subtarget, DAG))
7589       return Blend;
7590
7591   // Use dedicated unpack instructions for masks that match their pattern.
7592   if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7593     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, V1, V2);
7594   if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7595     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2i64, V1, V2);
7596
7597   // Try to use byte rotation instructions.
7598   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
7599   if (Subtarget->hasSSSE3())
7600     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
7601             DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
7602       return Rotate;
7603
7604   // If we have direct support for blends, we should lower by decomposing into
7605   // a permute. That will be faster than the domain cross.
7606   if (IsBlendSupported)
7607     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v2i64, V1, V2,
7608                                                       Mask, DAG);
7609
7610   // We implement this with SHUFPD which is pretty lame because it will likely
7611   // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
7612   // However, all the alternatives are still more cycles and newer chips don't
7613   // have this problem. It would be really nice if x86 had better shuffles here.
7614   V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V1);
7615   V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V2);
7616   return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7617                      DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
7618 }
7619
7620 /// \brief Test whether this can be lowered with a single SHUFPS instruction.
7621 ///
7622 /// This is used to disable more specialized lowerings when the shufps lowering
7623 /// will happen to be efficient.
7624 static bool isSingleSHUFPSMask(ArrayRef<int> Mask) {
7625   // This routine only handles 128-bit shufps.
7626   assert(Mask.size() == 4 && "Unsupported mask size!");
7627
7628   // To lower with a single SHUFPS we need to have the low half and high half
7629   // each requiring a single input.
7630   if (Mask[0] != -1 && Mask[1] != -1 && (Mask[0] < 4) != (Mask[1] < 4))
7631     return false;
7632   if (Mask[2] != -1 && Mask[3] != -1 && (Mask[2] < 4) != (Mask[3] < 4))
7633     return false;
7634
7635   return true;
7636 }
7637
7638 /// \brief Lower a vector shuffle using the SHUFPS instruction.
7639 ///
7640 /// This is a helper routine dedicated to lowering vector shuffles using SHUFPS.
7641 /// It makes no assumptions about whether this is the *best* lowering, it simply
7642 /// uses it.
7643 static SDValue lowerVectorShuffleWithSHUFPS(SDLoc DL, MVT VT,
7644                                             ArrayRef<int> Mask, SDValue V1,
7645                                             SDValue V2, SelectionDAG &DAG) {
7646   SDValue LowV = V1, HighV = V2;
7647   int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
7648
7649   int NumV2Elements =
7650       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7651
7652   if (NumV2Elements == 1) {
7653     int V2Index =
7654         std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
7655         Mask.begin();
7656
7657     // Compute the index adjacent to V2Index and in the same half by toggling
7658     // the low bit.
7659     int V2AdjIndex = V2Index ^ 1;
7660
7661     if (Mask[V2AdjIndex] == -1) {
7662       // Handles all the cases where we have a single V2 element and an undef.
7663       // This will only ever happen in the high lanes because we commute the
7664       // vector otherwise.
7665       if (V2Index < 2)
7666         std::swap(LowV, HighV);
7667       NewMask[V2Index] -= 4;
7668     } else {
7669       // Handle the case where the V2 element ends up adjacent to a V1 element.
7670       // To make this work, blend them together as the first step.
7671       int V1Index = V2AdjIndex;
7672       int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
7673       V2 = DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
7674                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
7675
7676       // Now proceed to reconstruct the final blend as we have the necessary
7677       // high or low half formed.
7678       if (V2Index < 2) {
7679         LowV = V2;
7680         HighV = V1;
7681       } else {
7682         HighV = V2;
7683       }
7684       NewMask[V1Index] = 2; // We put the V1 element in V2[2].
7685       NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
7686     }
7687   } else if (NumV2Elements == 2) {
7688     if (Mask[0] < 4 && Mask[1] < 4) {
7689       // Handle the easy case where we have V1 in the low lanes and V2 in the
7690       // high lanes.
7691       NewMask[2] -= 4;
7692       NewMask[3] -= 4;
7693     } else if (Mask[2] < 4 && Mask[3] < 4) {
7694       // We also handle the reversed case because this utility may get called
7695       // when we detect a SHUFPS pattern but can't easily commute the shuffle to
7696       // arrange things in the right direction.
7697       NewMask[0] -= 4;
7698       NewMask[1] -= 4;
7699       HighV = V1;
7700       LowV = V2;
7701     } else {
7702       // We have a mixture of V1 and V2 in both low and high lanes. Rather than
7703       // trying to place elements directly, just blend them and set up the final
7704       // shuffle to place them.
7705
7706       // The first two blend mask elements are for V1, the second two are for
7707       // V2.
7708       int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
7709                           Mask[2] < 4 ? Mask[2] : Mask[3],
7710                           (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
7711                           (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
7712       V1 = DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
7713                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
7714
7715       // Now we do a normal shuffle of V1 by giving V1 as both operands to
7716       // a blend.
7717       LowV = HighV = V1;
7718       NewMask[0] = Mask[0] < 4 ? 0 : 2;
7719       NewMask[1] = Mask[0] < 4 ? 2 : 0;
7720       NewMask[2] = Mask[2] < 4 ? 1 : 3;
7721       NewMask[3] = Mask[2] < 4 ? 3 : 1;
7722     }
7723   }
7724   return DAG.getNode(X86ISD::SHUFP, DL, VT, LowV, HighV,
7725                      getV4X86ShuffleImm8ForMask(NewMask, DL, DAG));
7726 }
7727
7728 /// \brief Lower 4-lane 32-bit floating point shuffles.
7729 ///
7730 /// Uses instructions exclusively from the floating point unit to minimize
7731 /// domain crossing penalties, as these are sufficient to implement all v4f32
7732 /// shuffles.
7733 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7734                                        const X86Subtarget *Subtarget,
7735                                        SelectionDAG &DAG) {
7736   SDLoc DL(Op);
7737   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7738   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7739   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7740   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7741   ArrayRef<int> Mask = SVOp->getMask();
7742   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7743
7744   int NumV2Elements =
7745       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7746
7747   if (NumV2Elements == 0) {
7748     // Check for being able to broadcast a single element.
7749     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f32, V1,
7750                                                           Mask, Subtarget, DAG))
7751       return Broadcast;
7752
7753     // Use even/odd duplicate instructions for masks that match their pattern.
7754     if (Subtarget->hasSSE3()) {
7755       if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
7756         return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v4f32, V1);
7757       if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3}))
7758         return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v4f32, V1);
7759     }
7760
7761     if (Subtarget->hasAVX()) {
7762       // If we have AVX, we can use VPERMILPS which will allow folding a load
7763       // into the shuffle.
7764       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f32, V1,
7765                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
7766     }
7767
7768     // Otherwise, use a straight shuffle of a single input vector. We pass the
7769     // input vector to both operands to simulate this with a SHUFPS.
7770     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
7771                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
7772   }
7773
7774   // There are special ways we can lower some single-element blends. However, we
7775   // have custom ways we can lower more complex single-element blends below that
7776   // we defer to if both this and BLENDPS fail to match, so restrict this to
7777   // when the V2 input is targeting element 0 of the mask -- that is the fast
7778   // case here.
7779   if (NumV2Elements == 1 && Mask[0] >= 4)
7780     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4f32, V1, V2,
7781                                                          Mask, Subtarget, DAG))
7782       return V;
7783
7784   if (Subtarget->hasSSE41()) {
7785     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f32, V1, V2, Mask,
7786                                                   Subtarget, DAG))
7787       return Blend;
7788
7789     // Use INSERTPS if we can complete the shuffle efficiently.
7790     if (SDValue V = lowerVectorShuffleAsInsertPS(Op, V1, V2, Mask, DAG))
7791       return V;
7792
7793     if (!isSingleSHUFPSMask(Mask))
7794       if (SDValue BlendPerm = lowerVectorShuffleAsBlendAndPermute(
7795               DL, MVT::v4f32, V1, V2, Mask, DAG))
7796         return BlendPerm;
7797   }
7798
7799   // Use dedicated unpack instructions for masks that match their pattern.
7800   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
7801     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V1, V2);
7802   if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
7803     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V1, V2);
7804   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
7805     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V2, V1);
7806   if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
7807     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V2, V1);
7808
7809   // Otherwise fall back to a SHUFPS lowering strategy.
7810   return lowerVectorShuffleWithSHUFPS(DL, MVT::v4f32, Mask, V1, V2, DAG);
7811 }
7812
7813 /// \brief Lower 4-lane i32 vector shuffles.
7814 ///
7815 /// We try to handle these with integer-domain shuffles where we can, but for
7816 /// blends we use the floating point domain blend instructions.
7817 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7818                                        const X86Subtarget *Subtarget,
7819                                        SelectionDAG &DAG) {
7820   SDLoc DL(Op);
7821   assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
7822   assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7823   assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7824   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7825   ArrayRef<int> Mask = SVOp->getMask();
7826   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7827
7828   // Whenever we can lower this as a zext, that instruction is strictly faster
7829   // than any alternative. It also allows us to fold memory operands into the
7830   // shuffle in many cases.
7831   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v4i32, V1, V2,
7832                                                          Mask, Subtarget, DAG))
7833     return ZExt;
7834
7835   int NumV2Elements =
7836       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7837
7838   if (NumV2Elements == 0) {
7839     // Check for being able to broadcast a single element.
7840     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i32, V1,
7841                                                           Mask, Subtarget, DAG))
7842       return Broadcast;
7843
7844     // Straight shuffle of a single input vector. For everything from SSE2
7845     // onward this has a single fast instruction with no scary immediates.
7846     // We coerce the shuffle pattern to be compatible with UNPCK instructions
7847     // but we aren't actually going to use the UNPCK instruction because doing
7848     // so prevents folding a load into this instruction or making a copy.
7849     const int UnpackLoMask[] = {0, 0, 1, 1};
7850     const int UnpackHiMask[] = {2, 2, 3, 3};
7851     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 1, 1}))
7852       Mask = UnpackLoMask;
7853     else if (isShuffleEquivalent(V1, V2, Mask, {2, 2, 3, 3}))
7854       Mask = UnpackHiMask;
7855
7856     return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
7857                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
7858   }
7859
7860   // Try to use shift instructions.
7861   if (SDValue Shift =
7862           lowerVectorShuffleAsShift(DL, MVT::v4i32, V1, V2, Mask, DAG))
7863     return Shift;
7864
7865   // There are special ways we can lower some single-element blends.
7866   if (NumV2Elements == 1)
7867     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4i32, V1, V2,
7868                                                          Mask, Subtarget, DAG))
7869       return V;
7870
7871   // We have different paths for blend lowering, but they all must use the
7872   // *exact* same predicate.
7873   bool IsBlendSupported = Subtarget->hasSSE41();
7874   if (IsBlendSupported)
7875     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i32, V1, V2, Mask,
7876                                                   Subtarget, DAG))
7877       return Blend;
7878
7879   if (SDValue Masked =
7880           lowerVectorShuffleAsBitMask(DL, MVT::v4i32, V1, V2, Mask, DAG))
7881     return Masked;
7882
7883   // Use dedicated unpack instructions for masks that match their pattern.
7884   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
7885     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V1, V2);
7886   if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
7887     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V1, V2);
7888   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
7889     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V2, V1);
7890   if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
7891     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V2, V1);
7892
7893   // Try to use byte rotation instructions.
7894   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
7895   if (Subtarget->hasSSSE3())
7896     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
7897             DL, MVT::v4i32, V1, V2, Mask, Subtarget, DAG))
7898       return Rotate;
7899
7900   // If we have direct support for blends, we should lower by decomposing into
7901   // a permute. That will be faster than the domain cross.
7902   if (IsBlendSupported)
7903     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i32, V1, V2,
7904                                                       Mask, DAG);
7905
7906   // Try to lower by permuting the inputs into an unpack instruction.
7907   if (SDValue Unpack =
7908           lowerVectorShuffleAsUnpack(DL, MVT::v4i32, V1, V2, Mask, DAG))
7909     return Unpack;
7910
7911   // We implement this with SHUFPS because it can blend from two vectors.
7912   // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
7913   // up the inputs, bypassing domain shift penalties that we would encur if we
7914   // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
7915   // relevant.
7916   return DAG.getNode(ISD::BITCAST, DL, MVT::v4i32,
7917                      DAG.getVectorShuffle(
7918                          MVT::v4f32, DL,
7919                          DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V1),
7920                          DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V2), Mask));
7921 }
7922
7923 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
7924 /// shuffle lowering, and the most complex part.
7925 ///
7926 /// The lowering strategy is to try to form pairs of input lanes which are
7927 /// targeted at the same half of the final vector, and then use a dword shuffle
7928 /// to place them onto the right half, and finally unpack the paired lanes into
7929 /// their final position.
7930 ///
7931 /// The exact breakdown of how to form these dword pairs and align them on the
7932 /// correct sides is really tricky. See the comments within the function for
7933 /// more of the details.
7934 ///
7935 /// This code also handles repeated 128-bit lanes of v8i16 shuffles, but each
7936 /// lane must shuffle the *exact* same way. In fact, you must pass a v8 Mask to
7937 /// this routine for it to work correctly. To shuffle a 256-bit or 512-bit i16
7938 /// vector, form the analogous 128-bit 8-element Mask.
7939 static SDValue lowerV8I16GeneralSingleInputVectorShuffle(
7940     SDLoc DL, MVT VT, SDValue V, MutableArrayRef<int> Mask,
7941     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7942   assert(VT.getScalarType() == MVT::i16 && "Bad input type!");
7943   MVT PSHUFDVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
7944
7945   assert(Mask.size() == 8 && "Shuffle mask length doen't match!");
7946   MutableArrayRef<int> LoMask = Mask.slice(0, 4);
7947   MutableArrayRef<int> HiMask = Mask.slice(4, 4);
7948
7949   SmallVector<int, 4> LoInputs;
7950   std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
7951                [](int M) { return M >= 0; });
7952   std::sort(LoInputs.begin(), LoInputs.end());
7953   LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
7954   SmallVector<int, 4> HiInputs;
7955   std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
7956                [](int M) { return M >= 0; });
7957   std::sort(HiInputs.begin(), HiInputs.end());
7958   HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
7959   int NumLToL =
7960       std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
7961   int NumHToL = LoInputs.size() - NumLToL;
7962   int NumLToH =
7963       std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
7964   int NumHToH = HiInputs.size() - NumLToH;
7965   MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
7966   MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
7967   MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
7968   MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
7969
7970   // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
7971   // such inputs we can swap two of the dwords across the half mark and end up
7972   // with <=2 inputs to each half in each half. Once there, we can fall through
7973   // to the generic code below. For example:
7974   //
7975   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
7976   // Mask:  [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
7977   //
7978   // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
7979   // and an existing 2-into-2 on the other half. In this case we may have to
7980   // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
7981   // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
7982   // Fortunately, we don't have to handle anything but a 2-into-2 pattern
7983   // because any other situation (including a 3-into-1 or 1-into-3 in the other
7984   // half than the one we target for fixing) will be fixed when we re-enter this
7985   // path. We will also combine away any sequence of PSHUFD instructions that
7986   // result into a single instruction. Here is an example of the tricky case:
7987   //
7988   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
7989   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
7990   //
7991   // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
7992   //
7993   // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
7994   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
7995   //
7996   // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
7997   // Mask:  [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
7998   //
7999   // The result is fine to be handled by the generic logic.
8000   auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
8001                           ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
8002                           int AOffset, int BOffset) {
8003     assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
8004            "Must call this with A having 3 or 1 inputs from the A half.");
8005     assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
8006            "Must call this with B having 1 or 3 inputs from the B half.");
8007     assert(AToAInputs.size() + BToAInputs.size() == 4 &&
8008            "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
8009
8010     // Compute the index of dword with only one word among the three inputs in
8011     // a half by taking the sum of the half with three inputs and subtracting
8012     // the sum of the actual three inputs. The difference is the remaining
8013     // slot.
8014     int ADWord, BDWord;
8015     int &TripleDWord = AToAInputs.size() == 3 ? ADWord : BDWord;
8016     int &OneInputDWord = AToAInputs.size() == 3 ? BDWord : ADWord;
8017     int TripleInputOffset = AToAInputs.size() == 3 ? AOffset : BOffset;
8018     ArrayRef<int> TripleInputs = AToAInputs.size() == 3 ? AToAInputs : BToAInputs;
8019     int OneInput = AToAInputs.size() == 3 ? BToAInputs[0] : AToAInputs[0];
8020     int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
8021     int TripleNonInputIdx =
8022         TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
8023     TripleDWord = TripleNonInputIdx / 2;
8024
8025     // We use xor with one to compute the adjacent DWord to whichever one the
8026     // OneInput is in.
8027     OneInputDWord = (OneInput / 2) ^ 1;
8028
8029     // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
8030     // and BToA inputs. If there is also such a problem with the BToB and AToB
8031     // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
8032     // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
8033     // is essential that we don't *create* a 3<-1 as then we might oscillate.
8034     if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
8035       // Compute how many inputs will be flipped by swapping these DWords. We
8036       // need
8037       // to balance this to ensure we don't form a 3-1 shuffle in the other
8038       // half.
8039       int NumFlippedAToBInputs =
8040           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
8041           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
8042       int NumFlippedBToBInputs =
8043           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
8044           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
8045       if ((NumFlippedAToBInputs == 1 &&
8046            (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
8047           (NumFlippedBToBInputs == 1 &&
8048            (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
8049         // We choose whether to fix the A half or B half based on whether that
8050         // half has zero flipped inputs. At zero, we may not be able to fix it
8051         // with that half. We also bias towards fixing the B half because that
8052         // will more commonly be the high half, and we have to bias one way.
8053         auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
8054                                                        ArrayRef<int> Inputs) {
8055           int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
8056           bool IsFixIdxInput = std::find(Inputs.begin(), Inputs.end(),
8057                                          PinnedIdx ^ 1) != Inputs.end();
8058           // Determine whether the free index is in the flipped dword or the
8059           // unflipped dword based on where the pinned index is. We use this bit
8060           // in an xor to conditionally select the adjacent dword.
8061           int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
8062           bool IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8063                                              FixFreeIdx) != Inputs.end();
8064           if (IsFixIdxInput == IsFixFreeIdxInput)
8065             FixFreeIdx += 1;
8066           IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8067                                         FixFreeIdx) != Inputs.end();
8068           assert(IsFixIdxInput != IsFixFreeIdxInput &&
8069                  "We need to be changing the number of flipped inputs!");
8070           int PSHUFHalfMask[] = {0, 1, 2, 3};
8071           std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
8072           V = DAG.getNode(FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
8073                           MVT::v8i16, V,
8074                           getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DL, DAG));
8075
8076           for (int &M : Mask)
8077             if (M != -1 && M == FixIdx)
8078               M = FixFreeIdx;
8079             else if (M != -1 && M == FixFreeIdx)
8080               M = FixIdx;
8081         };
8082         if (NumFlippedBToBInputs != 0) {
8083           int BPinnedIdx =
8084               BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8085           FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
8086         } else {
8087           assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
8088           int APinnedIdx =
8089               AToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8090           FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
8091         }
8092       }
8093     }
8094
8095     int PSHUFDMask[] = {0, 1, 2, 3};
8096     PSHUFDMask[ADWord] = BDWord;
8097     PSHUFDMask[BDWord] = ADWord;
8098     V = DAG.getNode(ISD::BITCAST, DL, VT,
8099                     DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT,
8100                                 DAG.getNode(ISD::BITCAST, DL, PSHUFDVT, V),
8101                                 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL,
8102                                                            DAG)));
8103
8104     // Adjust the mask to match the new locations of A and B.
8105     for (int &M : Mask)
8106       if (M != -1 && M/2 == ADWord)
8107         M = 2 * BDWord + M % 2;
8108       else if (M != -1 && M/2 == BDWord)
8109         M = 2 * ADWord + M % 2;
8110
8111     // Recurse back into this routine to re-compute state now that this isn't
8112     // a 3 and 1 problem.
8113     return lowerV8I16GeneralSingleInputVectorShuffle(DL, VT, V, Mask, Subtarget,
8114                                                      DAG);
8115   };
8116   if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
8117     return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
8118   else if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
8119     return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
8120
8121   // At this point there are at most two inputs to the low and high halves from
8122   // each half. That means the inputs can always be grouped into dwords and
8123   // those dwords can then be moved to the correct half with a dword shuffle.
8124   // We use at most one low and one high word shuffle to collect these paired
8125   // inputs into dwords, and finally a dword shuffle to place them.
8126   int PSHUFLMask[4] = {-1, -1, -1, -1};
8127   int PSHUFHMask[4] = {-1, -1, -1, -1};
8128   int PSHUFDMask[4] = {-1, -1, -1, -1};
8129
8130   // First fix the masks for all the inputs that are staying in their
8131   // original halves. This will then dictate the targets of the cross-half
8132   // shuffles.
8133   auto fixInPlaceInputs =
8134       [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
8135                     MutableArrayRef<int> SourceHalfMask,
8136                     MutableArrayRef<int> HalfMask, int HalfOffset) {
8137     if (InPlaceInputs.empty())
8138       return;
8139     if (InPlaceInputs.size() == 1) {
8140       SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8141           InPlaceInputs[0] - HalfOffset;
8142       PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
8143       return;
8144     }
8145     if (IncomingInputs.empty()) {
8146       // Just fix all of the in place inputs.
8147       for (int Input : InPlaceInputs) {
8148         SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
8149         PSHUFDMask[Input / 2] = Input / 2;
8150       }
8151       return;
8152     }
8153
8154     assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
8155     SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8156         InPlaceInputs[0] - HalfOffset;
8157     // Put the second input next to the first so that they are packed into
8158     // a dword. We find the adjacent index by toggling the low bit.
8159     int AdjIndex = InPlaceInputs[0] ^ 1;
8160     SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
8161     std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
8162     PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
8163   };
8164   fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
8165   fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
8166
8167   // Now gather the cross-half inputs and place them into a free dword of
8168   // their target half.
8169   // FIXME: This operation could almost certainly be simplified dramatically to
8170   // look more like the 3-1 fixing operation.
8171   auto moveInputsToRightHalf = [&PSHUFDMask](
8172       MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
8173       MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
8174       MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
8175       int DestOffset) {
8176     auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
8177       return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
8178     };
8179     auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
8180                                                int Word) {
8181       int LowWord = Word & ~1;
8182       int HighWord = Word | 1;
8183       return isWordClobbered(SourceHalfMask, LowWord) ||
8184              isWordClobbered(SourceHalfMask, HighWord);
8185     };
8186
8187     if (IncomingInputs.empty())
8188       return;
8189
8190     if (ExistingInputs.empty()) {
8191       // Map any dwords with inputs from them into the right half.
8192       for (int Input : IncomingInputs) {
8193         // If the source half mask maps over the inputs, turn those into
8194         // swaps and use the swapped lane.
8195         if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
8196           if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
8197             SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
8198                 Input - SourceOffset;
8199             // We have to swap the uses in our half mask in one sweep.
8200             for (int &M : HalfMask)
8201               if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
8202                 M = Input;
8203               else if (M == Input)
8204                 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8205           } else {
8206             assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
8207                        Input - SourceOffset &&
8208                    "Previous placement doesn't match!");
8209           }
8210           // Note that this correctly re-maps both when we do a swap and when
8211           // we observe the other side of the swap above. We rely on that to
8212           // avoid swapping the members of the input list directly.
8213           Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8214         }
8215
8216         // Map the input's dword into the correct half.
8217         if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
8218           PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
8219         else
8220           assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
8221                      Input / 2 &&
8222                  "Previous placement doesn't match!");
8223       }
8224
8225       // And just directly shift any other-half mask elements to be same-half
8226       // as we will have mirrored the dword containing the element into the
8227       // same position within that half.
8228       for (int &M : HalfMask)
8229         if (M >= SourceOffset && M < SourceOffset + 4) {
8230           M = M - SourceOffset + DestOffset;
8231           assert(M >= 0 && "This should never wrap below zero!");
8232         }
8233       return;
8234     }
8235
8236     // Ensure we have the input in a viable dword of its current half. This
8237     // is particularly tricky because the original position may be clobbered
8238     // by inputs being moved and *staying* in that half.
8239     if (IncomingInputs.size() == 1) {
8240       if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8241         int InputFixed = std::find(std::begin(SourceHalfMask),
8242                                    std::end(SourceHalfMask), -1) -
8243                          std::begin(SourceHalfMask) + SourceOffset;
8244         SourceHalfMask[InputFixed - SourceOffset] =
8245             IncomingInputs[0] - SourceOffset;
8246         std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
8247                      InputFixed);
8248         IncomingInputs[0] = InputFixed;
8249       }
8250     } else if (IncomingInputs.size() == 2) {
8251       if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
8252           isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8253         // We have two non-adjacent or clobbered inputs we need to extract from
8254         // the source half. To do this, we need to map them into some adjacent
8255         // dword slot in the source mask.
8256         int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
8257                               IncomingInputs[1] - SourceOffset};
8258
8259         // If there is a free slot in the source half mask adjacent to one of
8260         // the inputs, place the other input in it. We use (Index XOR 1) to
8261         // compute an adjacent index.
8262         if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
8263             SourceHalfMask[InputsFixed[0] ^ 1] == -1) {
8264           SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
8265           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8266           InputsFixed[1] = InputsFixed[0] ^ 1;
8267         } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
8268                    SourceHalfMask[InputsFixed[1] ^ 1] == -1) {
8269           SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
8270           SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
8271           InputsFixed[0] = InputsFixed[1] ^ 1;
8272         } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] == -1 &&
8273                    SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] == -1) {
8274           // The two inputs are in the same DWord but it is clobbered and the
8275           // adjacent DWord isn't used at all. Move both inputs to the free
8276           // slot.
8277           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
8278           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
8279           InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
8280           InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
8281         } else {
8282           // The only way we hit this point is if there is no clobbering
8283           // (because there are no off-half inputs to this half) and there is no
8284           // free slot adjacent to one of the inputs. In this case, we have to
8285           // swap an input with a non-input.
8286           for (int i = 0; i < 4; ++i)
8287             assert((SourceHalfMask[i] == -1 || SourceHalfMask[i] == i) &&
8288                    "We can't handle any clobbers here!");
8289           assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
8290                  "Cannot have adjacent inputs here!");
8291
8292           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8293           SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
8294
8295           // We also have to update the final source mask in this case because
8296           // it may need to undo the above swap.
8297           for (int &M : FinalSourceHalfMask)
8298             if (M == (InputsFixed[0] ^ 1) + SourceOffset)
8299               M = InputsFixed[1] + SourceOffset;
8300             else if (M == InputsFixed[1] + SourceOffset)
8301               M = (InputsFixed[0] ^ 1) + SourceOffset;
8302
8303           InputsFixed[1] = InputsFixed[0] ^ 1;
8304         }
8305
8306         // Point everything at the fixed inputs.
8307         for (int &M : HalfMask)
8308           if (M == IncomingInputs[0])
8309             M = InputsFixed[0] + SourceOffset;
8310           else if (M == IncomingInputs[1])
8311             M = InputsFixed[1] + SourceOffset;
8312
8313         IncomingInputs[0] = InputsFixed[0] + SourceOffset;
8314         IncomingInputs[1] = InputsFixed[1] + SourceOffset;
8315       }
8316     } else {
8317       llvm_unreachable("Unhandled input size!");
8318     }
8319
8320     // Now hoist the DWord down to the right half.
8321     int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
8322     assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
8323     PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
8324     for (int &M : HalfMask)
8325       for (int Input : IncomingInputs)
8326         if (M == Input)
8327           M = FreeDWord * 2 + Input % 2;
8328   };
8329   moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
8330                         /*SourceOffset*/ 4, /*DestOffset*/ 0);
8331   moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
8332                         /*SourceOffset*/ 0, /*DestOffset*/ 4);
8333
8334   // Now enact all the shuffles we've computed to move the inputs into their
8335   // target half.
8336   if (!isNoopShuffleMask(PSHUFLMask))
8337     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8338                     getV4X86ShuffleImm8ForMask(PSHUFLMask, DL, DAG));
8339   if (!isNoopShuffleMask(PSHUFHMask))
8340     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8341                     getV4X86ShuffleImm8ForMask(PSHUFHMask, DL, DAG));
8342   if (!isNoopShuffleMask(PSHUFDMask))
8343     V = DAG.getNode(ISD::BITCAST, DL, VT,
8344                     DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT,
8345                                 DAG.getNode(ISD::BITCAST, DL, PSHUFDVT, V),
8346                                 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL,
8347                                                            DAG)));
8348
8349   // At this point, each half should contain all its inputs, and we can then
8350   // just shuffle them into their final position.
8351   assert(std::count_if(LoMask.begin(), LoMask.end(),
8352                        [](int M) { return M >= 4; }) == 0 &&
8353          "Failed to lift all the high half inputs to the low mask!");
8354   assert(std::count_if(HiMask.begin(), HiMask.end(),
8355                        [](int M) { return M >= 0 && M < 4; }) == 0 &&
8356          "Failed to lift all the low half inputs to the high mask!");
8357
8358   // Do a half shuffle for the low mask.
8359   if (!isNoopShuffleMask(LoMask))
8360     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8361                     getV4X86ShuffleImm8ForMask(LoMask, DL, DAG));
8362
8363   // Do a half shuffle with the high mask after shifting its values down.
8364   for (int &M : HiMask)
8365     if (M >= 0)
8366       M -= 4;
8367   if (!isNoopShuffleMask(HiMask))
8368     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8369                     getV4X86ShuffleImm8ForMask(HiMask, DL, DAG));
8370
8371   return V;
8372 }
8373
8374 /// \brief Helper to form a PSHUFB-based shuffle+blend.
8375 static SDValue lowerVectorShuffleAsPSHUFB(SDLoc DL, MVT VT, SDValue V1,
8376                                           SDValue V2, ArrayRef<int> Mask,
8377                                           SelectionDAG &DAG, bool &V1InUse,
8378                                           bool &V2InUse) {
8379   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
8380   SDValue V1Mask[16];
8381   SDValue V2Mask[16];
8382   V1InUse = false;
8383   V2InUse = false;
8384
8385   int Size = Mask.size();
8386   int Scale = 16 / Size;
8387   for (int i = 0; i < 16; ++i) {
8388     if (Mask[i / Scale] == -1) {
8389       V1Mask[i] = V2Mask[i] = DAG.getUNDEF(MVT::i8);
8390     } else {
8391       const int ZeroMask = 0x80;
8392       int V1Idx = Mask[i / Scale] < Size ? Mask[i / Scale] * Scale + i % Scale
8393                                           : ZeroMask;
8394       int V2Idx = Mask[i / Scale] < Size
8395                       ? ZeroMask
8396                       : (Mask[i / Scale] - Size) * Scale + i % Scale;
8397       if (Zeroable[i / Scale])
8398         V1Idx = V2Idx = ZeroMask;
8399       V1Mask[i] = DAG.getConstant(V1Idx, DL, MVT::i8);
8400       V2Mask[i] = DAG.getConstant(V2Idx, DL, MVT::i8);
8401       V1InUse |= (ZeroMask != V1Idx);
8402       V2InUse |= (ZeroMask != V2Idx);
8403     }
8404   }
8405
8406   if (V1InUse)
8407     V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8408                      DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, V1),
8409                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
8410   if (V2InUse)
8411     V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8412                      DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, V2),
8413                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
8414
8415   // If we need shuffled inputs from both, blend the two.
8416   SDValue V;
8417   if (V1InUse && V2InUse)
8418     V = DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
8419   else
8420     V = V1InUse ? V1 : V2;
8421
8422   // Cast the result back to the correct type.
8423   return DAG.getNode(ISD::BITCAST, DL, VT, V);
8424 }
8425
8426 /// \brief Generic lowering of 8-lane i16 shuffles.
8427 ///
8428 /// This handles both single-input shuffles and combined shuffle/blends with
8429 /// two inputs. The single input shuffles are immediately delegated to
8430 /// a dedicated lowering routine.
8431 ///
8432 /// The blends are lowered in one of three fundamental ways. If there are few
8433 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
8434 /// of the input is significantly cheaper when lowered as an interleaving of
8435 /// the two inputs, try to interleave them. Otherwise, blend the low and high
8436 /// halves of the inputs separately (making them have relatively few inputs)
8437 /// and then concatenate them.
8438 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8439                                        const X86Subtarget *Subtarget,
8440                                        SelectionDAG &DAG) {
8441   SDLoc DL(Op);
8442   assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
8443   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8444   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8445   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8446   ArrayRef<int> OrigMask = SVOp->getMask();
8447   int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
8448                         OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
8449   MutableArrayRef<int> Mask(MaskStorage);
8450
8451   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
8452
8453   // Whenever we can lower this as a zext, that instruction is strictly faster
8454   // than any alternative.
8455   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
8456           DL, MVT::v8i16, V1, V2, OrigMask, Subtarget, DAG))
8457     return ZExt;
8458
8459   auto isV1 = [](int M) { return M >= 0 && M < 8; };
8460   (void)isV1;
8461   auto isV2 = [](int M) { return M >= 8; };
8462
8463   int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
8464
8465   if (NumV2Inputs == 0) {
8466     // Check for being able to broadcast a single element.
8467     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i16, V1,
8468                                                           Mask, Subtarget, DAG))
8469       return Broadcast;
8470
8471     // Try to use shift instructions.
8472     if (SDValue Shift =
8473             lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V1, Mask, DAG))
8474       return Shift;
8475
8476     // Use dedicated unpack instructions for masks that match their pattern.
8477     if (isShuffleEquivalent(V1, V1, Mask, {0, 0, 1, 1, 2, 2, 3, 3}))
8478       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V1);
8479     if (isShuffleEquivalent(V1, V1, Mask, {4, 4, 5, 5, 6, 6, 7, 7}))
8480       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V1);
8481
8482     // Try to use byte rotation instructions.
8483     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(DL, MVT::v8i16, V1, V1,
8484                                                         Mask, Subtarget, DAG))
8485       return Rotate;
8486
8487     return lowerV8I16GeneralSingleInputVectorShuffle(DL, MVT::v8i16, V1, Mask,
8488                                                      Subtarget, DAG);
8489   }
8490
8491   assert(std::any_of(Mask.begin(), Mask.end(), isV1) &&
8492          "All single-input shuffles should be canonicalized to be V1-input "
8493          "shuffles.");
8494
8495   // Try to use shift instructions.
8496   if (SDValue Shift =
8497           lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V2, Mask, DAG))
8498     return Shift;
8499
8500   // There are special ways we can lower some single-element blends.
8501   if (NumV2Inputs == 1)
8502     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v8i16, V1, V2,
8503                                                          Mask, Subtarget, DAG))
8504       return V;
8505
8506   // We have different paths for blend lowering, but they all must use the
8507   // *exact* same predicate.
8508   bool IsBlendSupported = Subtarget->hasSSE41();
8509   if (IsBlendSupported)
8510     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i16, V1, V2, Mask,
8511                                                   Subtarget, DAG))
8512       return Blend;
8513
8514   if (SDValue Masked =
8515           lowerVectorShuffleAsBitMask(DL, MVT::v8i16, V1, V2, Mask, DAG))
8516     return Masked;
8517
8518   // Use dedicated unpack instructions for masks that match their pattern.
8519   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 2, 10, 3, 11}))
8520     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V2);
8521   if (isShuffleEquivalent(V1, V2, Mask, {4, 12, 5, 13, 6, 14, 7, 15}))
8522     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V2);
8523
8524   // Try to use byte rotation instructions.
8525   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8526           DL, MVT::v8i16, V1, V2, Mask, Subtarget, DAG))
8527     return Rotate;
8528
8529   if (SDValue BitBlend =
8530           lowerVectorShuffleAsBitBlend(DL, MVT::v8i16, V1, V2, Mask, DAG))
8531     return BitBlend;
8532
8533   if (SDValue Unpack =
8534           lowerVectorShuffleAsUnpack(DL, MVT::v8i16, V1, V2, Mask, DAG))
8535     return Unpack;
8536
8537   // If we can't directly blend but can use PSHUFB, that will be better as it
8538   // can both shuffle and set up the inefficient blend.
8539   if (!IsBlendSupported && Subtarget->hasSSSE3()) {
8540     bool V1InUse, V2InUse;
8541     return lowerVectorShuffleAsPSHUFB(DL, MVT::v8i16, V1, V2, Mask, DAG,
8542                                       V1InUse, V2InUse);
8543   }
8544
8545   // We can always bit-blend if we have to so the fallback strategy is to
8546   // decompose into single-input permutes and blends.
8547   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i16, V1, V2,
8548                                                       Mask, DAG);
8549 }
8550
8551 /// \brief Check whether a compaction lowering can be done by dropping even
8552 /// elements and compute how many times even elements must be dropped.
8553 ///
8554 /// This handles shuffles which take every Nth element where N is a power of
8555 /// two. Example shuffle masks:
8556 ///
8557 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14,  0,  2,  4,  6,  8, 10, 12, 14
8558 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
8559 ///  N = 2:  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12
8560 ///  N = 2:  0,  4,  8, 12, 16, 20, 24, 28,  0,  4,  8, 12, 16, 20, 24, 28
8561 ///  N = 3:  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8
8562 ///  N = 3:  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24
8563 ///
8564 /// Any of these lanes can of course be undef.
8565 ///
8566 /// This routine only supports N <= 3.
8567 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
8568 /// for larger N.
8569 ///
8570 /// \returns N above, or the number of times even elements must be dropped if
8571 /// there is such a number. Otherwise returns zero.
8572 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
8573   // Figure out whether we're looping over two inputs or just one.
8574   bool IsSingleInput = isSingleInputShuffleMask(Mask);
8575
8576   // The modulus for the shuffle vector entries is based on whether this is
8577   // a single input or not.
8578   int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
8579   assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
8580          "We should only be called with masks with a power-of-2 size!");
8581
8582   uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
8583
8584   // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
8585   // and 2^3 simultaneously. This is because we may have ambiguity with
8586   // partially undef inputs.
8587   bool ViableForN[3] = {true, true, true};
8588
8589   for (int i = 0, e = Mask.size(); i < e; ++i) {
8590     // Ignore undef lanes, we'll optimistically collapse them to the pattern we
8591     // want.
8592     if (Mask[i] == -1)
8593       continue;
8594
8595     bool IsAnyViable = false;
8596     for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8597       if (ViableForN[j]) {
8598         uint64_t N = j + 1;
8599
8600         // The shuffle mask must be equal to (i * 2^N) % M.
8601         if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
8602           IsAnyViable = true;
8603         else
8604           ViableForN[j] = false;
8605       }
8606     // Early exit if we exhaust the possible powers of two.
8607     if (!IsAnyViable)
8608       break;
8609   }
8610
8611   for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8612     if (ViableForN[j])
8613       return j + 1;
8614
8615   // Return 0 as there is no viable power of two.
8616   return 0;
8617 }
8618
8619 /// \brief Generic lowering of v16i8 shuffles.
8620 ///
8621 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
8622 /// detect any complexity reducing interleaving. If that doesn't help, it uses
8623 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
8624 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
8625 /// back together.
8626 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8627                                        const X86Subtarget *Subtarget,
8628                                        SelectionDAG &DAG) {
8629   SDLoc DL(Op);
8630   assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
8631   assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8632   assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8633   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8634   ArrayRef<int> Mask = SVOp->getMask();
8635   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
8636
8637   // Try to use shift instructions.
8638   if (SDValue Shift =
8639           lowerVectorShuffleAsShift(DL, MVT::v16i8, V1, V2, Mask, DAG))
8640     return Shift;
8641
8642   // Try to use byte rotation instructions.
8643   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8644           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
8645     return Rotate;
8646
8647   // Try to use a zext lowering.
8648   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
8649           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
8650     return ZExt;
8651
8652   int NumV2Elements =
8653       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 16; });
8654
8655   // For single-input shuffles, there are some nicer lowering tricks we can use.
8656   if (NumV2Elements == 0) {
8657     // Check for being able to broadcast a single element.
8658     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i8, V1,
8659                                                           Mask, Subtarget, DAG))
8660       return Broadcast;
8661
8662     // Check whether we can widen this to an i16 shuffle by duplicating bytes.
8663     // Notably, this handles splat and partial-splat shuffles more efficiently.
8664     // However, it only makes sense if the pre-duplication shuffle simplifies
8665     // things significantly. Currently, this means we need to be able to
8666     // express the pre-duplication shuffle as an i16 shuffle.
8667     //
8668     // FIXME: We should check for other patterns which can be widened into an
8669     // i16 shuffle as well.
8670     auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
8671       for (int i = 0; i < 16; i += 2)
8672         if (Mask[i] != -1 && Mask[i + 1] != -1 && Mask[i] != Mask[i + 1])
8673           return false;
8674
8675       return true;
8676     };
8677     auto tryToWidenViaDuplication = [&]() -> SDValue {
8678       if (!canWidenViaDuplication(Mask))
8679         return SDValue();
8680       SmallVector<int, 4> LoInputs;
8681       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
8682                    [](int M) { return M >= 0 && M < 8; });
8683       std::sort(LoInputs.begin(), LoInputs.end());
8684       LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
8685                      LoInputs.end());
8686       SmallVector<int, 4> HiInputs;
8687       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
8688                    [](int M) { return M >= 8; });
8689       std::sort(HiInputs.begin(), HiInputs.end());
8690       HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
8691                      HiInputs.end());
8692
8693       bool TargetLo = LoInputs.size() >= HiInputs.size();
8694       ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
8695       ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
8696
8697       int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
8698       SmallDenseMap<int, int, 8> LaneMap;
8699       for (int I : InPlaceInputs) {
8700         PreDupI16Shuffle[I/2] = I/2;
8701         LaneMap[I] = I;
8702       }
8703       int j = TargetLo ? 0 : 4, je = j + 4;
8704       for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
8705         // Check if j is already a shuffle of this input. This happens when
8706         // there are two adjacent bytes after we move the low one.
8707         if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
8708           // If we haven't yet mapped the input, search for a slot into which
8709           // we can map it.
8710           while (j < je && PreDupI16Shuffle[j] != -1)
8711             ++j;
8712
8713           if (j == je)
8714             // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
8715             return SDValue();
8716
8717           // Map this input with the i16 shuffle.
8718           PreDupI16Shuffle[j] = MovingInputs[i] / 2;
8719         }
8720
8721         // Update the lane map based on the mapping we ended up with.
8722         LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
8723       }
8724       V1 = DAG.getNode(
8725           ISD::BITCAST, DL, MVT::v16i8,
8726           DAG.getVectorShuffle(MVT::v8i16, DL,
8727                                DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
8728                                DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
8729
8730       // Unpack the bytes to form the i16s that will be shuffled into place.
8731       V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
8732                        MVT::v16i8, V1, V1);
8733
8734       int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8735       for (int i = 0; i < 16; ++i)
8736         if (Mask[i] != -1) {
8737           int MappedMask = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
8738           assert(MappedMask < 8 && "Invalid v8 shuffle mask!");
8739           if (PostDupI16Shuffle[i / 2] == -1)
8740             PostDupI16Shuffle[i / 2] = MappedMask;
8741           else
8742             assert(PostDupI16Shuffle[i / 2] == MappedMask &&
8743                    "Conflicting entrties in the original shuffle!");
8744         }
8745       return DAG.getNode(
8746           ISD::BITCAST, DL, MVT::v16i8,
8747           DAG.getVectorShuffle(MVT::v8i16, DL,
8748                                DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
8749                                DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
8750     };
8751     if (SDValue V = tryToWidenViaDuplication())
8752       return V;
8753   }
8754
8755   // Use dedicated unpack instructions for masks that match their pattern.
8756   if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
8757                                          0, 16, 1, 17, 2, 18, 3, 19,
8758                                          // High half.
8759                                          4, 20, 5, 21, 6, 22, 7, 23}))
8760     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V1, V2);
8761   if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
8762                                          8, 24, 9, 25, 10, 26, 11, 27,
8763                                          // High half.
8764                                          12, 28, 13, 29, 14, 30, 15, 31}))
8765     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V1, V2);
8766
8767   // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
8768   // with PSHUFB. It is important to do this before we attempt to generate any
8769   // blends but after all of the single-input lowerings. If the single input
8770   // lowerings can find an instruction sequence that is faster than a PSHUFB, we
8771   // want to preserve that and we can DAG combine any longer sequences into
8772   // a PSHUFB in the end. But once we start blending from multiple inputs,
8773   // the complexity of DAG combining bad patterns back into PSHUFB is too high,
8774   // and there are *very* few patterns that would actually be faster than the
8775   // PSHUFB approach because of its ability to zero lanes.
8776   //
8777   // FIXME: The only exceptions to the above are blends which are exact
8778   // interleavings with direct instructions supporting them. We currently don't
8779   // handle those well here.
8780   if (Subtarget->hasSSSE3()) {
8781     bool V1InUse = false;
8782     bool V2InUse = false;
8783
8784     SDValue PSHUFB = lowerVectorShuffleAsPSHUFB(DL, MVT::v16i8, V1, V2, Mask,
8785                                                 DAG, V1InUse, V2InUse);
8786
8787     // If both V1 and V2 are in use and we can use a direct blend or an unpack,
8788     // do so. This avoids using them to handle blends-with-zero which is
8789     // important as a single pshufb is significantly faster for that.
8790     if (V1InUse && V2InUse) {
8791       if (Subtarget->hasSSE41())
8792         if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i8, V1, V2,
8793                                                       Mask, Subtarget, DAG))
8794           return Blend;
8795
8796       // We can use an unpack to do the blending rather than an or in some
8797       // cases. Even though the or may be (very minorly) more efficient, we
8798       // preference this lowering because there are common cases where part of
8799       // the complexity of the shuffles goes away when we do the final blend as
8800       // an unpack.
8801       // FIXME: It might be worth trying to detect if the unpack-feeding
8802       // shuffles will both be pshufb, in which case we shouldn't bother with
8803       // this.
8804       if (SDValue Unpack =
8805               lowerVectorShuffleAsUnpack(DL, MVT::v16i8, V1, V2, Mask, DAG))
8806         return Unpack;
8807     }
8808
8809     return PSHUFB;
8810   }
8811
8812   // There are special ways we can lower some single-element blends.
8813   if (NumV2Elements == 1)
8814     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v16i8, V1, V2,
8815                                                          Mask, Subtarget, DAG))
8816       return V;
8817
8818   if (SDValue BitBlend =
8819           lowerVectorShuffleAsBitBlend(DL, MVT::v16i8, V1, V2, Mask, DAG))
8820     return BitBlend;
8821
8822   // Check whether a compaction lowering can be done. This handles shuffles
8823   // which take every Nth element for some even N. See the helper function for
8824   // details.
8825   //
8826   // We special case these as they can be particularly efficiently handled with
8827   // the PACKUSB instruction on x86 and they show up in common patterns of
8828   // rearranging bytes to truncate wide elements.
8829   if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
8830     // NumEvenDrops is the power of two stride of the elements. Another way of
8831     // thinking about it is that we need to drop the even elements this many
8832     // times to get the original input.
8833     bool IsSingleInput = isSingleInputShuffleMask(Mask);
8834
8835     // First we need to zero all the dropped bytes.
8836     assert(NumEvenDrops <= 3 &&
8837            "No support for dropping even elements more than 3 times.");
8838     // We use the mask type to pick which bytes are preserved based on how many
8839     // elements are dropped.
8840     MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
8841     SDValue ByteClearMask =
8842         DAG.getNode(ISD::BITCAST, DL, MVT::v16i8,
8843                     DAG.getConstant(0xFF, DL, MaskVTs[NumEvenDrops - 1]));
8844     V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
8845     if (!IsSingleInput)
8846       V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
8847
8848     // Now pack things back together.
8849     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1);
8850     V2 = IsSingleInput ? V1 : DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V2);
8851     SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
8852     for (int i = 1; i < NumEvenDrops; ++i) {
8853       Result = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, Result);
8854       Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
8855     }
8856
8857     return Result;
8858   }
8859
8860   // Handle multi-input cases by blending single-input shuffles.
8861   if (NumV2Elements > 0)
8862     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v16i8, V1, V2,
8863                                                       Mask, DAG);
8864
8865   // The fallback path for single-input shuffles widens this into two v8i16
8866   // vectors with unpacks, shuffles those, and then pulls them back together
8867   // with a pack.
8868   SDValue V = V1;
8869
8870   int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8871   int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8872   for (int i = 0; i < 16; ++i)
8873     if (Mask[i] >= 0)
8874       (i < 8 ? LoBlendMask[i] : HiBlendMask[i % 8]) = Mask[i];
8875
8876   SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
8877
8878   SDValue VLoHalf, VHiHalf;
8879   // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
8880   // them out and avoid using UNPCK{L,H} to extract the elements of V as
8881   // i16s.
8882   if (std::none_of(std::begin(LoBlendMask), std::end(LoBlendMask),
8883                    [](int M) { return M >= 0 && M % 2 == 1; }) &&
8884       std::none_of(std::begin(HiBlendMask), std::end(HiBlendMask),
8885                    [](int M) { return M >= 0 && M % 2 == 1; })) {
8886     // Use a mask to drop the high bytes.
8887     VLoHalf = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V);
8888     VLoHalf = DAG.getNode(ISD::AND, DL, MVT::v8i16, VLoHalf,
8889                      DAG.getConstant(0x00FF, DL, MVT::v8i16));
8890
8891     // This will be a single vector shuffle instead of a blend so nuke VHiHalf.
8892     VHiHalf = DAG.getUNDEF(MVT::v8i16);
8893
8894     // Squash the masks to point directly into VLoHalf.
8895     for (int &M : LoBlendMask)
8896       if (M >= 0)
8897         M /= 2;
8898     for (int &M : HiBlendMask)
8899       if (M >= 0)
8900         M /= 2;
8901   } else {
8902     // Otherwise just unpack the low half of V into VLoHalf and the high half into
8903     // VHiHalf so that we can blend them as i16s.
8904     VLoHalf = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8905                      DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
8906     VHiHalf = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8907                      DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
8908   }
8909
8910   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, LoBlendMask);
8911   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, HiBlendMask);
8912
8913   return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
8914 }
8915
8916 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
8917 ///
8918 /// This routine breaks down the specific type of 128-bit shuffle and
8919 /// dispatches to the lowering routines accordingly.
8920 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8921                                         MVT VT, const X86Subtarget *Subtarget,
8922                                         SelectionDAG &DAG) {
8923   switch (VT.SimpleTy) {
8924   case MVT::v2i64:
8925     return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8926   case MVT::v2f64:
8927     return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8928   case MVT::v4i32:
8929     return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
8930   case MVT::v4f32:
8931     return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
8932   case MVT::v8i16:
8933     return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
8934   case MVT::v16i8:
8935     return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
8936
8937   default:
8938     llvm_unreachable("Unimplemented!");
8939   }
8940 }
8941
8942 /// \brief Helper function to test whether a shuffle mask could be
8943 /// simplified by widening the elements being shuffled.
8944 ///
8945 /// Appends the mask for wider elements in WidenedMask if valid. Otherwise
8946 /// leaves it in an unspecified state.
8947 ///
8948 /// NOTE: This must handle normal vector shuffle masks and *target* vector
8949 /// shuffle masks. The latter have the special property of a '-2' representing
8950 /// a zero-ed lane of a vector.
8951 static bool canWidenShuffleElements(ArrayRef<int> Mask,
8952                                     SmallVectorImpl<int> &WidenedMask) {
8953   for (int i = 0, Size = Mask.size(); i < Size; i += 2) {
8954     // If both elements are undef, its trivial.
8955     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] == SM_SentinelUndef) {
8956       WidenedMask.push_back(SM_SentinelUndef);
8957       continue;
8958     }
8959
8960     // Check for an undef mask and a mask value properly aligned to fit with
8961     // a pair of values. If we find such a case, use the non-undef mask's value.
8962     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] >= 0 && Mask[i + 1] % 2 == 1) {
8963       WidenedMask.push_back(Mask[i + 1] / 2);
8964       continue;
8965     }
8966     if (Mask[i + 1] == SM_SentinelUndef && Mask[i] >= 0 && Mask[i] % 2 == 0) {
8967       WidenedMask.push_back(Mask[i] / 2);
8968       continue;
8969     }
8970
8971     // When zeroing, we need to spread the zeroing across both lanes to widen.
8972     if (Mask[i] == SM_SentinelZero || Mask[i + 1] == SM_SentinelZero) {
8973       if ((Mask[i] == SM_SentinelZero || Mask[i] == SM_SentinelUndef) &&
8974           (Mask[i + 1] == SM_SentinelZero || Mask[i + 1] == SM_SentinelUndef)) {
8975         WidenedMask.push_back(SM_SentinelZero);
8976         continue;
8977       }
8978       return false;
8979     }
8980
8981     // Finally check if the two mask values are adjacent and aligned with
8982     // a pair.
8983     if (Mask[i] != SM_SentinelUndef && Mask[i] % 2 == 0 && Mask[i] + 1 == Mask[i + 1]) {
8984       WidenedMask.push_back(Mask[i] / 2);
8985       continue;
8986     }
8987
8988     // Otherwise we can't safely widen the elements used in this shuffle.
8989     return false;
8990   }
8991   assert(WidenedMask.size() == Mask.size() / 2 &&
8992          "Incorrect size of mask after widening the elements!");
8993
8994   return true;
8995 }
8996
8997 /// \brief Generic routine to split vector shuffle into half-sized shuffles.
8998 ///
8999 /// This routine just extracts two subvectors, shuffles them independently, and
9000 /// then concatenates them back together. This should work effectively with all
9001 /// AVX vector shuffle types.
9002 static SDValue splitAndLowerVectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9003                                           SDValue V2, ArrayRef<int> Mask,
9004                                           SelectionDAG &DAG) {
9005   assert(VT.getSizeInBits() >= 256 &&
9006          "Only for 256-bit or wider vector shuffles!");
9007   assert(V1.getSimpleValueType() == VT && "Bad operand type!");
9008   assert(V2.getSimpleValueType() == VT && "Bad operand type!");
9009
9010   ArrayRef<int> LoMask = Mask.slice(0, Mask.size() / 2);
9011   ArrayRef<int> HiMask = Mask.slice(Mask.size() / 2);
9012
9013   int NumElements = VT.getVectorNumElements();
9014   int SplitNumElements = NumElements / 2;
9015   MVT ScalarVT = VT.getScalarType();
9016   MVT SplitVT = MVT::getVectorVT(ScalarVT, NumElements / 2);
9017
9018   // Rather than splitting build-vectors, just build two narrower build
9019   // vectors. This helps shuffling with splats and zeros.
9020   auto SplitVector = [&](SDValue V) {
9021     while (V.getOpcode() == ISD::BITCAST)
9022       V = V->getOperand(0);
9023
9024     MVT OrigVT = V.getSimpleValueType();
9025     int OrigNumElements = OrigVT.getVectorNumElements();
9026     int OrigSplitNumElements = OrigNumElements / 2;
9027     MVT OrigScalarVT = OrigVT.getScalarType();
9028     MVT OrigSplitVT = MVT::getVectorVT(OrigScalarVT, OrigNumElements / 2);
9029
9030     SDValue LoV, HiV;
9031
9032     auto *BV = dyn_cast<BuildVectorSDNode>(V);
9033     if (!BV) {
9034       LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9035                         DAG.getIntPtrConstant(0, DL));
9036       HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9037                         DAG.getIntPtrConstant(OrigSplitNumElements, DL));
9038     } else {
9039
9040       SmallVector<SDValue, 16> LoOps, HiOps;
9041       for (int i = 0; i < OrigSplitNumElements; ++i) {
9042         LoOps.push_back(BV->getOperand(i));
9043         HiOps.push_back(BV->getOperand(i + OrigSplitNumElements));
9044       }
9045       LoV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, LoOps);
9046       HiV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, HiOps);
9047     }
9048     return std::make_pair(DAG.getNode(ISD::BITCAST, DL, SplitVT, LoV),
9049                           DAG.getNode(ISD::BITCAST, DL, SplitVT, HiV));
9050   };
9051
9052   SDValue LoV1, HiV1, LoV2, HiV2;
9053   std::tie(LoV1, HiV1) = SplitVector(V1);
9054   std::tie(LoV2, HiV2) = SplitVector(V2);
9055
9056   // Now create two 4-way blends of these half-width vectors.
9057   auto HalfBlend = [&](ArrayRef<int> HalfMask) {
9058     bool UseLoV1 = false, UseHiV1 = false, UseLoV2 = false, UseHiV2 = false;
9059     SmallVector<int, 32> V1BlendMask, V2BlendMask, BlendMask;
9060     for (int i = 0; i < SplitNumElements; ++i) {
9061       int M = HalfMask[i];
9062       if (M >= NumElements) {
9063         if (M >= NumElements + SplitNumElements)
9064           UseHiV2 = true;
9065         else
9066           UseLoV2 = true;
9067         V2BlendMask.push_back(M - NumElements);
9068         V1BlendMask.push_back(-1);
9069         BlendMask.push_back(SplitNumElements + i);
9070       } else if (M >= 0) {
9071         if (M >= SplitNumElements)
9072           UseHiV1 = true;
9073         else
9074           UseLoV1 = true;
9075         V2BlendMask.push_back(-1);
9076         V1BlendMask.push_back(M);
9077         BlendMask.push_back(i);
9078       } else {
9079         V2BlendMask.push_back(-1);
9080         V1BlendMask.push_back(-1);
9081         BlendMask.push_back(-1);
9082       }
9083     }
9084
9085     // Because the lowering happens after all combining takes place, we need to
9086     // manually combine these blend masks as much as possible so that we create
9087     // a minimal number of high-level vector shuffle nodes.
9088
9089     // First try just blending the halves of V1 or V2.
9090     if (!UseLoV1 && !UseHiV1 && !UseLoV2 && !UseHiV2)
9091       return DAG.getUNDEF(SplitVT);
9092     if (!UseLoV2 && !UseHiV2)
9093       return DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9094     if (!UseLoV1 && !UseHiV1)
9095       return DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9096
9097     SDValue V1Blend, V2Blend;
9098     if (UseLoV1 && UseHiV1) {
9099       V1Blend =
9100         DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9101     } else {
9102       // We only use half of V1 so map the usage down into the final blend mask.
9103       V1Blend = UseLoV1 ? LoV1 : HiV1;
9104       for (int i = 0; i < SplitNumElements; ++i)
9105         if (BlendMask[i] >= 0 && BlendMask[i] < SplitNumElements)
9106           BlendMask[i] = V1BlendMask[i] - (UseLoV1 ? 0 : SplitNumElements);
9107     }
9108     if (UseLoV2 && UseHiV2) {
9109       V2Blend =
9110         DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9111     } else {
9112       // We only use half of V2 so map the usage down into the final blend mask.
9113       V2Blend = UseLoV2 ? LoV2 : HiV2;
9114       for (int i = 0; i < SplitNumElements; ++i)
9115         if (BlendMask[i] >= SplitNumElements)
9116           BlendMask[i] = V2BlendMask[i] + (UseLoV2 ? SplitNumElements : 0);
9117     }
9118     return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
9119   };
9120   SDValue Lo = HalfBlend(LoMask);
9121   SDValue Hi = HalfBlend(HiMask);
9122   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
9123 }
9124
9125 /// \brief Either split a vector in halves or decompose the shuffles and the
9126 /// blend.
9127 ///
9128 /// This is provided as a good fallback for many lowerings of non-single-input
9129 /// shuffles with more than one 128-bit lane. In those cases, we want to select
9130 /// between splitting the shuffle into 128-bit components and stitching those
9131 /// back together vs. extracting the single-input shuffles and blending those
9132 /// results.
9133 static SDValue lowerVectorShuffleAsSplitOrBlend(SDLoc DL, MVT VT, SDValue V1,
9134                                                 SDValue V2, ArrayRef<int> Mask,
9135                                                 SelectionDAG &DAG) {
9136   assert(!isSingleInputShuffleMask(Mask) && "This routine must not be used to "
9137                                             "lower single-input shuffles as it "
9138                                             "could then recurse on itself.");
9139   int Size = Mask.size();
9140
9141   // If this can be modeled as a broadcast of two elements followed by a blend,
9142   // prefer that lowering. This is especially important because broadcasts can
9143   // often fold with memory operands.
9144   auto DoBothBroadcast = [&] {
9145     int V1BroadcastIdx = -1, V2BroadcastIdx = -1;
9146     for (int M : Mask)
9147       if (M >= Size) {
9148         if (V2BroadcastIdx == -1)
9149           V2BroadcastIdx = M - Size;
9150         else if (M - Size != V2BroadcastIdx)
9151           return false;
9152       } else if (M >= 0) {
9153         if (V1BroadcastIdx == -1)
9154           V1BroadcastIdx = M;
9155         else if (M != V1BroadcastIdx)
9156           return false;
9157       }
9158     return true;
9159   };
9160   if (DoBothBroadcast())
9161     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask,
9162                                                       DAG);
9163
9164   // If the inputs all stem from a single 128-bit lane of each input, then we
9165   // split them rather than blending because the split will decompose to
9166   // unusually few instructions.
9167   int LaneCount = VT.getSizeInBits() / 128;
9168   int LaneSize = Size / LaneCount;
9169   SmallBitVector LaneInputs[2];
9170   LaneInputs[0].resize(LaneCount, false);
9171   LaneInputs[1].resize(LaneCount, false);
9172   for (int i = 0; i < Size; ++i)
9173     if (Mask[i] >= 0)
9174       LaneInputs[Mask[i] / Size][(Mask[i] % Size) / LaneSize] = true;
9175   if (LaneInputs[0].count() <= 1 && LaneInputs[1].count() <= 1)
9176     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9177
9178   // Otherwise, just fall back to decomposed shuffles and a blend. This requires
9179   // that the decomposed single-input shuffles don't end up here.
9180   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9181 }
9182
9183 /// \brief Lower a vector shuffle crossing multiple 128-bit lanes as
9184 /// a permutation and blend of those lanes.
9185 ///
9186 /// This essentially blends the out-of-lane inputs to each lane into the lane
9187 /// from a permuted copy of the vector. This lowering strategy results in four
9188 /// instructions in the worst case for a single-input cross lane shuffle which
9189 /// is lower than any other fully general cross-lane shuffle strategy I'm aware
9190 /// of. Special cases for each particular shuffle pattern should be handled
9191 /// prior to trying this lowering.
9192 static SDValue lowerVectorShuffleAsLanePermuteAndBlend(SDLoc DL, MVT VT,
9193                                                        SDValue V1, SDValue V2,
9194                                                        ArrayRef<int> Mask,
9195                                                        SelectionDAG &DAG) {
9196   // FIXME: This should probably be generalized for 512-bit vectors as well.
9197   assert(VT.getSizeInBits() == 256 && "Only for 256-bit vector shuffles!");
9198   int LaneSize = Mask.size() / 2;
9199
9200   // If there are only inputs from one 128-bit lane, splitting will in fact be
9201   // less expensive. The flags track whether the given lane contains an element
9202   // that crosses to another lane.
9203   bool LaneCrossing[2] = {false, false};
9204   for (int i = 0, Size = Mask.size(); i < Size; ++i)
9205     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
9206       LaneCrossing[(Mask[i] % Size) / LaneSize] = true;
9207   if (!LaneCrossing[0] || !LaneCrossing[1])
9208     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9209
9210   if (isSingleInputShuffleMask(Mask)) {
9211     SmallVector<int, 32> FlippedBlendMask;
9212     for (int i = 0, Size = Mask.size(); i < Size; ++i)
9213       FlippedBlendMask.push_back(
9214           Mask[i] < 0 ? -1 : (((Mask[i] % Size) / LaneSize == i / LaneSize)
9215                                   ? Mask[i]
9216                                   : Mask[i] % LaneSize +
9217                                         (i / LaneSize) * LaneSize + Size));
9218
9219     // Flip the vector, and blend the results which should now be in-lane. The
9220     // VPERM2X128 mask uses the low 2 bits for the low source and bits 4 and
9221     // 5 for the high source. The value 3 selects the high half of source 2 and
9222     // the value 2 selects the low half of source 2. We only use source 2 to
9223     // allow folding it into a memory operand.
9224     unsigned PERMMask = 3 | 2 << 4;
9225     SDValue Flipped = DAG.getNode(X86ISD::VPERM2X128, DL, VT, DAG.getUNDEF(VT),
9226                                   V1, DAG.getConstant(PERMMask, DL, MVT::i8));
9227     return DAG.getVectorShuffle(VT, DL, V1, Flipped, FlippedBlendMask);
9228   }
9229
9230   // This now reduces to two single-input shuffles of V1 and V2 which at worst
9231   // will be handled by the above logic and a blend of the results, much like
9232   // other patterns in AVX.
9233   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9234 }
9235
9236 /// \brief Handle lowering 2-lane 128-bit shuffles.
9237 static SDValue lowerV2X128VectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9238                                         SDValue V2, ArrayRef<int> Mask,
9239                                         const X86Subtarget *Subtarget,
9240                                         SelectionDAG &DAG) {
9241   // TODO: If minimizing size and one of the inputs is a zero vector and the
9242   // the zero vector has only one use, we could use a VPERM2X128 to save the
9243   // instruction bytes needed to explicitly generate the zero vector.
9244
9245   // Blends are faster and handle all the non-lane-crossing cases.
9246   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, VT, V1, V2, Mask,
9247                                                 Subtarget, DAG))
9248     return Blend;
9249
9250   bool IsV1Zero = ISD::isBuildVectorAllZeros(V1.getNode());
9251   bool IsV2Zero = ISD::isBuildVectorAllZeros(V2.getNode());
9252
9253   // If either input operand is a zero vector, use VPERM2X128 because its mask
9254   // allows us to replace the zero input with an implicit zero.
9255   if (!IsV1Zero && !IsV2Zero) {
9256     // Check for patterns which can be matched with a single insert of a 128-bit
9257     // subvector.
9258     bool OnlyUsesV1 = isShuffleEquivalent(V1, V2, Mask, {0, 1, 0, 1});
9259     if (OnlyUsesV1 || isShuffleEquivalent(V1, V2, Mask, {0, 1, 4, 5})) {
9260       MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(),
9261                                    VT.getVectorNumElements() / 2);
9262       SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
9263                                 DAG.getIntPtrConstant(0, DL));
9264       SDValue HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT,
9265                                 OnlyUsesV1 ? V1 : V2,
9266                                 DAG.getIntPtrConstant(0, DL));
9267       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoV, HiV);
9268     }
9269   }
9270
9271   // Otherwise form a 128-bit permutation. After accounting for undefs,
9272   // convert the 64-bit shuffle mask selection values into 128-bit
9273   // selection bits by dividing the indexes by 2 and shifting into positions
9274   // defined by a vperm2*128 instruction's immediate control byte.
9275
9276   // The immediate permute control byte looks like this:
9277   //    [1:0] - select 128 bits from sources for low half of destination
9278   //    [2]   - ignore
9279   //    [3]   - zero low half of destination
9280   //    [5:4] - select 128 bits from sources for high half of destination
9281   //    [6]   - ignore
9282   //    [7]   - zero high half of destination
9283
9284   int MaskLO = Mask[0];
9285   if (MaskLO == SM_SentinelUndef)
9286     MaskLO = Mask[1] == SM_SentinelUndef ? 0 : Mask[1];
9287
9288   int MaskHI = Mask[2];
9289   if (MaskHI == SM_SentinelUndef)
9290     MaskHI = Mask[3] == SM_SentinelUndef ? 0 : Mask[3];
9291
9292   unsigned PermMask = MaskLO / 2 | (MaskHI / 2) << 4;
9293
9294   // If either input is a zero vector, replace it with an undef input.
9295   // Shuffle mask values <  4 are selecting elements of V1.
9296   // Shuffle mask values >= 4 are selecting elements of V2.
9297   // Adjust each half of the permute mask by clearing the half that was
9298   // selecting the zero vector and setting the zero mask bit.
9299   if (IsV1Zero) {
9300     V1 = DAG.getUNDEF(VT);
9301     if (MaskLO < 4)
9302       PermMask = (PermMask & 0xf0) | 0x08;
9303     if (MaskHI < 4)
9304       PermMask = (PermMask & 0x0f) | 0x80;
9305   }
9306   if (IsV2Zero) {
9307     V2 = DAG.getUNDEF(VT);
9308     if (MaskLO >= 4)
9309       PermMask = (PermMask & 0xf0) | 0x08;
9310     if (MaskHI >= 4)
9311       PermMask = (PermMask & 0x0f) | 0x80;
9312   }
9313
9314   return DAG.getNode(X86ISD::VPERM2X128, DL, VT, V1, V2,
9315                      DAG.getConstant(PermMask, DL, MVT::i8));
9316 }
9317
9318 /// \brief Lower a vector shuffle by first fixing the 128-bit lanes and then
9319 /// shuffling each lane.
9320 ///
9321 /// This will only succeed when the result of fixing the 128-bit lanes results
9322 /// in a single-input non-lane-crossing shuffle with a repeating shuffle mask in
9323 /// each 128-bit lanes. This handles many cases where we can quickly blend away
9324 /// the lane crosses early and then use simpler shuffles within each lane.
9325 ///
9326 /// FIXME: It might be worthwhile at some point to support this without
9327 /// requiring the 128-bit lane-relative shuffles to be repeating, but currently
9328 /// in x86 only floating point has interesting non-repeating shuffles, and even
9329 /// those are still *marginally* more expensive.
9330 static SDValue lowerVectorShuffleByMerging128BitLanes(
9331     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
9332     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
9333   assert(!isSingleInputShuffleMask(Mask) &&
9334          "This is only useful with multiple inputs.");
9335
9336   int Size = Mask.size();
9337   int LaneSize = 128 / VT.getScalarSizeInBits();
9338   int NumLanes = Size / LaneSize;
9339   assert(NumLanes > 1 && "Only handles 256-bit and wider shuffles.");
9340
9341   // See if we can build a hypothetical 128-bit lane-fixing shuffle mask. Also
9342   // check whether the in-128-bit lane shuffles share a repeating pattern.
9343   SmallVector<int, 4> Lanes;
9344   Lanes.resize(NumLanes, -1);
9345   SmallVector<int, 4> InLaneMask;
9346   InLaneMask.resize(LaneSize, -1);
9347   for (int i = 0; i < Size; ++i) {
9348     if (Mask[i] < 0)
9349       continue;
9350
9351     int j = i / LaneSize;
9352
9353     if (Lanes[j] < 0) {
9354       // First entry we've seen for this lane.
9355       Lanes[j] = Mask[i] / LaneSize;
9356     } else if (Lanes[j] != Mask[i] / LaneSize) {
9357       // This doesn't match the lane selected previously!
9358       return SDValue();
9359     }
9360
9361     // Check that within each lane we have a consistent shuffle mask.
9362     int k = i % LaneSize;
9363     if (InLaneMask[k] < 0) {
9364       InLaneMask[k] = Mask[i] % LaneSize;
9365     } else if (InLaneMask[k] != Mask[i] % LaneSize) {
9366       // This doesn't fit a repeating in-lane mask.
9367       return SDValue();
9368     }
9369   }
9370
9371   // First shuffle the lanes into place.
9372   MVT LaneVT = MVT::getVectorVT(VT.isFloatingPoint() ? MVT::f64 : MVT::i64,
9373                                 VT.getSizeInBits() / 64);
9374   SmallVector<int, 8> LaneMask;
9375   LaneMask.resize(NumLanes * 2, -1);
9376   for (int i = 0; i < NumLanes; ++i)
9377     if (Lanes[i] >= 0) {
9378       LaneMask[2 * i + 0] = 2*Lanes[i] + 0;
9379       LaneMask[2 * i + 1] = 2*Lanes[i] + 1;
9380     }
9381
9382   V1 = DAG.getNode(ISD::BITCAST, DL, LaneVT, V1);
9383   V2 = DAG.getNode(ISD::BITCAST, DL, LaneVT, V2);
9384   SDValue LaneShuffle = DAG.getVectorShuffle(LaneVT, DL, V1, V2, LaneMask);
9385
9386   // Cast it back to the type we actually want.
9387   LaneShuffle = DAG.getNode(ISD::BITCAST, DL, VT, LaneShuffle);
9388
9389   // Now do a simple shuffle that isn't lane crossing.
9390   SmallVector<int, 8> NewMask;
9391   NewMask.resize(Size, -1);
9392   for (int i = 0; i < Size; ++i)
9393     if (Mask[i] >= 0)
9394       NewMask[i] = (i / LaneSize) * LaneSize + Mask[i] % LaneSize;
9395   assert(!is128BitLaneCrossingShuffleMask(VT, NewMask) &&
9396          "Must not introduce lane crosses at this point!");
9397
9398   return DAG.getVectorShuffle(VT, DL, LaneShuffle, DAG.getUNDEF(VT), NewMask);
9399 }
9400
9401 /// \brief Test whether the specified input (0 or 1) is in-place blended by the
9402 /// given mask.
9403 ///
9404 /// This returns true if the elements from a particular input are already in the
9405 /// slot required by the given mask and require no permutation.
9406 static bool isShuffleMaskInputInPlace(int Input, ArrayRef<int> Mask) {
9407   assert((Input == 0 || Input == 1) && "Only two inputs to shuffles.");
9408   int Size = Mask.size();
9409   for (int i = 0; i < Size; ++i)
9410     if (Mask[i] >= 0 && Mask[i] / Size == Input && Mask[i] % Size != i)
9411       return false;
9412
9413   return true;
9414 }
9415
9416 /// \brief Handle lowering of 4-lane 64-bit floating point shuffles.
9417 ///
9418 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
9419 /// isn't available.
9420 static SDValue lowerV4F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9421                                        const X86Subtarget *Subtarget,
9422                                        SelectionDAG &DAG) {
9423   SDLoc DL(Op);
9424   assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9425   assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9426   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9427   ArrayRef<int> Mask = SVOp->getMask();
9428   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9429
9430   SmallVector<int, 4> WidenedMask;
9431   if (canWidenShuffleElements(Mask, WidenedMask))
9432     return lowerV2X128VectorShuffle(DL, MVT::v4f64, V1, V2, Mask, Subtarget,
9433                                     DAG);
9434
9435   if (isSingleInputShuffleMask(Mask)) {
9436     // Check for being able to broadcast a single element.
9437     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f64, V1,
9438                                                           Mask, Subtarget, DAG))
9439       return Broadcast;
9440
9441     // Use low duplicate instructions for masks that match their pattern.
9442     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
9443       return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v4f64, V1);
9444
9445     if (!is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask)) {
9446       // Non-half-crossing single input shuffles can be lowerid with an
9447       // interleaved permutation.
9448       unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
9449                               ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
9450       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f64, V1,
9451                          DAG.getConstant(VPERMILPMask, DL, MVT::i8));
9452     }
9453
9454     // With AVX2 we have direct support for this permutation.
9455     if (Subtarget->hasAVX2())
9456       return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4f64, V1,
9457                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
9458
9459     // Otherwise, fall back.
9460     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v4f64, V1, V2, Mask,
9461                                                    DAG);
9462   }
9463
9464   // X86 has dedicated unpack instructions that can handle specific blend
9465   // operations: UNPCKH and UNPCKL.
9466   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9467     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V1, V2);
9468   if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9469     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V1, V2);
9470   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9471     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V2, V1);
9472   if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9473     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V2, V1);
9474
9475   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f64, V1, V2, Mask,
9476                                                 Subtarget, DAG))
9477     return Blend;
9478
9479   // Check if the blend happens to exactly fit that of SHUFPD.
9480   if ((Mask[0] == -1 || Mask[0] < 2) &&
9481       (Mask[1] == -1 || (Mask[1] >= 4 && Mask[1] < 6)) &&
9482       (Mask[2] == -1 || (Mask[2] >= 2 && Mask[2] < 4)) &&
9483       (Mask[3] == -1 || Mask[3] >= 6)) {
9484     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 5) << 1) |
9485                           ((Mask[2] == 3) << 2) | ((Mask[3] == 7) << 3);
9486     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f64, V1, V2,
9487                        DAG.getConstant(SHUFPDMask, DL, MVT::i8));
9488   }
9489   if ((Mask[0] == -1 || (Mask[0] >= 4 && Mask[0] < 6)) &&
9490       (Mask[1] == -1 || Mask[1] < 2) &&
9491       (Mask[2] == -1 || Mask[2] >= 6) &&
9492       (Mask[3] == -1 || (Mask[3] >= 2 && Mask[3] < 4))) {
9493     unsigned SHUFPDMask = (Mask[0] == 5) | ((Mask[1] == 1) << 1) |
9494                           ((Mask[2] == 7) << 2) | ((Mask[3] == 3) << 3);
9495     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f64, V2, V1,
9496                        DAG.getConstant(SHUFPDMask, DL, MVT::i8));
9497   }
9498
9499   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9500   // shuffle. However, if we have AVX2 and either inputs are already in place,
9501   // we will be able to shuffle even across lanes the other input in a single
9502   // instruction so skip this pattern.
9503   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9504                                  isShuffleMaskInputInPlace(1, Mask))))
9505     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9506             DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
9507       return Result;
9508
9509   // If we have AVX2 then we always want to lower with a blend because an v4 we
9510   // can fully permute the elements.
9511   if (Subtarget->hasAVX2())
9512     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4f64, V1, V2,
9513                                                       Mask, DAG);
9514
9515   // Otherwise fall back on generic lowering.
9516   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v4f64, V1, V2, Mask, DAG);
9517 }
9518
9519 /// \brief Handle lowering of 4-lane 64-bit integer shuffles.
9520 ///
9521 /// This routine is only called when we have AVX2 and thus a reasonable
9522 /// instruction set for v4i64 shuffling..
9523 static SDValue lowerV4I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9524                                        const X86Subtarget *Subtarget,
9525                                        SelectionDAG &DAG) {
9526   SDLoc DL(Op);
9527   assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9528   assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9529   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9530   ArrayRef<int> Mask = SVOp->getMask();
9531   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9532   assert(Subtarget->hasAVX2() && "We can only lower v4i64 with AVX2!");
9533
9534   SmallVector<int, 4> WidenedMask;
9535   if (canWidenShuffleElements(Mask, WidenedMask))
9536     return lowerV2X128VectorShuffle(DL, MVT::v4i64, V1, V2, Mask, Subtarget,
9537                                     DAG);
9538
9539   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i64, V1, V2, Mask,
9540                                                 Subtarget, DAG))
9541     return Blend;
9542
9543   // Check for being able to broadcast a single element.
9544   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i64, V1,
9545                                                         Mask, Subtarget, DAG))
9546     return Broadcast;
9547
9548   // When the shuffle is mirrored between the 128-bit lanes of the unit, we can
9549   // use lower latency instructions that will operate on both 128-bit lanes.
9550   SmallVector<int, 2> RepeatedMask;
9551   if (is128BitLaneRepeatedShuffleMask(MVT::v4i64, Mask, RepeatedMask)) {
9552     if (isSingleInputShuffleMask(Mask)) {
9553       int PSHUFDMask[] = {-1, -1, -1, -1};
9554       for (int i = 0; i < 2; ++i)
9555         if (RepeatedMask[i] >= 0) {
9556           PSHUFDMask[2 * i] = 2 * RepeatedMask[i];
9557           PSHUFDMask[2 * i + 1] = 2 * RepeatedMask[i] + 1;
9558         }
9559       return DAG.getNode(
9560           ISD::BITCAST, DL, MVT::v4i64,
9561           DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32,
9562                       DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, V1),
9563                       getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
9564     }
9565   }
9566
9567   // AVX2 provides a direct instruction for permuting a single input across
9568   // lanes.
9569   if (isSingleInputShuffleMask(Mask))
9570     return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4i64, V1,
9571                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
9572
9573   // Try to use shift instructions.
9574   if (SDValue Shift =
9575           lowerVectorShuffleAsShift(DL, MVT::v4i64, V1, V2, Mask, DAG))
9576     return Shift;
9577
9578   // Use dedicated unpack instructions for masks that match their pattern.
9579   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9580     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V1, V2);
9581   if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9582     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V1, V2);
9583   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9584     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V2, V1);
9585   if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9586     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V2, V1);
9587
9588   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9589   // shuffle. However, if we have AVX2 and either inputs are already in place,
9590   // we will be able to shuffle even across lanes the other input in a single
9591   // instruction so skip this pattern.
9592   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9593                                  isShuffleMaskInputInPlace(1, Mask))))
9594     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9595             DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
9596       return Result;
9597
9598   // Otherwise fall back on generic blend lowering.
9599   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i64, V1, V2,
9600                                                     Mask, DAG);
9601 }
9602
9603 /// \brief Handle lowering of 8-lane 32-bit floating point shuffles.
9604 ///
9605 /// Also ends up handling lowering of 8-lane 32-bit integer shuffles when AVX2
9606 /// isn't available.
9607 static SDValue lowerV8F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9608                                        const X86Subtarget *Subtarget,
9609                                        SelectionDAG &DAG) {
9610   SDLoc DL(Op);
9611   assert(V1.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
9612   assert(V2.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
9613   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9614   ArrayRef<int> Mask = SVOp->getMask();
9615   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9616
9617   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8f32, V1, V2, Mask,
9618                                                 Subtarget, DAG))
9619     return Blend;
9620
9621   // Check for being able to broadcast a single element.
9622   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8f32, V1,
9623                                                         Mask, Subtarget, DAG))
9624     return Broadcast;
9625
9626   // If the shuffle mask is repeated in each 128-bit lane, we have many more
9627   // options to efficiently lower the shuffle.
9628   SmallVector<int, 4> RepeatedMask;
9629   if (is128BitLaneRepeatedShuffleMask(MVT::v8f32, Mask, RepeatedMask)) {
9630     assert(RepeatedMask.size() == 4 &&
9631            "Repeated masks must be half the mask width!");
9632
9633     // Use even/odd duplicate instructions for masks that match their pattern.
9634     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2, 4, 4, 6, 6}))
9635       return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v8f32, V1);
9636     if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3, 5, 5, 7, 7}))
9637       return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v8f32, V1);
9638
9639     if (isSingleInputShuffleMask(Mask))
9640       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, V1,
9641                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
9642
9643     // Use dedicated unpack instructions for masks that match their pattern.
9644     if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
9645       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V1, V2);
9646     if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
9647       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V1, V2);
9648     if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
9649       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V2, V1);
9650     if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
9651       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V2, V1);
9652
9653     // Otherwise, fall back to a SHUFPS sequence. Here it is important that we
9654     // have already handled any direct blends. We also need to squash the
9655     // repeated mask into a simulated v4f32 mask.
9656     for (int i = 0; i < 4; ++i)
9657       if (RepeatedMask[i] >= 8)
9658         RepeatedMask[i] -= 4;
9659     return lowerVectorShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask, V1, V2, DAG);
9660   }
9661
9662   // If we have a single input shuffle with different shuffle patterns in the
9663   // two 128-bit lanes use the variable mask to VPERMILPS.
9664   if (isSingleInputShuffleMask(Mask)) {
9665     SDValue VPermMask[8];
9666     for (int i = 0; i < 8; ++i)
9667       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
9668                                  : DAG.getConstant(Mask[i], DL, MVT::i32);
9669     if (!is128BitLaneCrossingShuffleMask(MVT::v8f32, Mask))
9670       return DAG.getNode(
9671           X86ISD::VPERMILPV, DL, MVT::v8f32, V1,
9672           DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask));
9673
9674     if (Subtarget->hasAVX2())
9675       return DAG.getNode(X86ISD::VPERMV, DL, MVT::v8f32,
9676                          DAG.getNode(ISD::BITCAST, DL, MVT::v8f32,
9677                                      DAG.getNode(ISD::BUILD_VECTOR, DL,
9678                                                  MVT::v8i32, VPermMask)),
9679                          V1);
9680
9681     // Otherwise, fall back.
9682     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v8f32, V1, V2, Mask,
9683                                                    DAG);
9684   }
9685
9686   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9687   // shuffle.
9688   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9689           DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
9690     return Result;
9691
9692   // If we have AVX2 then we always want to lower with a blend because at v8 we
9693   // can fully permute the elements.
9694   if (Subtarget->hasAVX2())
9695     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8f32, V1, V2,
9696                                                       Mask, DAG);
9697
9698   // Otherwise fall back on generic lowering.
9699   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask, DAG);
9700 }
9701
9702 /// \brief Handle lowering of 8-lane 32-bit integer shuffles.
9703 ///
9704 /// This routine is only called when we have AVX2 and thus a reasonable
9705 /// instruction set for v8i32 shuffling..
9706 static SDValue lowerV8I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9707                                        const X86Subtarget *Subtarget,
9708                                        SelectionDAG &DAG) {
9709   SDLoc DL(Op);
9710   assert(V1.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
9711   assert(V2.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
9712   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9713   ArrayRef<int> Mask = SVOp->getMask();
9714   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9715   assert(Subtarget->hasAVX2() && "We can only lower v8i32 with AVX2!");
9716
9717   // Whenever we can lower this as a zext, that instruction is strictly faster
9718   // than any alternative. It also allows us to fold memory operands into the
9719   // shuffle in many cases.
9720   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v8i32, V1, V2,
9721                                                          Mask, Subtarget, DAG))
9722     return ZExt;
9723
9724   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i32, V1, V2, Mask,
9725                                                 Subtarget, DAG))
9726     return Blend;
9727
9728   // Check for being able to broadcast a single element.
9729   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i32, V1,
9730                                                         Mask, Subtarget, DAG))
9731     return Broadcast;
9732
9733   // If the shuffle mask is repeated in each 128-bit lane we can use more
9734   // efficient instructions that mirror the shuffles across the two 128-bit
9735   // lanes.
9736   SmallVector<int, 4> RepeatedMask;
9737   if (is128BitLaneRepeatedShuffleMask(MVT::v8i32, Mask, RepeatedMask)) {
9738     assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
9739     if (isSingleInputShuffleMask(Mask))
9740       return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32, V1,
9741                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
9742
9743     // Use dedicated unpack instructions for masks that match their pattern.
9744     if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
9745       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V1, V2);
9746     if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
9747       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V1, V2);
9748     if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
9749       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V2, V1);
9750     if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
9751       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V2, V1);
9752   }
9753
9754   // Try to use shift instructions.
9755   if (SDValue Shift =
9756           lowerVectorShuffleAsShift(DL, MVT::v8i32, V1, V2, Mask, DAG))
9757     return Shift;
9758
9759   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9760           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
9761     return Rotate;
9762
9763   // If the shuffle patterns aren't repeated but it is a single input, directly
9764   // generate a cross-lane VPERMD instruction.
9765   if (isSingleInputShuffleMask(Mask)) {
9766     SDValue VPermMask[8];
9767     for (int i = 0; i < 8; ++i)
9768       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
9769                                  : DAG.getConstant(Mask[i], DL, MVT::i32);
9770     return DAG.getNode(
9771         X86ISD::VPERMV, DL, MVT::v8i32,
9772         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask), V1);
9773   }
9774
9775   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9776   // shuffle.
9777   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9778           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
9779     return Result;
9780
9781   // Otherwise fall back on generic blend lowering.
9782   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i32, V1, V2,
9783                                                     Mask, DAG);
9784 }
9785
9786 /// \brief Handle lowering of 16-lane 16-bit integer shuffles.
9787 ///
9788 /// This routine is only called when we have AVX2 and thus a reasonable
9789 /// instruction set for v16i16 shuffling..
9790 static SDValue lowerV16I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9791                                         const X86Subtarget *Subtarget,
9792                                         SelectionDAG &DAG) {
9793   SDLoc DL(Op);
9794   assert(V1.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
9795   assert(V2.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
9796   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9797   ArrayRef<int> Mask = SVOp->getMask();
9798   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
9799   assert(Subtarget->hasAVX2() && "We can only lower v16i16 with AVX2!");
9800
9801   // Whenever we can lower this as a zext, that instruction is strictly faster
9802   // than any alternative. It also allows us to fold memory operands into the
9803   // shuffle in many cases.
9804   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v16i16, V1, V2,
9805                                                          Mask, Subtarget, DAG))
9806     return ZExt;
9807
9808   // Check for being able to broadcast a single element.
9809   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i16, V1,
9810                                                         Mask, Subtarget, DAG))
9811     return Broadcast;
9812
9813   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i16, V1, V2, Mask,
9814                                                 Subtarget, DAG))
9815     return Blend;
9816
9817   // Use dedicated unpack instructions for masks that match their pattern.
9818   if (isShuffleEquivalent(V1, V2, Mask,
9819                           {// First 128-bit lane:
9820                            0, 16, 1, 17, 2, 18, 3, 19,
9821                            // Second 128-bit lane:
9822                            8, 24, 9, 25, 10, 26, 11, 27}))
9823     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i16, V1, V2);
9824   if (isShuffleEquivalent(V1, V2, Mask,
9825                           {// First 128-bit lane:
9826                            4, 20, 5, 21, 6, 22, 7, 23,
9827                            // Second 128-bit lane:
9828                            12, 28, 13, 29, 14, 30, 15, 31}))
9829     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i16, V1, V2);
9830
9831   // Try to use shift instructions.
9832   if (SDValue Shift =
9833           lowerVectorShuffleAsShift(DL, MVT::v16i16, V1, V2, Mask, DAG))
9834     return Shift;
9835
9836   // Try to use byte rotation instructions.
9837   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9838           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
9839     return Rotate;
9840
9841   if (isSingleInputShuffleMask(Mask)) {
9842     // There are no generalized cross-lane shuffle operations available on i16
9843     // element types.
9844     if (is128BitLaneCrossingShuffleMask(MVT::v16i16, Mask))
9845       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v16i16, V1, V2,
9846                                                      Mask, DAG);
9847
9848     SmallVector<int, 8> RepeatedMask;
9849     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
9850       // As this is a single-input shuffle, the repeated mask should be
9851       // a strictly valid v8i16 mask that we can pass through to the v8i16
9852       // lowering to handle even the v16 case.
9853       return lowerV8I16GeneralSingleInputVectorShuffle(
9854           DL, MVT::v16i16, V1, RepeatedMask, Subtarget, DAG);
9855     }
9856
9857     SDValue PSHUFBMask[32];
9858     for (int i = 0; i < 16; ++i) {
9859       if (Mask[i] == -1) {
9860         PSHUFBMask[2 * i] = PSHUFBMask[2 * i + 1] = DAG.getUNDEF(MVT::i8);
9861         continue;
9862       }
9863
9864       int M = i < 8 ? Mask[i] : Mask[i] - 8;
9865       assert(M >= 0 && M < 8 && "Invalid single-input mask!");
9866       PSHUFBMask[2 * i] = DAG.getConstant(2 * M, DL, MVT::i8);
9867       PSHUFBMask[2 * i + 1] = DAG.getConstant(2 * M + 1, DL, MVT::i8);
9868     }
9869     return DAG.getNode(
9870         ISD::BITCAST, DL, MVT::v16i16,
9871         DAG.getNode(
9872             X86ISD::PSHUFB, DL, MVT::v32i8,
9873             DAG.getNode(ISD::BITCAST, 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::v16i16, V1, V2, Mask, Subtarget, DAG))
9881     return Result;
9882
9883   // Otherwise fall back on generic lowering.
9884   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v16i16, V1, V2, Mask, DAG);
9885 }
9886
9887 /// \brief Handle lowering of 32-lane 8-bit integer shuffles.
9888 ///
9889 /// This routine is only called when we have AVX2 and thus a reasonable
9890 /// instruction set for v32i8 shuffling..
9891 static SDValue lowerV32I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9892                                        const X86Subtarget *Subtarget,
9893                                        SelectionDAG &DAG) {
9894   SDLoc DL(Op);
9895   assert(V1.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
9896   assert(V2.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
9897   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9898   ArrayRef<int> Mask = SVOp->getMask();
9899   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
9900   assert(Subtarget->hasAVX2() && "We can only lower v32i8 with AVX2!");
9901
9902   // Whenever we can lower this as a zext, that instruction is strictly faster
9903   // than any alternative. It also allows us to fold memory operands into the
9904   // shuffle in many cases.
9905   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v32i8, V1, V2,
9906                                                          Mask, Subtarget, DAG))
9907     return ZExt;
9908
9909   // Check for being able to broadcast a single element.
9910   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v32i8, V1,
9911                                                         Mask, Subtarget, DAG))
9912     return Broadcast;
9913
9914   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v32i8, V1, V2, Mask,
9915                                                 Subtarget, DAG))
9916     return Blend;
9917
9918   // Use dedicated unpack instructions for masks that match their pattern.
9919   // Note that these are repeated 128-bit lane unpacks, not unpacks across all
9920   // 256-bit lanes.
9921   if (isShuffleEquivalent(
9922           V1, V2, Mask,
9923           {// First 128-bit lane:
9924            0, 32, 1, 33, 2, 34, 3, 35, 4, 36, 5, 37, 6, 38, 7, 39,
9925            // Second 128-bit lane:
9926            16, 48, 17, 49, 18, 50, 19, 51, 20, 52, 21, 53, 22, 54, 23, 55}))
9927     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v32i8, V1, V2);
9928   if (isShuffleEquivalent(
9929           V1, V2, Mask,
9930           {// First 128-bit lane:
9931            8, 40, 9, 41, 10, 42, 11, 43, 12, 44, 13, 45, 14, 46, 15, 47,
9932            // Second 128-bit lane:
9933            24, 56, 25, 57, 26, 58, 27, 59, 28, 60, 29, 61, 30, 62, 31, 63}))
9934     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v32i8, V1, V2);
9935
9936   // Try to use shift instructions.
9937   if (SDValue Shift =
9938           lowerVectorShuffleAsShift(DL, MVT::v32i8, V1, V2, Mask, DAG))
9939     return Shift;
9940
9941   // Try to use byte rotation instructions.
9942   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9943           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
9944     return Rotate;
9945
9946   if (isSingleInputShuffleMask(Mask)) {
9947     // There are no generalized cross-lane shuffle operations available on i8
9948     // element types.
9949     if (is128BitLaneCrossingShuffleMask(MVT::v32i8, Mask))
9950       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v32i8, V1, V2,
9951                                                      Mask, DAG);
9952
9953     SDValue PSHUFBMask[32];
9954     for (int i = 0; i < 32; ++i)
9955       PSHUFBMask[i] =
9956           Mask[i] < 0
9957               ? DAG.getUNDEF(MVT::i8)
9958               : DAG.getConstant(Mask[i] < 16 ? Mask[i] : Mask[i] - 16, DL,
9959                                 MVT::i8);
9960
9961     return DAG.getNode(
9962         X86ISD::PSHUFB, DL, MVT::v32i8, V1,
9963         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask));
9964   }
9965
9966   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9967   // shuffle.
9968   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9969           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
9970     return Result;
9971
9972   // Otherwise fall back on generic lowering.
9973   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v32i8, V1, V2, Mask, DAG);
9974 }
9975
9976 /// \brief High-level routine to lower various 256-bit x86 vector shuffles.
9977 ///
9978 /// This routine either breaks down the specific type of a 256-bit x86 vector
9979 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
9980 /// together based on the available instructions.
9981 static SDValue lower256BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9982                                         MVT VT, const X86Subtarget *Subtarget,
9983                                         SelectionDAG &DAG) {
9984   SDLoc DL(Op);
9985   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9986   ArrayRef<int> Mask = SVOp->getMask();
9987
9988   // If we have a single input to the zero element, insert that into V1 if we
9989   // can do so cheaply.
9990   int NumElts = VT.getVectorNumElements();
9991   int NumV2Elements = std::count_if(Mask.begin(), Mask.end(), [NumElts](int M) {
9992     return M >= NumElts;
9993   });
9994
9995   if (NumV2Elements == 1 && Mask[0] >= NumElts)
9996     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
9997                               DL, VT, V1, V2, Mask, Subtarget, DAG))
9998       return Insertion;
9999
10000   // There is a really nice hard cut-over between AVX1 and AVX2 that means we can
10001   // check for those subtargets here and avoid much of the subtarget querying in
10002   // the per-vector-type lowering routines. With AVX1 we have essentially *zero*
10003   // ability to manipulate a 256-bit vector with integer types. Since we'll use
10004   // floating point types there eventually, just immediately cast everything to
10005   // a float and operate entirely in that domain.
10006   if (VT.isInteger() && !Subtarget->hasAVX2()) {
10007     int ElementBits = VT.getScalarSizeInBits();
10008     if (ElementBits < 32)
10009       // No floating point type available, decompose into 128-bit vectors.
10010       return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10011
10012     MVT FpVT = MVT::getVectorVT(MVT::getFloatingPointVT(ElementBits),
10013                                 VT.getVectorNumElements());
10014     V1 = DAG.getNode(ISD::BITCAST, DL, FpVT, V1);
10015     V2 = DAG.getNode(ISD::BITCAST, DL, FpVT, V2);
10016     return DAG.getNode(ISD::BITCAST, DL, VT,
10017                        DAG.getVectorShuffle(FpVT, DL, V1, V2, Mask));
10018   }
10019
10020   switch (VT.SimpleTy) {
10021   case MVT::v4f64:
10022     return lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10023   case MVT::v4i64:
10024     return lowerV4I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10025   case MVT::v8f32:
10026     return lowerV8F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10027   case MVT::v8i32:
10028     return lowerV8I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10029   case MVT::v16i16:
10030     return lowerV16I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10031   case MVT::v32i8:
10032     return lowerV32I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10033
10034   default:
10035     llvm_unreachable("Not a valid 256-bit x86 vector type!");
10036   }
10037 }
10038
10039 /// \brief Handle lowering of 8-lane 64-bit floating point shuffles.
10040 static SDValue lowerV8F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10041                                        const X86Subtarget *Subtarget,
10042                                        SelectionDAG &DAG) {
10043   SDLoc DL(Op);
10044   assert(V1.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10045   assert(V2.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10046   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10047   ArrayRef<int> Mask = SVOp->getMask();
10048   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10049
10050   // X86 has dedicated unpack instructions that can handle specific blend
10051   // operations: UNPCKH and UNPCKL.
10052   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
10053     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f64, V1, V2);
10054   if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
10055     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f64, V1, V2);
10056
10057   // FIXME: Implement direct support for this type!
10058   return splitAndLowerVectorShuffle(DL, MVT::v8f64, V1, V2, Mask, DAG);
10059 }
10060
10061 /// \brief Handle lowering of 16-lane 32-bit floating point shuffles.
10062 static SDValue lowerV16F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10063                                        const X86Subtarget *Subtarget,
10064                                        SelectionDAG &DAG) {
10065   SDLoc DL(Op);
10066   assert(V1.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10067   assert(V2.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10068   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10069   ArrayRef<int> Mask = SVOp->getMask();
10070   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10071
10072   // Use dedicated unpack instructions for masks that match their pattern.
10073   if (isShuffleEquivalent(V1, V2, Mask,
10074                           {// First 128-bit lane.
10075                            0, 16, 1, 17, 4, 20, 5, 21,
10076                            // Second 128-bit lane.
10077                            8, 24, 9, 25, 12, 28, 13, 29}))
10078     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16f32, V1, V2);
10079   if (isShuffleEquivalent(V1, V2, Mask,
10080                           {// First 128-bit lane.
10081                            2, 18, 3, 19, 6, 22, 7, 23,
10082                            // Second 128-bit lane.
10083                            10, 26, 11, 27, 14, 30, 15, 31}))
10084     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16f32, V1, V2);
10085
10086   // FIXME: Implement direct support for this type!
10087   return splitAndLowerVectorShuffle(DL, MVT::v16f32, V1, V2, Mask, DAG);
10088 }
10089
10090 /// \brief Handle lowering of 8-lane 64-bit integer shuffles.
10091 static SDValue lowerV8I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10092                                        const X86Subtarget *Subtarget,
10093                                        SelectionDAG &DAG) {
10094   SDLoc DL(Op);
10095   assert(V1.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10096   assert(V2.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10097   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10098   ArrayRef<int> Mask = SVOp->getMask();
10099   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10100
10101   // X86 has dedicated unpack instructions that can handle specific blend
10102   // operations: UNPCKH and UNPCKL.
10103   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
10104     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i64, V1, V2);
10105   if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
10106     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i64, V1, V2);
10107
10108   // FIXME: Implement direct support for this type!
10109   return splitAndLowerVectorShuffle(DL, MVT::v8i64, V1, V2, Mask, DAG);
10110 }
10111
10112 /// \brief Handle lowering of 16-lane 32-bit integer shuffles.
10113 static SDValue lowerV16I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10114                                        const X86Subtarget *Subtarget,
10115                                        SelectionDAG &DAG) {
10116   SDLoc DL(Op);
10117   assert(V1.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10118   assert(V2.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10119   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10120   ArrayRef<int> Mask = SVOp->getMask();
10121   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10122
10123   // Use dedicated unpack instructions for masks that match their pattern.
10124   if (isShuffleEquivalent(V1, V2, Mask,
10125                           {// First 128-bit lane.
10126                            0, 16, 1, 17, 4, 20, 5, 21,
10127                            // Second 128-bit lane.
10128                            8, 24, 9, 25, 12, 28, 13, 29}))
10129     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i32, V1, V2);
10130   if (isShuffleEquivalent(V1, V2, Mask,
10131                           {// First 128-bit lane.
10132                            2, 18, 3, 19, 6, 22, 7, 23,
10133                            // Second 128-bit lane.
10134                            10, 26, 11, 27, 14, 30, 15, 31}))
10135     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i32, V1, V2);
10136
10137   // FIXME: Implement direct support for this type!
10138   return splitAndLowerVectorShuffle(DL, MVT::v16i32, V1, V2, Mask, DAG);
10139 }
10140
10141 /// \brief Handle lowering of 32-lane 16-bit integer shuffles.
10142 static SDValue lowerV32I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10143                                         const X86Subtarget *Subtarget,
10144                                         SelectionDAG &DAG) {
10145   SDLoc DL(Op);
10146   assert(V1.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10147   assert(V2.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10148   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10149   ArrayRef<int> Mask = SVOp->getMask();
10150   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10151   assert(Subtarget->hasBWI() && "We can only lower v32i16 with AVX-512-BWI!");
10152
10153   // FIXME: Implement direct support for this type!
10154   return splitAndLowerVectorShuffle(DL, MVT::v32i16, V1, V2, Mask, DAG);
10155 }
10156
10157 /// \brief Handle lowering of 64-lane 8-bit integer shuffles.
10158 static SDValue lowerV64I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10159                                        const X86Subtarget *Subtarget,
10160                                        SelectionDAG &DAG) {
10161   SDLoc DL(Op);
10162   assert(V1.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10163   assert(V2.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10164   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10165   ArrayRef<int> Mask = SVOp->getMask();
10166   assert(Mask.size() == 64 && "Unexpected mask size for v64 shuffle!");
10167   assert(Subtarget->hasBWI() && "We can only lower v64i8 with AVX-512-BWI!");
10168
10169   // FIXME: Implement direct support for this type!
10170   return splitAndLowerVectorShuffle(DL, MVT::v64i8, V1, V2, Mask, DAG);
10171 }
10172
10173 /// \brief High-level routine to lower various 512-bit x86 vector shuffles.
10174 ///
10175 /// This routine either breaks down the specific type of a 512-bit x86 vector
10176 /// shuffle or splits it into two 256-bit shuffles and fuses the results back
10177 /// together based on the available instructions.
10178 static SDValue lower512BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10179                                         MVT VT, const X86Subtarget *Subtarget,
10180                                         SelectionDAG &DAG) {
10181   SDLoc DL(Op);
10182   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10183   ArrayRef<int> Mask = SVOp->getMask();
10184   assert(Subtarget->hasAVX512() &&
10185          "Cannot lower 512-bit vectors w/ basic ISA!");
10186
10187   // Check for being able to broadcast a single element.
10188   if (SDValue Broadcast =
10189           lowerVectorShuffleAsBroadcast(DL, VT, V1, Mask, Subtarget, DAG))
10190     return Broadcast;
10191
10192   // Dispatch to each element type for lowering. If we don't have supprot for
10193   // specific element type shuffles at 512 bits, immediately split them and
10194   // lower them. Each lowering routine of a given type is allowed to assume that
10195   // the requisite ISA extensions for that element type are available.
10196   switch (VT.SimpleTy) {
10197   case MVT::v8f64:
10198     return lowerV8F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10199   case MVT::v16f32:
10200     return lowerV16F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10201   case MVT::v8i64:
10202     return lowerV8I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10203   case MVT::v16i32:
10204     return lowerV16I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10205   case MVT::v32i16:
10206     if (Subtarget->hasBWI())
10207       return lowerV32I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10208     break;
10209   case MVT::v64i8:
10210     if (Subtarget->hasBWI())
10211       return lowerV64I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10212     break;
10213
10214   default:
10215     llvm_unreachable("Not a valid 512-bit x86 vector type!");
10216   }
10217
10218   // Otherwise fall back on splitting.
10219   return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10220 }
10221
10222 /// \brief Top-level lowering for x86 vector shuffles.
10223 ///
10224 /// This handles decomposition, canonicalization, and lowering of all x86
10225 /// vector shuffles. Most of the specific lowering strategies are encapsulated
10226 /// above in helper routines. The canonicalization attempts to widen shuffles
10227 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
10228 /// s.t. only one of the two inputs needs to be tested, etc.
10229 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
10230                                   SelectionDAG &DAG) {
10231   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10232   ArrayRef<int> Mask = SVOp->getMask();
10233   SDValue V1 = Op.getOperand(0);
10234   SDValue V2 = Op.getOperand(1);
10235   MVT VT = Op.getSimpleValueType();
10236   int NumElements = VT.getVectorNumElements();
10237   SDLoc dl(Op);
10238
10239   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
10240
10241   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
10242   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
10243   if (V1IsUndef && V2IsUndef)
10244     return DAG.getUNDEF(VT);
10245
10246   // When we create a shuffle node we put the UNDEF node to second operand,
10247   // but in some cases the first operand may be transformed to UNDEF.
10248   // In this case we should just commute the node.
10249   if (V1IsUndef)
10250     return DAG.getCommutedVectorShuffle(*SVOp);
10251
10252   // Check for non-undef masks pointing at an undef vector and make the masks
10253   // undef as well. This makes it easier to match the shuffle based solely on
10254   // the mask.
10255   if (V2IsUndef)
10256     for (int M : Mask)
10257       if (M >= NumElements) {
10258         SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
10259         for (int &M : NewMask)
10260           if (M >= NumElements)
10261             M = -1;
10262         return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
10263       }
10264
10265   // We actually see shuffles that are entirely re-arrangements of a set of
10266   // zero inputs. This mostly happens while decomposing complex shuffles into
10267   // simple ones. Directly lower these as a buildvector of zeros.
10268   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
10269   if (Zeroable.all())
10270     return getZeroVector(VT, Subtarget, DAG, dl);
10271
10272   // Try to collapse shuffles into using a vector type with fewer elements but
10273   // wider element types. We cap this to not form integers or floating point
10274   // elements wider than 64 bits, but it might be interesting to form i128
10275   // integers to handle flipping the low and high halves of AVX 256-bit vectors.
10276   SmallVector<int, 16> WidenedMask;
10277   if (VT.getScalarSizeInBits() < 64 &&
10278       canWidenShuffleElements(Mask, WidenedMask)) {
10279     MVT NewEltVT = VT.isFloatingPoint()
10280                        ? MVT::getFloatingPointVT(VT.getScalarSizeInBits() * 2)
10281                        : MVT::getIntegerVT(VT.getScalarSizeInBits() * 2);
10282     MVT NewVT = MVT::getVectorVT(NewEltVT, VT.getVectorNumElements() / 2);
10283     // Make sure that the new vector type is legal. For example, v2f64 isn't
10284     // legal on SSE1.
10285     if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
10286       V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
10287       V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
10288       return DAG.getNode(ISD::BITCAST, dl, VT,
10289                          DAG.getVectorShuffle(NewVT, dl, V1, V2, WidenedMask));
10290     }
10291   }
10292
10293   int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
10294   for (int M : SVOp->getMask())
10295     if (M < 0)
10296       ++NumUndefElements;
10297     else if (M < NumElements)
10298       ++NumV1Elements;
10299     else
10300       ++NumV2Elements;
10301
10302   // Commute the shuffle as needed such that more elements come from V1 than
10303   // V2. This allows us to match the shuffle pattern strictly on how many
10304   // elements come from V1 without handling the symmetric cases.
10305   if (NumV2Elements > NumV1Elements)
10306     return DAG.getCommutedVectorShuffle(*SVOp);
10307
10308   // When the number of V1 and V2 elements are the same, try to minimize the
10309   // number of uses of V2 in the low half of the vector. When that is tied,
10310   // ensure that the sum of indices for V1 is equal to or lower than the sum
10311   // indices for V2. When those are equal, try to ensure that the number of odd
10312   // indices for V1 is lower than the number of odd indices for V2.
10313   if (NumV1Elements == NumV2Elements) {
10314     int LowV1Elements = 0, LowV2Elements = 0;
10315     for (int M : SVOp->getMask().slice(0, NumElements / 2))
10316       if (M >= NumElements)
10317         ++LowV2Elements;
10318       else if (M >= 0)
10319         ++LowV1Elements;
10320     if (LowV2Elements > LowV1Elements) {
10321       return DAG.getCommutedVectorShuffle(*SVOp);
10322     } else if (LowV2Elements == LowV1Elements) {
10323       int SumV1Indices = 0, SumV2Indices = 0;
10324       for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10325         if (SVOp->getMask()[i] >= NumElements)
10326           SumV2Indices += i;
10327         else if (SVOp->getMask()[i] >= 0)
10328           SumV1Indices += i;
10329       if (SumV2Indices < SumV1Indices) {
10330         return DAG.getCommutedVectorShuffle(*SVOp);
10331       } else if (SumV2Indices == SumV1Indices) {
10332         int NumV1OddIndices = 0, NumV2OddIndices = 0;
10333         for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10334           if (SVOp->getMask()[i] >= NumElements)
10335             NumV2OddIndices += i % 2;
10336           else if (SVOp->getMask()[i] >= 0)
10337             NumV1OddIndices += i % 2;
10338         if (NumV2OddIndices < NumV1OddIndices)
10339           return DAG.getCommutedVectorShuffle(*SVOp);
10340       }
10341     }
10342   }
10343
10344   // For each vector width, delegate to a specialized lowering routine.
10345   if (VT.getSizeInBits() == 128)
10346     return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10347
10348   if (VT.getSizeInBits() == 256)
10349     return lower256BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10350
10351   // Force AVX-512 vectors to be scalarized for now.
10352   // FIXME: Implement AVX-512 support!
10353   if (VT.getSizeInBits() == 512)
10354     return lower512BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10355
10356   llvm_unreachable("Unimplemented!");
10357 }
10358
10359 // This function assumes its argument is a BUILD_VECTOR of constants or
10360 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
10361 // true.
10362 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
10363                                     unsigned &MaskValue) {
10364   MaskValue = 0;
10365   unsigned NumElems = BuildVector->getNumOperands();
10366   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
10367   unsigned NumLanes = (NumElems - 1) / 8 + 1;
10368   unsigned NumElemsInLane = NumElems / NumLanes;
10369
10370   // Blend for v16i16 should be symetric for the both lanes.
10371   for (unsigned i = 0; i < NumElemsInLane; ++i) {
10372     SDValue EltCond = BuildVector->getOperand(i);
10373     SDValue SndLaneEltCond =
10374         (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
10375
10376     int Lane1Cond = -1, Lane2Cond = -1;
10377     if (isa<ConstantSDNode>(EltCond))
10378       Lane1Cond = !isZero(EltCond);
10379     if (isa<ConstantSDNode>(SndLaneEltCond))
10380       Lane2Cond = !isZero(SndLaneEltCond);
10381
10382     if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
10383       // Lane1Cond != 0, means we want the first argument.
10384       // Lane1Cond == 0, means we want the second argument.
10385       // The encoding of this argument is 0 for the first argument, 1
10386       // for the second. Therefore, invert the condition.
10387       MaskValue |= !Lane1Cond << i;
10388     else if (Lane1Cond < 0)
10389       MaskValue |= !Lane2Cond << i;
10390     else
10391       return false;
10392   }
10393   return true;
10394 }
10395
10396 /// \brief Try to lower a VSELECT instruction to a vector shuffle.
10397 static SDValue lowerVSELECTtoVectorShuffle(SDValue Op,
10398                                            const X86Subtarget *Subtarget,
10399                                            SelectionDAG &DAG) {
10400   SDValue Cond = Op.getOperand(0);
10401   SDValue LHS = Op.getOperand(1);
10402   SDValue RHS = Op.getOperand(2);
10403   SDLoc dl(Op);
10404   MVT VT = Op.getSimpleValueType();
10405
10406   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
10407     return SDValue();
10408   auto *CondBV = cast<BuildVectorSDNode>(Cond);
10409
10410   // Only non-legal VSELECTs reach this lowering, convert those into generic
10411   // shuffles and re-use the shuffle lowering path for blends.
10412   SmallVector<int, 32> Mask;
10413   for (int i = 0, Size = VT.getVectorNumElements(); i < Size; ++i) {
10414     SDValue CondElt = CondBV->getOperand(i);
10415     Mask.push_back(
10416         isa<ConstantSDNode>(CondElt) ? i + (isZero(CondElt) ? Size : 0) : -1);
10417   }
10418   return DAG.getVectorShuffle(VT, dl, LHS, RHS, Mask);
10419 }
10420
10421 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
10422   // A vselect where all conditions and data are constants can be optimized into
10423   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
10424   if (ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(0).getNode()) &&
10425       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(1).getNode()) &&
10426       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(2).getNode()))
10427     return SDValue();
10428
10429   // Try to lower this to a blend-style vector shuffle. This can handle all
10430   // constant condition cases.
10431   if (SDValue BlendOp = lowerVSELECTtoVectorShuffle(Op, Subtarget, DAG))
10432     return BlendOp;
10433
10434   // Variable blends are only legal from SSE4.1 onward.
10435   if (!Subtarget->hasSSE41())
10436     return SDValue();
10437
10438   // Only some types will be legal on some subtargets. If we can emit a legal
10439   // VSELECT-matching blend, return Op, and but if we need to expand, return
10440   // a null value.
10441   switch (Op.getSimpleValueType().SimpleTy) {
10442   default:
10443     // Most of the vector types have blends past SSE4.1.
10444     return Op;
10445
10446   case MVT::v32i8:
10447     // The byte blends for AVX vectors were introduced only in AVX2.
10448     if (Subtarget->hasAVX2())
10449       return Op;
10450
10451     return SDValue();
10452
10453   case MVT::v8i16:
10454   case MVT::v16i16:
10455     // AVX-512 BWI and VLX features support VSELECT with i16 elements.
10456     if (Subtarget->hasBWI() && Subtarget->hasVLX())
10457       return Op;
10458
10459     // FIXME: We should custom lower this by fixing the condition and using i8
10460     // blends.
10461     return SDValue();
10462   }
10463 }
10464
10465 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
10466   MVT VT = Op.getSimpleValueType();
10467   SDLoc dl(Op);
10468
10469   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
10470     return SDValue();
10471
10472   if (VT.getSizeInBits() == 8) {
10473     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
10474                                   Op.getOperand(0), Op.getOperand(1));
10475     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10476                                   DAG.getValueType(VT));
10477     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10478   }
10479
10480   if (VT.getSizeInBits() == 16) {
10481     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10482     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
10483     if (Idx == 0)
10484       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
10485                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10486                                      DAG.getNode(ISD::BITCAST, dl,
10487                                                  MVT::v4i32,
10488                                                  Op.getOperand(0)),
10489                                      Op.getOperand(1)));
10490     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
10491                                   Op.getOperand(0), Op.getOperand(1));
10492     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10493                                   DAG.getValueType(VT));
10494     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10495   }
10496
10497   if (VT == MVT::f32) {
10498     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
10499     // the result back to FR32 register. It's only worth matching if the
10500     // result has a single use which is a store or a bitcast to i32.  And in
10501     // the case of a store, it's not worth it if the index is a constant 0,
10502     // because a MOVSSmr can be used instead, which is smaller and faster.
10503     if (!Op.hasOneUse())
10504       return SDValue();
10505     SDNode *User = *Op.getNode()->use_begin();
10506     if ((User->getOpcode() != ISD::STORE ||
10507          (isa<ConstantSDNode>(Op.getOperand(1)) &&
10508           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
10509         (User->getOpcode() != ISD::BITCAST ||
10510          User->getValueType(0) != MVT::i32))
10511       return SDValue();
10512     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10513                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
10514                                               Op.getOperand(0)),
10515                                               Op.getOperand(1));
10516     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
10517   }
10518
10519   if (VT == MVT::i32 || VT == MVT::i64) {
10520     // ExtractPS/pextrq works with constant index.
10521     if (isa<ConstantSDNode>(Op.getOperand(1)))
10522       return Op;
10523   }
10524   return SDValue();
10525 }
10526
10527 /// Extract one bit from mask vector, like v16i1 or v8i1.
10528 /// AVX-512 feature.
10529 SDValue
10530 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
10531   SDValue Vec = Op.getOperand(0);
10532   SDLoc dl(Vec);
10533   MVT VecVT = Vec.getSimpleValueType();
10534   SDValue Idx = Op.getOperand(1);
10535   MVT EltVT = Op.getSimpleValueType();
10536
10537   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
10538   assert((VecVT.getVectorNumElements() <= 16 || Subtarget->hasBWI()) &&
10539          "Unexpected vector type in ExtractBitFromMaskVector");
10540
10541   // variable index can't be handled in mask registers,
10542   // extend vector to VR512
10543   if (!isa<ConstantSDNode>(Idx)) {
10544     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
10545     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
10546     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
10547                               ExtVT.getVectorElementType(), Ext, Idx);
10548     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
10549   }
10550
10551   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10552   const TargetRegisterClass* rc = getRegClassFor(VecVT);
10553   if (!Subtarget->hasDQI() && (VecVT.getVectorNumElements() <= 8))
10554     rc = getRegClassFor(MVT::v16i1);
10555   unsigned MaxSift = rc->getSize()*8 - 1;
10556   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
10557                     DAG.getConstant(MaxSift - IdxVal, dl, MVT::i8));
10558   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
10559                     DAG.getConstant(MaxSift, dl, MVT::i8));
10560   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
10561                        DAG.getIntPtrConstant(0, dl));
10562 }
10563
10564 SDValue
10565 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
10566                                            SelectionDAG &DAG) const {
10567   SDLoc dl(Op);
10568   SDValue Vec = Op.getOperand(0);
10569   MVT VecVT = Vec.getSimpleValueType();
10570   SDValue Idx = Op.getOperand(1);
10571
10572   if (Op.getSimpleValueType() == MVT::i1)
10573     return ExtractBitFromMaskVector(Op, DAG);
10574
10575   if (!isa<ConstantSDNode>(Idx)) {
10576     if (VecVT.is512BitVector() ||
10577         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
10578          VecVT.getVectorElementType().getSizeInBits() == 32)) {
10579
10580       MVT MaskEltVT =
10581         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
10582       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
10583                                     MaskEltVT.getSizeInBits());
10584
10585       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
10586       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
10587                                 getZeroVector(MaskVT, Subtarget, DAG, dl),
10588                                 Idx, DAG.getConstant(0, dl, getPointerTy()));
10589       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
10590       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
10591                         Perm, DAG.getConstant(0, dl, getPointerTy()));
10592     }
10593     return SDValue();
10594   }
10595
10596   // If this is a 256-bit vector result, first extract the 128-bit vector and
10597   // then extract the element from the 128-bit vector.
10598   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
10599
10600     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10601     // Get the 128-bit vector.
10602     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
10603     MVT EltVT = VecVT.getVectorElementType();
10604
10605     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
10606
10607     //if (IdxVal >= NumElems/2)
10608     //  IdxVal -= NumElems/2;
10609     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
10610     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
10611                        DAG.getConstant(IdxVal, dl, MVT::i32));
10612   }
10613
10614   assert(VecVT.is128BitVector() && "Unexpected vector length");
10615
10616   if (Subtarget->hasSSE41()) {
10617     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
10618     if (Res.getNode())
10619       return Res;
10620   }
10621
10622   MVT VT = Op.getSimpleValueType();
10623   // TODO: handle v16i8.
10624   if (VT.getSizeInBits() == 16) {
10625     SDValue Vec = Op.getOperand(0);
10626     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10627     if (Idx == 0)
10628       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
10629                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10630                                      DAG.getNode(ISD::BITCAST, dl,
10631                                                  MVT::v4i32, Vec),
10632                                      Op.getOperand(1)));
10633     // Transform it so it match pextrw which produces a 32-bit result.
10634     MVT EltVT = MVT::i32;
10635     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
10636                                   Op.getOperand(0), Op.getOperand(1));
10637     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
10638                                   DAG.getValueType(VT));
10639     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10640   }
10641
10642   if (VT.getSizeInBits() == 32) {
10643     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10644     if (Idx == 0)
10645       return Op;
10646
10647     // SHUFPS the element to the lowest double word, then movss.
10648     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
10649     MVT VVT = Op.getOperand(0).getSimpleValueType();
10650     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10651                                        DAG.getUNDEF(VVT), Mask);
10652     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10653                        DAG.getIntPtrConstant(0, dl));
10654   }
10655
10656   if (VT.getSizeInBits() == 64) {
10657     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
10658     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
10659     //        to match extract_elt for f64.
10660     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10661     if (Idx == 0)
10662       return Op;
10663
10664     // UNPCKHPD the element to the lowest double word, then movsd.
10665     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
10666     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
10667     int Mask[2] = { 1, -1 };
10668     MVT VVT = Op.getOperand(0).getSimpleValueType();
10669     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10670                                        DAG.getUNDEF(VVT), Mask);
10671     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10672                        DAG.getIntPtrConstant(0, dl));
10673   }
10674
10675   return SDValue();
10676 }
10677
10678 /// Insert one bit to mask vector, like v16i1 or v8i1.
10679 /// AVX-512 feature.
10680 SDValue
10681 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
10682   SDLoc dl(Op);
10683   SDValue Vec = Op.getOperand(0);
10684   SDValue Elt = Op.getOperand(1);
10685   SDValue Idx = Op.getOperand(2);
10686   MVT VecVT = Vec.getSimpleValueType();
10687
10688   if (!isa<ConstantSDNode>(Idx)) {
10689     // Non constant index. Extend source and destination,
10690     // insert element and then truncate the result.
10691     MVT ExtVecVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
10692     MVT ExtEltVT = (VecVT == MVT::v8i1 ?  MVT::i64 : MVT::i32);
10693     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
10694       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
10695       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
10696     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
10697   }
10698
10699   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10700   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
10701   if (IdxVal)
10702     EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
10703                            DAG.getConstant(IdxVal, dl, MVT::i8));
10704   if (Vec.getOpcode() == ISD::UNDEF)
10705     return EltInVec;
10706   return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
10707 }
10708
10709 SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
10710                                                   SelectionDAG &DAG) const {
10711   MVT VT = Op.getSimpleValueType();
10712   MVT EltVT = VT.getVectorElementType();
10713
10714   if (EltVT == MVT::i1)
10715     return InsertBitToMaskVector(Op, DAG);
10716
10717   SDLoc dl(Op);
10718   SDValue N0 = Op.getOperand(0);
10719   SDValue N1 = Op.getOperand(1);
10720   SDValue N2 = Op.getOperand(2);
10721   if (!isa<ConstantSDNode>(N2))
10722     return SDValue();
10723   auto *N2C = cast<ConstantSDNode>(N2);
10724   unsigned IdxVal = N2C->getZExtValue();
10725
10726   // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
10727   // into that, and then insert the subvector back into the result.
10728   if (VT.is256BitVector() || VT.is512BitVector()) {
10729     // With a 256-bit vector, we can insert into the zero element efficiently
10730     // using a blend if we have AVX or AVX2 and the right data type.
10731     if (VT.is256BitVector() && IdxVal == 0) {
10732       // TODO: It is worthwhile to cast integer to floating point and back
10733       // and incur a domain crossing penalty if that's what we'll end up
10734       // doing anyway after extracting to a 128-bit vector.
10735       if ((Subtarget->hasAVX() && (EltVT == MVT::f64 || EltVT == MVT::f32)) ||
10736           (Subtarget->hasAVX2() && EltVT == MVT::i32)) {
10737         SDValue N1Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, N1);
10738         N2 = DAG.getIntPtrConstant(1, dl);
10739         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1Vec, N2);
10740       }
10741     }
10742
10743     // Get the desired 128-bit vector chunk.
10744     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
10745
10746     // Insert the element into the desired chunk.
10747     unsigned NumEltsIn128 = 128 / EltVT.getSizeInBits();
10748     unsigned IdxIn128 = IdxVal - (IdxVal / NumEltsIn128) * NumEltsIn128;
10749
10750     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
10751                     DAG.getConstant(IdxIn128, dl, MVT::i32));
10752
10753     // Insert the changed part back into the bigger vector
10754     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
10755   }
10756   assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
10757
10758   if (Subtarget->hasSSE41()) {
10759     if (EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) {
10760       unsigned Opc;
10761       if (VT == MVT::v8i16) {
10762         Opc = X86ISD::PINSRW;
10763       } else {
10764         assert(VT == MVT::v16i8);
10765         Opc = X86ISD::PINSRB;
10766       }
10767
10768       // Transform it so it match pinsr{b,w} which expects a GR32 as its second
10769       // argument.
10770       if (N1.getValueType() != MVT::i32)
10771         N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
10772       if (N2.getValueType() != MVT::i32)
10773         N2 = DAG.getIntPtrConstant(IdxVal, dl);
10774       return DAG.getNode(Opc, dl, VT, N0, N1, N2);
10775     }
10776
10777     if (EltVT == MVT::f32) {
10778       // Bits [7:6] of the constant are the source select. This will always be
10779       //   zero here. The DAG Combiner may combine an extract_elt index into
10780       //   these bits. For example (insert (extract, 3), 2) could be matched by
10781       //   putting the '3' into bits [7:6] of X86ISD::INSERTPS.
10782       // Bits [5:4] of the constant are the destination select. This is the
10783       //   value of the incoming immediate.
10784       // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
10785       //   combine either bitwise AND or insert of float 0.0 to set these bits.
10786
10787       const Function *F = DAG.getMachineFunction().getFunction();
10788       bool MinSize = F->hasFnAttribute(Attribute::MinSize);
10789       if (IdxVal == 0 && (!MinSize || !MayFoldLoad(N1))) {
10790         // If this is an insertion of 32-bits into the low 32-bits of
10791         // a vector, we prefer to generate a blend with immediate rather
10792         // than an insertps. Blends are simpler operations in hardware and so
10793         // will always have equal or better performance than insertps.
10794         // But if optimizing for size and there's a load folding opportunity,
10795         // generate insertps because blendps does not have a 32-bit memory
10796         // operand form.
10797         N2 = DAG.getIntPtrConstant(1, dl);
10798         N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
10799         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1, N2);
10800       }
10801       N2 = DAG.getIntPtrConstant(IdxVal << 4, dl);
10802       // Create this as a scalar to vector..
10803       N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
10804       return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
10805     }
10806
10807     if (EltVT == MVT::i32 || EltVT == MVT::i64) {
10808       // PINSR* works with constant index.
10809       return Op;
10810     }
10811   }
10812
10813   if (EltVT == MVT::i8)
10814     return SDValue();
10815
10816   if (EltVT.getSizeInBits() == 16) {
10817     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
10818     // as its second argument.
10819     if (N1.getValueType() != MVT::i32)
10820       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
10821     if (N2.getValueType() != MVT::i32)
10822       N2 = DAG.getIntPtrConstant(IdxVal, dl);
10823     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
10824   }
10825   return SDValue();
10826 }
10827
10828 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
10829   SDLoc dl(Op);
10830   MVT OpVT = Op.getSimpleValueType();
10831
10832   // If this is a 256-bit vector result, first insert into a 128-bit
10833   // vector and then insert into the 256-bit vector.
10834   if (!OpVT.is128BitVector()) {
10835     // Insert into a 128-bit vector.
10836     unsigned SizeFactor = OpVT.getSizeInBits()/128;
10837     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
10838                                  OpVT.getVectorNumElements() / SizeFactor);
10839
10840     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
10841
10842     // Insert the 128-bit vector.
10843     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
10844   }
10845
10846   if (OpVT == MVT::v1i64 &&
10847       Op.getOperand(0).getValueType() == MVT::i64)
10848     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
10849
10850   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
10851   assert(OpVT.is128BitVector() && "Expected an SSE type!");
10852   return DAG.getNode(ISD::BITCAST, dl, OpVT,
10853                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
10854 }
10855
10856 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
10857 // a simple subregister reference or explicit instructions to grab
10858 // upper bits of a vector.
10859 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10860                                       SelectionDAG &DAG) {
10861   SDLoc dl(Op);
10862   SDValue In =  Op.getOperand(0);
10863   SDValue Idx = Op.getOperand(1);
10864   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10865   MVT ResVT   = Op.getSimpleValueType();
10866   MVT InVT    = In.getSimpleValueType();
10867
10868   if (Subtarget->hasFp256()) {
10869     if (ResVT.is128BitVector() &&
10870         (InVT.is256BitVector() || InVT.is512BitVector()) &&
10871         isa<ConstantSDNode>(Idx)) {
10872       return Extract128BitVector(In, IdxVal, DAG, dl);
10873     }
10874     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
10875         isa<ConstantSDNode>(Idx)) {
10876       return Extract256BitVector(In, IdxVal, DAG, dl);
10877     }
10878   }
10879   return SDValue();
10880 }
10881
10882 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
10883 // simple superregister reference or explicit instructions to insert
10884 // the upper bits of a vector.
10885 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10886                                      SelectionDAG &DAG) {
10887   if (!Subtarget->hasAVX())
10888     return SDValue();
10889
10890   SDLoc dl(Op);
10891   SDValue Vec = Op.getOperand(0);
10892   SDValue SubVec = Op.getOperand(1);
10893   SDValue Idx = Op.getOperand(2);
10894
10895   if (!isa<ConstantSDNode>(Idx))
10896     return SDValue();
10897
10898   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10899   MVT OpVT = Op.getSimpleValueType();
10900   MVT SubVecVT = SubVec.getSimpleValueType();
10901
10902   // Fold two 16-byte subvector loads into one 32-byte load:
10903   // (insert_subvector (insert_subvector undef, (load addr), 0),
10904   //                   (load addr + 16), Elts/2)
10905   // --> load32 addr
10906   if ((IdxVal == OpVT.getVectorNumElements() / 2) &&
10907       Vec.getOpcode() == ISD::INSERT_SUBVECTOR &&
10908       OpVT.is256BitVector() && SubVecVT.is128BitVector() &&
10909       !Subtarget->isUnalignedMem32Slow()) {
10910     SDValue SubVec2 = Vec.getOperand(1);
10911     if (auto *Idx2 = dyn_cast<ConstantSDNode>(Vec.getOperand(2))) {
10912       if (Idx2->getZExtValue() == 0) {
10913         SDValue Ops[] = { SubVec2, SubVec };
10914         SDValue LD = EltsFromConsecutiveLoads(OpVT, Ops, dl, DAG, false);
10915         if (LD.getNode())
10916           return LD;
10917       }
10918     }
10919   }
10920
10921   if ((OpVT.is256BitVector() || OpVT.is512BitVector()) &&
10922       SubVecVT.is128BitVector())
10923     return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
10924
10925   if (OpVT.is512BitVector() && SubVecVT.is256BitVector())
10926     return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
10927
10928   if (OpVT.getVectorElementType() == MVT::i1) {
10929     if (IdxVal == 0  && Vec.getOpcode() == ISD::UNDEF) // the operation is legal
10930       return Op;
10931     SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
10932     SDValue Undef = DAG.getUNDEF(OpVT);
10933     unsigned NumElems = OpVT.getVectorNumElements();
10934     SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
10935
10936     if (IdxVal == OpVT.getVectorNumElements() / 2) {
10937       // Zero upper bits of the Vec
10938       Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
10939       Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
10940
10941       SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
10942                                  SubVec, ZeroIdx);
10943       Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
10944       return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
10945     }
10946     if (IdxVal == 0) {
10947       SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
10948                                  SubVec, ZeroIdx);
10949       // Zero upper bits of the Vec2
10950       Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
10951       Vec2 = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec2, ShiftBits);
10952       // Zero lower bits of the Vec
10953       Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
10954       Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
10955       // Merge them together
10956       return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
10957     }
10958   }
10959   return SDValue();
10960 }
10961
10962 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
10963 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
10964 // one of the above mentioned nodes. It has to be wrapped because otherwise
10965 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
10966 // be used to form addressing mode. These wrapped nodes will be selected
10967 // into MOV32ri.
10968 SDValue
10969 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
10970   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
10971
10972   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10973   // global base reg.
10974   unsigned char OpFlag = 0;
10975   unsigned WrapperKind = X86ISD::Wrapper;
10976   CodeModel::Model M = DAG.getTarget().getCodeModel();
10977
10978   if (Subtarget->isPICStyleRIPRel() &&
10979       (M == CodeModel::Small || M == CodeModel::Kernel))
10980     WrapperKind = X86ISD::WrapperRIP;
10981   else if (Subtarget->isPICStyleGOT())
10982     OpFlag = X86II::MO_GOTOFF;
10983   else if (Subtarget->isPICStyleStubPIC())
10984     OpFlag = X86II::MO_PIC_BASE_OFFSET;
10985
10986   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
10987                                              CP->getAlignment(),
10988                                              CP->getOffset(), OpFlag);
10989   SDLoc DL(CP);
10990   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10991   // With PIC, the address is actually $g + Offset.
10992   if (OpFlag) {
10993     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10994                          DAG.getNode(X86ISD::GlobalBaseReg,
10995                                      SDLoc(), getPointerTy()),
10996                          Result);
10997   }
10998
10999   return Result;
11000 }
11001
11002 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
11003   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
11004
11005   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11006   // global base reg.
11007   unsigned char OpFlag = 0;
11008   unsigned WrapperKind = X86ISD::Wrapper;
11009   CodeModel::Model M = DAG.getTarget().getCodeModel();
11010
11011   if (Subtarget->isPICStyleRIPRel() &&
11012       (M == CodeModel::Small || M == CodeModel::Kernel))
11013     WrapperKind = X86ISD::WrapperRIP;
11014   else if (Subtarget->isPICStyleGOT())
11015     OpFlag = X86II::MO_GOTOFF;
11016   else if (Subtarget->isPICStyleStubPIC())
11017     OpFlag = X86II::MO_PIC_BASE_OFFSET;
11018
11019   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
11020                                           OpFlag);
11021   SDLoc DL(JT);
11022   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
11023
11024   // With PIC, the address is actually $g + Offset.
11025   if (OpFlag)
11026     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11027                          DAG.getNode(X86ISD::GlobalBaseReg,
11028                                      SDLoc(), getPointerTy()),
11029                          Result);
11030
11031   return Result;
11032 }
11033
11034 SDValue
11035 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
11036   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
11037
11038   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11039   // global base reg.
11040   unsigned char OpFlag = 0;
11041   unsigned WrapperKind = X86ISD::Wrapper;
11042   CodeModel::Model M = DAG.getTarget().getCodeModel();
11043
11044   if (Subtarget->isPICStyleRIPRel() &&
11045       (M == CodeModel::Small || M == CodeModel::Kernel)) {
11046     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
11047       OpFlag = X86II::MO_GOTPCREL;
11048     WrapperKind = X86ISD::WrapperRIP;
11049   } else if (Subtarget->isPICStyleGOT()) {
11050     OpFlag = X86II::MO_GOT;
11051   } else if (Subtarget->isPICStyleStubPIC()) {
11052     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
11053   } else if (Subtarget->isPICStyleStubNoDynamic()) {
11054     OpFlag = X86II::MO_DARWIN_NONLAZY;
11055   }
11056
11057   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
11058
11059   SDLoc DL(Op);
11060   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
11061
11062   // With PIC, the address is actually $g + Offset.
11063   if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
11064       !Subtarget->is64Bit()) {
11065     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11066                          DAG.getNode(X86ISD::GlobalBaseReg,
11067                                      SDLoc(), getPointerTy()),
11068                          Result);
11069   }
11070
11071   // For symbols that require a load from a stub to get the address, emit the
11072   // load.
11073   if (isGlobalStubReference(OpFlag))
11074     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
11075                          MachinePointerInfo::getGOT(), false, false, false, 0);
11076
11077   return Result;
11078 }
11079
11080 SDValue
11081 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
11082   // Create the TargetBlockAddressAddress node.
11083   unsigned char OpFlags =
11084     Subtarget->ClassifyBlockAddressReference();
11085   CodeModel::Model M = DAG.getTarget().getCodeModel();
11086   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
11087   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
11088   SDLoc dl(Op);
11089   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
11090                                              OpFlags);
11091
11092   if (Subtarget->isPICStyleRIPRel() &&
11093       (M == CodeModel::Small || M == CodeModel::Kernel))
11094     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
11095   else
11096     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
11097
11098   // With PIC, the address is actually $g + Offset.
11099   if (isGlobalRelativeToPICBase(OpFlags)) {
11100     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
11101                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
11102                          Result);
11103   }
11104
11105   return Result;
11106 }
11107
11108 SDValue
11109 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
11110                                       int64_t Offset, SelectionDAG &DAG) const {
11111   // Create the TargetGlobalAddress node, folding in the constant
11112   // offset if it is legal.
11113   unsigned char OpFlags =
11114       Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
11115   CodeModel::Model M = DAG.getTarget().getCodeModel();
11116   SDValue Result;
11117   if (OpFlags == X86II::MO_NO_FLAG &&
11118       X86::isOffsetSuitableForCodeModel(Offset, M)) {
11119     // A direct static reference to a global.
11120     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
11121     Offset = 0;
11122   } else {
11123     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
11124   }
11125
11126   if (Subtarget->isPICStyleRIPRel() &&
11127       (M == CodeModel::Small || M == CodeModel::Kernel))
11128     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
11129   else
11130     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
11131
11132   // With PIC, the address is actually $g + Offset.
11133   if (isGlobalRelativeToPICBase(OpFlags)) {
11134     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
11135                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
11136                          Result);
11137   }
11138
11139   // For globals that require a load from a stub to get the address, emit the
11140   // load.
11141   if (isGlobalStubReference(OpFlags))
11142     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
11143                          MachinePointerInfo::getGOT(), false, false, false, 0);
11144
11145   // If there was a non-zero offset that we didn't fold, create an explicit
11146   // addition for it.
11147   if (Offset != 0)
11148     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
11149                          DAG.getConstant(Offset, dl, getPointerTy()));
11150
11151   return Result;
11152 }
11153
11154 SDValue
11155 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
11156   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
11157   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
11158   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
11159 }
11160
11161 static SDValue
11162 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
11163            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
11164            unsigned char OperandFlags, bool LocalDynamic = false) {
11165   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11166   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11167   SDLoc dl(GA);
11168   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11169                                            GA->getValueType(0),
11170                                            GA->getOffset(),
11171                                            OperandFlags);
11172
11173   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
11174                                            : X86ISD::TLSADDR;
11175
11176   if (InFlag) {
11177     SDValue Ops[] = { Chain,  TGA, *InFlag };
11178     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11179   } else {
11180     SDValue Ops[]  = { Chain, TGA };
11181     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11182   }
11183
11184   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
11185   MFI->setAdjustsStack(true);
11186   MFI->setHasCalls(true);
11187
11188   SDValue Flag = Chain.getValue(1);
11189   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
11190 }
11191
11192 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
11193 static SDValue
11194 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11195                                 const EVT PtrVT) {
11196   SDValue InFlag;
11197   SDLoc dl(GA);  // ? function entry point might be better
11198   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11199                                    DAG.getNode(X86ISD::GlobalBaseReg,
11200                                                SDLoc(), PtrVT), InFlag);
11201   InFlag = Chain.getValue(1);
11202
11203   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
11204 }
11205
11206 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
11207 static SDValue
11208 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11209                                 const EVT PtrVT) {
11210   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
11211                     X86::RAX, X86II::MO_TLSGD);
11212 }
11213
11214 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
11215                                            SelectionDAG &DAG,
11216                                            const EVT PtrVT,
11217                                            bool is64Bit) {
11218   SDLoc dl(GA);
11219
11220   // Get the start address of the TLS block for this module.
11221   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
11222       .getInfo<X86MachineFunctionInfo>();
11223   MFI->incNumLocalDynamicTLSAccesses();
11224
11225   SDValue Base;
11226   if (is64Bit) {
11227     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
11228                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
11229   } else {
11230     SDValue InFlag;
11231     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11232         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
11233     InFlag = Chain.getValue(1);
11234     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
11235                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
11236   }
11237
11238   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
11239   // of Base.
11240
11241   // Build x@dtpoff.
11242   unsigned char OperandFlags = X86II::MO_DTPOFF;
11243   unsigned WrapperKind = X86ISD::Wrapper;
11244   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11245                                            GA->getValueType(0),
11246                                            GA->getOffset(), OperandFlags);
11247   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11248
11249   // Add x@dtpoff with the base.
11250   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
11251 }
11252
11253 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
11254 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11255                                    const EVT PtrVT, TLSModel::Model model,
11256                                    bool is64Bit, bool isPIC) {
11257   SDLoc dl(GA);
11258
11259   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
11260   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
11261                                                          is64Bit ? 257 : 256));
11262
11263   SDValue ThreadPointer =
11264       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0, dl),
11265                   MachinePointerInfo(Ptr), false, false, false, 0);
11266
11267   unsigned char OperandFlags = 0;
11268   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
11269   // initialexec.
11270   unsigned WrapperKind = X86ISD::Wrapper;
11271   if (model == TLSModel::LocalExec) {
11272     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
11273   } else if (model == TLSModel::InitialExec) {
11274     if (is64Bit) {
11275       OperandFlags = X86II::MO_GOTTPOFF;
11276       WrapperKind = X86ISD::WrapperRIP;
11277     } else {
11278       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
11279     }
11280   } else {
11281     llvm_unreachable("Unexpected model");
11282   }
11283
11284   // emit "addl x@ntpoff,%eax" (local exec)
11285   // or "addl x@indntpoff,%eax" (initial exec)
11286   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
11287   SDValue TGA =
11288       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
11289                                  GA->getOffset(), OperandFlags);
11290   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11291
11292   if (model == TLSModel::InitialExec) {
11293     if (isPIC && !is64Bit) {
11294       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
11295                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
11296                            Offset);
11297     }
11298
11299     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
11300                          MachinePointerInfo::getGOT(), false, false, false, 0);
11301   }
11302
11303   // The address of the thread local variable is the add of the thread
11304   // pointer with the offset of the variable.
11305   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
11306 }
11307
11308 SDValue
11309 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
11310
11311   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
11312   const GlobalValue *GV = GA->getGlobal();
11313
11314   if (Subtarget->isTargetELF()) {
11315     TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
11316     switch (model) {
11317       case TLSModel::GeneralDynamic:
11318         if (Subtarget->is64Bit())
11319           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
11320         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
11321       case TLSModel::LocalDynamic:
11322         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
11323                                            Subtarget->is64Bit());
11324       case TLSModel::InitialExec:
11325       case TLSModel::LocalExec:
11326         return LowerToTLSExecModel(
11327             GA, DAG, getPointerTy(), model, Subtarget->is64Bit(),
11328             DAG.getTarget().getRelocationModel() == Reloc::PIC_);
11329     }
11330     llvm_unreachable("Unknown TLS model.");
11331   }
11332
11333   if (Subtarget->isTargetDarwin()) {
11334     // Darwin only has one model of TLS.  Lower to that.
11335     unsigned char OpFlag = 0;
11336     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
11337                            X86ISD::WrapperRIP : X86ISD::Wrapper;
11338
11339     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11340     // global base reg.
11341     bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
11342                  !Subtarget->is64Bit();
11343     if (PIC32)
11344       OpFlag = X86II::MO_TLVP_PIC_BASE;
11345     else
11346       OpFlag = X86II::MO_TLVP;
11347     SDLoc DL(Op);
11348     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
11349                                                 GA->getValueType(0),
11350                                                 GA->getOffset(), OpFlag);
11351     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
11352
11353     // With PIC32, the address is actually $g + Offset.
11354     if (PIC32)
11355       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11356                            DAG.getNode(X86ISD::GlobalBaseReg,
11357                                        SDLoc(), getPointerTy()),
11358                            Offset);
11359
11360     // Lowering the machine isd will make sure everything is in the right
11361     // location.
11362     SDValue Chain = DAG.getEntryNode();
11363     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11364     SDValue Args[] = { Chain, Offset };
11365     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
11366
11367     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
11368     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11369     MFI->setAdjustsStack(true);
11370
11371     // And our return value (tls address) is in the standard call return value
11372     // location.
11373     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11374     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
11375                               Chain.getValue(1));
11376   }
11377
11378   if (Subtarget->isTargetKnownWindowsMSVC() ||
11379       Subtarget->isTargetWindowsGNU()) {
11380     // Just use the implicit TLS architecture
11381     // Need to generate someting similar to:
11382     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
11383     //                                  ; from TEB
11384     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
11385     //   mov     rcx, qword [rdx+rcx*8]
11386     //   mov     eax, .tls$:tlsvar
11387     //   [rax+rcx] contains the address
11388     // Windows 64bit: gs:0x58
11389     // Windows 32bit: fs:__tls_array
11390
11391     SDLoc dl(GA);
11392     SDValue Chain = DAG.getEntryNode();
11393
11394     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
11395     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
11396     // use its literal value of 0x2C.
11397     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
11398                                         ? Type::getInt8PtrTy(*DAG.getContext(),
11399                                                              256)
11400                                         : Type::getInt32PtrTy(*DAG.getContext(),
11401                                                               257));
11402
11403     SDValue TlsArray =
11404         Subtarget->is64Bit()
11405             ? DAG.getIntPtrConstant(0x58, dl)
11406             : (Subtarget->isTargetWindowsGNU()
11407                    ? DAG.getIntPtrConstant(0x2C, dl)
11408                    : DAG.getExternalSymbol("_tls_array", getPointerTy()));
11409
11410     SDValue ThreadPointer =
11411         DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
11412                     MachinePointerInfo(Ptr), false, false, false, 0);
11413
11414     SDValue res;
11415     if (GV->getThreadLocalMode() == GlobalVariable::LocalExecTLSModel) {
11416       res = ThreadPointer;
11417     } else {
11418       // Load the _tls_index variable
11419       SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
11420       if (Subtarget->is64Bit())
11421         IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain, IDX,
11422                              MachinePointerInfo(), MVT::i32, false, false,
11423                              false, 0);
11424       else
11425         IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
11426                           false, false, false, 0);
11427
11428       SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()), dl,
11429                                       getPointerTy());
11430       IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
11431
11432       res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
11433     }
11434
11435     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
11436                       false, false, false, 0);
11437
11438     // Get the offset of start of .tls section
11439     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11440                                              GA->getValueType(0),
11441                                              GA->getOffset(), X86II::MO_SECREL);
11442     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
11443
11444     // The address of the thread local variable is the add of the thread
11445     // pointer with the offset of the variable.
11446     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
11447   }
11448
11449   llvm_unreachable("TLS not implemented for this target.");
11450 }
11451
11452 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
11453 /// and take a 2 x i32 value to shift plus a shift amount.
11454 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
11455   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
11456   MVT VT = Op.getSimpleValueType();
11457   unsigned VTBits = VT.getSizeInBits();
11458   SDLoc dl(Op);
11459   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
11460   SDValue ShOpLo = Op.getOperand(0);
11461   SDValue ShOpHi = Op.getOperand(1);
11462   SDValue ShAmt  = Op.getOperand(2);
11463   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
11464   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
11465   // during isel.
11466   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11467                                   DAG.getConstant(VTBits - 1, dl, MVT::i8));
11468   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
11469                                      DAG.getConstant(VTBits - 1, dl, MVT::i8))
11470                        : DAG.getConstant(0, dl, VT);
11471
11472   SDValue Tmp2, Tmp3;
11473   if (Op.getOpcode() == ISD::SHL_PARTS) {
11474     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
11475     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
11476   } else {
11477     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
11478     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
11479   }
11480
11481   // If the shift amount is larger or equal than the width of a part we can't
11482   // rely on the results of shld/shrd. Insert a test and select the appropriate
11483   // values for large shift amounts.
11484   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11485                                 DAG.getConstant(VTBits, dl, MVT::i8));
11486   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11487                              AndNode, DAG.getConstant(0, dl, MVT::i8));
11488
11489   SDValue Hi, Lo;
11490   SDValue CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
11491   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
11492   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
11493
11494   if (Op.getOpcode() == ISD::SHL_PARTS) {
11495     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11496     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11497   } else {
11498     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11499     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11500   }
11501
11502   SDValue Ops[2] = { Lo, Hi };
11503   return DAG.getMergeValues(Ops, dl);
11504 }
11505
11506 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
11507                                            SelectionDAG &DAG) const {
11508   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
11509   SDLoc dl(Op);
11510
11511   if (SrcVT.isVector()) {
11512     if (SrcVT.getVectorElementType() == MVT::i1) {
11513       MVT IntegerVT = MVT::getVectorVT(MVT::i32, SrcVT.getVectorNumElements());
11514       return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
11515                          DAG.getNode(ISD::SIGN_EXTEND, dl, IntegerVT,
11516                                      Op.getOperand(0)));
11517     }
11518     return SDValue();
11519   }
11520
11521   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
11522          "Unknown SINT_TO_FP to lower!");
11523
11524   // These are really Legal; return the operand so the caller accepts it as
11525   // Legal.
11526   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
11527     return Op;
11528   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
11529       Subtarget->is64Bit()) {
11530     return Op;
11531   }
11532
11533   unsigned Size = SrcVT.getSizeInBits()/8;
11534   MachineFunction &MF = DAG.getMachineFunction();
11535   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
11536   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11537   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11538                                StackSlot,
11539                                MachinePointerInfo::getFixedStack(SSFI),
11540                                false, false, 0);
11541   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
11542 }
11543
11544 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
11545                                      SDValue StackSlot,
11546                                      SelectionDAG &DAG) const {
11547   // Build the FILD
11548   SDLoc DL(Op);
11549   SDVTList Tys;
11550   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
11551   if (useSSE)
11552     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
11553   else
11554     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
11555
11556   unsigned ByteSize = SrcVT.getSizeInBits()/8;
11557
11558   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
11559   MachineMemOperand *MMO;
11560   if (FI) {
11561     int SSFI = FI->getIndex();
11562     MMO =
11563       DAG.getMachineFunction()
11564       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11565                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
11566   } else {
11567     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
11568     StackSlot = StackSlot.getOperand(1);
11569   }
11570   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
11571   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
11572                                            X86ISD::FILD, DL,
11573                                            Tys, Ops, SrcVT, MMO);
11574
11575   if (useSSE) {
11576     Chain = Result.getValue(1);
11577     SDValue InFlag = Result.getValue(2);
11578
11579     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
11580     // shouldn't be necessary except that RFP cannot be live across
11581     // multiple blocks. When stackifier is fixed, they can be uncoupled.
11582     MachineFunction &MF = DAG.getMachineFunction();
11583     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
11584     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
11585     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11586     Tys = DAG.getVTList(MVT::Other);
11587     SDValue Ops[] = {
11588       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
11589     };
11590     MachineMemOperand *MMO =
11591       DAG.getMachineFunction()
11592       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11593                             MachineMemOperand::MOStore, SSFISize, SSFISize);
11594
11595     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
11596                                     Ops, Op.getValueType(), MMO);
11597     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
11598                          MachinePointerInfo::getFixedStack(SSFI),
11599                          false, false, false, 0);
11600   }
11601
11602   return Result;
11603 }
11604
11605 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
11606 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
11607                                                SelectionDAG &DAG) const {
11608   // This algorithm is not obvious. Here it is what we're trying to output:
11609   /*
11610      movq       %rax,  %xmm0
11611      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
11612      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
11613      #ifdef __SSE3__
11614        haddpd   %xmm0, %xmm0
11615      #else
11616        pshufd   $0x4e, %xmm0, %xmm1
11617        addpd    %xmm1, %xmm0
11618      #endif
11619   */
11620
11621   SDLoc dl(Op);
11622   LLVMContext *Context = DAG.getContext();
11623
11624   // Build some magic constants.
11625   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
11626   Constant *C0 = ConstantDataVector::get(*Context, CV0);
11627   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
11628
11629   SmallVector<Constant*,2> CV1;
11630   CV1.push_back(
11631     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11632                                       APInt(64, 0x4330000000000000ULL))));
11633   CV1.push_back(
11634     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11635                                       APInt(64, 0x4530000000000000ULL))));
11636   Constant *C1 = ConstantVector::get(CV1);
11637   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
11638
11639   // Load the 64-bit value into an XMM register.
11640   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
11641                             Op.getOperand(0));
11642   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
11643                               MachinePointerInfo::getConstantPool(),
11644                               false, false, false, 16);
11645   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
11646                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
11647                               CLod0);
11648
11649   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
11650                               MachinePointerInfo::getConstantPool(),
11651                               false, false, false, 16);
11652   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
11653   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
11654   SDValue Result;
11655
11656   if (Subtarget->hasSSE3()) {
11657     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
11658     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
11659   } else {
11660     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
11661     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
11662                                            S2F, 0x4E, DAG);
11663     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
11664                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
11665                          Sub);
11666   }
11667
11668   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
11669                      DAG.getIntPtrConstant(0, dl));
11670 }
11671
11672 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
11673 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
11674                                                SelectionDAG &DAG) const {
11675   SDLoc dl(Op);
11676   // FP constant to bias correct the final result.
11677   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
11678                                    MVT::f64);
11679
11680   // Load the 32-bit value into an XMM register.
11681   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
11682                              Op.getOperand(0));
11683
11684   // Zero out the upper parts of the register.
11685   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
11686
11687   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11688                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
11689                      DAG.getIntPtrConstant(0, dl));
11690
11691   // Or the load with the bias.
11692   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
11693                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
11694                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
11695                                                    MVT::v2f64, Load)),
11696                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
11697                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
11698                                                    MVT::v2f64, Bias)));
11699   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11700                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
11701                    DAG.getIntPtrConstant(0, dl));
11702
11703   // Subtract the bias.
11704   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
11705
11706   // Handle final rounding.
11707   EVT DestVT = Op.getValueType();
11708
11709   if (DestVT.bitsLT(MVT::f64))
11710     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
11711                        DAG.getIntPtrConstant(0, dl));
11712   if (DestVT.bitsGT(MVT::f64))
11713     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
11714
11715   // Handle final rounding.
11716   return Sub;
11717 }
11718
11719 static SDValue lowerUINT_TO_FP_vXi32(SDValue Op, SelectionDAG &DAG,
11720                                      const X86Subtarget &Subtarget) {
11721   // The algorithm is the following:
11722   // #ifdef __SSE4_1__
11723   //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
11724   //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
11725   //                                 (uint4) 0x53000000, 0xaa);
11726   // #else
11727   //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
11728   //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
11729   // #endif
11730   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
11731   //     return (float4) lo + fhi;
11732
11733   SDLoc DL(Op);
11734   SDValue V = Op->getOperand(0);
11735   EVT VecIntVT = V.getValueType();
11736   bool Is128 = VecIntVT == MVT::v4i32;
11737   EVT VecFloatVT = Is128 ? MVT::v4f32 : MVT::v8f32;
11738   // If we convert to something else than the supported type, e.g., to v4f64,
11739   // abort early.
11740   if (VecFloatVT != Op->getValueType(0))
11741     return SDValue();
11742
11743   unsigned NumElts = VecIntVT.getVectorNumElements();
11744   assert((VecIntVT == MVT::v4i32 || VecIntVT == MVT::v8i32) &&
11745          "Unsupported custom type");
11746   assert(NumElts <= 8 && "The size of the constant array must be fixed");
11747
11748   // In the #idef/#else code, we have in common:
11749   // - The vector of constants:
11750   // -- 0x4b000000
11751   // -- 0x53000000
11752   // - A shift:
11753   // -- v >> 16
11754
11755   // Create the splat vector for 0x4b000000.
11756   SDValue CstLow = DAG.getConstant(0x4b000000, DL, MVT::i32);
11757   SDValue CstLowArray[] = {CstLow, CstLow, CstLow, CstLow,
11758                            CstLow, CstLow, CstLow, CstLow};
11759   SDValue VecCstLow = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
11760                                   makeArrayRef(&CstLowArray[0], NumElts));
11761   // Create the splat vector for 0x53000000.
11762   SDValue CstHigh = DAG.getConstant(0x53000000, DL, MVT::i32);
11763   SDValue CstHighArray[] = {CstHigh, CstHigh, CstHigh, CstHigh,
11764                             CstHigh, CstHigh, CstHigh, CstHigh};
11765   SDValue VecCstHigh = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
11766                                    makeArrayRef(&CstHighArray[0], NumElts));
11767
11768   // Create the right shift.
11769   SDValue CstShift = DAG.getConstant(16, DL, MVT::i32);
11770   SDValue CstShiftArray[] = {CstShift, CstShift, CstShift, CstShift,
11771                              CstShift, CstShift, CstShift, CstShift};
11772   SDValue VecCstShift = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
11773                                     makeArrayRef(&CstShiftArray[0], NumElts));
11774   SDValue HighShift = DAG.getNode(ISD::SRL, DL, VecIntVT, V, VecCstShift);
11775
11776   SDValue Low, High;
11777   if (Subtarget.hasSSE41()) {
11778     EVT VecI16VT = Is128 ? MVT::v8i16 : MVT::v16i16;
11779     //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
11780     SDValue VecCstLowBitcast =
11781         DAG.getNode(ISD::BITCAST, DL, VecI16VT, VecCstLow);
11782     SDValue VecBitcast = DAG.getNode(ISD::BITCAST, DL, VecI16VT, V);
11783     // Low will be bitcasted right away, so do not bother bitcasting back to its
11784     // original type.
11785     Low = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecBitcast,
11786                       VecCstLowBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
11787     //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
11788     //                                 (uint4) 0x53000000, 0xaa);
11789     SDValue VecCstHighBitcast =
11790         DAG.getNode(ISD::BITCAST, DL, VecI16VT, VecCstHigh);
11791     SDValue VecShiftBitcast =
11792         DAG.getNode(ISD::BITCAST, DL, VecI16VT, HighShift);
11793     // High will be bitcasted right away, so do not bother bitcasting back to
11794     // its original type.
11795     High = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecShiftBitcast,
11796                        VecCstHighBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
11797   } else {
11798     SDValue CstMask = DAG.getConstant(0xffff, DL, MVT::i32);
11799     SDValue VecCstMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT, CstMask,
11800                                      CstMask, CstMask, CstMask);
11801     //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
11802     SDValue LowAnd = DAG.getNode(ISD::AND, DL, VecIntVT, V, VecCstMask);
11803     Low = DAG.getNode(ISD::OR, DL, VecIntVT, LowAnd, VecCstLow);
11804
11805     //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
11806     High = DAG.getNode(ISD::OR, DL, VecIntVT, HighShift, VecCstHigh);
11807   }
11808
11809   // Create the vector constant for -(0x1.0p39f + 0x1.0p23f).
11810   SDValue CstFAdd = DAG.getConstantFP(
11811       APFloat(APFloat::IEEEsingle, APInt(32, 0xD3000080)), DL, MVT::f32);
11812   SDValue CstFAddArray[] = {CstFAdd, CstFAdd, CstFAdd, CstFAdd,
11813                             CstFAdd, CstFAdd, CstFAdd, CstFAdd};
11814   SDValue VecCstFAdd = DAG.getNode(ISD::BUILD_VECTOR, DL, VecFloatVT,
11815                                    makeArrayRef(&CstFAddArray[0], NumElts));
11816
11817   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
11818   SDValue HighBitcast = DAG.getNode(ISD::BITCAST, DL, VecFloatVT, High);
11819   SDValue FHigh =
11820       DAG.getNode(ISD::FADD, DL, VecFloatVT, HighBitcast, VecCstFAdd);
11821   //     return (float4) lo + fhi;
11822   SDValue LowBitcast = DAG.getNode(ISD::BITCAST, DL, VecFloatVT, Low);
11823   return DAG.getNode(ISD::FADD, DL, VecFloatVT, LowBitcast, FHigh);
11824 }
11825
11826 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
11827                                                SelectionDAG &DAG) const {
11828   SDValue N0 = Op.getOperand(0);
11829   MVT SVT = N0.getSimpleValueType();
11830   SDLoc dl(Op);
11831
11832   switch (SVT.SimpleTy) {
11833   default:
11834     llvm_unreachable("Custom UINT_TO_FP is not supported!");
11835   case MVT::v4i8:
11836   case MVT::v4i16:
11837   case MVT::v8i8:
11838   case MVT::v8i16: {
11839     MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
11840     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
11841                        DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
11842   }
11843   case MVT::v4i32:
11844   case MVT::v8i32:
11845     return lowerUINT_TO_FP_vXi32(Op, DAG, *Subtarget);
11846   case MVT::v16i8:
11847   case MVT::v16i16:
11848     if (Subtarget->hasAVX512())
11849       return DAG.getNode(ISD::UINT_TO_FP, dl, Op.getValueType(),
11850                          DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v16i32, N0));
11851   }
11852   llvm_unreachable(nullptr);
11853 }
11854
11855 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
11856                                            SelectionDAG &DAG) const {
11857   SDValue N0 = Op.getOperand(0);
11858   SDLoc dl(Op);
11859
11860   if (Op.getValueType().isVector())
11861     return lowerUINT_TO_FP_vec(Op, DAG);
11862
11863   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
11864   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
11865   // the optimization here.
11866   if (DAG.SignBitIsZero(N0))
11867     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
11868
11869   MVT SrcVT = N0.getSimpleValueType();
11870   MVT DstVT = Op.getSimpleValueType();
11871   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
11872     return LowerUINT_TO_FP_i64(Op, DAG);
11873   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
11874     return LowerUINT_TO_FP_i32(Op, DAG);
11875   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
11876     return SDValue();
11877
11878   // Make a 64-bit buffer, and use it to build an FILD.
11879   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
11880   if (SrcVT == MVT::i32) {
11881     SDValue WordOff = DAG.getConstant(4, dl, getPointerTy());
11882     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
11883                                      getPointerTy(), StackSlot, WordOff);
11884     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11885                                   StackSlot, MachinePointerInfo(),
11886                                   false, false, 0);
11887     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, dl, MVT::i32),
11888                                   OffsetSlot, MachinePointerInfo(),
11889                                   false, false, 0);
11890     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
11891     return Fild;
11892   }
11893
11894   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
11895   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11896                                StackSlot, MachinePointerInfo(),
11897                                false, false, 0);
11898   // For i64 source, we need to add the appropriate power of 2 if the input
11899   // was negative.  This is the same as the optimization in
11900   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
11901   // we must be careful to do the computation in x87 extended precision, not
11902   // in SSE. (The generic code can't know it's OK to do this, or how to.)
11903   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
11904   MachineMemOperand *MMO =
11905     DAG.getMachineFunction()
11906     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11907                           MachineMemOperand::MOLoad, 8, 8);
11908
11909   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
11910   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
11911   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
11912                                          MVT::i64, MMO);
11913
11914   APInt FF(32, 0x5F800000ULL);
11915
11916   // Check whether the sign bit is set.
11917   SDValue SignSet = DAG.getSetCC(dl,
11918                                  getSetCCResultType(*DAG.getContext(), MVT::i64),
11919                                  Op.getOperand(0),
11920                                  DAG.getConstant(0, dl, MVT::i64), ISD::SETLT);
11921
11922   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
11923   SDValue FudgePtr = DAG.getConstantPool(
11924                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
11925                                          getPointerTy());
11926
11927   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
11928   SDValue Zero = DAG.getIntPtrConstant(0, dl);
11929   SDValue Four = DAG.getIntPtrConstant(4, dl);
11930   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
11931                                Zero, Four);
11932   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
11933
11934   // Load the value out, extending it from f32 to f80.
11935   // FIXME: Avoid the extend by constructing the right constant pool?
11936   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
11937                                  FudgePtr, MachinePointerInfo::getConstantPool(),
11938                                  MVT::f32, false, false, false, 4);
11939   // Extend everything to 80 bits to force it to be done on x87.
11940   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
11941   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add,
11942                      DAG.getIntPtrConstant(0, dl));
11943 }
11944
11945 std::pair<SDValue,SDValue>
11946 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
11947                                     bool IsSigned, bool IsReplace) const {
11948   SDLoc DL(Op);
11949
11950   EVT DstTy = Op.getValueType();
11951
11952   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
11953     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
11954     DstTy = MVT::i64;
11955   }
11956
11957   assert(DstTy.getSimpleVT() <= MVT::i64 &&
11958          DstTy.getSimpleVT() >= MVT::i16 &&
11959          "Unknown FP_TO_INT to lower!");
11960
11961   // These are really Legal.
11962   if (DstTy == MVT::i32 &&
11963       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
11964     return std::make_pair(SDValue(), SDValue());
11965   if (Subtarget->is64Bit() &&
11966       DstTy == MVT::i64 &&
11967       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
11968     return std::make_pair(SDValue(), SDValue());
11969
11970   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
11971   // stack slot, or into the FTOL runtime function.
11972   MachineFunction &MF = DAG.getMachineFunction();
11973   unsigned MemSize = DstTy.getSizeInBits()/8;
11974   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
11975   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11976
11977   unsigned Opc;
11978   if (!IsSigned && isIntegerTypeFTOL(DstTy))
11979     Opc = X86ISD::WIN_FTOL;
11980   else
11981     switch (DstTy.getSimpleVT().SimpleTy) {
11982     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
11983     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
11984     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
11985     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
11986     }
11987
11988   SDValue Chain = DAG.getEntryNode();
11989   SDValue Value = Op.getOperand(0);
11990   EVT TheVT = Op.getOperand(0).getValueType();
11991   // FIXME This causes a redundant load/store if the SSE-class value is already
11992   // in memory, such as if it is on the callstack.
11993   if (isScalarFPTypeInSSEReg(TheVT)) {
11994     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
11995     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
11996                          MachinePointerInfo::getFixedStack(SSFI),
11997                          false, false, 0);
11998     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
11999     SDValue Ops[] = {
12000       Chain, StackSlot, DAG.getValueType(TheVT)
12001     };
12002
12003     MachineMemOperand *MMO =
12004       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
12005                               MachineMemOperand::MOLoad, MemSize, MemSize);
12006     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
12007     Chain = Value.getValue(1);
12008     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
12009     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
12010   }
12011
12012   MachineMemOperand *MMO =
12013     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
12014                             MachineMemOperand::MOStore, MemSize, MemSize);
12015
12016   if (Opc != X86ISD::WIN_FTOL) {
12017     // Build the FP_TO_INT*_IN_MEM
12018     SDValue Ops[] = { Chain, Value, StackSlot };
12019     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
12020                                            Ops, DstTy, MMO);
12021     return std::make_pair(FIST, StackSlot);
12022   } else {
12023     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
12024       DAG.getVTList(MVT::Other, MVT::Glue),
12025       Chain, Value);
12026     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
12027       MVT::i32, ftol.getValue(1));
12028     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
12029       MVT::i32, eax.getValue(2));
12030     SDValue Ops[] = { eax, edx };
12031     SDValue pair = IsReplace
12032       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
12033       : DAG.getMergeValues(Ops, DL);
12034     return std::make_pair(pair, SDValue());
12035   }
12036 }
12037
12038 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
12039                               const X86Subtarget *Subtarget) {
12040   MVT VT = Op->getSimpleValueType(0);
12041   SDValue In = Op->getOperand(0);
12042   MVT InVT = In.getSimpleValueType();
12043   SDLoc dl(Op);
12044
12045   if (VT.is512BitVector() || InVT.getScalarType() == MVT::i1)
12046     return DAG.getNode(ISD::ZERO_EXTEND, dl, VT, In);
12047
12048   // Optimize vectors in AVX mode:
12049   //
12050   //   v8i16 -> v8i32
12051   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
12052   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
12053   //   Concat upper and lower parts.
12054   //
12055   //   v4i32 -> v4i64
12056   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
12057   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
12058   //   Concat upper and lower parts.
12059   //
12060
12061   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
12062       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
12063       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
12064     return SDValue();
12065
12066   if (Subtarget->hasInt256())
12067     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
12068
12069   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
12070   SDValue Undef = DAG.getUNDEF(InVT);
12071   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
12072   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12073   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12074
12075   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
12076                              VT.getVectorNumElements()/2);
12077
12078   OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
12079   OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
12080
12081   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
12082 }
12083
12084 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
12085                                         SelectionDAG &DAG) {
12086   MVT VT = Op->getSimpleValueType(0);
12087   SDValue In = Op->getOperand(0);
12088   MVT InVT = In.getSimpleValueType();
12089   SDLoc DL(Op);
12090   unsigned int NumElts = VT.getVectorNumElements();
12091   if (NumElts != 8 && NumElts != 16)
12092     return SDValue();
12093
12094   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
12095     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
12096
12097   assert(InVT.getVectorElementType() == MVT::i1);
12098   MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
12099   SDValue One =
12100    DAG.getConstant(APInt(ExtVT.getScalarSizeInBits(), 1), DL, ExtVT);
12101   SDValue Zero =
12102    DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), DL, ExtVT);
12103
12104   SDValue V = DAG.getNode(ISD::VSELECT, DL, ExtVT, In, One, Zero);
12105   if (VT.is512BitVector())
12106     return V;
12107   return DAG.getNode(X86ISD::VTRUNC, DL, VT, V);
12108 }
12109
12110 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12111                                SelectionDAG &DAG) {
12112   if (Subtarget->hasFp256()) {
12113     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
12114     if (Res.getNode())
12115       return Res;
12116   }
12117
12118   return SDValue();
12119 }
12120
12121 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12122                                 SelectionDAG &DAG) {
12123   SDLoc DL(Op);
12124   MVT VT = Op.getSimpleValueType();
12125   SDValue In = Op.getOperand(0);
12126   MVT SVT = In.getSimpleValueType();
12127
12128   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
12129     return LowerZERO_EXTEND_AVX512(Op, DAG);
12130
12131   if (Subtarget->hasFp256()) {
12132     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
12133     if (Res.getNode())
12134       return Res;
12135   }
12136
12137   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
12138          VT.getVectorNumElements() != SVT.getVectorNumElements());
12139   return SDValue();
12140 }
12141
12142 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
12143   SDLoc DL(Op);
12144   MVT VT = Op.getSimpleValueType();
12145   SDValue In = Op.getOperand(0);
12146   MVT InVT = In.getSimpleValueType();
12147
12148   if (VT == MVT::i1) {
12149     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
12150            "Invalid scalar TRUNCATE operation");
12151     if (InVT.getSizeInBits() >= 32)
12152       return SDValue();
12153     In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
12154     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
12155   }
12156   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
12157          "Invalid TRUNCATE operation");
12158
12159   // move vector to mask - truncate solution for SKX
12160   if (VT.getVectorElementType() == MVT::i1) {
12161     if (InVT.is512BitVector() && InVT.getScalarSizeInBits() <= 16 &&
12162         Subtarget->hasBWI())
12163       return Op; // legal, will go to VPMOVB2M, VPMOVW2M
12164     if ((InVT.is256BitVector() || InVT.is128BitVector()) 
12165         && InVT.getScalarSizeInBits() <= 16 &&
12166         Subtarget->hasBWI() && Subtarget->hasVLX())
12167       return Op; // legal, will go to VPMOVB2M, VPMOVW2M
12168     if (InVT.is512BitVector() && InVT.getScalarSizeInBits() >= 32 &&
12169         Subtarget->hasDQI())
12170       return Op; // legal, will go to VPMOVD2M, VPMOVQ2M
12171     if ((InVT.is256BitVector() || InVT.is128BitVector()) 
12172         && InVT.getScalarSizeInBits() >= 32 &&
12173         Subtarget->hasDQI() && Subtarget->hasVLX())
12174       return Op; // legal, will go to VPMOVB2M, VPMOVQ2M
12175   }
12176   if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
12177     if (VT.getVectorElementType().getSizeInBits() >=8)
12178       return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
12179
12180     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
12181     unsigned NumElts = InVT.getVectorNumElements();
12182     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
12183     if (InVT.getSizeInBits() < 512) {
12184       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
12185       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
12186       InVT = ExtVT;
12187     }
12188
12189     SDValue OneV =
12190      DAG.getConstant(APInt::getSignBit(InVT.getScalarSizeInBits()), DL, InVT);
12191     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
12192     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
12193   }
12194
12195   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
12196     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
12197     if (Subtarget->hasInt256()) {
12198       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
12199       In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
12200       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
12201                                 ShufMask);
12202       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
12203                          DAG.getIntPtrConstant(0, DL));
12204     }
12205
12206     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12207                                DAG.getIntPtrConstant(0, DL));
12208     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12209                                DAG.getIntPtrConstant(2, DL));
12210     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
12211     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
12212     static const int ShufMask[] = {0, 2, 4, 6};
12213     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
12214   }
12215
12216   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
12217     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
12218     if (Subtarget->hasInt256()) {
12219       In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
12220
12221       SmallVector<SDValue,32> pshufbMask;
12222       for (unsigned i = 0; i < 2; ++i) {
12223         pshufbMask.push_back(DAG.getConstant(0x0, DL, MVT::i8));
12224         pshufbMask.push_back(DAG.getConstant(0x1, DL, MVT::i8));
12225         pshufbMask.push_back(DAG.getConstant(0x4, DL, MVT::i8));
12226         pshufbMask.push_back(DAG.getConstant(0x5, DL, MVT::i8));
12227         pshufbMask.push_back(DAG.getConstant(0x8, DL, MVT::i8));
12228         pshufbMask.push_back(DAG.getConstant(0x9, DL, MVT::i8));
12229         pshufbMask.push_back(DAG.getConstant(0xc, DL, MVT::i8));
12230         pshufbMask.push_back(DAG.getConstant(0xd, DL, MVT::i8));
12231         for (unsigned j = 0; j < 8; ++j)
12232           pshufbMask.push_back(DAG.getConstant(0x80, DL, MVT::i8));
12233       }
12234       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
12235       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
12236       In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
12237
12238       static const int ShufMask[] = {0,  2,  -1,  -1};
12239       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
12240                                 &ShufMask[0]);
12241       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12242                        DAG.getIntPtrConstant(0, DL));
12243       return DAG.getNode(ISD::BITCAST, DL, VT, In);
12244     }
12245
12246     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12247                                DAG.getIntPtrConstant(0, DL));
12248
12249     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12250                                DAG.getIntPtrConstant(4, DL));
12251
12252     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
12253     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
12254
12255     // The PSHUFB mask:
12256     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
12257                                    -1, -1, -1, -1, -1, -1, -1, -1};
12258
12259     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
12260     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
12261     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
12262
12263     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
12264     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
12265
12266     // The MOVLHPS Mask:
12267     static const int ShufMask2[] = {0, 1, 4, 5};
12268     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
12269     return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
12270   }
12271
12272   // Handle truncation of V256 to V128 using shuffles.
12273   if (!VT.is128BitVector() || !InVT.is256BitVector())
12274     return SDValue();
12275
12276   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
12277
12278   unsigned NumElems = VT.getVectorNumElements();
12279   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
12280
12281   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
12282   // Prepare truncation shuffle mask
12283   for (unsigned i = 0; i != NumElems; ++i)
12284     MaskVec[i] = i * 2;
12285   SDValue V = DAG.getVectorShuffle(NVT, DL,
12286                                    DAG.getNode(ISD::BITCAST, DL, NVT, In),
12287                                    DAG.getUNDEF(NVT), &MaskVec[0]);
12288   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
12289                      DAG.getIntPtrConstant(0, DL));
12290 }
12291
12292 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
12293                                            SelectionDAG &DAG) const {
12294   assert(!Op.getSimpleValueType().isVector());
12295
12296   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12297     /*IsSigned=*/ true, /*IsReplace=*/ false);
12298   SDValue FIST = Vals.first, StackSlot = Vals.second;
12299   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
12300   if (!FIST.getNode()) return Op;
12301
12302   if (StackSlot.getNode())
12303     // Load the result.
12304     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12305                        FIST, StackSlot, MachinePointerInfo(),
12306                        false, false, false, 0);
12307
12308   // The node is the result.
12309   return FIST;
12310 }
12311
12312 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
12313                                            SelectionDAG &DAG) const {
12314   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12315     /*IsSigned=*/ false, /*IsReplace=*/ false);
12316   SDValue FIST = Vals.first, StackSlot = Vals.second;
12317   assert(FIST.getNode() && "Unexpected failure");
12318
12319   if (StackSlot.getNode())
12320     // Load the result.
12321     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12322                        FIST, StackSlot, MachinePointerInfo(),
12323                        false, false, false, 0);
12324
12325   // The node is the result.
12326   return FIST;
12327 }
12328
12329 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
12330   SDLoc DL(Op);
12331   MVT VT = Op.getSimpleValueType();
12332   SDValue In = Op.getOperand(0);
12333   MVT SVT = In.getSimpleValueType();
12334
12335   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
12336
12337   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
12338                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
12339                                  In, DAG.getUNDEF(SVT)));
12340 }
12341
12342 /// The only differences between FABS and FNEG are the mask and the logic op.
12343 /// FNEG also has a folding opportunity for FNEG(FABS(x)).
12344 static SDValue LowerFABSorFNEG(SDValue Op, SelectionDAG &DAG) {
12345   assert((Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) &&
12346          "Wrong opcode for lowering FABS or FNEG.");
12347
12348   bool IsFABS = (Op.getOpcode() == ISD::FABS);
12349
12350   // If this is a FABS and it has an FNEG user, bail out to fold the combination
12351   // into an FNABS. We'll lower the FABS after that if it is still in use.
12352   if (IsFABS)
12353     for (SDNode *User : Op->uses())
12354       if (User->getOpcode() == ISD::FNEG)
12355         return Op;
12356
12357   SDValue Op0 = Op.getOperand(0);
12358   bool IsFNABS = !IsFABS && (Op0.getOpcode() == ISD::FABS);
12359
12360   SDLoc dl(Op);
12361   MVT VT = Op.getSimpleValueType();
12362   // Assume scalar op for initialization; update for vector if needed.
12363   // Note that there are no scalar bitwise logical SSE/AVX instructions, so we
12364   // generate a 16-byte vector constant and logic op even for the scalar case.
12365   // Using a 16-byte mask allows folding the load of the mask with
12366   // the logic op, so it can save (~4 bytes) on code size.
12367   MVT EltVT = VT;
12368   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
12369   // FIXME: Use function attribute "OptimizeForSize" and/or CodeGenOpt::Level to
12370   // decide if we should generate a 16-byte constant mask when we only need 4 or
12371   // 8 bytes for the scalar case.
12372   if (VT.isVector()) {
12373     EltVT = VT.getVectorElementType();
12374     NumElts = VT.getVectorNumElements();
12375   }
12376
12377   unsigned EltBits = EltVT.getSizeInBits();
12378   LLVMContext *Context = DAG.getContext();
12379   // For FABS, mask is 0x7f...; for FNEG, mask is 0x80...
12380   APInt MaskElt =
12381     IsFABS ? APInt::getSignedMaxValue(EltBits) : APInt::getSignBit(EltBits);
12382   Constant *C = ConstantInt::get(*Context, MaskElt);
12383   C = ConstantVector::getSplat(NumElts, C);
12384   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12385   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
12386   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
12387   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
12388                              MachinePointerInfo::getConstantPool(),
12389                              false, false, false, Alignment);
12390
12391   if (VT.isVector()) {
12392     // For a vector, cast operands to a vector type, perform the logic op,
12393     // and cast the result back to the original value type.
12394     MVT VecVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
12395     SDValue MaskCasted = DAG.getNode(ISD::BITCAST, dl, VecVT, Mask);
12396     SDValue Operand = IsFNABS ?
12397       DAG.getNode(ISD::BITCAST, dl, VecVT, Op0.getOperand(0)) :
12398       DAG.getNode(ISD::BITCAST, dl, VecVT, Op0);
12399     unsigned BitOp = IsFABS ? ISD::AND : IsFNABS ? ISD::OR : ISD::XOR;
12400     return DAG.getNode(ISD::BITCAST, dl, VT,
12401                        DAG.getNode(BitOp, dl, VecVT, Operand, MaskCasted));
12402   }
12403
12404   // If not vector, then scalar.
12405   unsigned BitOp = IsFABS ? X86ISD::FAND : IsFNABS ? X86ISD::FOR : X86ISD::FXOR;
12406   SDValue Operand = IsFNABS ? Op0.getOperand(0) : Op0;
12407   return DAG.getNode(BitOp, dl, VT, Operand, Mask);
12408 }
12409
12410 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
12411   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12412   LLVMContext *Context = DAG.getContext();
12413   SDValue Op0 = Op.getOperand(0);
12414   SDValue Op1 = Op.getOperand(1);
12415   SDLoc dl(Op);
12416   MVT VT = Op.getSimpleValueType();
12417   MVT SrcVT = Op1.getSimpleValueType();
12418
12419   // If second operand is smaller, extend it first.
12420   if (SrcVT.bitsLT(VT)) {
12421     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
12422     SrcVT = VT;
12423   }
12424   // And if it is bigger, shrink it first.
12425   if (SrcVT.bitsGT(VT)) {
12426     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1, dl));
12427     SrcVT = VT;
12428   }
12429
12430   // At this point the operands and the result should have the same
12431   // type, and that won't be f80 since that is not custom lowered.
12432
12433   const fltSemantics &Sem =
12434       VT == MVT::f64 ? APFloat::IEEEdouble : APFloat::IEEEsingle;
12435   const unsigned SizeInBits = VT.getSizeInBits();
12436
12437   SmallVector<Constant *, 4> CV(
12438       VT == MVT::f64 ? 2 : 4,
12439       ConstantFP::get(*Context, APFloat(Sem, APInt(SizeInBits, 0))));
12440
12441   // First, clear all bits but the sign bit from the second operand (sign).
12442   CV[0] = ConstantFP::get(*Context,
12443                           APFloat(Sem, APInt::getHighBitsSet(SizeInBits, 1)));
12444   Constant *C = ConstantVector::get(CV);
12445   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
12446   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
12447                               MachinePointerInfo::getConstantPool(),
12448                               false, false, false, 16);
12449   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
12450
12451   // Next, clear the sign bit from the first operand (magnitude).
12452   // If it's a constant, we can clear it here.
12453   if (ConstantFPSDNode *Op0CN = dyn_cast<ConstantFPSDNode>(Op0)) {
12454     APFloat APF = Op0CN->getValueAPF();
12455     // If the magnitude is a positive zero, the sign bit alone is enough.
12456     if (APF.isPosZero())
12457       return SignBit;
12458     APF.clearSign();
12459     CV[0] = ConstantFP::get(*Context, APF);
12460   } else {
12461     CV[0] = ConstantFP::get(
12462         *Context,
12463         APFloat(Sem, APInt::getLowBitsSet(SizeInBits, SizeInBits - 1)));
12464   }
12465   C = ConstantVector::get(CV);
12466   CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
12467   SDValue Val = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
12468                             MachinePointerInfo::getConstantPool(),
12469                             false, false, false, 16);
12470   // If the magnitude operand wasn't a constant, we need to AND out the sign.
12471   if (!isa<ConstantFPSDNode>(Op0))
12472     Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Val);
12473
12474   // OR the magnitude value with the sign bit.
12475   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
12476 }
12477
12478 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
12479   SDValue N0 = Op.getOperand(0);
12480   SDLoc dl(Op);
12481   MVT VT = Op.getSimpleValueType();
12482
12483   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
12484   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
12485                                   DAG.getConstant(1, dl, VT));
12486   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, dl, VT));
12487 }
12488
12489 // Check whether an OR'd tree is PTEST-able.
12490 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
12491                                       SelectionDAG &DAG) {
12492   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
12493
12494   if (!Subtarget->hasSSE41())
12495     return SDValue();
12496
12497   if (!Op->hasOneUse())
12498     return SDValue();
12499
12500   SDNode *N = Op.getNode();
12501   SDLoc DL(N);
12502
12503   SmallVector<SDValue, 8> Opnds;
12504   DenseMap<SDValue, unsigned> VecInMap;
12505   SmallVector<SDValue, 8> VecIns;
12506   EVT VT = MVT::Other;
12507
12508   // Recognize a special case where a vector is casted into wide integer to
12509   // test all 0s.
12510   Opnds.push_back(N->getOperand(0));
12511   Opnds.push_back(N->getOperand(1));
12512
12513   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
12514     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
12515     // BFS traverse all OR'd operands.
12516     if (I->getOpcode() == ISD::OR) {
12517       Opnds.push_back(I->getOperand(0));
12518       Opnds.push_back(I->getOperand(1));
12519       // Re-evaluate the number of nodes to be traversed.
12520       e += 2; // 2 more nodes (LHS and RHS) are pushed.
12521       continue;
12522     }
12523
12524     // Quit if a non-EXTRACT_VECTOR_ELT
12525     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
12526       return SDValue();
12527
12528     // Quit if without a constant index.
12529     SDValue Idx = I->getOperand(1);
12530     if (!isa<ConstantSDNode>(Idx))
12531       return SDValue();
12532
12533     SDValue ExtractedFromVec = I->getOperand(0);
12534     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
12535     if (M == VecInMap.end()) {
12536       VT = ExtractedFromVec.getValueType();
12537       // Quit if not 128/256-bit vector.
12538       if (!VT.is128BitVector() && !VT.is256BitVector())
12539         return SDValue();
12540       // Quit if not the same type.
12541       if (VecInMap.begin() != VecInMap.end() &&
12542           VT != VecInMap.begin()->first.getValueType())
12543         return SDValue();
12544       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
12545       VecIns.push_back(ExtractedFromVec);
12546     }
12547     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
12548   }
12549
12550   assert((VT.is128BitVector() || VT.is256BitVector()) &&
12551          "Not extracted from 128-/256-bit vector.");
12552
12553   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
12554
12555   for (DenseMap<SDValue, unsigned>::const_iterator
12556         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
12557     // Quit if not all elements are used.
12558     if (I->second != FullMask)
12559       return SDValue();
12560   }
12561
12562   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
12563
12564   // Cast all vectors into TestVT for PTEST.
12565   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
12566     VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
12567
12568   // If more than one full vectors are evaluated, OR them first before PTEST.
12569   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
12570     // Each iteration will OR 2 nodes and append the result until there is only
12571     // 1 node left, i.e. the final OR'd value of all vectors.
12572     SDValue LHS = VecIns[Slot];
12573     SDValue RHS = VecIns[Slot + 1];
12574     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
12575   }
12576
12577   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
12578                      VecIns.back(), VecIns.back());
12579 }
12580
12581 /// \brief return true if \c Op has a use that doesn't just read flags.
12582 static bool hasNonFlagsUse(SDValue Op) {
12583   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
12584        ++UI) {
12585     SDNode *User = *UI;
12586     unsigned UOpNo = UI.getOperandNo();
12587     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
12588       // Look pass truncate.
12589       UOpNo = User->use_begin().getOperandNo();
12590       User = *User->use_begin();
12591     }
12592
12593     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
12594         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
12595       return true;
12596   }
12597   return false;
12598 }
12599
12600 /// Emit nodes that will be selected as "test Op0,Op0", or something
12601 /// equivalent.
12602 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
12603                                     SelectionDAG &DAG) const {
12604   if (Op.getValueType() == MVT::i1) {
12605     SDValue ExtOp = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i8, Op);
12606     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, ExtOp,
12607                        DAG.getConstant(0, dl, MVT::i8));
12608   }
12609   // CF and OF aren't always set the way we want. Determine which
12610   // of these we need.
12611   bool NeedCF = false;
12612   bool NeedOF = false;
12613   switch (X86CC) {
12614   default: break;
12615   case X86::COND_A: case X86::COND_AE:
12616   case X86::COND_B: case X86::COND_BE:
12617     NeedCF = true;
12618     break;
12619   case X86::COND_G: case X86::COND_GE:
12620   case X86::COND_L: case X86::COND_LE:
12621   case X86::COND_O: case X86::COND_NO: {
12622     // Check if we really need to set the
12623     // Overflow flag. If NoSignedWrap is present
12624     // that is not actually needed.
12625     switch (Op->getOpcode()) {
12626     case ISD::ADD:
12627     case ISD::SUB:
12628     case ISD::MUL:
12629     case ISD::SHL: {
12630       const auto *BinNode = cast<BinaryWithFlagsSDNode>(Op.getNode());
12631       if (BinNode->Flags.hasNoSignedWrap())
12632         break;
12633     }
12634     default:
12635       NeedOF = true;
12636       break;
12637     }
12638     break;
12639   }
12640   }
12641   // See if we can use the EFLAGS value from the operand instead of
12642   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
12643   // we prove that the arithmetic won't overflow, we can't use OF or CF.
12644   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
12645     // Emit a CMP with 0, which is the TEST pattern.
12646     //if (Op.getValueType() == MVT::i1)
12647     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
12648     //                     DAG.getConstant(0, MVT::i1));
12649     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12650                        DAG.getConstant(0, dl, Op.getValueType()));
12651   }
12652   unsigned Opcode = 0;
12653   unsigned NumOperands = 0;
12654
12655   // Truncate operations may prevent the merge of the SETCC instruction
12656   // and the arithmetic instruction before it. Attempt to truncate the operands
12657   // of the arithmetic instruction and use a reduced bit-width instruction.
12658   bool NeedTruncation = false;
12659   SDValue ArithOp = Op;
12660   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
12661     SDValue Arith = Op->getOperand(0);
12662     // Both the trunc and the arithmetic op need to have one user each.
12663     if (Arith->hasOneUse())
12664       switch (Arith.getOpcode()) {
12665         default: break;
12666         case ISD::ADD:
12667         case ISD::SUB:
12668         case ISD::AND:
12669         case ISD::OR:
12670         case ISD::XOR: {
12671           NeedTruncation = true;
12672           ArithOp = Arith;
12673         }
12674       }
12675   }
12676
12677   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
12678   // which may be the result of a CAST.  We use the variable 'Op', which is the
12679   // non-casted variable when we check for possible users.
12680   switch (ArithOp.getOpcode()) {
12681   case ISD::ADD:
12682     // Due to an isel shortcoming, be conservative if this add is likely to be
12683     // selected as part of a load-modify-store instruction. When the root node
12684     // in a match is a store, isel doesn't know how to remap non-chain non-flag
12685     // uses of other nodes in the match, such as the ADD in this case. This
12686     // leads to the ADD being left around and reselected, with the result being
12687     // two adds in the output.  Alas, even if none our users are stores, that
12688     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
12689     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
12690     // climbing the DAG back to the root, and it doesn't seem to be worth the
12691     // effort.
12692     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12693          UE = Op.getNode()->use_end(); UI != UE; ++UI)
12694       if (UI->getOpcode() != ISD::CopyToReg &&
12695           UI->getOpcode() != ISD::SETCC &&
12696           UI->getOpcode() != ISD::STORE)
12697         goto default_case;
12698
12699     if (ConstantSDNode *C =
12700         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
12701       // An add of one will be selected as an INC.
12702       if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
12703         Opcode = X86ISD::INC;
12704         NumOperands = 1;
12705         break;
12706       }
12707
12708       // An add of negative one (subtract of one) will be selected as a DEC.
12709       if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
12710         Opcode = X86ISD::DEC;
12711         NumOperands = 1;
12712         break;
12713       }
12714     }
12715
12716     // Otherwise use a regular EFLAGS-setting add.
12717     Opcode = X86ISD::ADD;
12718     NumOperands = 2;
12719     break;
12720   case ISD::SHL:
12721   case ISD::SRL:
12722     // If we have a constant logical shift that's only used in a comparison
12723     // against zero turn it into an equivalent AND. This allows turning it into
12724     // a TEST instruction later.
12725     if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
12726         isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
12727       EVT VT = Op.getValueType();
12728       unsigned BitWidth = VT.getSizeInBits();
12729       unsigned ShAmt = Op->getConstantOperandVal(1);
12730       if (ShAmt >= BitWidth) // Avoid undefined shifts.
12731         break;
12732       APInt Mask = ArithOp.getOpcode() == ISD::SRL
12733                        ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
12734                        : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
12735       if (!Mask.isSignedIntN(32)) // Avoid large immediates.
12736         break;
12737       SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
12738                                 DAG.getConstant(Mask, dl, VT));
12739       DAG.ReplaceAllUsesWith(Op, New);
12740       DAG.RemoveDeadNode(Op.getNode());
12741       Op = New;
12742     }
12743     break;
12744
12745   case ISD::AND:
12746     // If the primary and result isn't used, don't bother using X86ISD::AND,
12747     // because a TEST instruction will be better.
12748     if (!hasNonFlagsUse(Op))
12749       break;
12750     // FALL THROUGH
12751   case ISD::SUB:
12752   case ISD::OR:
12753   case ISD::XOR:
12754     // Due to the ISEL shortcoming noted above, be conservative if this op is
12755     // likely to be selected as part of a load-modify-store instruction.
12756     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12757            UE = Op.getNode()->use_end(); UI != UE; ++UI)
12758       if (UI->getOpcode() == ISD::STORE)
12759         goto default_case;
12760
12761     // Otherwise use a regular EFLAGS-setting instruction.
12762     switch (ArithOp.getOpcode()) {
12763     default: llvm_unreachable("unexpected operator!");
12764     case ISD::SUB: Opcode = X86ISD::SUB; break;
12765     case ISD::XOR: Opcode = X86ISD::XOR; break;
12766     case ISD::AND: Opcode = X86ISD::AND; break;
12767     case ISD::OR: {
12768       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
12769         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
12770         if (EFLAGS.getNode())
12771           return EFLAGS;
12772       }
12773       Opcode = X86ISD::OR;
12774       break;
12775     }
12776     }
12777
12778     NumOperands = 2;
12779     break;
12780   case X86ISD::ADD:
12781   case X86ISD::SUB:
12782   case X86ISD::INC:
12783   case X86ISD::DEC:
12784   case X86ISD::OR:
12785   case X86ISD::XOR:
12786   case X86ISD::AND:
12787     return SDValue(Op.getNode(), 1);
12788   default:
12789   default_case:
12790     break;
12791   }
12792
12793   // If we found that truncation is beneficial, perform the truncation and
12794   // update 'Op'.
12795   if (NeedTruncation) {
12796     EVT VT = Op.getValueType();
12797     SDValue WideVal = Op->getOperand(0);
12798     EVT WideVT = WideVal.getValueType();
12799     unsigned ConvertedOp = 0;
12800     // Use a target machine opcode to prevent further DAGCombine
12801     // optimizations that may separate the arithmetic operations
12802     // from the setcc node.
12803     switch (WideVal.getOpcode()) {
12804       default: break;
12805       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
12806       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
12807       case ISD::AND: ConvertedOp = X86ISD::AND; break;
12808       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
12809       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
12810     }
12811
12812     if (ConvertedOp) {
12813       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12814       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
12815         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
12816         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
12817         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
12818       }
12819     }
12820   }
12821
12822   if (Opcode == 0)
12823     // Emit a CMP with 0, which is the TEST pattern.
12824     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12825                        DAG.getConstant(0, dl, Op.getValueType()));
12826
12827   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12828   SmallVector<SDValue, 4> Ops(Op->op_begin(), Op->op_begin() + NumOperands);
12829
12830   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
12831   DAG.ReplaceAllUsesWith(Op, New);
12832   return SDValue(New.getNode(), 1);
12833 }
12834
12835 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
12836 /// equivalent.
12837 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
12838                                    SDLoc dl, SelectionDAG &DAG) const {
12839   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
12840     if (C->getAPIntValue() == 0)
12841       return EmitTest(Op0, X86CC, dl, DAG);
12842
12843      if (Op0.getValueType() == MVT::i1)
12844        llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
12845   }
12846
12847   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
12848        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
12849     // Do the comparison at i32 if it's smaller, besides the Atom case.
12850     // This avoids subregister aliasing issues. Keep the smaller reference
12851     // if we're optimizing for size, however, as that'll allow better folding
12852     // of memory operations.
12853     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
12854         !DAG.getMachineFunction().getFunction()->hasFnAttribute(
12855             Attribute::MinSize) &&
12856         !Subtarget->isAtom()) {
12857       unsigned ExtendOp =
12858           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
12859       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
12860       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
12861     }
12862     // Use SUB instead of CMP to enable CSE between SUB and CMP.
12863     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
12864     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
12865                               Op0, Op1);
12866     return SDValue(Sub.getNode(), 1);
12867   }
12868   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
12869 }
12870
12871 /// Convert a comparison if required by the subtarget.
12872 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
12873                                                  SelectionDAG &DAG) const {
12874   // If the subtarget does not support the FUCOMI instruction, floating-point
12875   // comparisons have to be converted.
12876   if (Subtarget->hasCMov() ||
12877       Cmp.getOpcode() != X86ISD::CMP ||
12878       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
12879       !Cmp.getOperand(1).getValueType().isFloatingPoint())
12880     return Cmp;
12881
12882   // The instruction selector will select an FUCOM instruction instead of
12883   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
12884   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
12885   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
12886   SDLoc dl(Cmp);
12887   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
12888   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
12889   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
12890                             DAG.getConstant(8, dl, MVT::i8));
12891   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
12892   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
12893 }
12894
12895 /// The minimum architected relative accuracy is 2^-12. We need one
12896 /// Newton-Raphson step to have a good float result (24 bits of precision).
12897 SDValue X86TargetLowering::getRsqrtEstimate(SDValue Op,
12898                                             DAGCombinerInfo &DCI,
12899                                             unsigned &RefinementSteps,
12900                                             bool &UseOneConstNR) const {
12901   // FIXME: We should use instruction latency models to calculate the cost of
12902   // each potential sequence, but this is very hard to do reliably because
12903   // at least Intel's Core* chips have variable timing based on the number of
12904   // significant digits in the divisor and/or sqrt operand.
12905   if (!Subtarget->useSqrtEst())
12906     return SDValue();
12907
12908   EVT VT = Op.getValueType();
12909
12910   // SSE1 has rsqrtss and rsqrtps.
12911   // TODO: Add support for AVX512 (v16f32).
12912   // It is likely not profitable to do this for f64 because a double-precision
12913   // rsqrt estimate with refinement on x86 prior to FMA requires at least 16
12914   // instructions: convert to single, rsqrtss, convert back to double, refine
12915   // (3 steps = at least 13 insts). If an 'rsqrtsd' variant was added to the ISA
12916   // along with FMA, this could be a throughput win.
12917   if ((Subtarget->hasSSE1() && (VT == MVT::f32 || VT == MVT::v4f32)) ||
12918       (Subtarget->hasAVX() && VT == MVT::v8f32)) {
12919     RefinementSteps = 1;
12920     UseOneConstNR = false;
12921     return DCI.DAG.getNode(X86ISD::FRSQRT, SDLoc(Op), VT, Op);
12922   }
12923   return SDValue();
12924 }
12925
12926 /// The minimum architected relative accuracy is 2^-12. We need one
12927 /// Newton-Raphson step to have a good float result (24 bits of precision).
12928 SDValue X86TargetLowering::getRecipEstimate(SDValue Op,
12929                                             DAGCombinerInfo &DCI,
12930                                             unsigned &RefinementSteps) const {
12931   // FIXME: We should use instruction latency models to calculate the cost of
12932   // each potential sequence, but this is very hard to do reliably because
12933   // at least Intel's Core* chips have variable timing based on the number of
12934   // significant digits in the divisor.
12935   if (!Subtarget->useReciprocalEst())
12936     return SDValue();
12937
12938   EVT VT = Op.getValueType();
12939
12940   // SSE1 has rcpss and rcpps. AVX adds a 256-bit variant for rcpps.
12941   // TODO: Add support for AVX512 (v16f32).
12942   // It is likely not profitable to do this for f64 because a double-precision
12943   // reciprocal estimate with refinement on x86 prior to FMA requires
12944   // 15 instructions: convert to single, rcpss, convert back to double, refine
12945   // (3 steps = 12 insts). If an 'rcpsd' variant was added to the ISA
12946   // along with FMA, this could be a throughput win.
12947   if ((Subtarget->hasSSE1() && (VT == MVT::f32 || VT == MVT::v4f32)) ||
12948       (Subtarget->hasAVX() && VT == MVT::v8f32)) {
12949     RefinementSteps = ReciprocalEstimateRefinementSteps;
12950     return DCI.DAG.getNode(X86ISD::FRCP, SDLoc(Op), VT, Op);
12951   }
12952   return SDValue();
12953 }
12954
12955 /// If we have at least two divisions that use the same divisor, convert to
12956 /// multplication by a reciprocal. This may need to be adjusted for a given
12957 /// CPU if a division's cost is not at least twice the cost of a multiplication.
12958 /// This is because we still need one division to calculate the reciprocal and
12959 /// then we need two multiplies by that reciprocal as replacements for the
12960 /// original divisions.
12961 bool X86TargetLowering::combineRepeatedFPDivisors(unsigned NumUsers) const {
12962   return NumUsers > 1;
12963 }
12964
12965 static bool isAllOnes(SDValue V) {
12966   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
12967   return C && C->isAllOnesValue();
12968 }
12969
12970 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
12971 /// if it's possible.
12972 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
12973                                      SDLoc dl, SelectionDAG &DAG) const {
12974   SDValue Op0 = And.getOperand(0);
12975   SDValue Op1 = And.getOperand(1);
12976   if (Op0.getOpcode() == ISD::TRUNCATE)
12977     Op0 = Op0.getOperand(0);
12978   if (Op1.getOpcode() == ISD::TRUNCATE)
12979     Op1 = Op1.getOperand(0);
12980
12981   SDValue LHS, RHS;
12982   if (Op1.getOpcode() == ISD::SHL)
12983     std::swap(Op0, Op1);
12984   if (Op0.getOpcode() == ISD::SHL) {
12985     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
12986       if (And00C->getZExtValue() == 1) {
12987         // If we looked past a truncate, check that it's only truncating away
12988         // known zeros.
12989         unsigned BitWidth = Op0.getValueSizeInBits();
12990         unsigned AndBitWidth = And.getValueSizeInBits();
12991         if (BitWidth > AndBitWidth) {
12992           APInt Zeros, Ones;
12993           DAG.computeKnownBits(Op0, Zeros, Ones);
12994           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
12995             return SDValue();
12996         }
12997         LHS = Op1;
12998         RHS = Op0.getOperand(1);
12999       }
13000   } else if (Op1.getOpcode() == ISD::Constant) {
13001     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
13002     uint64_t AndRHSVal = AndRHS->getZExtValue();
13003     SDValue AndLHS = Op0;
13004
13005     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
13006       LHS = AndLHS.getOperand(0);
13007       RHS = AndLHS.getOperand(1);
13008     }
13009
13010     // Use BT if the immediate can't be encoded in a TEST instruction.
13011     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
13012       LHS = AndLHS;
13013       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), dl, LHS.getValueType());
13014     }
13015   }
13016
13017   if (LHS.getNode()) {
13018     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
13019     // instruction.  Since the shift amount is in-range-or-undefined, we know
13020     // that doing a bittest on the i32 value is ok.  We extend to i32 because
13021     // the encoding for the i16 version is larger than the i32 version.
13022     // Also promote i16 to i32 for performance / code size reason.
13023     if (LHS.getValueType() == MVT::i8 ||
13024         LHS.getValueType() == MVT::i16)
13025       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
13026
13027     // If the operand types disagree, extend the shift amount to match.  Since
13028     // BT ignores high bits (like shifts) we can use anyextend.
13029     if (LHS.getValueType() != RHS.getValueType())
13030       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
13031
13032     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
13033     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
13034     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13035                        DAG.getConstant(Cond, dl, MVT::i8), BT);
13036   }
13037
13038   return SDValue();
13039 }
13040
13041 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
13042 /// mask CMPs.
13043 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
13044                               SDValue &Op1) {
13045   unsigned SSECC;
13046   bool Swap = false;
13047
13048   // SSE Condition code mapping:
13049   //  0 - EQ
13050   //  1 - LT
13051   //  2 - LE
13052   //  3 - UNORD
13053   //  4 - NEQ
13054   //  5 - NLT
13055   //  6 - NLE
13056   //  7 - ORD
13057   switch (SetCCOpcode) {
13058   default: llvm_unreachable("Unexpected SETCC condition");
13059   case ISD::SETOEQ:
13060   case ISD::SETEQ:  SSECC = 0; break;
13061   case ISD::SETOGT:
13062   case ISD::SETGT:  Swap = true; // Fallthrough
13063   case ISD::SETLT:
13064   case ISD::SETOLT: SSECC = 1; break;
13065   case ISD::SETOGE:
13066   case ISD::SETGE:  Swap = true; // Fallthrough
13067   case ISD::SETLE:
13068   case ISD::SETOLE: SSECC = 2; break;
13069   case ISD::SETUO:  SSECC = 3; break;
13070   case ISD::SETUNE:
13071   case ISD::SETNE:  SSECC = 4; break;
13072   case ISD::SETULE: Swap = true; // Fallthrough
13073   case ISD::SETUGE: SSECC = 5; break;
13074   case ISD::SETULT: Swap = true; // Fallthrough
13075   case ISD::SETUGT: SSECC = 6; break;
13076   case ISD::SETO:   SSECC = 7; break;
13077   case ISD::SETUEQ:
13078   case ISD::SETONE: SSECC = 8; break;
13079   }
13080   if (Swap)
13081     std::swap(Op0, Op1);
13082
13083   return SSECC;
13084 }
13085
13086 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
13087 // ones, and then concatenate the result back.
13088 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
13089   MVT VT = Op.getSimpleValueType();
13090
13091   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
13092          "Unsupported value type for operation");
13093
13094   unsigned NumElems = VT.getVectorNumElements();
13095   SDLoc dl(Op);
13096   SDValue CC = Op.getOperand(2);
13097
13098   // Extract the LHS vectors
13099   SDValue LHS = Op.getOperand(0);
13100   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13101   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13102
13103   // Extract the RHS vectors
13104   SDValue RHS = Op.getOperand(1);
13105   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
13106   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
13107
13108   // Issue the operation on the smaller types and concatenate the result back
13109   MVT EltVT = VT.getVectorElementType();
13110   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13111   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
13112                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
13113                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
13114 }
13115
13116 static SDValue LowerBoolVSETCC_AVX512(SDValue Op, SelectionDAG &DAG) {
13117   SDValue Op0 = Op.getOperand(0);
13118   SDValue Op1 = Op.getOperand(1);
13119   SDValue CC = Op.getOperand(2);
13120   MVT VT = Op.getSimpleValueType();
13121   SDLoc dl(Op);
13122
13123   assert(Op0.getValueType().getVectorElementType() == MVT::i1 &&
13124          "Unexpected type for boolean compare operation");
13125   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13126   SDValue NotOp0 = DAG.getNode(ISD::XOR, dl, VT, Op0,
13127                                DAG.getConstant(-1, dl, VT));
13128   SDValue NotOp1 = DAG.getNode(ISD::XOR, dl, VT, Op1,
13129                                DAG.getConstant(-1, dl, VT));
13130   switch (SetCCOpcode) {
13131   default: llvm_unreachable("Unexpected SETCC condition");
13132   case ISD::SETNE:
13133     // (x != y) -> ~(x ^ y)
13134     return DAG.getNode(ISD::XOR, dl, VT,
13135                        DAG.getNode(ISD::XOR, dl, VT, Op0, Op1),
13136                        DAG.getConstant(-1, dl, VT));
13137   case ISD::SETEQ:
13138     // (x == y) -> (x ^ y)
13139     return DAG.getNode(ISD::XOR, dl, VT, Op0, Op1);
13140   case ISD::SETUGT:
13141   case ISD::SETGT:
13142     // (x > y) -> (x & ~y)
13143     return DAG.getNode(ISD::AND, dl, VT, Op0, NotOp1);
13144   case ISD::SETULT:
13145   case ISD::SETLT:
13146     // (x < y) -> (~x & y)
13147     return DAG.getNode(ISD::AND, dl, VT, NotOp0, Op1);
13148   case ISD::SETULE:
13149   case ISD::SETLE:
13150     // (x <= y) -> (~x | y)
13151     return DAG.getNode(ISD::OR, dl, VT, NotOp0, Op1);
13152   case ISD::SETUGE:
13153   case ISD::SETGE:
13154     // (x >=y) -> (x | ~y)
13155     return DAG.getNode(ISD::OR, dl, VT, Op0, NotOp1);
13156   }
13157 }
13158
13159 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
13160                                      const X86Subtarget *Subtarget) {
13161   SDValue Op0 = Op.getOperand(0);
13162   SDValue Op1 = Op.getOperand(1);
13163   SDValue CC = Op.getOperand(2);
13164   MVT VT = Op.getSimpleValueType();
13165   SDLoc dl(Op);
13166
13167   assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 8 &&
13168          Op.getValueType().getScalarType() == MVT::i1 &&
13169          "Cannot set masked compare for this operation");
13170
13171   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13172   unsigned  Opc = 0;
13173   bool Unsigned = false;
13174   bool Swap = false;
13175   unsigned SSECC;
13176   switch (SetCCOpcode) {
13177   default: llvm_unreachable("Unexpected SETCC condition");
13178   case ISD::SETNE:  SSECC = 4; break;
13179   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
13180   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
13181   case ISD::SETLT:  Swap = true; //fall-through
13182   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
13183   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
13184   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
13185   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
13186   case ISD::SETULE: Unsigned = true; //fall-through
13187   case ISD::SETLE:  SSECC = 2; break;
13188   }
13189
13190   if (Swap)
13191     std::swap(Op0, Op1);
13192   if (Opc)
13193     return DAG.getNode(Opc, dl, VT, Op0, Op1);
13194   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
13195   return DAG.getNode(Opc, dl, VT, Op0, Op1,
13196                      DAG.getConstant(SSECC, dl, MVT::i8));
13197 }
13198
13199 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
13200 /// operand \p Op1.  If non-trivial (for example because it's not constant)
13201 /// return an empty value.
13202 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
13203 {
13204   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
13205   if (!BV)
13206     return SDValue();
13207
13208   MVT VT = Op1.getSimpleValueType();
13209   MVT EVT = VT.getVectorElementType();
13210   unsigned n = VT.getVectorNumElements();
13211   SmallVector<SDValue, 8> ULTOp1;
13212
13213   for (unsigned i = 0; i < n; ++i) {
13214     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
13215     if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
13216       return SDValue();
13217
13218     // Avoid underflow.
13219     APInt Val = Elt->getAPIntValue();
13220     if (Val == 0)
13221       return SDValue();
13222
13223     ULTOp1.push_back(DAG.getConstant(Val - 1, dl, EVT));
13224   }
13225
13226   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
13227 }
13228
13229 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
13230                            SelectionDAG &DAG) {
13231   SDValue Op0 = Op.getOperand(0);
13232   SDValue Op1 = Op.getOperand(1);
13233   SDValue CC = Op.getOperand(2);
13234   MVT VT = Op.getSimpleValueType();
13235   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13236   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
13237   SDLoc dl(Op);
13238
13239   if (isFP) {
13240 #ifndef NDEBUG
13241     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
13242     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
13243 #endif
13244
13245     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
13246     unsigned Opc = X86ISD::CMPP;
13247     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
13248       assert(VT.getVectorNumElements() <= 16);
13249       Opc = X86ISD::CMPM;
13250     }
13251     // In the two special cases we can't handle, emit two comparisons.
13252     if (SSECC == 8) {
13253       unsigned CC0, CC1;
13254       unsigned CombineOpc;
13255       if (SetCCOpcode == ISD::SETUEQ) {
13256         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
13257       } else {
13258         assert(SetCCOpcode == ISD::SETONE);
13259         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
13260       }
13261
13262       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13263                                  DAG.getConstant(CC0, dl, MVT::i8));
13264       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13265                                  DAG.getConstant(CC1, dl, MVT::i8));
13266       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
13267     }
13268     // Handle all other FP comparisons here.
13269     return DAG.getNode(Opc, dl, VT, Op0, Op1,
13270                        DAG.getConstant(SSECC, dl, MVT::i8));
13271   }
13272
13273   // Break 256-bit integer vector compare into smaller ones.
13274   if (VT.is256BitVector() && !Subtarget->hasInt256())
13275     return Lower256IntVSETCC(Op, DAG);
13276
13277   EVT OpVT = Op1.getValueType();
13278   if (OpVT.getVectorElementType() == MVT::i1)
13279     return LowerBoolVSETCC_AVX512(Op, DAG);
13280
13281   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
13282   if (Subtarget->hasAVX512()) {
13283     if (Op1.getValueType().is512BitVector() ||
13284         (Subtarget->hasBWI() && Subtarget->hasVLX()) ||
13285         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
13286       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
13287
13288     // In AVX-512 architecture setcc returns mask with i1 elements,
13289     // But there is no compare instruction for i8 and i16 elements in KNL.
13290     // We are not talking about 512-bit operands in this case, these
13291     // types are illegal.
13292     if (MaskResult &&
13293         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
13294          OpVT.getVectorElementType().getSizeInBits() >= 8))
13295       return DAG.getNode(ISD::TRUNCATE, dl, VT,
13296                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
13297   }
13298
13299   // We are handling one of the integer comparisons here.  Since SSE only has
13300   // GT and EQ comparisons for integer, swapping operands and multiple
13301   // operations may be required for some comparisons.
13302   unsigned Opc;
13303   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
13304   bool Subus = false;
13305
13306   switch (SetCCOpcode) {
13307   default: llvm_unreachable("Unexpected SETCC condition");
13308   case ISD::SETNE:  Invert = true;
13309   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
13310   case ISD::SETLT:  Swap = true;
13311   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
13312   case ISD::SETGE:  Swap = true;
13313   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
13314                     Invert = true; break;
13315   case ISD::SETULT: Swap = true;
13316   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
13317                     FlipSigns = true; break;
13318   case ISD::SETUGE: Swap = true;
13319   case ISD::SETULE: Opc = X86ISD::PCMPGT;
13320                     FlipSigns = true; Invert = true; break;
13321   }
13322
13323   // Special case: Use min/max operations for SETULE/SETUGE
13324   MVT VET = VT.getVectorElementType();
13325   bool hasMinMax =
13326        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
13327     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
13328
13329   if (hasMinMax) {
13330     switch (SetCCOpcode) {
13331     default: break;
13332     case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
13333     case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
13334     }
13335
13336     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
13337   }
13338
13339   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
13340   if (!MinMax && hasSubus) {
13341     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
13342     // Op0 u<= Op1:
13343     //   t = psubus Op0, Op1
13344     //   pcmpeq t, <0..0>
13345     switch (SetCCOpcode) {
13346     default: break;
13347     case ISD::SETULT: {
13348       // If the comparison is against a constant we can turn this into a
13349       // setule.  With psubus, setule does not require a swap.  This is
13350       // beneficial because the constant in the register is no longer
13351       // destructed as the destination so it can be hoisted out of a loop.
13352       // Only do this pre-AVX since vpcmp* is no longer destructive.
13353       if (Subtarget->hasAVX())
13354         break;
13355       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
13356       if (ULEOp1.getNode()) {
13357         Op1 = ULEOp1;
13358         Subus = true; Invert = false; Swap = false;
13359       }
13360       break;
13361     }
13362     // Psubus is better than flip-sign because it requires no inversion.
13363     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
13364     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
13365     }
13366
13367     if (Subus) {
13368       Opc = X86ISD::SUBUS;
13369       FlipSigns = false;
13370     }
13371   }
13372
13373   if (Swap)
13374     std::swap(Op0, Op1);
13375
13376   // Check that the operation in question is available (most are plain SSE2,
13377   // but PCMPGTQ and PCMPEQQ have different requirements).
13378   if (VT == MVT::v2i64) {
13379     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
13380       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
13381
13382       // First cast everything to the right type.
13383       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
13384       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
13385
13386       // Since SSE has no unsigned integer comparisons, we need to flip the sign
13387       // bits of the inputs before performing those operations. The lower
13388       // compare is always unsigned.
13389       SDValue SB;
13390       if (FlipSigns) {
13391         SB = DAG.getConstant(0x80000000U, dl, MVT::v4i32);
13392       } else {
13393         SDValue Sign = DAG.getConstant(0x80000000U, dl, MVT::i32);
13394         SDValue Zero = DAG.getConstant(0x00000000U, dl, MVT::i32);
13395         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
13396                          Sign, Zero, Sign, Zero);
13397       }
13398       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
13399       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
13400
13401       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
13402       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
13403       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
13404
13405       // Create masks for only the low parts/high parts of the 64 bit integers.
13406       static const int MaskHi[] = { 1, 1, 3, 3 };
13407       static const int MaskLo[] = { 0, 0, 2, 2 };
13408       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
13409       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
13410       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
13411
13412       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
13413       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
13414
13415       if (Invert)
13416         Result = DAG.getNOT(dl, Result, MVT::v4i32);
13417
13418       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
13419     }
13420
13421     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
13422       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
13423       // pcmpeqd + pshufd + pand.
13424       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
13425
13426       // First cast everything to the right type.
13427       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
13428       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
13429
13430       // Do the compare.
13431       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
13432
13433       // Make sure the lower and upper halves are both all-ones.
13434       static const int Mask[] = { 1, 0, 3, 2 };
13435       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
13436       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
13437
13438       if (Invert)
13439         Result = DAG.getNOT(dl, Result, MVT::v4i32);
13440
13441       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
13442     }
13443   }
13444
13445   // Since SSE has no unsigned integer comparisons, we need to flip the sign
13446   // bits of the inputs before performing those operations.
13447   if (FlipSigns) {
13448     EVT EltVT = VT.getVectorElementType();
13449     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), dl,
13450                                  VT);
13451     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
13452     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
13453   }
13454
13455   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
13456
13457   // If the logical-not of the result is required, perform that now.
13458   if (Invert)
13459     Result = DAG.getNOT(dl, Result, VT);
13460
13461   if (MinMax)
13462     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
13463
13464   if (Subus)
13465     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
13466                          getZeroVector(VT, Subtarget, DAG, dl));
13467
13468   return Result;
13469 }
13470
13471 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
13472
13473   MVT VT = Op.getSimpleValueType();
13474
13475   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
13476
13477   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
13478          && "SetCC type must be 8-bit or 1-bit integer");
13479   SDValue Op0 = Op.getOperand(0);
13480   SDValue Op1 = Op.getOperand(1);
13481   SDLoc dl(Op);
13482   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
13483
13484   // Optimize to BT if possible.
13485   // Lower (X & (1 << N)) == 0 to BT(X, N).
13486   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
13487   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
13488   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
13489       Op1.getOpcode() == ISD::Constant &&
13490       cast<ConstantSDNode>(Op1)->isNullValue() &&
13491       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13492     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
13493     if (NewSetCC.getNode()) {
13494       if (VT == MVT::i1)
13495         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewSetCC);
13496       return NewSetCC;
13497     }
13498   }
13499
13500   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
13501   // these.
13502   if (Op1.getOpcode() == ISD::Constant &&
13503       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
13504        cast<ConstantSDNode>(Op1)->isNullValue()) &&
13505       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13506
13507     // If the input is a setcc, then reuse the input setcc or use a new one with
13508     // the inverted condition.
13509     if (Op0.getOpcode() == X86ISD::SETCC) {
13510       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
13511       bool Invert = (CC == ISD::SETNE) ^
13512         cast<ConstantSDNode>(Op1)->isNullValue();
13513       if (!Invert)
13514         return Op0;
13515
13516       CCode = X86::GetOppositeBranchCondition(CCode);
13517       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13518                                   DAG.getConstant(CCode, dl, MVT::i8),
13519                                   Op0.getOperand(1));
13520       if (VT == MVT::i1)
13521         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13522       return SetCC;
13523     }
13524   }
13525   if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
13526       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
13527       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13528
13529     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
13530     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, dl, MVT::i1), NewCC);
13531   }
13532
13533   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
13534   unsigned X86CC = TranslateX86CC(CC, dl, isFP, Op0, Op1, DAG);
13535   if (X86CC == X86::COND_INVALID)
13536     return SDValue();
13537
13538   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
13539   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
13540   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13541                               DAG.getConstant(X86CC, dl, MVT::i8), EFLAGS);
13542   if (VT == MVT::i1)
13543     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13544   return SetCC;
13545 }
13546
13547 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
13548 static bool isX86LogicalCmp(SDValue Op) {
13549   unsigned Opc = Op.getNode()->getOpcode();
13550   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
13551       Opc == X86ISD::SAHF)
13552     return true;
13553   if (Op.getResNo() == 1 &&
13554       (Opc == X86ISD::ADD ||
13555        Opc == X86ISD::SUB ||
13556        Opc == X86ISD::ADC ||
13557        Opc == X86ISD::SBB ||
13558        Opc == X86ISD::SMUL ||
13559        Opc == X86ISD::UMUL ||
13560        Opc == X86ISD::INC ||
13561        Opc == X86ISD::DEC ||
13562        Opc == X86ISD::OR ||
13563        Opc == X86ISD::XOR ||
13564        Opc == X86ISD::AND))
13565     return true;
13566
13567   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
13568     return true;
13569
13570   return false;
13571 }
13572
13573 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
13574   if (V.getOpcode() != ISD::TRUNCATE)
13575     return false;
13576
13577   SDValue VOp0 = V.getOperand(0);
13578   unsigned InBits = VOp0.getValueSizeInBits();
13579   unsigned Bits = V.getValueSizeInBits();
13580   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
13581 }
13582
13583 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
13584   bool addTest = true;
13585   SDValue Cond  = Op.getOperand(0);
13586   SDValue Op1 = Op.getOperand(1);
13587   SDValue Op2 = Op.getOperand(2);
13588   SDLoc DL(Op);
13589   EVT VT = Op1.getValueType();
13590   SDValue CC;
13591
13592   // Lower FP selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
13593   // are available or VBLENDV if AVX is available.
13594   // Otherwise FP cmovs get lowered into a less efficient branch sequence later.
13595   if (Cond.getOpcode() == ISD::SETCC &&
13596       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
13597        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
13598       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
13599     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
13600     int SSECC = translateX86FSETCC(
13601         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
13602
13603     if (SSECC != 8) {
13604       if (Subtarget->hasAVX512()) {
13605         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
13606                                   DAG.getConstant(SSECC, DL, MVT::i8));
13607         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
13608       }
13609
13610       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
13611                                 DAG.getConstant(SSECC, DL, MVT::i8));
13612
13613       // If we have AVX, we can use a variable vector select (VBLENDV) instead
13614       // of 3 logic instructions for size savings and potentially speed.
13615       // Unfortunately, there is no scalar form of VBLENDV.
13616
13617       // If either operand is a constant, don't try this. We can expect to
13618       // optimize away at least one of the logic instructions later in that
13619       // case, so that sequence would be faster than a variable blend.
13620
13621       // BLENDV was introduced with SSE 4.1, but the 2 register form implicitly
13622       // uses XMM0 as the selection register. That may need just as many
13623       // instructions as the AND/ANDN/OR sequence due to register moves, so
13624       // don't bother.
13625
13626       if (Subtarget->hasAVX() &&
13627           !isa<ConstantFPSDNode>(Op1) && !isa<ConstantFPSDNode>(Op2)) {
13628
13629         // Convert to vectors, do a VSELECT, and convert back to scalar.
13630         // All of the conversions should be optimized away.
13631
13632         EVT VecVT = VT == MVT::f32 ? MVT::v4f32 : MVT::v2f64;
13633         SDValue VOp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op1);
13634         SDValue VOp2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op2);
13635         SDValue VCmp = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Cmp);
13636
13637         EVT VCmpVT = VT == MVT::f32 ? MVT::v4i32 : MVT::v2i64;
13638         VCmp = DAG.getNode(ISD::BITCAST, DL, VCmpVT, VCmp);
13639
13640         SDValue VSel = DAG.getNode(ISD::VSELECT, DL, VecVT, VCmp, VOp1, VOp2);
13641
13642         return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
13643                            VSel, DAG.getIntPtrConstant(0, DL));
13644       }
13645       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
13646       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
13647       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
13648     }
13649   }
13650
13651     if (VT.isVector() && VT.getScalarType() == MVT::i1) {
13652       SDValue Op1Scalar;
13653       if (ISD::isBuildVectorOfConstantSDNodes(Op1.getNode()))
13654         Op1Scalar = ConvertI1VectorToInterger(Op1, DAG);
13655       else if (Op1.getOpcode() == ISD::BITCAST && Op1.getOperand(0))
13656         Op1Scalar = Op1.getOperand(0);
13657       SDValue Op2Scalar;
13658       if (ISD::isBuildVectorOfConstantSDNodes(Op2.getNode()))
13659         Op2Scalar = ConvertI1VectorToInterger(Op2, DAG);
13660       else if (Op2.getOpcode() == ISD::BITCAST && Op2.getOperand(0))
13661         Op2Scalar = Op2.getOperand(0);
13662       if (Op1Scalar.getNode() && Op2Scalar.getNode()) {
13663         SDValue newSelect = DAG.getNode(ISD::SELECT, DL, 
13664                                         Op1Scalar.getValueType(),
13665                                         Cond, Op1Scalar, Op2Scalar);
13666         if (newSelect.getValueSizeInBits() == VT.getSizeInBits())
13667           return DAG.getNode(ISD::BITCAST, DL, VT, newSelect);
13668         SDValue ExtVec = DAG.getNode(ISD::BITCAST, DL, MVT::v8i1, newSelect);
13669         return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, ExtVec,
13670                            DAG.getIntPtrConstant(0, DL));
13671     }
13672   }
13673
13674   if (VT == MVT::v4i1 || VT == MVT::v2i1) {
13675     SDValue zeroConst = DAG.getIntPtrConstant(0, DL);
13676     Op1 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
13677                       DAG.getUNDEF(MVT::v8i1), Op1, zeroConst);
13678     Op2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
13679                       DAG.getUNDEF(MVT::v8i1), Op2, zeroConst);
13680     SDValue newSelect = DAG.getNode(ISD::SELECT, DL, MVT::v8i1,
13681                                     Cond, Op1, Op2);
13682     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, newSelect, zeroConst);
13683   }
13684
13685   if (Cond.getOpcode() == ISD::SETCC) {
13686     SDValue NewCond = LowerSETCC(Cond, DAG);
13687     if (NewCond.getNode())
13688       Cond = NewCond;
13689   }
13690
13691   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
13692   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
13693   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
13694   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
13695   if (Cond.getOpcode() == X86ISD::SETCC &&
13696       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
13697       isZero(Cond.getOperand(1).getOperand(1))) {
13698     SDValue Cmp = Cond.getOperand(1);
13699
13700     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
13701
13702     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
13703         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
13704       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
13705
13706       SDValue CmpOp0 = Cmp.getOperand(0);
13707       // Apply further optimizations for special cases
13708       // (select (x != 0), -1, 0) -> neg & sbb
13709       // (select (x == 0), 0, -1) -> neg & sbb
13710       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
13711         if (YC->isNullValue() &&
13712             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
13713           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
13714           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
13715                                     DAG.getConstant(0, DL,
13716                                                     CmpOp0.getValueType()),
13717                                     CmpOp0);
13718           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13719                                     DAG.getConstant(X86::COND_B, DL, MVT::i8),
13720                                     SDValue(Neg.getNode(), 1));
13721           return Res;
13722         }
13723
13724       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
13725                         CmpOp0, DAG.getConstant(1, DL, CmpOp0.getValueType()));
13726       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
13727
13728       SDValue Res =   // Res = 0 or -1.
13729         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13730                     DAG.getConstant(X86::COND_B, DL, MVT::i8), Cmp);
13731
13732       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
13733         Res = DAG.getNOT(DL, Res, Res.getValueType());
13734
13735       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
13736       if (!N2C || !N2C->isNullValue())
13737         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
13738       return Res;
13739     }
13740   }
13741
13742   // Look past (and (setcc_carry (cmp ...)), 1).
13743   if (Cond.getOpcode() == ISD::AND &&
13744       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
13745     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
13746     if (C && C->getAPIntValue() == 1)
13747       Cond = Cond.getOperand(0);
13748   }
13749
13750   // If condition flag is set by a X86ISD::CMP, then use it as the condition
13751   // setting operand in place of the X86ISD::SETCC.
13752   unsigned CondOpcode = Cond.getOpcode();
13753   if (CondOpcode == X86ISD::SETCC ||
13754       CondOpcode == X86ISD::SETCC_CARRY) {
13755     CC = Cond.getOperand(0);
13756
13757     SDValue Cmp = Cond.getOperand(1);
13758     unsigned Opc = Cmp.getOpcode();
13759     MVT VT = Op.getSimpleValueType();
13760
13761     bool IllegalFPCMov = false;
13762     if (VT.isFloatingPoint() && !VT.isVector() &&
13763         !isScalarFPTypeInSSEReg(VT))  // FPStack?
13764       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
13765
13766     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
13767         Opc == X86ISD::BT) { // FIXME
13768       Cond = Cmp;
13769       addTest = false;
13770     }
13771   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
13772              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
13773              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
13774               Cond.getOperand(0).getValueType() != MVT::i8)) {
13775     SDValue LHS = Cond.getOperand(0);
13776     SDValue RHS = Cond.getOperand(1);
13777     unsigned X86Opcode;
13778     unsigned X86Cond;
13779     SDVTList VTs;
13780     switch (CondOpcode) {
13781     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
13782     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
13783     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
13784     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
13785     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
13786     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
13787     default: llvm_unreachable("unexpected overflowing operator");
13788     }
13789     if (CondOpcode == ISD::UMULO)
13790       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
13791                           MVT::i32);
13792     else
13793       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
13794
13795     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
13796
13797     if (CondOpcode == ISD::UMULO)
13798       Cond = X86Op.getValue(2);
13799     else
13800       Cond = X86Op.getValue(1);
13801
13802     CC = DAG.getConstant(X86Cond, DL, MVT::i8);
13803     addTest = false;
13804   }
13805
13806   if (addTest) {
13807     // Look pass the truncate if the high bits are known zero.
13808     if (isTruncWithZeroHighBitsInput(Cond, DAG))
13809         Cond = Cond.getOperand(0);
13810
13811     // We know the result of AND is compared against zero. Try to match
13812     // it to BT.
13813     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
13814       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
13815       if (NewSetCC.getNode()) {
13816         CC = NewSetCC.getOperand(0);
13817         Cond = NewSetCC.getOperand(1);
13818         addTest = false;
13819       }
13820     }
13821   }
13822
13823   if (addTest) {
13824     CC = DAG.getConstant(X86::COND_NE, DL, MVT::i8);
13825     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
13826   }
13827
13828   // a <  b ? -1 :  0 -> RES = ~setcc_carry
13829   // a <  b ?  0 : -1 -> RES = setcc_carry
13830   // a >= b ? -1 :  0 -> RES = setcc_carry
13831   // a >= b ?  0 : -1 -> RES = ~setcc_carry
13832   if (Cond.getOpcode() == X86ISD::SUB) {
13833     Cond = ConvertCmpIfNecessary(Cond, DAG);
13834     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
13835
13836     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
13837         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
13838       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13839                                 DAG.getConstant(X86::COND_B, DL, MVT::i8),
13840                                 Cond);
13841       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
13842         return DAG.getNOT(DL, Res, Res.getValueType());
13843       return Res;
13844     }
13845   }
13846
13847   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
13848   // widen the cmov and push the truncate through. This avoids introducing a new
13849   // branch during isel and doesn't add any extensions.
13850   if (Op.getValueType() == MVT::i8 &&
13851       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
13852     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
13853     if (T1.getValueType() == T2.getValueType() &&
13854         // Blacklist CopyFromReg to avoid partial register stalls.
13855         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
13856       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
13857       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
13858       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
13859     }
13860   }
13861
13862   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
13863   // condition is true.
13864   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
13865   SDValue Ops[] = { Op2, Op1, CC, Cond };
13866   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
13867 }
13868
13869 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, const X86Subtarget *Subtarget,
13870                                        SelectionDAG &DAG) {
13871   MVT VT = Op->getSimpleValueType(0);
13872   SDValue In = Op->getOperand(0);
13873   MVT InVT = In.getSimpleValueType();
13874   MVT VTElt = VT.getVectorElementType();
13875   MVT InVTElt = InVT.getVectorElementType();
13876   SDLoc dl(Op);
13877
13878   // SKX processor
13879   if ((InVTElt == MVT::i1) &&
13880       (((Subtarget->hasBWI() && Subtarget->hasVLX() &&
13881         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() <= 16)) ||
13882
13883        ((Subtarget->hasBWI() && VT.is512BitVector() &&
13884         VTElt.getSizeInBits() <= 16)) ||
13885
13886        ((Subtarget->hasDQI() && Subtarget->hasVLX() &&
13887         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() >= 32)) ||
13888
13889        ((Subtarget->hasDQI() && VT.is512BitVector() &&
13890         VTElt.getSizeInBits() >= 32))))
13891     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13892
13893   unsigned int NumElts = VT.getVectorNumElements();
13894
13895   if (NumElts != 8 && NumElts != 16)
13896     return SDValue();
13897
13898   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1) {
13899     if (In.getOpcode() == X86ISD::VSEXT || In.getOpcode() == X86ISD::VZEXT)
13900       return DAG.getNode(In.getOpcode(), dl, VT, In.getOperand(0));
13901     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13902   }
13903
13904   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
13905   MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
13906   SDValue NegOne =
13907    DAG.getConstant(APInt::getAllOnesValue(ExtVT.getScalarSizeInBits()), dl,
13908                    ExtVT);
13909   SDValue Zero =
13910    DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), dl, ExtVT);
13911
13912   SDValue V = DAG.getNode(ISD::VSELECT, dl, ExtVT, In, NegOne, Zero);
13913   if (VT.is512BitVector())
13914     return V;
13915   return DAG.getNode(X86ISD::VTRUNC, dl, VT, V);
13916 }
13917
13918 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
13919                                 SelectionDAG &DAG) {
13920   MVT VT = Op->getSimpleValueType(0);
13921   SDValue In = Op->getOperand(0);
13922   MVT InVT = In.getSimpleValueType();
13923   SDLoc dl(Op);
13924
13925   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
13926     return LowerSIGN_EXTEND_AVX512(Op, Subtarget, DAG);
13927
13928   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
13929       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
13930       (VT != MVT::v16i16 || InVT != MVT::v16i8))
13931     return SDValue();
13932
13933   if (Subtarget->hasInt256())
13934     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13935
13936   // Optimize vectors in AVX mode
13937   // Sign extend  v8i16 to v8i32 and
13938   //              v4i32 to v4i64
13939   //
13940   // Divide input vector into two parts
13941   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
13942   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
13943   // concat the vectors to original VT
13944
13945   unsigned NumElems = InVT.getVectorNumElements();
13946   SDValue Undef = DAG.getUNDEF(InVT);
13947
13948   SmallVector<int,8> ShufMask1(NumElems, -1);
13949   for (unsigned i = 0; i != NumElems/2; ++i)
13950     ShufMask1[i] = i;
13951
13952   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
13953
13954   SmallVector<int,8> ShufMask2(NumElems, -1);
13955   for (unsigned i = 0; i != NumElems/2; ++i)
13956     ShufMask2[i] = i + NumElems/2;
13957
13958   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
13959
13960   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
13961                                 VT.getVectorNumElements()/2);
13962
13963   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
13964   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
13965
13966   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
13967 }
13968
13969 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
13970 // may emit an illegal shuffle but the expansion is still better than scalar
13971 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
13972 // we'll emit a shuffle and a arithmetic shift.
13973 // FIXME: Is the expansion actually better than scalar code? It doesn't seem so.
13974 // TODO: It is possible to support ZExt by zeroing the undef values during
13975 // the shuffle phase or after the shuffle.
13976 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
13977                                  SelectionDAG &DAG) {
13978   MVT RegVT = Op.getSimpleValueType();
13979   assert(RegVT.isVector() && "We only custom lower vector sext loads.");
13980   assert(RegVT.isInteger() &&
13981          "We only custom lower integer vector sext loads.");
13982
13983   // Nothing useful we can do without SSE2 shuffles.
13984   assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
13985
13986   LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
13987   SDLoc dl(Ld);
13988   EVT MemVT = Ld->getMemoryVT();
13989   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13990   unsigned RegSz = RegVT.getSizeInBits();
13991
13992   ISD::LoadExtType Ext = Ld->getExtensionType();
13993
13994   assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
13995          && "Only anyext and sext are currently implemented.");
13996   assert(MemVT != RegVT && "Cannot extend to the same type");
13997   assert(MemVT.isVector() && "Must load a vector from memory");
13998
13999   unsigned NumElems = RegVT.getVectorNumElements();
14000   unsigned MemSz = MemVT.getSizeInBits();
14001   assert(RegSz > MemSz && "Register size must be greater than the mem size");
14002
14003   if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
14004     // The only way in which we have a legal 256-bit vector result but not the
14005     // integer 256-bit operations needed to directly lower a sextload is if we
14006     // have AVX1 but not AVX2. In that case, we can always emit a sextload to
14007     // a 128-bit vector and a normal sign_extend to 256-bits that should get
14008     // correctly legalized. We do this late to allow the canonical form of
14009     // sextload to persist throughout the rest of the DAG combiner -- it wants
14010     // to fold together any extensions it can, and so will fuse a sign_extend
14011     // of an sextload into a sextload targeting a wider value.
14012     SDValue Load;
14013     if (MemSz == 128) {
14014       // Just switch this to a normal load.
14015       assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
14016                                        "it must be a legal 128-bit vector "
14017                                        "type!");
14018       Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
14019                   Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
14020                   Ld->isInvariant(), Ld->getAlignment());
14021     } else {
14022       assert(MemSz < 128 &&
14023              "Can't extend a type wider than 128 bits to a 256 bit vector!");
14024       // Do an sext load to a 128-bit vector type. We want to use the same
14025       // number of elements, but elements half as wide. This will end up being
14026       // recursively lowered by this routine, but will succeed as we definitely
14027       // have all the necessary features if we're using AVX1.
14028       EVT HalfEltVT =
14029           EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
14030       EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
14031       Load =
14032           DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
14033                          Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
14034                          Ld->isNonTemporal(), Ld->isInvariant(),
14035                          Ld->getAlignment());
14036     }
14037
14038     // Replace chain users with the new chain.
14039     assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
14040     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
14041
14042     // Finally, do a normal sign-extend to the desired register.
14043     return DAG.getSExtOrTrunc(Load, dl, RegVT);
14044   }
14045
14046   // All sizes must be a power of two.
14047   assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
14048          "Non-power-of-two elements are not custom lowered!");
14049
14050   // Attempt to load the original value using scalar loads.
14051   // Find the largest scalar type that divides the total loaded size.
14052   MVT SclrLoadTy = MVT::i8;
14053   for (MVT Tp : MVT::integer_valuetypes()) {
14054     if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
14055       SclrLoadTy = Tp;
14056     }
14057   }
14058
14059   // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
14060   if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
14061       (64 <= MemSz))
14062     SclrLoadTy = MVT::f64;
14063
14064   // Calculate the number of scalar loads that we need to perform
14065   // in order to load our vector from memory.
14066   unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
14067
14068   assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
14069          "Can only lower sext loads with a single scalar load!");
14070
14071   unsigned loadRegZize = RegSz;
14072   if (Ext == ISD::SEXTLOAD && RegSz >= 256)
14073     loadRegZize = 128;
14074
14075   // Represent our vector as a sequence of elements which are the
14076   // largest scalar that we can load.
14077   EVT LoadUnitVecVT = EVT::getVectorVT(
14078       *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
14079
14080   // Represent the data using the same element type that is stored in
14081   // memory. In practice, we ''widen'' MemVT.
14082   EVT WideVecVT =
14083       EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
14084                        loadRegZize / MemVT.getScalarType().getSizeInBits());
14085
14086   assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
14087          "Invalid vector type");
14088
14089   // We can't shuffle using an illegal type.
14090   assert(TLI.isTypeLegal(WideVecVT) &&
14091          "We only lower types that form legal widened vector types");
14092
14093   SmallVector<SDValue, 8> Chains;
14094   SDValue Ptr = Ld->getBasePtr();
14095   SDValue Increment =
14096       DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, dl, TLI.getPointerTy());
14097   SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
14098
14099   for (unsigned i = 0; i < NumLoads; ++i) {
14100     // Perform a single load.
14101     SDValue ScalarLoad =
14102         DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
14103                     Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
14104                     Ld->getAlignment());
14105     Chains.push_back(ScalarLoad.getValue(1));
14106     // Create the first element type using SCALAR_TO_VECTOR in order to avoid
14107     // another round of DAGCombining.
14108     if (i == 0)
14109       Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
14110     else
14111       Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
14112                         ScalarLoad, DAG.getIntPtrConstant(i, dl));
14113
14114     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
14115   }
14116
14117   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
14118
14119   // Bitcast the loaded value to a vector of the original element type, in
14120   // the size of the target vector type.
14121   SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
14122   unsigned SizeRatio = RegSz / MemSz;
14123
14124   if (Ext == ISD::SEXTLOAD) {
14125     // If we have SSE4.1, we can directly emit a VSEXT node.
14126     if (Subtarget->hasSSE41()) {
14127       SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
14128       DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14129       return Sext;
14130     }
14131
14132     // Otherwise we'll shuffle the small elements in the high bits of the
14133     // larger type and perform an arithmetic shift. If the shift is not legal
14134     // it's better to scalarize.
14135     assert(TLI.isOperationLegalOrCustom(ISD::SRA, RegVT) &&
14136            "We can't implement a sext load without an arithmetic right shift!");
14137
14138     // Redistribute the loaded elements into the different locations.
14139     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
14140     for (unsigned i = 0; i != NumElems; ++i)
14141       ShuffleVec[i * SizeRatio + SizeRatio - 1] = i;
14142
14143     SDValue Shuff = DAG.getVectorShuffle(
14144         WideVecVT, dl, SlicedVec, DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
14145
14146     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
14147
14148     // Build the arithmetic shift.
14149     unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
14150                    MemVT.getVectorElementType().getSizeInBits();
14151     Shuff =
14152         DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
14153                     DAG.getConstant(Amt, dl, RegVT));
14154
14155     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14156     return Shuff;
14157   }
14158
14159   // Redistribute the loaded elements into the different locations.
14160   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
14161   for (unsigned i = 0; i != NumElems; ++i)
14162     ShuffleVec[i * SizeRatio] = i;
14163
14164   SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
14165                                        DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
14166
14167   // Bitcast to the requested type.
14168   Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
14169   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14170   return Shuff;
14171 }
14172
14173 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
14174 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
14175 // from the AND / OR.
14176 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
14177   Opc = Op.getOpcode();
14178   if (Opc != ISD::OR && Opc != ISD::AND)
14179     return false;
14180   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
14181           Op.getOperand(0).hasOneUse() &&
14182           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
14183           Op.getOperand(1).hasOneUse());
14184 }
14185
14186 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
14187 // 1 and that the SETCC node has a single use.
14188 static bool isXor1OfSetCC(SDValue Op) {
14189   if (Op.getOpcode() != ISD::XOR)
14190     return false;
14191   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
14192   if (N1C && N1C->getAPIntValue() == 1) {
14193     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
14194       Op.getOperand(0).hasOneUse();
14195   }
14196   return false;
14197 }
14198
14199 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
14200   bool addTest = true;
14201   SDValue Chain = Op.getOperand(0);
14202   SDValue Cond  = Op.getOperand(1);
14203   SDValue Dest  = Op.getOperand(2);
14204   SDLoc dl(Op);
14205   SDValue CC;
14206   bool Inverted = false;
14207
14208   if (Cond.getOpcode() == ISD::SETCC) {
14209     // Check for setcc([su]{add,sub,mul}o == 0).
14210     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
14211         isa<ConstantSDNode>(Cond.getOperand(1)) &&
14212         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
14213         Cond.getOperand(0).getResNo() == 1 &&
14214         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
14215          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
14216          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
14217          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
14218          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
14219          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
14220       Inverted = true;
14221       Cond = Cond.getOperand(0);
14222     } else {
14223       SDValue NewCond = LowerSETCC(Cond, DAG);
14224       if (NewCond.getNode())
14225         Cond = NewCond;
14226     }
14227   }
14228 #if 0
14229   // FIXME: LowerXALUO doesn't handle these!!
14230   else if (Cond.getOpcode() == X86ISD::ADD  ||
14231            Cond.getOpcode() == X86ISD::SUB  ||
14232            Cond.getOpcode() == X86ISD::SMUL ||
14233            Cond.getOpcode() == X86ISD::UMUL)
14234     Cond = LowerXALUO(Cond, DAG);
14235 #endif
14236
14237   // Look pass (and (setcc_carry (cmp ...)), 1).
14238   if (Cond.getOpcode() == ISD::AND &&
14239       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
14240     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
14241     if (C && C->getAPIntValue() == 1)
14242       Cond = Cond.getOperand(0);
14243   }
14244
14245   // If condition flag is set by a X86ISD::CMP, then use it as the condition
14246   // setting operand in place of the X86ISD::SETCC.
14247   unsigned CondOpcode = Cond.getOpcode();
14248   if (CondOpcode == X86ISD::SETCC ||
14249       CondOpcode == X86ISD::SETCC_CARRY) {
14250     CC = Cond.getOperand(0);
14251
14252     SDValue Cmp = Cond.getOperand(1);
14253     unsigned Opc = Cmp.getOpcode();
14254     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
14255     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
14256       Cond = Cmp;
14257       addTest = false;
14258     } else {
14259       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
14260       default: break;
14261       case X86::COND_O:
14262       case X86::COND_B:
14263         // These can only come from an arithmetic instruction with overflow,
14264         // e.g. SADDO, UADDO.
14265         Cond = Cond.getNode()->getOperand(1);
14266         addTest = false;
14267         break;
14268       }
14269     }
14270   }
14271   CondOpcode = Cond.getOpcode();
14272   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
14273       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
14274       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
14275        Cond.getOperand(0).getValueType() != MVT::i8)) {
14276     SDValue LHS = Cond.getOperand(0);
14277     SDValue RHS = Cond.getOperand(1);
14278     unsigned X86Opcode;
14279     unsigned X86Cond;
14280     SDVTList VTs;
14281     // Keep this in sync with LowerXALUO, otherwise we might create redundant
14282     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
14283     // X86ISD::INC).
14284     switch (CondOpcode) {
14285     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
14286     case ISD::SADDO:
14287       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14288         if (C->isOne()) {
14289           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
14290           break;
14291         }
14292       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
14293     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
14294     case ISD::SSUBO:
14295       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14296         if (C->isOne()) {
14297           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
14298           break;
14299         }
14300       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
14301     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
14302     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
14303     default: llvm_unreachable("unexpected overflowing operator");
14304     }
14305     if (Inverted)
14306       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
14307     if (CondOpcode == ISD::UMULO)
14308       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
14309                           MVT::i32);
14310     else
14311       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14312
14313     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
14314
14315     if (CondOpcode == ISD::UMULO)
14316       Cond = X86Op.getValue(2);
14317     else
14318       Cond = X86Op.getValue(1);
14319
14320     CC = DAG.getConstant(X86Cond, dl, MVT::i8);
14321     addTest = false;
14322   } else {
14323     unsigned CondOpc;
14324     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
14325       SDValue Cmp = Cond.getOperand(0).getOperand(1);
14326       if (CondOpc == ISD::OR) {
14327         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
14328         // two branches instead of an explicit OR instruction with a
14329         // separate test.
14330         if (Cmp == Cond.getOperand(1).getOperand(1) &&
14331             isX86LogicalCmp(Cmp)) {
14332           CC = Cond.getOperand(0).getOperand(0);
14333           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14334                               Chain, Dest, CC, Cmp);
14335           CC = Cond.getOperand(1).getOperand(0);
14336           Cond = Cmp;
14337           addTest = false;
14338         }
14339       } else { // ISD::AND
14340         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
14341         // two branches instead of an explicit AND instruction with a
14342         // separate test. However, we only do this if this block doesn't
14343         // have a fall-through edge, because this requires an explicit
14344         // jmp when the condition is false.
14345         if (Cmp == Cond.getOperand(1).getOperand(1) &&
14346             isX86LogicalCmp(Cmp) &&
14347             Op.getNode()->hasOneUse()) {
14348           X86::CondCode CCode =
14349             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
14350           CCode = X86::GetOppositeBranchCondition(CCode);
14351           CC = DAG.getConstant(CCode, dl, MVT::i8);
14352           SDNode *User = *Op.getNode()->use_begin();
14353           // Look for an unconditional branch following this conditional branch.
14354           // We need this because we need to reverse the successors in order
14355           // to implement FCMP_OEQ.
14356           if (User->getOpcode() == ISD::BR) {
14357             SDValue FalseBB = User->getOperand(1);
14358             SDNode *NewBR =
14359               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14360             assert(NewBR == User);
14361             (void)NewBR;
14362             Dest = FalseBB;
14363
14364             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14365                                 Chain, Dest, CC, Cmp);
14366             X86::CondCode CCode =
14367               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
14368             CCode = X86::GetOppositeBranchCondition(CCode);
14369             CC = DAG.getConstant(CCode, dl, MVT::i8);
14370             Cond = Cmp;
14371             addTest = false;
14372           }
14373         }
14374       }
14375     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
14376       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
14377       // It should be transformed during dag combiner except when the condition
14378       // is set by a arithmetics with overflow node.
14379       X86::CondCode CCode =
14380         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
14381       CCode = X86::GetOppositeBranchCondition(CCode);
14382       CC = DAG.getConstant(CCode, dl, MVT::i8);
14383       Cond = Cond.getOperand(0).getOperand(1);
14384       addTest = false;
14385     } else if (Cond.getOpcode() == ISD::SETCC &&
14386                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
14387       // For FCMP_OEQ, we can emit
14388       // two branches instead of an explicit AND instruction with a
14389       // separate test. However, we only do this if this block doesn't
14390       // have a fall-through edge, because this requires an explicit
14391       // jmp when the condition is false.
14392       if (Op.getNode()->hasOneUse()) {
14393         SDNode *User = *Op.getNode()->use_begin();
14394         // Look for an unconditional branch following this conditional branch.
14395         // We need this because we need to reverse the successors in order
14396         // to implement FCMP_OEQ.
14397         if (User->getOpcode() == ISD::BR) {
14398           SDValue FalseBB = User->getOperand(1);
14399           SDNode *NewBR =
14400             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14401           assert(NewBR == User);
14402           (void)NewBR;
14403           Dest = FalseBB;
14404
14405           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14406                                     Cond.getOperand(0), Cond.getOperand(1));
14407           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14408           CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
14409           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14410                               Chain, Dest, CC, Cmp);
14411           CC = DAG.getConstant(X86::COND_P, dl, MVT::i8);
14412           Cond = Cmp;
14413           addTest = false;
14414         }
14415       }
14416     } else if (Cond.getOpcode() == ISD::SETCC &&
14417                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
14418       // For FCMP_UNE, we can emit
14419       // two branches instead of an explicit AND instruction with a
14420       // separate test. However, we only do this if this block doesn't
14421       // have a fall-through edge, because this requires an explicit
14422       // jmp when the condition is false.
14423       if (Op.getNode()->hasOneUse()) {
14424         SDNode *User = *Op.getNode()->use_begin();
14425         // Look for an unconditional branch following this conditional branch.
14426         // We need this because we need to reverse the successors in order
14427         // to implement FCMP_UNE.
14428         if (User->getOpcode() == ISD::BR) {
14429           SDValue FalseBB = User->getOperand(1);
14430           SDNode *NewBR =
14431             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14432           assert(NewBR == User);
14433           (void)NewBR;
14434
14435           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14436                                     Cond.getOperand(0), Cond.getOperand(1));
14437           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14438           CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
14439           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14440                               Chain, Dest, CC, Cmp);
14441           CC = DAG.getConstant(X86::COND_NP, dl, MVT::i8);
14442           Cond = Cmp;
14443           addTest = false;
14444           Dest = FalseBB;
14445         }
14446       }
14447     }
14448   }
14449
14450   if (addTest) {
14451     // Look pass the truncate if the high bits are known zero.
14452     if (isTruncWithZeroHighBitsInput(Cond, DAG))
14453         Cond = Cond.getOperand(0);
14454
14455     // We know the result of AND is compared against zero. Try to match
14456     // it to BT.
14457     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
14458       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
14459       if (NewSetCC.getNode()) {
14460         CC = NewSetCC.getOperand(0);
14461         Cond = NewSetCC.getOperand(1);
14462         addTest = false;
14463       }
14464     }
14465   }
14466
14467   if (addTest) {
14468     X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
14469     CC = DAG.getConstant(X86Cond, dl, MVT::i8);
14470     Cond = EmitTest(Cond, X86Cond, dl, DAG);
14471   }
14472   Cond = ConvertCmpIfNecessary(Cond, DAG);
14473   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14474                      Chain, Dest, CC, Cond);
14475 }
14476
14477 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
14478 // Calls to _alloca are needed to probe the stack when allocating more than 4k
14479 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
14480 // that the guard pages used by the OS virtual memory manager are allocated in
14481 // correct sequence.
14482 SDValue
14483 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
14484                                            SelectionDAG &DAG) const {
14485   MachineFunction &MF = DAG.getMachineFunction();
14486   bool SplitStack = MF.shouldSplitStack();
14487   bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMachO()) ||
14488                SplitStack;
14489   SDLoc dl(Op);
14490
14491   if (!Lower) {
14492     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14493     SDNode* Node = Op.getNode();
14494
14495     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
14496     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
14497         " not tell us which reg is the stack pointer!");
14498     EVT VT = Node->getValueType(0);
14499     SDValue Tmp1 = SDValue(Node, 0);
14500     SDValue Tmp2 = SDValue(Node, 1);
14501     SDValue Tmp3 = Node->getOperand(2);
14502     SDValue Chain = Tmp1.getOperand(0);
14503
14504     // Chain the dynamic stack allocation so that it doesn't modify the stack
14505     // pointer when other instructions are using the stack.
14506     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, dl, true),
14507         SDLoc(Node));
14508
14509     SDValue Size = Tmp2.getOperand(1);
14510     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
14511     Chain = SP.getValue(1);
14512     unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
14513     const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
14514     unsigned StackAlign = TFI.getStackAlignment();
14515     Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
14516     if (Align > StackAlign)
14517       Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
14518           DAG.getConstant(-(uint64_t)Align, dl, VT));
14519     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
14520
14521     Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
14522         DAG.getIntPtrConstant(0, dl, true), SDValue(),
14523         SDLoc(Node));
14524
14525     SDValue Ops[2] = { Tmp1, Tmp2 };
14526     return DAG.getMergeValues(Ops, dl);
14527   }
14528
14529   // Get the inputs.
14530   SDValue Chain = Op.getOperand(0);
14531   SDValue Size  = Op.getOperand(1);
14532   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
14533   EVT VT = Op.getNode()->getValueType(0);
14534
14535   bool Is64Bit = Subtarget->is64Bit();
14536   EVT SPTy = getPointerTy();
14537
14538   if (SplitStack) {
14539     MachineRegisterInfo &MRI = MF.getRegInfo();
14540
14541     if (Is64Bit) {
14542       // The 64 bit implementation of segmented stacks needs to clobber both r10
14543       // r11. This makes it impossible to use it along with nested parameters.
14544       const Function *F = MF.getFunction();
14545
14546       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
14547            I != E; ++I)
14548         if (I->hasNestAttr())
14549           report_fatal_error("Cannot use segmented stacks with functions that "
14550                              "have nested arguments.");
14551     }
14552
14553     const TargetRegisterClass *AddrRegClass =
14554       getRegClassFor(getPointerTy());
14555     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
14556     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
14557     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
14558                                 DAG.getRegister(Vreg, SPTy));
14559     SDValue Ops1[2] = { Value, Chain };
14560     return DAG.getMergeValues(Ops1, dl);
14561   } else {
14562     SDValue Flag;
14563     const unsigned Reg = (Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX);
14564
14565     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
14566     Flag = Chain.getValue(1);
14567     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
14568
14569     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
14570
14571     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
14572     unsigned SPReg = RegInfo->getStackRegister();
14573     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
14574     Chain = SP.getValue(1);
14575
14576     if (Align) {
14577       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
14578                        DAG.getConstant(-(uint64_t)Align, dl, VT));
14579       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
14580     }
14581
14582     SDValue Ops1[2] = { SP, Chain };
14583     return DAG.getMergeValues(Ops1, dl);
14584   }
14585 }
14586
14587 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
14588   MachineFunction &MF = DAG.getMachineFunction();
14589   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
14590
14591   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
14592   SDLoc DL(Op);
14593
14594   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
14595     // vastart just stores the address of the VarArgsFrameIndex slot into the
14596     // memory location argument.
14597     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
14598                                    getPointerTy());
14599     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
14600                         MachinePointerInfo(SV), false, false, 0);
14601   }
14602
14603   // __va_list_tag:
14604   //   gp_offset         (0 - 6 * 8)
14605   //   fp_offset         (48 - 48 + 8 * 16)
14606   //   overflow_arg_area (point to parameters coming in memory).
14607   //   reg_save_area
14608   SmallVector<SDValue, 8> MemOps;
14609   SDValue FIN = Op.getOperand(1);
14610   // Store gp_offset
14611   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
14612                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
14613                                                DL, MVT::i32),
14614                                FIN, MachinePointerInfo(SV), false, false, 0);
14615   MemOps.push_back(Store);
14616
14617   // Store fp_offset
14618   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14619                     FIN, DAG.getIntPtrConstant(4, DL));
14620   Store = DAG.getStore(Op.getOperand(0), DL,
14621                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(), DL,
14622                                        MVT::i32),
14623                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
14624   MemOps.push_back(Store);
14625
14626   // Store ptr to overflow_arg_area
14627   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14628                     FIN, DAG.getIntPtrConstant(4, DL));
14629   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
14630                                     getPointerTy());
14631   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
14632                        MachinePointerInfo(SV, 8),
14633                        false, false, 0);
14634   MemOps.push_back(Store);
14635
14636   // Store ptr to reg_save_area.
14637   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14638                     FIN, DAG.getIntPtrConstant(8, DL));
14639   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
14640                                     getPointerTy());
14641   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
14642                        MachinePointerInfo(SV, 16), false, false, 0);
14643   MemOps.push_back(Store);
14644   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
14645 }
14646
14647 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
14648   assert(Subtarget->is64Bit() &&
14649          "LowerVAARG only handles 64-bit va_arg!");
14650   assert((Subtarget->isTargetLinux() ||
14651           Subtarget->isTargetDarwin()) &&
14652           "Unhandled target in LowerVAARG");
14653   assert(Op.getNode()->getNumOperands() == 4);
14654   SDValue Chain = Op.getOperand(0);
14655   SDValue SrcPtr = Op.getOperand(1);
14656   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
14657   unsigned Align = Op.getConstantOperandVal(3);
14658   SDLoc dl(Op);
14659
14660   EVT ArgVT = Op.getNode()->getValueType(0);
14661   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
14662   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
14663   uint8_t ArgMode;
14664
14665   // Decide which area this value should be read from.
14666   // TODO: Implement the AMD64 ABI in its entirety. This simple
14667   // selection mechanism works only for the basic types.
14668   if (ArgVT == MVT::f80) {
14669     llvm_unreachable("va_arg for f80 not yet implemented");
14670   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
14671     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
14672   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
14673     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
14674   } else {
14675     llvm_unreachable("Unhandled argument type in LowerVAARG");
14676   }
14677
14678   if (ArgMode == 2) {
14679     // Sanity Check: Make sure using fp_offset makes sense.
14680     assert(!Subtarget->useSoftFloat() &&
14681            !(DAG.getMachineFunction().getFunction()->hasFnAttribute(
14682                Attribute::NoImplicitFloat)) &&
14683            Subtarget->hasSSE1());
14684   }
14685
14686   // Insert VAARG_64 node into the DAG
14687   // VAARG_64 returns two values: Variable Argument Address, Chain
14688   SDValue InstOps[] = {Chain, SrcPtr, DAG.getConstant(ArgSize, dl, MVT::i32),
14689                        DAG.getConstant(ArgMode, dl, MVT::i8),
14690                        DAG.getConstant(Align, dl, MVT::i32)};
14691   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
14692   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
14693                                           VTs, InstOps, MVT::i64,
14694                                           MachinePointerInfo(SV),
14695                                           /*Align=*/0,
14696                                           /*Volatile=*/false,
14697                                           /*ReadMem=*/true,
14698                                           /*WriteMem=*/true);
14699   Chain = VAARG.getValue(1);
14700
14701   // Load the next argument and return it
14702   return DAG.getLoad(ArgVT, dl,
14703                      Chain,
14704                      VAARG,
14705                      MachinePointerInfo(),
14706                      false, false, false, 0);
14707 }
14708
14709 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
14710                            SelectionDAG &DAG) {
14711   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
14712   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
14713   SDValue Chain = Op.getOperand(0);
14714   SDValue DstPtr = Op.getOperand(1);
14715   SDValue SrcPtr = Op.getOperand(2);
14716   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
14717   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
14718   SDLoc DL(Op);
14719
14720   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
14721                        DAG.getIntPtrConstant(24, DL), 8, /*isVolatile*/false,
14722                        false, false,
14723                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
14724 }
14725
14726 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
14727 // amount is a constant. Takes immediate version of shift as input.
14728 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
14729                                           SDValue SrcOp, uint64_t ShiftAmt,
14730                                           SelectionDAG &DAG) {
14731   MVT ElementType = VT.getVectorElementType();
14732
14733   // Fold this packed shift into its first operand if ShiftAmt is 0.
14734   if (ShiftAmt == 0)
14735     return SrcOp;
14736
14737   // Check for ShiftAmt >= element width
14738   if (ShiftAmt >= ElementType.getSizeInBits()) {
14739     if (Opc == X86ISD::VSRAI)
14740       ShiftAmt = ElementType.getSizeInBits() - 1;
14741     else
14742       return DAG.getConstant(0, dl, VT);
14743   }
14744
14745   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
14746          && "Unknown target vector shift-by-constant node");
14747
14748   // Fold this packed vector shift into a build vector if SrcOp is a
14749   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
14750   if (VT == SrcOp.getSimpleValueType() &&
14751       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
14752     SmallVector<SDValue, 8> Elts;
14753     unsigned NumElts = SrcOp->getNumOperands();
14754     ConstantSDNode *ND;
14755
14756     switch(Opc) {
14757     default: llvm_unreachable(nullptr);
14758     case X86ISD::VSHLI:
14759       for (unsigned i=0; i!=NumElts; ++i) {
14760         SDValue CurrentOp = SrcOp->getOperand(i);
14761         if (CurrentOp->getOpcode() == ISD::UNDEF) {
14762           Elts.push_back(CurrentOp);
14763           continue;
14764         }
14765         ND = cast<ConstantSDNode>(CurrentOp);
14766         const APInt &C = ND->getAPIntValue();
14767         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), dl, ElementType));
14768       }
14769       break;
14770     case X86ISD::VSRLI:
14771       for (unsigned i=0; i!=NumElts; ++i) {
14772         SDValue CurrentOp = SrcOp->getOperand(i);
14773         if (CurrentOp->getOpcode() == ISD::UNDEF) {
14774           Elts.push_back(CurrentOp);
14775           continue;
14776         }
14777         ND = cast<ConstantSDNode>(CurrentOp);
14778         const APInt &C = ND->getAPIntValue();
14779         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), dl, ElementType));
14780       }
14781       break;
14782     case X86ISD::VSRAI:
14783       for (unsigned i=0; i!=NumElts; ++i) {
14784         SDValue CurrentOp = SrcOp->getOperand(i);
14785         if (CurrentOp->getOpcode() == ISD::UNDEF) {
14786           Elts.push_back(CurrentOp);
14787           continue;
14788         }
14789         ND = cast<ConstantSDNode>(CurrentOp);
14790         const APInt &C = ND->getAPIntValue();
14791         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), dl, ElementType));
14792       }
14793       break;
14794     }
14795
14796     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
14797   }
14798
14799   return DAG.getNode(Opc, dl, VT, SrcOp,
14800                      DAG.getConstant(ShiftAmt, dl, MVT::i8));
14801 }
14802
14803 // getTargetVShiftNode - Handle vector element shifts where the shift amount
14804 // may or may not be a constant. Takes immediate version of shift as input.
14805 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
14806                                    SDValue SrcOp, SDValue ShAmt,
14807                                    SelectionDAG &DAG) {
14808   MVT SVT = ShAmt.getSimpleValueType();
14809   assert((SVT == MVT::i32 || SVT == MVT::i64) && "Unexpected value type!");
14810
14811   // Catch shift-by-constant.
14812   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
14813     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
14814                                       CShAmt->getZExtValue(), DAG);
14815
14816   // Change opcode to non-immediate version
14817   switch (Opc) {
14818     default: llvm_unreachable("Unknown target vector shift node");
14819     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
14820     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
14821     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
14822   }
14823
14824   const X86Subtarget &Subtarget =
14825       static_cast<const X86Subtarget &>(DAG.getSubtarget());
14826   if (Subtarget.hasSSE41() && ShAmt.getOpcode() == ISD::ZERO_EXTEND &&
14827       ShAmt.getOperand(0).getSimpleValueType() == MVT::i16) {
14828     // Let the shuffle legalizer expand this shift amount node.
14829     SDValue Op0 = ShAmt.getOperand(0);
14830     Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(Op0), MVT::v8i16, Op0);
14831     ShAmt = getShuffleVectorZeroOrUndef(Op0, 0, true, &Subtarget, DAG);
14832   } else {
14833     // Need to build a vector containing shift amount.
14834     // SSE/AVX packed shifts only use the lower 64-bit of the shift count.
14835     SmallVector<SDValue, 4> ShOps;
14836     ShOps.push_back(ShAmt);
14837     if (SVT == MVT::i32) {
14838       ShOps.push_back(DAG.getConstant(0, dl, SVT));
14839       ShOps.push_back(DAG.getUNDEF(SVT));
14840     }
14841     ShOps.push_back(DAG.getUNDEF(SVT));
14842
14843     MVT BVT = SVT == MVT::i32 ? MVT::v4i32 : MVT::v2i64;
14844     ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, BVT, ShOps);
14845   }
14846
14847   // The return type has to be a 128-bit type with the same element
14848   // type as the input type.
14849   MVT EltVT = VT.getVectorElementType();
14850   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
14851
14852   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
14853   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
14854 }
14855
14856 /// \brief Return (and \p Op, \p Mask) for compare instructions or
14857 /// (vselect \p Mask, \p Op, \p PreservedSrc) for others along with the
14858 /// necessary casting for \p Mask when lowering masking intrinsics.
14859 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
14860                                     SDValue PreservedSrc,
14861                                     const X86Subtarget *Subtarget,
14862                                     SelectionDAG &DAG) {
14863     EVT VT = Op.getValueType();
14864     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
14865                                   MVT::i1, VT.getVectorNumElements());
14866     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14867                                      Mask.getValueType().getSizeInBits());
14868     SDLoc dl(Op);
14869
14870     assert(MaskVT.isSimple() && "invalid mask type");
14871
14872     if (isAllOnes(Mask))
14873       return Op;
14874
14875     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
14876     // are extracted by EXTRACT_SUBVECTOR.
14877     SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
14878                               DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
14879                               DAG.getIntPtrConstant(0, dl));
14880
14881     switch (Op.getOpcode()) {
14882       default: break;
14883       case X86ISD::PCMPEQM:
14884       case X86ISD::PCMPGTM:
14885       case X86ISD::CMPM:
14886       case X86ISD::CMPMU:
14887         return DAG.getNode(ISD::AND, dl, VT, Op, VMask);
14888     }
14889     if (PreservedSrc.getOpcode() == ISD::UNDEF)
14890       PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
14891     return DAG.getNode(ISD::VSELECT, dl, VT, VMask, Op, PreservedSrc);
14892 }
14893
14894 /// \brief Creates an SDNode for a predicated scalar operation.
14895 /// \returns (X86vselect \p Mask, \p Op, \p PreservedSrc).
14896 /// The mask is comming as MVT::i8 and it should be truncated
14897 /// to MVT::i1 while lowering masking intrinsics.
14898 /// The main difference between ScalarMaskingNode and VectorMaskingNode is using
14899 /// "X86select" instead of "vselect". We just can't create the "vselect" node for
14900 /// a scalar instruction.
14901 static SDValue getScalarMaskingNode(SDValue Op, SDValue Mask,
14902                                     SDValue PreservedSrc,
14903                                     const X86Subtarget *Subtarget,
14904                                     SelectionDAG &DAG) {
14905     if (isAllOnes(Mask))
14906       return Op;
14907
14908     EVT VT = Op.getValueType();
14909     SDLoc dl(Op);
14910     // The mask should be of type MVT::i1
14911     SDValue IMask = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Mask);
14912
14913     if (PreservedSrc.getOpcode() == ISD::UNDEF)
14914       PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
14915     return DAG.getNode(X86ISD::SELECT, dl, VT, IMask, Op, PreservedSrc);
14916 }
14917
14918 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
14919                                        SelectionDAG &DAG) {
14920   SDLoc dl(Op);
14921   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14922   EVT VT = Op.getValueType();
14923   const IntrinsicData* IntrData = getIntrinsicWithoutChain(IntNo);
14924   if (IntrData) {
14925     switch(IntrData->Type) {
14926     case INTR_TYPE_1OP:
14927       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1));
14928     case INTR_TYPE_2OP:
14929       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
14930         Op.getOperand(2));
14931     case INTR_TYPE_3OP:
14932       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
14933         Op.getOperand(2), Op.getOperand(3));
14934     case INTR_TYPE_1OP_MASK_RM: {
14935       SDValue Src = Op.getOperand(1);
14936       SDValue Src0 = Op.getOperand(2);
14937       SDValue Mask = Op.getOperand(3);
14938       SDValue RoundingMode = Op.getOperand(4);
14939       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src,
14940                                               RoundingMode),
14941                                   Mask, Src0, Subtarget, DAG);
14942     }
14943     case INTR_TYPE_SCALAR_MASK_RM: {
14944       SDValue Src1 = Op.getOperand(1);
14945       SDValue Src2 = Op.getOperand(2);
14946       SDValue Src0 = Op.getOperand(3);
14947       SDValue Mask = Op.getOperand(4);
14948       // There are 2 kinds of intrinsics in this group:
14949       // (1) With supress-all-exceptions (sae) or rounding mode- 6 operands
14950       // (2) With rounding mode and sae - 7 operands.
14951       if (Op.getNumOperands() == 6) {
14952         SDValue Sae  = Op.getOperand(5);
14953         unsigned Opc = IntrData->Opc1 ? IntrData->Opc1 : IntrData->Opc0;
14954         return getScalarMaskingNode(DAG.getNode(Opc, dl, VT, Src1, Src2,
14955                                                 Sae),
14956                                     Mask, Src0, Subtarget, DAG);
14957       }
14958       assert(Op.getNumOperands() == 7 && "Unexpected intrinsic form");
14959       SDValue RoundingMode  = Op.getOperand(5);
14960       SDValue Sae  = Op.getOperand(6);
14961       return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
14962                                               RoundingMode, Sae),
14963                                   Mask, Src0, Subtarget, DAG);
14964     }
14965     case INTR_TYPE_2OP_MASK: {
14966       SDValue Src1 = Op.getOperand(1);
14967       SDValue Src2 = Op.getOperand(2);
14968       SDValue PassThru = Op.getOperand(3);
14969       SDValue Mask = Op.getOperand(4);
14970       // We specify 2 possible opcodes for intrinsics with rounding modes.
14971       // First, we check if the intrinsic may have non-default rounding mode,
14972       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
14973       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
14974       if (IntrWithRoundingModeOpcode != 0) {
14975         SDValue Rnd = Op.getOperand(5);
14976         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
14977         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
14978           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
14979                                       dl, Op.getValueType(),
14980                                       Src1, Src2, Rnd),
14981                                       Mask, PassThru, Subtarget, DAG);
14982         }
14983       }
14984       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
14985                                               Src1,Src2),
14986                                   Mask, PassThru, Subtarget, DAG);
14987     }
14988     case FMA_OP_MASK: {
14989       SDValue Src1 = Op.getOperand(1);
14990       SDValue Src2 = Op.getOperand(2);
14991       SDValue Src3 = Op.getOperand(3);
14992       SDValue Mask = Op.getOperand(4);
14993       // We specify 2 possible opcodes for intrinsics with rounding modes.
14994       // First, we check if the intrinsic may have non-default rounding mode,
14995       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
14996       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
14997       if (IntrWithRoundingModeOpcode != 0) {
14998         SDValue Rnd = Op.getOperand(5);
14999         if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
15000             X86::STATIC_ROUNDING::CUR_DIRECTION)
15001           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15002                                                   dl, Op.getValueType(),
15003                                                   Src1, Src2, Src3, Rnd),
15004                                       Mask, Src1, Subtarget, DAG);
15005       }
15006       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0,
15007                                               dl, Op.getValueType(),
15008                                               Src1, Src2, Src3),
15009                                   Mask, Src1, Subtarget, DAG);
15010     }
15011     case CMP_MASK:
15012     case CMP_MASK_CC: {
15013       // Comparison intrinsics with masks.
15014       // Example of transformation:
15015       // (i8 (int_x86_avx512_mask_pcmpeq_q_128
15016       //             (v2i64 %a), (v2i64 %b), (i8 %mask))) ->
15017       // (i8 (bitcast
15018       //   (v8i1 (insert_subvector undef,
15019       //           (v2i1 (and (PCMPEQM %a, %b),
15020       //                      (extract_subvector
15021       //                         (v8i1 (bitcast %mask)), 0))), 0))))
15022       EVT VT = Op.getOperand(1).getValueType();
15023       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15024                                     VT.getVectorNumElements());
15025       SDValue Mask = Op.getOperand((IntrData->Type == CMP_MASK_CC) ? 4 : 3);
15026       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15027                                        Mask.getValueType().getSizeInBits());
15028       SDValue Cmp;
15029       if (IntrData->Type == CMP_MASK_CC) {
15030         SDValue CC = Op.getOperand(3);
15031         CC = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, CC);
15032         // We specify 2 possible opcodes for intrinsics with rounding modes.
15033         // First, we check if the intrinsic may have non-default rounding mode,
15034         // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15035         if (IntrData->Opc1 != 0) {
15036           SDValue Rnd = Op.getOperand(5);
15037           if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
15038               X86::STATIC_ROUNDING::CUR_DIRECTION)
15039             Cmp = DAG.getNode(IntrData->Opc1, dl, MaskVT, Op.getOperand(1),
15040                               Op.getOperand(2), CC, Rnd);
15041         }
15042         //default rounding mode
15043         if(!Cmp.getNode())
15044             Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
15045                               Op.getOperand(2), CC);
15046
15047       } else {
15048         assert(IntrData->Type == CMP_MASK && "Unexpected intrinsic type!");
15049         Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
15050                           Op.getOperand(2));
15051       }
15052       SDValue CmpMask = getVectorMaskingNode(Cmp, Mask,
15053                                              DAG.getTargetConstant(0, dl,
15054                                                                    MaskVT),
15055                                              Subtarget, DAG);
15056       SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
15057                                 DAG.getUNDEF(BitcastVT), CmpMask,
15058                                 DAG.getIntPtrConstant(0, dl));
15059       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
15060     }
15061     case COMI: { // Comparison intrinsics
15062       ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
15063       SDValue LHS = Op.getOperand(1);
15064       SDValue RHS = Op.getOperand(2);
15065       unsigned X86CC = TranslateX86CC(CC, dl, true, LHS, RHS, DAG);
15066       assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
15067       SDValue Cond = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
15068       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15069                                   DAG.getConstant(X86CC, dl, MVT::i8), Cond);
15070       return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15071     }
15072     case VSHIFT:
15073       return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
15074                                  Op.getOperand(1), Op.getOperand(2), DAG);
15075     case VSHIFT_MASK:
15076       return getVectorMaskingNode(getTargetVShiftNode(IntrData->Opc0, dl,
15077                                                       Op.getSimpleValueType(),
15078                                                       Op.getOperand(1),
15079                                                       Op.getOperand(2), DAG),
15080                                   Op.getOperand(4), Op.getOperand(3), Subtarget,
15081                                   DAG);
15082     case COMPRESS_EXPAND_IN_REG: {
15083       SDValue Mask = Op.getOperand(3);
15084       SDValue DataToCompress = Op.getOperand(1);
15085       SDValue PassThru = Op.getOperand(2);
15086       if (isAllOnes(Mask)) // return data as is
15087         return Op.getOperand(1);
15088       EVT VT = Op.getValueType();
15089       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15090                                     VT.getVectorNumElements());
15091       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15092                                        Mask.getValueType().getSizeInBits());
15093       SDLoc dl(Op);
15094       SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15095                                   DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
15096                                   DAG.getIntPtrConstant(0, dl));
15097
15098       return DAG.getNode(IntrData->Opc0, dl, VT, VMask, DataToCompress,
15099                          PassThru);
15100     }
15101     case BLEND: {
15102       SDValue Mask = Op.getOperand(3);
15103       EVT VT = Op.getValueType();
15104       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15105                                     VT.getVectorNumElements());
15106       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15107                                        Mask.getValueType().getSizeInBits());
15108       SDLoc dl(Op);
15109       SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15110                                   DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
15111                                   DAG.getIntPtrConstant(0, dl));
15112       return DAG.getNode(IntrData->Opc0, dl, VT, VMask, Op.getOperand(1),
15113                          Op.getOperand(2));
15114     }
15115     default:
15116       break;
15117     }
15118   }
15119
15120   switch (IntNo) {
15121   default: return SDValue();    // Don't custom lower most intrinsics.
15122
15123   case Intrinsic::x86_avx2_permd:
15124   case Intrinsic::x86_avx2_permps:
15125     // Operands intentionally swapped. Mask is last operand to intrinsic,
15126     // but second operand for node/instruction.
15127     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
15128                        Op.getOperand(2), Op.getOperand(1));
15129
15130   case Intrinsic::x86_avx512_mask_valign_q_512:
15131   case Intrinsic::x86_avx512_mask_valign_d_512:
15132     // Vector source operands are swapped.
15133     return getVectorMaskingNode(DAG.getNode(X86ISD::VALIGN, dl,
15134                                             Op.getValueType(), Op.getOperand(2),
15135                                             Op.getOperand(1),
15136                                             Op.getOperand(3)),
15137                                 Op.getOperand(5), Op.getOperand(4),
15138                                 Subtarget, DAG);
15139
15140   // ptest and testp intrinsics. The intrinsic these come from are designed to
15141   // return an integer value, not just an instruction so lower it to the ptest
15142   // or testp pattern and a setcc for the result.
15143   case Intrinsic::x86_sse41_ptestz:
15144   case Intrinsic::x86_sse41_ptestc:
15145   case Intrinsic::x86_sse41_ptestnzc:
15146   case Intrinsic::x86_avx_ptestz_256:
15147   case Intrinsic::x86_avx_ptestc_256:
15148   case Intrinsic::x86_avx_ptestnzc_256:
15149   case Intrinsic::x86_avx_vtestz_ps:
15150   case Intrinsic::x86_avx_vtestc_ps:
15151   case Intrinsic::x86_avx_vtestnzc_ps:
15152   case Intrinsic::x86_avx_vtestz_pd:
15153   case Intrinsic::x86_avx_vtestc_pd:
15154   case Intrinsic::x86_avx_vtestnzc_pd:
15155   case Intrinsic::x86_avx_vtestz_ps_256:
15156   case Intrinsic::x86_avx_vtestc_ps_256:
15157   case Intrinsic::x86_avx_vtestnzc_ps_256:
15158   case Intrinsic::x86_avx_vtestz_pd_256:
15159   case Intrinsic::x86_avx_vtestc_pd_256:
15160   case Intrinsic::x86_avx_vtestnzc_pd_256: {
15161     bool IsTestPacked = false;
15162     unsigned X86CC;
15163     switch (IntNo) {
15164     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
15165     case Intrinsic::x86_avx_vtestz_ps:
15166     case Intrinsic::x86_avx_vtestz_pd:
15167     case Intrinsic::x86_avx_vtestz_ps_256:
15168     case Intrinsic::x86_avx_vtestz_pd_256:
15169       IsTestPacked = true; // Fallthrough
15170     case Intrinsic::x86_sse41_ptestz:
15171     case Intrinsic::x86_avx_ptestz_256:
15172       // ZF = 1
15173       X86CC = X86::COND_E;
15174       break;
15175     case Intrinsic::x86_avx_vtestc_ps:
15176     case Intrinsic::x86_avx_vtestc_pd:
15177     case Intrinsic::x86_avx_vtestc_ps_256:
15178     case Intrinsic::x86_avx_vtestc_pd_256:
15179       IsTestPacked = true; // Fallthrough
15180     case Intrinsic::x86_sse41_ptestc:
15181     case Intrinsic::x86_avx_ptestc_256:
15182       // CF = 1
15183       X86CC = X86::COND_B;
15184       break;
15185     case Intrinsic::x86_avx_vtestnzc_ps:
15186     case Intrinsic::x86_avx_vtestnzc_pd:
15187     case Intrinsic::x86_avx_vtestnzc_ps_256:
15188     case Intrinsic::x86_avx_vtestnzc_pd_256:
15189       IsTestPacked = true; // Fallthrough
15190     case Intrinsic::x86_sse41_ptestnzc:
15191     case Intrinsic::x86_avx_ptestnzc_256:
15192       // ZF and CF = 0
15193       X86CC = X86::COND_A;
15194       break;
15195     }
15196
15197     SDValue LHS = Op.getOperand(1);
15198     SDValue RHS = Op.getOperand(2);
15199     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
15200     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
15201     SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
15202     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
15203     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15204   }
15205   case Intrinsic::x86_avx512_kortestz_w:
15206   case Intrinsic::x86_avx512_kortestc_w: {
15207     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
15208     SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
15209     SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
15210     SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
15211     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
15212     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
15213     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15214   }
15215
15216   case Intrinsic::x86_sse42_pcmpistria128:
15217   case Intrinsic::x86_sse42_pcmpestria128:
15218   case Intrinsic::x86_sse42_pcmpistric128:
15219   case Intrinsic::x86_sse42_pcmpestric128:
15220   case Intrinsic::x86_sse42_pcmpistrio128:
15221   case Intrinsic::x86_sse42_pcmpestrio128:
15222   case Intrinsic::x86_sse42_pcmpistris128:
15223   case Intrinsic::x86_sse42_pcmpestris128:
15224   case Intrinsic::x86_sse42_pcmpistriz128:
15225   case Intrinsic::x86_sse42_pcmpestriz128: {
15226     unsigned Opcode;
15227     unsigned X86CC;
15228     switch (IntNo) {
15229     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
15230     case Intrinsic::x86_sse42_pcmpistria128:
15231       Opcode = X86ISD::PCMPISTRI;
15232       X86CC = X86::COND_A;
15233       break;
15234     case Intrinsic::x86_sse42_pcmpestria128:
15235       Opcode = X86ISD::PCMPESTRI;
15236       X86CC = X86::COND_A;
15237       break;
15238     case Intrinsic::x86_sse42_pcmpistric128:
15239       Opcode = X86ISD::PCMPISTRI;
15240       X86CC = X86::COND_B;
15241       break;
15242     case Intrinsic::x86_sse42_pcmpestric128:
15243       Opcode = X86ISD::PCMPESTRI;
15244       X86CC = X86::COND_B;
15245       break;
15246     case Intrinsic::x86_sse42_pcmpistrio128:
15247       Opcode = X86ISD::PCMPISTRI;
15248       X86CC = X86::COND_O;
15249       break;
15250     case Intrinsic::x86_sse42_pcmpestrio128:
15251       Opcode = X86ISD::PCMPESTRI;
15252       X86CC = X86::COND_O;
15253       break;
15254     case Intrinsic::x86_sse42_pcmpistris128:
15255       Opcode = X86ISD::PCMPISTRI;
15256       X86CC = X86::COND_S;
15257       break;
15258     case Intrinsic::x86_sse42_pcmpestris128:
15259       Opcode = X86ISD::PCMPESTRI;
15260       X86CC = X86::COND_S;
15261       break;
15262     case Intrinsic::x86_sse42_pcmpistriz128:
15263       Opcode = X86ISD::PCMPISTRI;
15264       X86CC = X86::COND_E;
15265       break;
15266     case Intrinsic::x86_sse42_pcmpestriz128:
15267       Opcode = X86ISD::PCMPESTRI;
15268       X86CC = X86::COND_E;
15269       break;
15270     }
15271     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
15272     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
15273     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
15274     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15275                                 DAG.getConstant(X86CC, dl, MVT::i8),
15276                                 SDValue(PCMP.getNode(), 1));
15277     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15278   }
15279
15280   case Intrinsic::x86_sse42_pcmpistri128:
15281   case Intrinsic::x86_sse42_pcmpestri128: {
15282     unsigned Opcode;
15283     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
15284       Opcode = X86ISD::PCMPISTRI;
15285     else
15286       Opcode = X86ISD::PCMPESTRI;
15287
15288     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
15289     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
15290     return DAG.getNode(Opcode, dl, VTs, NewOps);
15291   }
15292   }
15293 }
15294
15295 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15296                               SDValue Src, SDValue Mask, SDValue Base,
15297                               SDValue Index, SDValue ScaleOp, SDValue Chain,
15298                               const X86Subtarget * Subtarget) {
15299   SDLoc dl(Op);
15300   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15301   assert(C && "Invalid scale type");
15302   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
15303   EVT MaskVT = MVT::getVectorVT(MVT::i1,
15304                              Index.getSimpleValueType().getVectorNumElements());
15305   SDValue MaskInReg;
15306   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15307   if (MaskC)
15308     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
15309   else
15310     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
15311   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
15312   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
15313   SDValue Segment = DAG.getRegister(0, MVT::i32);
15314   if (Src.getOpcode() == ISD::UNDEF)
15315     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
15316   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
15317   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
15318   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
15319   return DAG.getMergeValues(RetOps, dl);
15320 }
15321
15322 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15323                                SDValue Src, SDValue Mask, SDValue Base,
15324                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
15325   SDLoc dl(Op);
15326   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15327   assert(C && "Invalid scale type");
15328   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
15329   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
15330   SDValue Segment = DAG.getRegister(0, MVT::i32);
15331   EVT MaskVT = MVT::getVectorVT(MVT::i1,
15332                              Index.getSimpleValueType().getVectorNumElements());
15333   SDValue MaskInReg;
15334   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15335   if (MaskC)
15336     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
15337   else
15338     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
15339   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
15340   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
15341   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
15342   return SDValue(Res, 1);
15343 }
15344
15345 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15346                                SDValue Mask, SDValue Base, SDValue Index,
15347                                SDValue ScaleOp, SDValue Chain) {
15348   SDLoc dl(Op);
15349   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15350   assert(C && "Invalid scale type");
15351   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
15352   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
15353   SDValue Segment = DAG.getRegister(0, MVT::i32);
15354   EVT MaskVT =
15355     MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
15356   SDValue MaskInReg;
15357   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15358   if (MaskC)
15359     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
15360   else
15361     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
15362   //SDVTList VTs = DAG.getVTList(MVT::Other);
15363   SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
15364   SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
15365   return SDValue(Res, 0);
15366 }
15367
15368 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
15369 // read performance monitor counters (x86_rdpmc).
15370 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
15371                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
15372                               SmallVectorImpl<SDValue> &Results) {
15373   assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
15374   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
15375   SDValue LO, HI;
15376
15377   // The ECX register is used to select the index of the performance counter
15378   // to read.
15379   SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
15380                                    N->getOperand(2));
15381   SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
15382
15383   // Reads the content of a 64-bit performance counter and returns it in the
15384   // registers EDX:EAX.
15385   if (Subtarget->is64Bit()) {
15386     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
15387     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
15388                             LO.getValue(2));
15389   } else {
15390     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
15391     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
15392                             LO.getValue(2));
15393   }
15394   Chain = HI.getValue(1);
15395
15396   if (Subtarget->is64Bit()) {
15397     // The EAX register is loaded with the low-order 32 bits. The EDX register
15398     // is loaded with the supported high-order bits of the counter.
15399     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
15400                               DAG.getConstant(32, DL, MVT::i8));
15401     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
15402     Results.push_back(Chain);
15403     return;
15404   }
15405
15406   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
15407   SDValue Ops[] = { LO, HI };
15408   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
15409   Results.push_back(Pair);
15410   Results.push_back(Chain);
15411 }
15412
15413 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
15414 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
15415 // also used to custom lower READCYCLECOUNTER nodes.
15416 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
15417                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
15418                               SmallVectorImpl<SDValue> &Results) {
15419   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
15420   SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
15421   SDValue LO, HI;
15422
15423   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
15424   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
15425   // and the EAX register is loaded with the low-order 32 bits.
15426   if (Subtarget->is64Bit()) {
15427     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
15428     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
15429                             LO.getValue(2));
15430   } else {
15431     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
15432     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
15433                             LO.getValue(2));
15434   }
15435   SDValue Chain = HI.getValue(1);
15436
15437   if (Opcode == X86ISD::RDTSCP_DAG) {
15438     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
15439
15440     // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
15441     // the ECX register. Add 'ecx' explicitly to the chain.
15442     SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
15443                                      HI.getValue(2));
15444     // Explicitly store the content of ECX at the location passed in input
15445     // to the 'rdtscp' intrinsic.
15446     Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
15447                          MachinePointerInfo(), false, false, 0);
15448   }
15449
15450   if (Subtarget->is64Bit()) {
15451     // The EDX register is loaded with the high-order 32 bits of the MSR, and
15452     // the EAX register is loaded with the low-order 32 bits.
15453     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
15454                               DAG.getConstant(32, DL, MVT::i8));
15455     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
15456     Results.push_back(Chain);
15457     return;
15458   }
15459
15460   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
15461   SDValue Ops[] = { LO, HI };
15462   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
15463   Results.push_back(Pair);
15464   Results.push_back(Chain);
15465 }
15466
15467 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
15468                                      SelectionDAG &DAG) {
15469   SmallVector<SDValue, 2> Results;
15470   SDLoc DL(Op);
15471   getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
15472                           Results);
15473   return DAG.getMergeValues(Results, DL);
15474 }
15475
15476
15477 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
15478                                       SelectionDAG &DAG) {
15479   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
15480
15481   const IntrinsicData* IntrData = getIntrinsicWithChain(IntNo);
15482   if (!IntrData)
15483     return SDValue();
15484
15485   SDLoc dl(Op);
15486   switch(IntrData->Type) {
15487   default:
15488     llvm_unreachable("Unknown Intrinsic Type");
15489     break;
15490   case RDSEED:
15491   case RDRAND: {
15492     // Emit the node with the right value type.
15493     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
15494     SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
15495
15496     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
15497     // Otherwise return the value from Rand, which is always 0, casted to i32.
15498     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
15499                       DAG.getConstant(1, dl, Op->getValueType(1)),
15500                       DAG.getConstant(X86::COND_B, dl, MVT::i32),
15501                       SDValue(Result.getNode(), 1) };
15502     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
15503                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
15504                                   Ops);
15505
15506     // Return { result, isValid, chain }.
15507     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
15508                        SDValue(Result.getNode(), 2));
15509   }
15510   case GATHER: {
15511   //gather(v1, mask, index, base, scale);
15512     SDValue Chain = Op.getOperand(0);
15513     SDValue Src   = Op.getOperand(2);
15514     SDValue Base  = Op.getOperand(3);
15515     SDValue Index = Op.getOperand(4);
15516     SDValue Mask  = Op.getOperand(5);
15517     SDValue Scale = Op.getOperand(6);
15518     return getGatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale,
15519                          Chain, Subtarget);
15520   }
15521   case SCATTER: {
15522   //scatter(base, mask, index, v1, scale);
15523     SDValue Chain = Op.getOperand(0);
15524     SDValue Base  = Op.getOperand(2);
15525     SDValue Mask  = Op.getOperand(3);
15526     SDValue Index = Op.getOperand(4);
15527     SDValue Src   = Op.getOperand(5);
15528     SDValue Scale = Op.getOperand(6);
15529     return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index,
15530                           Scale, Chain);
15531   }
15532   case PREFETCH: {
15533     SDValue Hint = Op.getOperand(6);
15534     unsigned HintVal = cast<ConstantSDNode>(Hint)->getZExtValue();
15535     assert(HintVal < 2 && "Wrong prefetch hint in intrinsic: should be 0 or 1");
15536     unsigned Opcode = (HintVal ? IntrData->Opc1 : IntrData->Opc0);
15537     SDValue Chain = Op.getOperand(0);
15538     SDValue Mask  = Op.getOperand(2);
15539     SDValue Index = Op.getOperand(3);
15540     SDValue Base  = Op.getOperand(4);
15541     SDValue Scale = Op.getOperand(5);
15542     return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
15543   }
15544   // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
15545   case RDTSC: {
15546     SmallVector<SDValue, 2> Results;
15547     getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget,
15548                             Results);
15549     return DAG.getMergeValues(Results, dl);
15550   }
15551   // Read Performance Monitoring Counters.
15552   case RDPMC: {
15553     SmallVector<SDValue, 2> Results;
15554     getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
15555     return DAG.getMergeValues(Results, dl);
15556   }
15557   // XTEST intrinsics.
15558   case XTEST: {
15559     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
15560     SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
15561     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15562                                 DAG.getConstant(X86::COND_NE, dl, MVT::i8),
15563                                 InTrans);
15564     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
15565     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
15566                        Ret, SDValue(InTrans.getNode(), 1));
15567   }
15568   // ADC/ADCX/SBB
15569   case ADX: {
15570     SmallVector<SDValue, 2> Results;
15571     SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
15572     SDVTList VTs = DAG.getVTList(Op.getOperand(3)->getValueType(0), MVT::Other);
15573     SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(2),
15574                                 DAG.getConstant(-1, dl, MVT::i8));
15575     SDValue Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(3),
15576                               Op.getOperand(4), GenCF.getValue(1));
15577     SDValue Store = DAG.getStore(Op.getOperand(0), dl, Res.getValue(0),
15578                                  Op.getOperand(5), MachinePointerInfo(),
15579                                  false, false, 0);
15580     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15581                                 DAG.getConstant(X86::COND_B, dl, MVT::i8),
15582                                 Res.getValue(1));
15583     Results.push_back(SetCC);
15584     Results.push_back(Store);
15585     return DAG.getMergeValues(Results, dl);
15586   }
15587   case COMPRESS_TO_MEM: {
15588     SDLoc dl(Op);
15589     SDValue Mask = Op.getOperand(4);
15590     SDValue DataToCompress = Op.getOperand(3);
15591     SDValue Addr = Op.getOperand(2);
15592     SDValue Chain = Op.getOperand(0);
15593
15594     if (isAllOnes(Mask)) // return just a store
15595       return DAG.getStore(Chain, dl, DataToCompress, Addr,
15596                           MachinePointerInfo(), false, false, 0);
15597
15598     EVT VT = DataToCompress.getValueType();
15599     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15600                                   VT.getVectorNumElements());
15601     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15602                                      Mask.getValueType().getSizeInBits());
15603     SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15604                                 DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
15605                                 DAG.getIntPtrConstant(0, dl));
15606
15607     SDValue Compressed =  DAG.getNode(IntrData->Opc0, dl, VT, VMask,
15608                                       DataToCompress, DAG.getUNDEF(VT));
15609     return DAG.getStore(Chain, dl, Compressed, Addr,
15610                         MachinePointerInfo(), false, false, 0);
15611   }
15612   case EXPAND_FROM_MEM: {
15613     SDLoc dl(Op);
15614     SDValue Mask = Op.getOperand(4);
15615     SDValue PathThru = Op.getOperand(3);
15616     SDValue Addr = Op.getOperand(2);
15617     SDValue Chain = Op.getOperand(0);
15618     EVT VT = Op.getValueType();
15619
15620     if (isAllOnes(Mask)) // return just a load
15621       return DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(), false, false,
15622                          false, 0);
15623     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15624                                   VT.getVectorNumElements());
15625     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15626                                      Mask.getValueType().getSizeInBits());
15627     SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15628                                 DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
15629                                 DAG.getIntPtrConstant(0, dl));
15630
15631     SDValue DataToExpand = DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(),
15632                                    false, false, false, 0);
15633
15634     SDValue Results[] = {
15635         DAG.getNode(IntrData->Opc0, dl, VT, VMask, DataToExpand, PathThru),
15636         Chain};
15637     return DAG.getMergeValues(Results, dl);
15638   }
15639   }
15640 }
15641
15642 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
15643                                            SelectionDAG &DAG) const {
15644   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
15645   MFI->setReturnAddressIsTaken(true);
15646
15647   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
15648     return SDValue();
15649
15650   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15651   SDLoc dl(Op);
15652   EVT PtrVT = getPointerTy();
15653
15654   if (Depth > 0) {
15655     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
15656     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15657     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), dl, PtrVT);
15658     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15659                        DAG.getNode(ISD::ADD, dl, PtrVT,
15660                                    FrameAddr, Offset),
15661                        MachinePointerInfo(), false, false, false, 0);
15662   }
15663
15664   // Just load the return address.
15665   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
15666   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15667                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
15668 }
15669
15670 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
15671   MachineFunction &MF = DAG.getMachineFunction();
15672   MachineFrameInfo *MFI = MF.getFrameInfo();
15673   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
15674   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15675   EVT VT = Op.getValueType();
15676
15677   MFI->setFrameAddressIsTaken(true);
15678
15679   if (MF.getTarget().getMCAsmInfo()->usesWindowsCFI()) {
15680     // Depth > 0 makes no sense on targets which use Windows unwind codes.  It
15681     // is not possible to crawl up the stack without looking at the unwind codes
15682     // simultaneously.
15683     int FrameAddrIndex = FuncInfo->getFAIndex();
15684     if (!FrameAddrIndex) {
15685       // Set up a frame object for the return address.
15686       unsigned SlotSize = RegInfo->getSlotSize();
15687       FrameAddrIndex = MF.getFrameInfo()->CreateFixedObject(
15688           SlotSize, /*Offset=*/0, /*IsImmutable=*/false);
15689       FuncInfo->setFAIndex(FrameAddrIndex);
15690     }
15691     return DAG.getFrameIndex(FrameAddrIndex, VT);
15692   }
15693
15694   unsigned FrameReg =
15695       RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
15696   SDLoc dl(Op);  // FIXME probably not meaningful
15697   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15698   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
15699           (FrameReg == X86::EBP && VT == MVT::i32)) &&
15700          "Invalid Frame Register!");
15701   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
15702   while (Depth--)
15703     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
15704                             MachinePointerInfo(),
15705                             false, false, false, 0);
15706   return FrameAddr;
15707 }
15708
15709 // FIXME? Maybe this could be a TableGen attribute on some registers and
15710 // this table could be generated automatically from RegInfo.
15711 unsigned X86TargetLowering::getRegisterByName(const char* RegName,
15712                                               EVT VT) const {
15713   unsigned Reg = StringSwitch<unsigned>(RegName)
15714                        .Case("esp", X86::ESP)
15715                        .Case("rsp", X86::RSP)
15716                        .Default(0);
15717   if (Reg)
15718     return Reg;
15719   report_fatal_error("Invalid register name global variable");
15720 }
15721
15722 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
15723                                                      SelectionDAG &DAG) const {
15724   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15725   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize(), SDLoc(Op));
15726 }
15727
15728 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
15729   SDValue Chain     = Op.getOperand(0);
15730   SDValue Offset    = Op.getOperand(1);
15731   SDValue Handler   = Op.getOperand(2);
15732   SDLoc dl      (Op);
15733
15734   EVT PtrVT = getPointerTy();
15735   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15736   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
15737   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
15738           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
15739          "Invalid Frame Register!");
15740   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
15741   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
15742
15743   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
15744                                  DAG.getIntPtrConstant(RegInfo->getSlotSize(),
15745                                                        dl));
15746   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
15747   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
15748                        false, false, 0);
15749   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
15750
15751   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
15752                      DAG.getRegister(StoreAddrReg, PtrVT));
15753 }
15754
15755 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
15756                                                SelectionDAG &DAG) const {
15757   SDLoc DL(Op);
15758   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
15759                      DAG.getVTList(MVT::i32, MVT::Other),
15760                      Op.getOperand(0), Op.getOperand(1));
15761 }
15762
15763 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
15764                                                 SelectionDAG &DAG) const {
15765   SDLoc DL(Op);
15766   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
15767                      Op.getOperand(0), Op.getOperand(1));
15768 }
15769
15770 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
15771   return Op.getOperand(0);
15772 }
15773
15774 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
15775                                                 SelectionDAG &DAG) const {
15776   SDValue Root = Op.getOperand(0);
15777   SDValue Trmp = Op.getOperand(1); // trampoline
15778   SDValue FPtr = Op.getOperand(2); // nested function
15779   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
15780   SDLoc dl (Op);
15781
15782   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
15783   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
15784
15785   if (Subtarget->is64Bit()) {
15786     SDValue OutChains[6];
15787
15788     // Large code-model.
15789     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
15790     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
15791
15792     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
15793     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
15794
15795     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
15796
15797     // Load the pointer to the nested function into R11.
15798     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
15799     SDValue Addr = Trmp;
15800     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
15801                                 Addr, MachinePointerInfo(TrmpAddr),
15802                                 false, false, 0);
15803
15804     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15805                        DAG.getConstant(2, dl, MVT::i64));
15806     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
15807                                 MachinePointerInfo(TrmpAddr, 2),
15808                                 false, false, 2);
15809
15810     // Load the 'nest' parameter value into R10.
15811     // R10 is specified in X86CallingConv.td
15812     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
15813     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15814                        DAG.getConstant(10, dl, MVT::i64));
15815     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
15816                                 Addr, MachinePointerInfo(TrmpAddr, 10),
15817                                 false, false, 0);
15818
15819     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15820                        DAG.getConstant(12, dl, MVT::i64));
15821     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
15822                                 MachinePointerInfo(TrmpAddr, 12),
15823                                 false, false, 2);
15824
15825     // Jump to the nested function.
15826     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
15827     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15828                        DAG.getConstant(20, dl, MVT::i64));
15829     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
15830                                 Addr, MachinePointerInfo(TrmpAddr, 20),
15831                                 false, false, 0);
15832
15833     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
15834     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15835                        DAG.getConstant(22, dl, MVT::i64));
15836     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, dl, MVT::i8),
15837                                 Addr, MachinePointerInfo(TrmpAddr, 22),
15838                                 false, false, 0);
15839
15840     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
15841   } else {
15842     const Function *Func =
15843       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
15844     CallingConv::ID CC = Func->getCallingConv();
15845     unsigned NestReg;
15846
15847     switch (CC) {
15848     default:
15849       llvm_unreachable("Unsupported calling convention");
15850     case CallingConv::C:
15851     case CallingConv::X86_StdCall: {
15852       // Pass 'nest' parameter in ECX.
15853       // Must be kept in sync with X86CallingConv.td
15854       NestReg = X86::ECX;
15855
15856       // Check that ECX wasn't needed by an 'inreg' parameter.
15857       FunctionType *FTy = Func->getFunctionType();
15858       const AttributeSet &Attrs = Func->getAttributes();
15859
15860       if (!Attrs.isEmpty() && !Func->isVarArg()) {
15861         unsigned InRegCount = 0;
15862         unsigned Idx = 1;
15863
15864         for (FunctionType::param_iterator I = FTy->param_begin(),
15865              E = FTy->param_end(); I != E; ++I, ++Idx)
15866           if (Attrs.hasAttribute(Idx, Attribute::InReg))
15867             // FIXME: should only count parameters that are lowered to integers.
15868             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
15869
15870         if (InRegCount > 2) {
15871           report_fatal_error("Nest register in use - reduce number of inreg"
15872                              " parameters!");
15873         }
15874       }
15875       break;
15876     }
15877     case CallingConv::X86_FastCall:
15878     case CallingConv::X86_ThisCall:
15879     case CallingConv::Fast:
15880       // Pass 'nest' parameter in EAX.
15881       // Must be kept in sync with X86CallingConv.td
15882       NestReg = X86::EAX;
15883       break;
15884     }
15885
15886     SDValue OutChains[4];
15887     SDValue Addr, Disp;
15888
15889     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15890                        DAG.getConstant(10, dl, MVT::i32));
15891     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
15892
15893     // This is storing the opcode for MOV32ri.
15894     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
15895     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
15896     OutChains[0] = DAG.getStore(Root, dl,
15897                                 DAG.getConstant(MOV32ri|N86Reg, dl, MVT::i8),
15898                                 Trmp, MachinePointerInfo(TrmpAddr),
15899                                 false, false, 0);
15900
15901     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15902                        DAG.getConstant(1, dl, MVT::i32));
15903     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
15904                                 MachinePointerInfo(TrmpAddr, 1),
15905                                 false, false, 1);
15906
15907     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
15908     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15909                        DAG.getConstant(5, dl, MVT::i32));
15910     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, dl, MVT::i8),
15911                                 Addr, MachinePointerInfo(TrmpAddr, 5),
15912                                 false, false, 1);
15913
15914     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15915                        DAG.getConstant(6, dl, MVT::i32));
15916     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
15917                                 MachinePointerInfo(TrmpAddr, 6),
15918                                 false, false, 1);
15919
15920     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
15921   }
15922 }
15923
15924 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
15925                                             SelectionDAG &DAG) const {
15926   /*
15927    The rounding mode is in bits 11:10 of FPSR, and has the following
15928    settings:
15929      00 Round to nearest
15930      01 Round to -inf
15931      10 Round to +inf
15932      11 Round to 0
15933
15934   FLT_ROUNDS, on the other hand, expects the following:
15935     -1 Undefined
15936      0 Round to 0
15937      1 Round to nearest
15938      2 Round to +inf
15939      3 Round to -inf
15940
15941   To perform the conversion, we do:
15942     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
15943   */
15944
15945   MachineFunction &MF = DAG.getMachineFunction();
15946   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
15947   unsigned StackAlignment = TFI.getStackAlignment();
15948   MVT VT = Op.getSimpleValueType();
15949   SDLoc DL(Op);
15950
15951   // Save FP Control Word to stack slot
15952   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
15953   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
15954
15955   MachineMemOperand *MMO =
15956    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
15957                            MachineMemOperand::MOStore, 2, 2);
15958
15959   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
15960   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
15961                                           DAG.getVTList(MVT::Other),
15962                                           Ops, MVT::i16, MMO);
15963
15964   // Load FP Control Word from stack slot
15965   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
15966                             MachinePointerInfo(), false, false, false, 0);
15967
15968   // Transform as necessary
15969   SDValue CWD1 =
15970     DAG.getNode(ISD::SRL, DL, MVT::i16,
15971                 DAG.getNode(ISD::AND, DL, MVT::i16,
15972                             CWD, DAG.getConstant(0x800, DL, MVT::i16)),
15973                 DAG.getConstant(11, DL, MVT::i8));
15974   SDValue CWD2 =
15975     DAG.getNode(ISD::SRL, DL, MVT::i16,
15976                 DAG.getNode(ISD::AND, DL, MVT::i16,
15977                             CWD, DAG.getConstant(0x400, DL, MVT::i16)),
15978                 DAG.getConstant(9, DL, MVT::i8));
15979
15980   SDValue RetVal =
15981     DAG.getNode(ISD::AND, DL, MVT::i16,
15982                 DAG.getNode(ISD::ADD, DL, MVT::i16,
15983                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
15984                             DAG.getConstant(1, DL, MVT::i16)),
15985                 DAG.getConstant(3, DL, MVT::i16));
15986
15987   return DAG.getNode((VT.getSizeInBits() < 16 ?
15988                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
15989 }
15990
15991 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
15992   MVT VT = Op.getSimpleValueType();
15993   EVT OpVT = VT;
15994   unsigned NumBits = VT.getSizeInBits();
15995   SDLoc dl(Op);
15996
15997   Op = Op.getOperand(0);
15998   if (VT == MVT::i8) {
15999     // Zero extend to i32 since there is not an i8 bsr.
16000     OpVT = MVT::i32;
16001     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
16002   }
16003
16004   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
16005   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
16006   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
16007
16008   // If src is zero (i.e. bsr sets ZF), returns NumBits.
16009   SDValue Ops[] = {
16010     Op,
16011     DAG.getConstant(NumBits + NumBits - 1, dl, OpVT),
16012     DAG.getConstant(X86::COND_E, dl, MVT::i8),
16013     Op.getValue(1)
16014   };
16015   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
16016
16017   // Finally xor with NumBits-1.
16018   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
16019                    DAG.getConstant(NumBits - 1, dl, OpVT));
16020
16021   if (VT == MVT::i8)
16022     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
16023   return Op;
16024 }
16025
16026 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
16027   MVT VT = Op.getSimpleValueType();
16028   EVT OpVT = VT;
16029   unsigned NumBits = VT.getSizeInBits();
16030   SDLoc dl(Op);
16031
16032   Op = Op.getOperand(0);
16033   if (VT == MVT::i8) {
16034     // Zero extend to i32 since there is not an i8 bsr.
16035     OpVT = MVT::i32;
16036     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
16037   }
16038
16039   // Issue a bsr (scan bits in reverse).
16040   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
16041   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
16042
16043   // And xor with NumBits-1.
16044   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
16045                    DAG.getConstant(NumBits - 1, dl, OpVT));
16046
16047   if (VT == MVT::i8)
16048     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
16049   return Op;
16050 }
16051
16052 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
16053   MVT VT = Op.getSimpleValueType();
16054   unsigned NumBits = VT.getSizeInBits();
16055   SDLoc dl(Op);
16056   Op = Op.getOperand(0);
16057
16058   // Issue a bsf (scan bits forward) which also sets EFLAGS.
16059   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
16060   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
16061
16062   // If src is zero (i.e. bsf sets ZF), returns NumBits.
16063   SDValue Ops[] = {
16064     Op,
16065     DAG.getConstant(NumBits, dl, VT),
16066     DAG.getConstant(X86::COND_E, dl, MVT::i8),
16067     Op.getValue(1)
16068   };
16069   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
16070 }
16071
16072 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
16073 // ones, and then concatenate the result back.
16074 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
16075   MVT VT = Op.getSimpleValueType();
16076
16077   assert(VT.is256BitVector() && VT.isInteger() &&
16078          "Unsupported value type for operation");
16079
16080   unsigned NumElems = VT.getVectorNumElements();
16081   SDLoc dl(Op);
16082
16083   // Extract the LHS vectors
16084   SDValue LHS = Op.getOperand(0);
16085   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
16086   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
16087
16088   // Extract the RHS vectors
16089   SDValue RHS = Op.getOperand(1);
16090   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
16091   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
16092
16093   MVT EltVT = VT.getVectorElementType();
16094   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16095
16096   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
16097                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
16098                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
16099 }
16100
16101 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
16102   assert(Op.getSimpleValueType().is256BitVector() &&
16103          Op.getSimpleValueType().isInteger() &&
16104          "Only handle AVX 256-bit vector integer operation");
16105   return Lower256IntArith(Op, DAG);
16106 }
16107
16108 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
16109   assert(Op.getSimpleValueType().is256BitVector() &&
16110          Op.getSimpleValueType().isInteger() &&
16111          "Only handle AVX 256-bit vector integer operation");
16112   return Lower256IntArith(Op, DAG);
16113 }
16114
16115 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
16116                         SelectionDAG &DAG) {
16117   SDLoc dl(Op);
16118   MVT VT = Op.getSimpleValueType();
16119
16120   // Decompose 256-bit ops into smaller 128-bit ops.
16121   if (VT.is256BitVector() && !Subtarget->hasInt256())
16122     return Lower256IntArith(Op, DAG);
16123
16124   SDValue A = Op.getOperand(0);
16125   SDValue B = Op.getOperand(1);
16126
16127   // Lower v16i8/v32i8 mul as promotion to v8i16/v16i16 vector
16128   // pairs, multiply and truncate.
16129   if (VT == MVT::v16i8 || VT == MVT::v32i8) {
16130     if (Subtarget->hasInt256()) {
16131       if (VT == MVT::v32i8) {
16132         MVT SubVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() / 2);
16133         SDValue Lo = DAG.getIntPtrConstant(0, dl);
16134         SDValue Hi = DAG.getIntPtrConstant(VT.getVectorNumElements() / 2, dl);
16135         SDValue ALo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Lo);
16136         SDValue BLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Lo);
16137         SDValue AHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Hi);
16138         SDValue BHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Hi);
16139         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
16140                            DAG.getNode(ISD::MUL, dl, SubVT, ALo, BLo),
16141                            DAG.getNode(ISD::MUL, dl, SubVT, AHi, BHi));
16142       }
16143
16144       MVT ExVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements());
16145       return DAG.getNode(
16146           ISD::TRUNCATE, dl, VT,
16147           DAG.getNode(ISD::MUL, dl, ExVT,
16148                       DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, A),
16149                       DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, B)));
16150     }
16151
16152     assert(VT == MVT::v16i8 &&
16153            "Pre-AVX2 support only supports v16i8 multiplication");
16154     MVT ExVT = MVT::v8i16;
16155
16156     // Extract the lo parts and sign extend to i16
16157     SDValue ALo, BLo;
16158     if (Subtarget->hasSSE41()) {
16159       ALo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, A);
16160       BLo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, B);
16161     } else {
16162       const int ShufMask[] = {-1, 0, -1, 1, -1, 2, -1, 3,
16163                               -1, 4, -1, 5, -1, 6, -1, 7};
16164       ALo = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16165       BLo = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16166       ALo = DAG.getNode(ISD::BITCAST, dl, ExVT, ALo);
16167       BLo = DAG.getNode(ISD::BITCAST, dl, ExVT, BLo);
16168       ALo = DAG.getNode(ISD::SRA, dl, ExVT, ALo, DAG.getConstant(8, dl, ExVT));
16169       BLo = DAG.getNode(ISD::SRA, dl, ExVT, BLo, DAG.getConstant(8, dl, ExVT));
16170     }
16171
16172     // Extract the hi parts and sign extend to i16
16173     SDValue AHi, BHi;
16174     if (Subtarget->hasSSE41()) {
16175       const int ShufMask[] = {8,  9,  10, 11, 12, 13, 14, 15,
16176                               -1, -1, -1, -1, -1, -1, -1, -1};
16177       AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16178       BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16179       AHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, AHi);
16180       BHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, BHi);
16181     } else {
16182       const int ShufMask[] = {-1, 8,  -1, 9,  -1, 10, -1, 11,
16183                               -1, 12, -1, 13, -1, 14, -1, 15};
16184       AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16185       BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16186       AHi = DAG.getNode(ISD::BITCAST, dl, ExVT, AHi);
16187       BHi = DAG.getNode(ISD::BITCAST, dl, ExVT, BHi);
16188       AHi = DAG.getNode(ISD::SRA, dl, ExVT, AHi, DAG.getConstant(8, dl, ExVT));
16189       BHi = DAG.getNode(ISD::SRA, dl, ExVT, BHi, DAG.getConstant(8, dl, ExVT));
16190     }
16191
16192     // Multiply, mask the lower 8bits of the lo/hi results and pack
16193     SDValue RLo = DAG.getNode(ISD::MUL, dl, ExVT, ALo, BLo);
16194     SDValue RHi = DAG.getNode(ISD::MUL, dl, ExVT, AHi, BHi);
16195     RLo = DAG.getNode(ISD::AND, dl, ExVT, RLo, DAG.getConstant(255, dl, ExVT));
16196     RHi = DAG.getNode(ISD::AND, dl, ExVT, RHi, DAG.getConstant(255, dl, ExVT));
16197     return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
16198   }
16199
16200   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
16201   if (VT == MVT::v4i32) {
16202     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
16203            "Should not custom lower when pmuldq is available!");
16204
16205     // Extract the odd parts.
16206     static const int UnpackMask[] = { 1, -1, 3, -1 };
16207     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
16208     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
16209
16210     // Multiply the even parts.
16211     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
16212     // Now multiply odd parts.
16213     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
16214
16215     Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
16216     Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
16217
16218     // Merge the two vectors back together with a shuffle. This expands into 2
16219     // shuffles.
16220     static const int ShufMask[] = { 0, 4, 2, 6 };
16221     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
16222   }
16223
16224   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
16225          "Only know how to lower V2I64/V4I64/V8I64 multiply");
16226
16227   //  Ahi = psrlqi(a, 32);
16228   //  Bhi = psrlqi(b, 32);
16229   //
16230   //  AloBlo = pmuludq(a, b);
16231   //  AloBhi = pmuludq(a, Bhi);
16232   //  AhiBlo = pmuludq(Ahi, b);
16233
16234   //  AloBhi = psllqi(AloBhi, 32);
16235   //  AhiBlo = psllqi(AhiBlo, 32);
16236   //  return AloBlo + AloBhi + AhiBlo;
16237
16238   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
16239   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
16240
16241   // Bit cast to 32-bit vectors for MULUDQ
16242   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
16243                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
16244   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
16245   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
16246   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
16247   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
16248
16249   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
16250   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
16251   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
16252
16253   AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
16254   AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
16255
16256   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
16257   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
16258 }
16259
16260 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
16261   assert(Subtarget->isTargetWin64() && "Unexpected target");
16262   EVT VT = Op.getValueType();
16263   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
16264          "Unexpected return type for lowering");
16265
16266   RTLIB::Libcall LC;
16267   bool isSigned;
16268   switch (Op->getOpcode()) {
16269   default: llvm_unreachable("Unexpected request for libcall!");
16270   case ISD::SDIV:      isSigned = true;  LC = RTLIB::SDIV_I128;    break;
16271   case ISD::UDIV:      isSigned = false; LC = RTLIB::UDIV_I128;    break;
16272   case ISD::SREM:      isSigned = true;  LC = RTLIB::SREM_I128;    break;
16273   case ISD::UREM:      isSigned = false; LC = RTLIB::UREM_I128;    break;
16274   case ISD::SDIVREM:   isSigned = true;  LC = RTLIB::SDIVREM_I128; break;
16275   case ISD::UDIVREM:   isSigned = false; LC = RTLIB::UDIVREM_I128; break;
16276   }
16277
16278   SDLoc dl(Op);
16279   SDValue InChain = DAG.getEntryNode();
16280
16281   TargetLowering::ArgListTy Args;
16282   TargetLowering::ArgListEntry Entry;
16283   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
16284     EVT ArgVT = Op->getOperand(i).getValueType();
16285     assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
16286            "Unexpected argument type for lowering");
16287     SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
16288     Entry.Node = StackPtr;
16289     InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
16290                            false, false, 16);
16291     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
16292     Entry.Ty = PointerType::get(ArgTy,0);
16293     Entry.isSExt = false;
16294     Entry.isZExt = false;
16295     Args.push_back(Entry);
16296   }
16297
16298   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
16299                                          getPointerTy());
16300
16301   TargetLowering::CallLoweringInfo CLI(DAG);
16302   CLI.setDebugLoc(dl).setChain(InChain)
16303     .setCallee(getLibcallCallingConv(LC),
16304                static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
16305                Callee, std::move(Args), 0)
16306     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
16307
16308   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
16309   return DAG.getNode(ISD::BITCAST, dl, VT, CallInfo.first);
16310 }
16311
16312 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
16313                              SelectionDAG &DAG) {
16314   SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
16315   EVT VT = Op0.getValueType();
16316   SDLoc dl(Op);
16317
16318   assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
16319          (VT == MVT::v8i32 && Subtarget->hasInt256()));
16320
16321   // PMULxD operations multiply each even value (starting at 0) of LHS with
16322   // the related value of RHS and produce a widen result.
16323   // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
16324   // => <2 x i64> <ae|cg>
16325   //
16326   // In other word, to have all the results, we need to perform two PMULxD:
16327   // 1. one with the even values.
16328   // 2. one with the odd values.
16329   // To achieve #2, with need to place the odd values at an even position.
16330   //
16331   // Place the odd value at an even position (basically, shift all values 1
16332   // step to the left):
16333   const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
16334   // <a|b|c|d> => <b|undef|d|undef>
16335   SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
16336   // <e|f|g|h> => <f|undef|h|undef>
16337   SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
16338
16339   // Emit two multiplies, one for the lower 2 ints and one for the higher 2
16340   // ints.
16341   MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
16342   bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
16343   unsigned Opcode =
16344       (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
16345   // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
16346   // => <2 x i64> <ae|cg>
16347   SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
16348                              DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
16349   // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
16350   // => <2 x i64> <bf|dh>
16351   SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
16352                              DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
16353
16354   // Shuffle it back into the right order.
16355   SDValue Highs, Lows;
16356   if (VT == MVT::v8i32) {
16357     const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
16358     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
16359     const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
16360     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
16361   } else {
16362     const int HighMask[] = {1, 5, 3, 7};
16363     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
16364     const int LowMask[] = {0, 4, 2, 6};
16365     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
16366   }
16367
16368   // If we have a signed multiply but no PMULDQ fix up the high parts of a
16369   // unsigned multiply.
16370   if (IsSigned && !Subtarget->hasSSE41()) {
16371     SDValue ShAmt =
16372         DAG.getConstant(31, dl,
16373                         DAG.getTargetLoweringInfo().getShiftAmountTy(VT));
16374     SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
16375                              DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
16376     SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
16377                              DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
16378
16379     SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
16380     Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
16381   }
16382
16383   // The first result of MUL_LOHI is actually the low value, followed by the
16384   // high value.
16385   SDValue Ops[] = {Lows, Highs};
16386   return DAG.getMergeValues(Ops, dl);
16387 }
16388
16389 // Return true if the requred (according to Opcode) shift-imm form is natively
16390 // supported by the Subtarget
16391 static bool SupportedVectorShiftWithImm(MVT VT, const X86Subtarget *Subtarget, 
16392                                         unsigned Opcode) {
16393   if (VT.getScalarSizeInBits() < 16)
16394     return false;
16395  
16396   if (VT.is512BitVector() &&
16397       (VT.getScalarSizeInBits() > 16 || Subtarget->hasBWI()))
16398     return true;
16399
16400   bool LShift = VT.is128BitVector() || 
16401     (VT.is256BitVector() && Subtarget->hasInt256());
16402
16403   bool AShift = LShift && (Subtarget->hasVLX() ||
16404     (VT != MVT::v2i64 && VT != MVT::v4i64));
16405   return (Opcode == ISD::SRA) ? AShift : LShift;
16406 }
16407
16408 // The shift amount is a variable, but it is the same for all vector lanes.
16409 // These instrcutions are defined together with shift-immediate.
16410 static 
16411 bool SupportedVectorShiftWithBaseAmnt(MVT VT, const X86Subtarget *Subtarget, 
16412                                       unsigned Opcode) {
16413   return SupportedVectorShiftWithImm(VT, Subtarget, Opcode);
16414 }
16415
16416 // Return true if the requred (according to Opcode) variable-shift form is
16417 // natively supported by the Subtarget
16418 static bool SupportedVectorVarShift(MVT VT, const X86Subtarget *Subtarget, 
16419                                     unsigned Opcode) {
16420
16421   if (!Subtarget->hasInt256() || VT.getScalarSizeInBits() < 16)
16422     return false;
16423
16424   // vXi16 supported only on AVX-512, BWI
16425   if (VT.getScalarSizeInBits() == 16 && !Subtarget->hasBWI())
16426     return false;
16427
16428   if (VT.is512BitVector() || Subtarget->hasVLX())
16429     return true;
16430
16431   bool LShift = VT.is128BitVector() || VT.is256BitVector();
16432   bool AShift = LShift &&  VT != MVT::v2i64 && VT != MVT::v4i64;
16433   return (Opcode == ISD::SRA) ? AShift : LShift;
16434 }
16435
16436 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
16437                                          const X86Subtarget *Subtarget) {
16438   MVT VT = Op.getSimpleValueType();
16439   SDLoc dl(Op);
16440   SDValue R = Op.getOperand(0);
16441   SDValue Amt = Op.getOperand(1);
16442
16443   unsigned X86Opc = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
16444     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
16445
16446   // Optimize shl/srl/sra with constant shift amount.
16447   if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
16448     if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
16449       uint64_t ShiftAmt = ShiftConst->getZExtValue();
16450
16451       if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
16452         return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
16453
16454       if (VT == MVT::v16i8 || (Subtarget->hasInt256() && VT == MVT::v32i8)) {
16455         unsigned NumElts = VT.getVectorNumElements();
16456         MVT ShiftVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
16457
16458         if (Op.getOpcode() == ISD::SHL) {
16459           // Make a large shift.
16460           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ShiftVT,
16461                                                    R, ShiftAmt, DAG);
16462           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
16463           // Zero out the rightmost bits.
16464           SmallVector<SDValue, 32> V(
16465               NumElts, DAG.getConstant(uint8_t(-1U << ShiftAmt), dl, MVT::i8));
16466           return DAG.getNode(ISD::AND, dl, VT, SHL,
16467                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
16468         }
16469         if (Op.getOpcode() == ISD::SRL) {
16470           // Make a large shift.
16471           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ShiftVT,
16472                                                    R, ShiftAmt, DAG);
16473           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
16474           // Zero out the leftmost bits.
16475           SmallVector<SDValue, 32> V(
16476               NumElts, DAG.getConstant(uint8_t(-1U) >> ShiftAmt, dl, MVT::i8));
16477           return DAG.getNode(ISD::AND, dl, VT, SRL,
16478                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
16479         }
16480         if (Op.getOpcode() == ISD::SRA) {
16481           if (ShiftAmt == 7) {
16482             // R s>> 7  ===  R s< 0
16483             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
16484             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
16485           }
16486
16487           // R s>> a === ((R u>> a) ^ m) - m
16488           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
16489           SmallVector<SDValue, 32> V(NumElts,
16490                                      DAG.getConstant(128 >> ShiftAmt, dl,
16491                                                      MVT::i8));
16492           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
16493           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
16494           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
16495           return Res;
16496         }
16497         llvm_unreachable("Unknown shift opcode.");
16498       }
16499     }
16500   }
16501
16502   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
16503   if (!Subtarget->is64Bit() &&
16504       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
16505       Amt.getOpcode() == ISD::BITCAST &&
16506       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
16507     Amt = Amt.getOperand(0);
16508     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
16509                      VT.getVectorNumElements();
16510     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
16511     uint64_t ShiftAmt = 0;
16512     for (unsigned i = 0; i != Ratio; ++i) {
16513       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
16514       if (!C)
16515         return SDValue();
16516       // 6 == Log2(64)
16517       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
16518     }
16519     // Check remaining shift amounts.
16520     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
16521       uint64_t ShAmt = 0;
16522       for (unsigned j = 0; j != Ratio; ++j) {
16523         ConstantSDNode *C =
16524           dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
16525         if (!C)
16526           return SDValue();
16527         // 6 == Log2(64)
16528         ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
16529       }
16530       if (ShAmt != ShiftAmt)
16531         return SDValue();
16532     }
16533     return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
16534   }
16535
16536   return SDValue();
16537 }
16538
16539 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
16540                                         const X86Subtarget* Subtarget) {
16541   MVT VT = Op.getSimpleValueType();
16542   SDLoc dl(Op);
16543   SDValue R = Op.getOperand(0);
16544   SDValue Amt = Op.getOperand(1);
16545
16546   unsigned X86OpcI = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
16547     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
16548
16549   unsigned X86OpcV = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHL :
16550     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRL : X86ISD::VSRA;
16551
16552   if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode())) {
16553     SDValue BaseShAmt;
16554     EVT EltVT = VT.getVectorElementType();
16555
16556     if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Amt)) {
16557       // Check if this build_vector node is doing a splat.
16558       // If so, then set BaseShAmt equal to the splat value.
16559       BaseShAmt = BV->getSplatValue();
16560       if (BaseShAmt && BaseShAmt.getOpcode() == ISD::UNDEF)
16561         BaseShAmt = SDValue();
16562     } else {
16563       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
16564         Amt = Amt.getOperand(0);
16565
16566       ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt);
16567       if (SVN && SVN->isSplat()) {
16568         unsigned SplatIdx = (unsigned)SVN->getSplatIndex();
16569         SDValue InVec = Amt.getOperand(0);
16570         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
16571           assert((SplatIdx < InVec.getValueType().getVectorNumElements()) &&
16572                  "Unexpected shuffle index found!");
16573           BaseShAmt = InVec.getOperand(SplatIdx);
16574         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
16575            if (ConstantSDNode *C =
16576                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
16577              if (C->getZExtValue() == SplatIdx)
16578                BaseShAmt = InVec.getOperand(1);
16579            }
16580         }
16581
16582         if (!BaseShAmt)
16583           // Avoid introducing an extract element from a shuffle.
16584           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InVec,
16585                                   DAG.getIntPtrConstant(SplatIdx, dl));
16586       }
16587     }
16588
16589     if (BaseShAmt.getNode()) {
16590       assert(EltVT.bitsLE(MVT::i64) && "Unexpected element type!");
16591       if (EltVT != MVT::i64 && EltVT.bitsGT(MVT::i32))
16592         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, BaseShAmt);
16593       else if (EltVT.bitsLT(MVT::i32))
16594         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
16595
16596       return getTargetVShiftNode(X86OpcI, dl, VT, R, BaseShAmt, DAG);
16597     }
16598   }
16599
16600   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
16601   if (!Subtarget->is64Bit() && VT == MVT::v2i64  &&
16602       Amt.getOpcode() == ISD::BITCAST &&
16603       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
16604     Amt = Amt.getOperand(0);
16605     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
16606                      VT.getVectorNumElements();
16607     std::vector<SDValue> Vals(Ratio);
16608     for (unsigned i = 0; i != Ratio; ++i)
16609       Vals[i] = Amt.getOperand(i);
16610     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
16611       for (unsigned j = 0; j != Ratio; ++j)
16612         if (Vals[j] != Amt.getOperand(i + j))
16613           return SDValue();
16614     }
16615     return DAG.getNode(X86OpcV, dl, VT, R, Op.getOperand(1));
16616   }
16617   return SDValue();
16618 }
16619
16620 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
16621                           SelectionDAG &DAG) {
16622   MVT VT = Op.getSimpleValueType();
16623   SDLoc dl(Op);
16624   SDValue R = Op.getOperand(0);
16625   SDValue Amt = Op.getOperand(1);
16626
16627   assert(VT.isVector() && "Custom lowering only for vector shifts!");
16628   assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
16629
16630   if (SDValue V = LowerScalarImmediateShift(Op, DAG, Subtarget))
16631     return V;
16632
16633   if (SDValue V = LowerScalarVariableShift(Op, DAG, Subtarget))
16634       return V;
16635
16636   if (SupportedVectorVarShift(VT, Subtarget, Op.getOpcode()))
16637     return Op;
16638
16639   // 2i64 vector logical shifts can efficiently avoid scalarization - do the
16640   // shifts per-lane and then shuffle the partial results back together.
16641   if (VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) {
16642     // Splat the shift amounts so the scalar shifts above will catch it.
16643     SDValue Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {0, 0});
16644     SDValue Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {1, 1});
16645     SDValue R0 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt0);
16646     SDValue R1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt1);
16647     return DAG.getVectorShuffle(VT, dl, R0, R1, {0, 3});
16648   }
16649
16650   // If possible, lower this packed shift into a vector multiply instead of
16651   // expanding it into a sequence of scalar shifts.
16652   // Do this only if the vector shift count is a constant build_vector.
16653   if (Op.getOpcode() == ISD::SHL &&
16654       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
16655        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
16656       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
16657     SmallVector<SDValue, 8> Elts;
16658     EVT SVT = VT.getScalarType();
16659     unsigned SVTBits = SVT.getSizeInBits();
16660     const APInt &One = APInt(SVTBits, 1);
16661     unsigned NumElems = VT.getVectorNumElements();
16662
16663     for (unsigned i=0; i !=NumElems; ++i) {
16664       SDValue Op = Amt->getOperand(i);
16665       if (Op->getOpcode() == ISD::UNDEF) {
16666         Elts.push_back(Op);
16667         continue;
16668       }
16669
16670       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
16671       const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
16672       uint64_t ShAmt = C.getZExtValue();
16673       if (ShAmt >= SVTBits) {
16674         Elts.push_back(DAG.getUNDEF(SVT));
16675         continue;
16676       }
16677       Elts.push_back(DAG.getConstant(One.shl(ShAmt), dl, SVT));
16678     }
16679     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
16680     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
16681   }
16682
16683   // Lower SHL with variable shift amount.
16684   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
16685     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, dl, VT));
16686
16687     Op = DAG.getNode(ISD::ADD, dl, VT, Op,
16688                      DAG.getConstant(0x3f800000U, dl, VT));
16689     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
16690     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
16691     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
16692   }
16693
16694   // If possible, lower this shift as a sequence of two shifts by
16695   // constant plus a MOVSS/MOVSD instead of scalarizing it.
16696   // Example:
16697   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
16698   //
16699   // Could be rewritten as:
16700   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
16701   //
16702   // The advantage is that the two shifts from the example would be
16703   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
16704   // the vector shift into four scalar shifts plus four pairs of vector
16705   // insert/extract.
16706   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
16707       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
16708     unsigned TargetOpcode = X86ISD::MOVSS;
16709     bool CanBeSimplified;
16710     // The splat value for the first packed shift (the 'X' from the example).
16711     SDValue Amt1 = Amt->getOperand(0);
16712     // The splat value for the second packed shift (the 'Y' from the example).
16713     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
16714                                         Amt->getOperand(2);
16715
16716     // See if it is possible to replace this node with a sequence of
16717     // two shifts followed by a MOVSS/MOVSD
16718     if (VT == MVT::v4i32) {
16719       // Check if it is legal to use a MOVSS.
16720       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
16721                         Amt2 == Amt->getOperand(3);
16722       if (!CanBeSimplified) {
16723         // Otherwise, check if we can still simplify this node using a MOVSD.
16724         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
16725                           Amt->getOperand(2) == Amt->getOperand(3);
16726         TargetOpcode = X86ISD::MOVSD;
16727         Amt2 = Amt->getOperand(2);
16728       }
16729     } else {
16730       // Do similar checks for the case where the machine value type
16731       // is MVT::v8i16.
16732       CanBeSimplified = Amt1 == Amt->getOperand(1);
16733       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
16734         CanBeSimplified = Amt2 == Amt->getOperand(i);
16735
16736       if (!CanBeSimplified) {
16737         TargetOpcode = X86ISD::MOVSD;
16738         CanBeSimplified = true;
16739         Amt2 = Amt->getOperand(4);
16740         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
16741           CanBeSimplified = Amt1 == Amt->getOperand(i);
16742         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
16743           CanBeSimplified = Amt2 == Amt->getOperand(j);
16744       }
16745     }
16746
16747     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
16748         isa<ConstantSDNode>(Amt2)) {
16749       // Replace this node with two shifts followed by a MOVSS/MOVSD.
16750       EVT CastVT = MVT::v4i32;
16751       SDValue Splat1 =
16752         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), dl, VT);
16753       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
16754       SDValue Splat2 =
16755         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), dl, VT);
16756       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
16757       if (TargetOpcode == X86ISD::MOVSD)
16758         CastVT = MVT::v2i64;
16759       SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
16760       SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
16761       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
16762                                             BitCast1, DAG);
16763       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
16764     }
16765   }
16766
16767   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
16768     // Turn 'a' into a mask suitable for VSELECT: a = a << 5;
16769     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, dl, VT));
16770
16771     SDValue VSelM = DAG.getConstant(0x80, dl, VT);
16772     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16773     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16774
16775     // r = VSELECT(r, shl(r, 4), a);
16776     SDValue M = DAG.getNode(ISD::SHL, dl, VT, R, DAG.getConstant(4, dl, VT));
16777     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
16778
16779     // a += a
16780     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
16781     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16782     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16783
16784     // r = VSELECT(r, shl(r, 2), a);
16785     M = DAG.getNode(ISD::SHL, dl, VT, R, DAG.getConstant(2, dl, VT));
16786     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
16787
16788     // a += a
16789     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
16790     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16791     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16792
16793     // return VSELECT(r, r+r, a);
16794     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
16795                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
16796     return R;
16797   }
16798
16799   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
16800   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
16801   // solution better.
16802   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
16803     MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
16804     unsigned ExtOpc =
16805         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
16806     R = DAG.getNode(ExtOpc, dl, NewVT, R);
16807     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
16808     return DAG.getNode(ISD::TRUNCATE, dl, VT,
16809                        DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
16810   }
16811
16812   // Decompose 256-bit shifts into smaller 128-bit shifts.
16813   if (VT.is256BitVector()) {
16814     unsigned NumElems = VT.getVectorNumElements();
16815     MVT EltVT = VT.getVectorElementType();
16816     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16817
16818     // Extract the two vectors
16819     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
16820     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
16821
16822     // Recreate the shift amount vectors
16823     SDValue Amt1, Amt2;
16824     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
16825       // Constant shift amount
16826       SmallVector<SDValue, 8> Ops(Amt->op_begin(), Amt->op_begin() + NumElems);
16827       ArrayRef<SDValue> Amt1Csts = makeArrayRef(Ops).slice(0, NumElems / 2);
16828       ArrayRef<SDValue> Amt2Csts = makeArrayRef(Ops).slice(NumElems / 2);
16829
16830       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
16831       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
16832     } else {
16833       // Variable shift amount
16834       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
16835       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
16836     }
16837
16838     // Issue new vector shifts for the smaller types
16839     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
16840     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
16841
16842     // Concatenate the result back
16843     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
16844   }
16845
16846   return SDValue();
16847 }
16848
16849 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
16850   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
16851   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
16852   // looks for this combo and may remove the "setcc" instruction if the "setcc"
16853   // has only one use.
16854   SDNode *N = Op.getNode();
16855   SDValue LHS = N->getOperand(0);
16856   SDValue RHS = N->getOperand(1);
16857   unsigned BaseOp = 0;
16858   unsigned Cond = 0;
16859   SDLoc DL(Op);
16860   switch (Op.getOpcode()) {
16861   default: llvm_unreachable("Unknown ovf instruction!");
16862   case ISD::SADDO:
16863     // A subtract of one will be selected as a INC. Note that INC doesn't
16864     // set CF, so we can't do this for UADDO.
16865     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16866       if (C->isOne()) {
16867         BaseOp = X86ISD::INC;
16868         Cond = X86::COND_O;
16869         break;
16870       }
16871     BaseOp = X86ISD::ADD;
16872     Cond = X86::COND_O;
16873     break;
16874   case ISD::UADDO:
16875     BaseOp = X86ISD::ADD;
16876     Cond = X86::COND_B;
16877     break;
16878   case ISD::SSUBO:
16879     // A subtract of one will be selected as a DEC. Note that DEC doesn't
16880     // set CF, so we can't do this for USUBO.
16881     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16882       if (C->isOne()) {
16883         BaseOp = X86ISD::DEC;
16884         Cond = X86::COND_O;
16885         break;
16886       }
16887     BaseOp = X86ISD::SUB;
16888     Cond = X86::COND_O;
16889     break;
16890   case ISD::USUBO:
16891     BaseOp = X86ISD::SUB;
16892     Cond = X86::COND_B;
16893     break;
16894   case ISD::SMULO:
16895     BaseOp = N->getValueType(0) == MVT::i8 ? X86ISD::SMUL8 : X86ISD::SMUL;
16896     Cond = X86::COND_O;
16897     break;
16898   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
16899     if (N->getValueType(0) == MVT::i8) {
16900       BaseOp = X86ISD::UMUL8;
16901       Cond = X86::COND_O;
16902       break;
16903     }
16904     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
16905                                  MVT::i32);
16906     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
16907
16908     SDValue SetCC =
16909       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16910                   DAG.getConstant(X86::COND_O, DL, MVT::i32),
16911                   SDValue(Sum.getNode(), 2));
16912
16913     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
16914   }
16915   }
16916
16917   // Also sets EFLAGS.
16918   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
16919   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
16920
16921   SDValue SetCC =
16922     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
16923                 DAG.getConstant(Cond, DL, MVT::i32),
16924                 SDValue(Sum.getNode(), 1));
16925
16926   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
16927 }
16928
16929 /// Returns true if the operand type is exactly twice the native width, and
16930 /// the corresponding cmpxchg8b or cmpxchg16b instruction is available.
16931 /// Used to know whether to use cmpxchg8/16b when expanding atomic operations
16932 /// (otherwise we leave them alone to become __sync_fetch_and_... calls).
16933 bool X86TargetLowering::needsCmpXchgNb(const Type *MemType) const {
16934   unsigned OpWidth = MemType->getPrimitiveSizeInBits();
16935
16936   if (OpWidth == 64)
16937     return !Subtarget->is64Bit(); // FIXME this should be Subtarget.hasCmpxchg8b
16938   else if (OpWidth == 128)
16939     return Subtarget->hasCmpxchg16b();
16940   else
16941     return false;
16942 }
16943
16944 bool X86TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
16945   return needsCmpXchgNb(SI->getValueOperand()->getType());
16946 }
16947
16948 // Note: this turns large loads into lock cmpxchg8b/16b.
16949 // FIXME: On 32 bits x86, fild/movq might be faster than lock cmpxchg8b.
16950 bool X86TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
16951   auto PTy = cast<PointerType>(LI->getPointerOperand()->getType());
16952   return needsCmpXchgNb(PTy->getElementType());
16953 }
16954
16955 TargetLoweringBase::AtomicRMWExpansionKind
16956 X86TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
16957   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
16958   const Type *MemType = AI->getType();
16959
16960   // If the operand is too big, we must see if cmpxchg8/16b is available
16961   // and default to library calls otherwise.
16962   if (MemType->getPrimitiveSizeInBits() > NativeWidth) {
16963     return needsCmpXchgNb(MemType) ? AtomicRMWExpansionKind::CmpXChg
16964                                    : AtomicRMWExpansionKind::None;
16965   }
16966
16967   AtomicRMWInst::BinOp Op = AI->getOperation();
16968   switch (Op) {
16969   default:
16970     llvm_unreachable("Unknown atomic operation");
16971   case AtomicRMWInst::Xchg:
16972   case AtomicRMWInst::Add:
16973   case AtomicRMWInst::Sub:
16974     // It's better to use xadd, xsub or xchg for these in all cases.
16975     return AtomicRMWExpansionKind::None;
16976   case AtomicRMWInst::Or:
16977   case AtomicRMWInst::And:
16978   case AtomicRMWInst::Xor:
16979     // If the atomicrmw's result isn't actually used, we can just add a "lock"
16980     // prefix to a normal instruction for these operations.
16981     return !AI->use_empty() ? AtomicRMWExpansionKind::CmpXChg
16982                             : AtomicRMWExpansionKind::None;
16983   case AtomicRMWInst::Nand:
16984   case AtomicRMWInst::Max:
16985   case AtomicRMWInst::Min:
16986   case AtomicRMWInst::UMax:
16987   case AtomicRMWInst::UMin:
16988     // These always require a non-trivial set of data operations on x86. We must
16989     // use a cmpxchg loop.
16990     return AtomicRMWExpansionKind::CmpXChg;
16991   }
16992 }
16993
16994 static bool hasMFENCE(const X86Subtarget& Subtarget) {
16995   // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
16996   // no-sse2). There isn't any reason to disable it if the target processor
16997   // supports it.
16998   return Subtarget.hasSSE2() || Subtarget.is64Bit();
16999 }
17000
17001 LoadInst *
17002 X86TargetLowering::lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *AI) const {
17003   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
17004   const Type *MemType = AI->getType();
17005   // Accesses larger than the native width are turned into cmpxchg/libcalls, so
17006   // there is no benefit in turning such RMWs into loads, and it is actually
17007   // harmful as it introduces a mfence.
17008   if (MemType->getPrimitiveSizeInBits() > NativeWidth)
17009     return nullptr;
17010
17011   auto Builder = IRBuilder<>(AI);
17012   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
17013   auto SynchScope = AI->getSynchScope();
17014   // We must restrict the ordering to avoid generating loads with Release or
17015   // ReleaseAcquire orderings.
17016   auto Order = AtomicCmpXchgInst::getStrongestFailureOrdering(AI->getOrdering());
17017   auto Ptr = AI->getPointerOperand();
17018
17019   // Before the load we need a fence. Here is an example lifted from
17020   // http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf showing why a fence
17021   // is required:
17022   // Thread 0:
17023   //   x.store(1, relaxed);
17024   //   r1 = y.fetch_add(0, release);
17025   // Thread 1:
17026   //   y.fetch_add(42, acquire);
17027   //   r2 = x.load(relaxed);
17028   // r1 = r2 = 0 is impossible, but becomes possible if the idempotent rmw is
17029   // lowered to just a load without a fence. A mfence flushes the store buffer,
17030   // making the optimization clearly correct.
17031   // FIXME: it is required if isAtLeastRelease(Order) but it is not clear
17032   // otherwise, we might be able to be more agressive on relaxed idempotent
17033   // rmw. In practice, they do not look useful, so we don't try to be
17034   // especially clever.
17035   if (SynchScope == SingleThread)
17036     // FIXME: we could just insert an X86ISD::MEMBARRIER here, except we are at
17037     // the IR level, so we must wrap it in an intrinsic.
17038     return nullptr;
17039
17040   if (!hasMFENCE(*Subtarget))
17041     // FIXME: it might make sense to use a locked operation here but on a
17042     // different cache-line to prevent cache-line bouncing. In practice it
17043     // is probably a small win, and x86 processors without mfence are rare
17044     // enough that we do not bother.
17045     return nullptr;
17046
17047   Function *MFence =
17048       llvm::Intrinsic::getDeclaration(M, Intrinsic::x86_sse2_mfence);
17049   Builder.CreateCall(MFence, {});
17050
17051   // Finally we can emit the atomic load.
17052   LoadInst *Loaded = Builder.CreateAlignedLoad(Ptr,
17053           AI->getType()->getPrimitiveSizeInBits());
17054   Loaded->setAtomic(Order, SynchScope);
17055   AI->replaceAllUsesWith(Loaded);
17056   AI->eraseFromParent();
17057   return Loaded;
17058 }
17059
17060 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
17061                                  SelectionDAG &DAG) {
17062   SDLoc dl(Op);
17063   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
17064     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
17065   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
17066     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
17067
17068   // The only fence that needs an instruction is a sequentially-consistent
17069   // cross-thread fence.
17070   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
17071     if (hasMFENCE(*Subtarget))
17072       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
17073
17074     SDValue Chain = Op.getOperand(0);
17075     SDValue Zero = DAG.getConstant(0, dl, MVT::i32);
17076     SDValue Ops[] = {
17077       DAG.getRegister(X86::ESP, MVT::i32),     // Base
17078       DAG.getTargetConstant(1, dl, MVT::i8),   // Scale
17079       DAG.getRegister(0, MVT::i32),            // Index
17080       DAG.getTargetConstant(0, dl, MVT::i32),  // Disp
17081       DAG.getRegister(0, MVT::i32),            // Segment.
17082       Zero,
17083       Chain
17084     };
17085     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
17086     return SDValue(Res, 0);
17087   }
17088
17089   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
17090   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
17091 }
17092
17093 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
17094                              SelectionDAG &DAG) {
17095   MVT T = Op.getSimpleValueType();
17096   SDLoc DL(Op);
17097   unsigned Reg = 0;
17098   unsigned size = 0;
17099   switch(T.SimpleTy) {
17100   default: llvm_unreachable("Invalid value type!");
17101   case MVT::i8:  Reg = X86::AL;  size = 1; break;
17102   case MVT::i16: Reg = X86::AX;  size = 2; break;
17103   case MVT::i32: Reg = X86::EAX; size = 4; break;
17104   case MVT::i64:
17105     assert(Subtarget->is64Bit() && "Node not type legal!");
17106     Reg = X86::RAX; size = 8;
17107     break;
17108   }
17109   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
17110                                   Op.getOperand(2), SDValue());
17111   SDValue Ops[] = { cpIn.getValue(0),
17112                     Op.getOperand(1),
17113                     Op.getOperand(3),
17114                     DAG.getTargetConstant(size, DL, MVT::i8),
17115                     cpIn.getValue(1) };
17116   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
17117   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
17118   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
17119                                            Ops, T, MMO);
17120
17121   SDValue cpOut =
17122     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
17123   SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
17124                                       MVT::i32, cpOut.getValue(2));
17125   SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
17126                                 DAG.getConstant(X86::COND_E, DL, MVT::i8),
17127                                 EFLAGS);
17128
17129   DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
17130   DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
17131   DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
17132   return SDValue();
17133 }
17134
17135 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
17136                             SelectionDAG &DAG) {
17137   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
17138   MVT DstVT = Op.getSimpleValueType();
17139
17140   if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
17141     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
17142     if (DstVT != MVT::f64)
17143       // This conversion needs to be expanded.
17144       return SDValue();
17145
17146     SDValue InVec = Op->getOperand(0);
17147     SDLoc dl(Op);
17148     unsigned NumElts = SrcVT.getVectorNumElements();
17149     EVT SVT = SrcVT.getVectorElementType();
17150
17151     // Widen the vector in input in the case of MVT::v2i32.
17152     // Example: from MVT::v2i32 to MVT::v4i32.
17153     SmallVector<SDValue, 16> Elts;
17154     for (unsigned i = 0, e = NumElts; i != e; ++i)
17155       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
17156                                  DAG.getIntPtrConstant(i, dl)));
17157
17158     // Explicitly mark the extra elements as Undef.
17159     Elts.append(NumElts, DAG.getUNDEF(SVT));
17160
17161     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
17162     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
17163     SDValue ToV2F64 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, BV);
17164     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
17165                        DAG.getIntPtrConstant(0, dl));
17166   }
17167
17168   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
17169          Subtarget->hasMMX() && "Unexpected custom BITCAST");
17170   assert((DstVT == MVT::i64 ||
17171           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
17172          "Unexpected custom BITCAST");
17173   // i64 <=> MMX conversions are Legal.
17174   if (SrcVT==MVT::i64 && DstVT.isVector())
17175     return Op;
17176   if (DstVT==MVT::i64 && SrcVT.isVector())
17177     return Op;
17178   // MMX <=> MMX conversions are Legal.
17179   if (SrcVT.isVector() && DstVT.isVector())
17180     return Op;
17181   // All other conversions need to be expanded.
17182   return SDValue();
17183 }
17184
17185 static SDValue LowerCTPOP(SDValue Op, const X86Subtarget *Subtarget,
17186                           SelectionDAG &DAG) {
17187   SDNode *Node = Op.getNode();
17188   SDLoc dl(Node);
17189
17190   Op = Op.getOperand(0);
17191   EVT VT = Op.getValueType();
17192   assert((VT.is128BitVector() || VT.is256BitVector()) &&
17193          "CTPOP lowering only implemented for 128/256-bit wide vector types");
17194
17195   unsigned NumElts = VT.getVectorNumElements();
17196   EVT EltVT = VT.getVectorElementType();
17197   unsigned Len = EltVT.getSizeInBits();
17198
17199   // This is the vectorized version of the "best" algorithm from
17200   // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
17201   // with a minor tweak to use a series of adds + shifts instead of vector
17202   // multiplications. Implemented for the v2i64, v4i64, v4i32, v8i32 types:
17203   //
17204   //  v2i64, v4i64, v4i32 => Only profitable w/ popcnt disabled
17205   //  v8i32 => Always profitable
17206   //
17207   // FIXME: There a couple of possible improvements:
17208   //
17209   // 1) Support for i8 and i16 vectors (needs measurements if popcnt enabled).
17210   // 2) Use strategies from http://wm.ite.pl/articles/sse-popcount.html
17211   //
17212   assert(EltVT.isInteger() && (Len == 32 || Len == 64) && Len % 8 == 0 &&
17213          "CTPOP not implemented for this vector element type.");
17214
17215   // X86 canonicalize ANDs to vXi64, generate the appropriate bitcasts to avoid
17216   // extra legalization.
17217   bool NeedsBitcast = EltVT == MVT::i32;
17218   MVT BitcastVT = VT.is256BitVector() ? MVT::v4i64 : MVT::v2i64;
17219
17220   SDValue Cst55 = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x55)), dl,
17221                                   EltVT);
17222   SDValue Cst33 = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x33)), dl,
17223                                   EltVT);
17224   SDValue Cst0F = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x0F)), dl,
17225                                   EltVT);
17226
17227   // v = v - ((v >> 1) & 0x55555555...)
17228   SmallVector<SDValue, 8> Ones(NumElts, DAG.getConstant(1, dl, EltVT));
17229   SDValue OnesV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ones);
17230   SDValue Srl = DAG.getNode(ISD::SRL, dl, VT, Op, OnesV);
17231   if (NeedsBitcast)
17232     Srl = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Srl);
17233
17234   SmallVector<SDValue, 8> Mask55(NumElts, Cst55);
17235   SDValue M55 = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Mask55);
17236   if (NeedsBitcast)
17237     M55 = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M55);
17238
17239   SDValue And = DAG.getNode(ISD::AND, dl, Srl.getValueType(), Srl, M55);
17240   if (VT != And.getValueType())
17241     And = DAG.getNode(ISD::BITCAST, dl, VT, And);
17242   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, Op, And);
17243
17244   // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
17245   SmallVector<SDValue, 8> Mask33(NumElts, Cst33);
17246   SDValue M33 = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Mask33);
17247   SmallVector<SDValue, 8> Twos(NumElts, DAG.getConstant(2, dl, EltVT));
17248   SDValue TwosV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Twos);
17249
17250   Srl = DAG.getNode(ISD::SRL, dl, VT, Sub, TwosV);
17251   if (NeedsBitcast) {
17252     Srl = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Srl);
17253     M33 = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M33);
17254     Sub = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Sub);
17255   }
17256
17257   SDValue AndRHS = DAG.getNode(ISD::AND, dl, M33.getValueType(), Srl, M33);
17258   SDValue AndLHS = DAG.getNode(ISD::AND, dl, M33.getValueType(), Sub, M33);
17259   if (VT != AndRHS.getValueType()) {
17260     AndRHS = DAG.getNode(ISD::BITCAST, dl, VT, AndRHS);
17261     AndLHS = DAG.getNode(ISD::BITCAST, dl, VT, AndLHS);
17262   }
17263   SDValue Add = DAG.getNode(ISD::ADD, dl, VT, AndLHS, AndRHS);
17264
17265   // v = (v + (v >> 4)) & 0x0F0F0F0F...
17266   SmallVector<SDValue, 8> Fours(NumElts, DAG.getConstant(4, dl, EltVT));
17267   SDValue FoursV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Fours);
17268   Srl = DAG.getNode(ISD::SRL, dl, VT, Add, FoursV);
17269   Add = DAG.getNode(ISD::ADD, dl, VT, Add, Srl);
17270
17271   SmallVector<SDValue, 8> Mask0F(NumElts, Cst0F);
17272   SDValue M0F = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Mask0F);
17273   if (NeedsBitcast) {
17274     Add = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Add);
17275     M0F = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M0F);
17276   }
17277   And = DAG.getNode(ISD::AND, dl, M0F.getValueType(), Add, M0F);
17278   if (VT != And.getValueType())
17279     And = DAG.getNode(ISD::BITCAST, dl, VT, And);
17280
17281   // The algorithm mentioned above uses:
17282   //    v = (v * 0x01010101...) >> (Len - 8)
17283   //
17284   // Change it to use vector adds + vector shifts which yield faster results on
17285   // Haswell than using vector integer multiplication.
17286   //
17287   // For i32 elements:
17288   //    v = v + (v >> 8)
17289   //    v = v + (v >> 16)
17290   //
17291   // For i64 elements:
17292   //    v = v + (v >> 8)
17293   //    v = v + (v >> 16)
17294   //    v = v + (v >> 32)
17295   //
17296   Add = And;
17297   SmallVector<SDValue, 8> Csts;
17298   for (unsigned i = 8; i <= Len/2; i *= 2) {
17299     Csts.assign(NumElts, DAG.getConstant(i, dl, EltVT));
17300     SDValue CstsV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Csts);
17301     Srl = DAG.getNode(ISD::SRL, dl, VT, Add, CstsV);
17302     Add = DAG.getNode(ISD::ADD, dl, VT, Add, Srl);
17303     Csts.clear();
17304   }
17305
17306   // The result is on the least significant 6-bits on i32 and 7-bits on i64.
17307   SDValue Cst3F = DAG.getConstant(APInt(Len, Len == 32 ? 0x3F : 0x7F), dl,
17308                                   EltVT);
17309   SmallVector<SDValue, 8> Cst3FV(NumElts, Cst3F);
17310   SDValue M3F = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Cst3FV);
17311   if (NeedsBitcast) {
17312     Add = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Add);
17313     M3F = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M3F);
17314   }
17315   And = DAG.getNode(ISD::AND, dl, M3F.getValueType(), Add, M3F);
17316   if (VT != And.getValueType())
17317     And = DAG.getNode(ISD::BITCAST, dl, VT, And);
17318
17319   return And;
17320 }
17321
17322 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
17323   SDNode *Node = Op.getNode();
17324   SDLoc dl(Node);
17325   EVT T = Node->getValueType(0);
17326   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
17327                               DAG.getConstant(0, dl, T), Node->getOperand(2));
17328   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
17329                        cast<AtomicSDNode>(Node)->getMemoryVT(),
17330                        Node->getOperand(0),
17331                        Node->getOperand(1), negOp,
17332                        cast<AtomicSDNode>(Node)->getMemOperand(),
17333                        cast<AtomicSDNode>(Node)->getOrdering(),
17334                        cast<AtomicSDNode>(Node)->getSynchScope());
17335 }
17336
17337 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
17338   SDNode *Node = Op.getNode();
17339   SDLoc dl(Node);
17340   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
17341
17342   // Convert seq_cst store -> xchg
17343   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
17344   // FIXME: On 32-bit, store -> fist or movq would be more efficient
17345   //        (The only way to get a 16-byte store is cmpxchg16b)
17346   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
17347   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
17348       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
17349     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
17350                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
17351                                  Node->getOperand(0),
17352                                  Node->getOperand(1), Node->getOperand(2),
17353                                  cast<AtomicSDNode>(Node)->getMemOperand(),
17354                                  cast<AtomicSDNode>(Node)->getOrdering(),
17355                                  cast<AtomicSDNode>(Node)->getSynchScope());
17356     return Swap.getValue(1);
17357   }
17358   // Other atomic stores have a simple pattern.
17359   return Op;
17360 }
17361
17362 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
17363   EVT VT = Op.getNode()->getSimpleValueType(0);
17364
17365   // Let legalize expand this if it isn't a legal type yet.
17366   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
17367     return SDValue();
17368
17369   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
17370
17371   unsigned Opc;
17372   bool ExtraOp = false;
17373   switch (Op.getOpcode()) {
17374   default: llvm_unreachable("Invalid code");
17375   case ISD::ADDC: Opc = X86ISD::ADD; break;
17376   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
17377   case ISD::SUBC: Opc = X86ISD::SUB; break;
17378   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
17379   }
17380
17381   if (!ExtraOp)
17382     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
17383                        Op.getOperand(1));
17384   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
17385                      Op.getOperand(1), Op.getOperand(2));
17386 }
17387
17388 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
17389                             SelectionDAG &DAG) {
17390   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
17391
17392   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
17393   // which returns the values as { float, float } (in XMM0) or
17394   // { double, double } (which is returned in XMM0, XMM1).
17395   SDLoc dl(Op);
17396   SDValue Arg = Op.getOperand(0);
17397   EVT ArgVT = Arg.getValueType();
17398   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
17399
17400   TargetLowering::ArgListTy Args;
17401   TargetLowering::ArgListEntry Entry;
17402
17403   Entry.Node = Arg;
17404   Entry.Ty = ArgTy;
17405   Entry.isSExt = false;
17406   Entry.isZExt = false;
17407   Args.push_back(Entry);
17408
17409   bool isF64 = ArgVT == MVT::f64;
17410   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
17411   // the small struct {f32, f32} is returned in (eax, edx). For f64,
17412   // the results are returned via SRet in memory.
17413   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
17414   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17415   SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
17416
17417   Type *RetTy = isF64
17418     ? (Type*)StructType::get(ArgTy, ArgTy, nullptr)
17419     : (Type*)VectorType::get(ArgTy, 4);
17420
17421   TargetLowering::CallLoweringInfo CLI(DAG);
17422   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
17423     .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
17424
17425   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
17426
17427   if (isF64)
17428     // Returned in xmm0 and xmm1.
17429     return CallResult.first;
17430
17431   // Returned in bits 0:31 and 32:64 xmm0.
17432   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
17433                                CallResult.first, DAG.getIntPtrConstant(0, dl));
17434   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
17435                                CallResult.first, DAG.getIntPtrConstant(1, dl));
17436   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
17437   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
17438 }
17439
17440 static SDValue LowerMSCATTER(SDValue Op, const X86Subtarget *Subtarget,
17441                              SelectionDAG &DAG) {
17442   assert(Subtarget->hasAVX512() &&
17443          "MGATHER/MSCATTER are supported on AVX-512 arch only");
17444
17445   MaskedScatterSDNode *N = cast<MaskedScatterSDNode>(Op.getNode());
17446   EVT VT = N->getValue().getValueType();
17447   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported scatter op");
17448   SDLoc dl(Op);
17449
17450   // X86 scatter kills mask register, so its type should be added to
17451   // the list of return values
17452   if (N->getNumValues() == 1) {
17453     SDValue Index = N->getIndex();
17454     if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
17455         !Index.getValueType().is512BitVector())
17456       Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
17457
17458     SDVTList VTs = DAG.getVTList(N->getMask().getValueType(), MVT::Other);
17459     SDValue Ops[] = { N->getOperand(0), N->getOperand(1),  N->getOperand(2),
17460                       N->getOperand(3), Index };
17461
17462     SDValue NewScatter = DAG.getMaskedScatter(VTs, VT, dl, Ops, N->getMemOperand());
17463     DAG.ReplaceAllUsesWith(Op, SDValue(NewScatter.getNode(), 1));
17464     return SDValue(NewScatter.getNode(), 0);
17465   }
17466   return Op;
17467 }
17468
17469 static SDValue LowerMGATHER(SDValue Op, const X86Subtarget *Subtarget,
17470                             SelectionDAG &DAG) {
17471   assert(Subtarget->hasAVX512() &&
17472          "MGATHER/MSCATTER are supported on AVX-512 arch only");
17473
17474   MaskedGatherSDNode *N = cast<MaskedGatherSDNode>(Op.getNode());
17475   EVT VT = Op.getValueType();
17476   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported gather op");
17477   SDLoc dl(Op);
17478
17479   SDValue Index = N->getIndex();
17480   if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
17481       !Index.getValueType().is512BitVector()) {
17482     Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
17483     SDValue Ops[] = { N->getOperand(0), N->getOperand(1),  N->getOperand(2),
17484                       N->getOperand(3), Index };
17485     DAG.UpdateNodeOperands(N, Ops);
17486   }
17487   return Op;
17488 }
17489
17490 SDValue X86TargetLowering::LowerGC_TRANSITION_START(SDValue Op,
17491                                                     SelectionDAG &DAG) const {
17492   // TODO: Eventually, the lowering of these nodes should be informed by or
17493   // deferred to the GC strategy for the function in which they appear. For
17494   // now, however, they must be lowered to something. Since they are logically
17495   // no-ops in the case of a null GC strategy (or a GC strategy which does not
17496   // require special handling for these nodes), lower them as literal NOOPs for
17497   // the time being.
17498   SmallVector<SDValue, 2> Ops;
17499
17500   Ops.push_back(Op.getOperand(0));
17501   if (Op->getGluedNode())
17502     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
17503
17504   SDLoc OpDL(Op);
17505   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
17506   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
17507
17508   return NOOP;
17509 }
17510
17511 SDValue X86TargetLowering::LowerGC_TRANSITION_END(SDValue Op,
17512                                                   SelectionDAG &DAG) const {
17513   // TODO: Eventually, the lowering of these nodes should be informed by or
17514   // deferred to the GC strategy for the function in which they appear. For
17515   // now, however, they must be lowered to something. Since they are logically
17516   // no-ops in the case of a null GC strategy (or a GC strategy which does not
17517   // require special handling for these nodes), lower them as literal NOOPs for
17518   // the time being.
17519   SmallVector<SDValue, 2> Ops;
17520
17521   Ops.push_back(Op.getOperand(0));
17522   if (Op->getGluedNode())
17523     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
17524
17525   SDLoc OpDL(Op);
17526   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
17527   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
17528
17529   return NOOP;
17530 }
17531
17532 /// LowerOperation - Provide custom lowering hooks for some operations.
17533 ///
17534 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
17535   switch (Op.getOpcode()) {
17536   default: llvm_unreachable("Should not custom lower this!");
17537   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
17538   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
17539     return LowerCMP_SWAP(Op, Subtarget, DAG);
17540   case ISD::CTPOP:              return LowerCTPOP(Op, Subtarget, DAG);
17541   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
17542   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
17543   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
17544   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, Subtarget, DAG);
17545   case ISD::VECTOR_SHUFFLE:     return lowerVectorShuffle(Op, Subtarget, DAG);
17546   case ISD::VSELECT:            return LowerVSELECT(Op, DAG);
17547   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
17548   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
17549   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
17550   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
17551   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
17552   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
17553   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
17554   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
17555   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
17556   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
17557   case ISD::SHL_PARTS:
17558   case ISD::SRA_PARTS:
17559   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
17560   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
17561   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
17562   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
17563   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
17564   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
17565   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
17566   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
17567   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
17568   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
17569   case ISD::LOAD:               return LowerExtendedLoad(Op, Subtarget, DAG);
17570   case ISD::FABS:
17571   case ISD::FNEG:               return LowerFABSorFNEG(Op, DAG);
17572   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
17573   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
17574   case ISD::SETCC:              return LowerSETCC(Op, DAG);
17575   case ISD::SELECT:             return LowerSELECT(Op, DAG);
17576   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
17577   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
17578   case ISD::VASTART:            return LowerVASTART(Op, DAG);
17579   case ISD::VAARG:              return LowerVAARG(Op, DAG);
17580   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
17581   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, Subtarget, DAG);
17582   case ISD::INTRINSIC_VOID:
17583   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
17584   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
17585   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
17586   case ISD::FRAME_TO_ARGS_OFFSET:
17587                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
17588   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
17589   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
17590   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
17591   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
17592   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
17593   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
17594   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
17595   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
17596   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
17597   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
17598   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
17599   case ISD::UMUL_LOHI:
17600   case ISD::SMUL_LOHI:          return LowerMUL_LOHI(Op, Subtarget, DAG);
17601   case ISD::SRA:
17602   case ISD::SRL:
17603   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
17604   case ISD::SADDO:
17605   case ISD::UADDO:
17606   case ISD::SSUBO:
17607   case ISD::USUBO:
17608   case ISD::SMULO:
17609   case ISD::UMULO:              return LowerXALUO(Op, DAG);
17610   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
17611   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
17612   case ISD::ADDC:
17613   case ISD::ADDE:
17614   case ISD::SUBC:
17615   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
17616   case ISD::ADD:                return LowerADD(Op, DAG);
17617   case ISD::SUB:                return LowerSUB(Op, DAG);
17618   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
17619   case ISD::MGATHER:            return LowerMGATHER(Op, Subtarget, DAG);
17620   case ISD::MSCATTER:           return LowerMSCATTER(Op, Subtarget, DAG);
17621   case ISD::GC_TRANSITION_START:
17622                                 return LowerGC_TRANSITION_START(Op, DAG);
17623   case ISD::GC_TRANSITION_END:  return LowerGC_TRANSITION_END(Op, DAG);
17624   }
17625 }
17626
17627 /// ReplaceNodeResults - Replace a node with an illegal result type
17628 /// with a new node built out of custom code.
17629 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
17630                                            SmallVectorImpl<SDValue>&Results,
17631                                            SelectionDAG &DAG) const {
17632   SDLoc dl(N);
17633   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17634   switch (N->getOpcode()) {
17635   default:
17636     llvm_unreachable("Do not know how to custom type legalize this operation!");
17637   // We might have generated v2f32 FMIN/FMAX operations. Widen them to v4f32.
17638   case X86ISD::FMINC:
17639   case X86ISD::FMIN:
17640   case X86ISD::FMAXC:
17641   case X86ISD::FMAX: {
17642     EVT VT = N->getValueType(0);
17643     if (VT != MVT::v2f32)
17644       llvm_unreachable("Unexpected type (!= v2f32) on FMIN/FMAX.");
17645     SDValue UNDEF = DAG.getUNDEF(VT);
17646     SDValue LHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
17647                               N->getOperand(0), UNDEF);
17648     SDValue RHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
17649                               N->getOperand(1), UNDEF);
17650     Results.push_back(DAG.getNode(N->getOpcode(), dl, MVT::v4f32, LHS, RHS));
17651     return;
17652   }
17653   case ISD::SIGN_EXTEND_INREG:
17654   case ISD::ADDC:
17655   case ISD::ADDE:
17656   case ISD::SUBC:
17657   case ISD::SUBE:
17658     // We don't want to expand or promote these.
17659     return;
17660   case ISD::SDIV:
17661   case ISD::UDIV:
17662   case ISD::SREM:
17663   case ISD::UREM:
17664   case ISD::SDIVREM:
17665   case ISD::UDIVREM: {
17666     SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
17667     Results.push_back(V);
17668     return;
17669   }
17670   case ISD::FP_TO_SINT:
17671     // FP_TO_INT*_IN_MEM is not legal for f16 inputs.  Do not convert
17672     // (FP_TO_SINT (load f16)) to FP_TO_INT*.
17673     if (N->getOperand(0).getValueType() == MVT::f16)
17674       break;
17675     // fallthrough
17676   case ISD::FP_TO_UINT: {
17677     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
17678
17679     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
17680       return;
17681
17682     std::pair<SDValue,SDValue> Vals =
17683         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
17684     SDValue FIST = Vals.first, StackSlot = Vals.second;
17685     if (FIST.getNode()) {
17686       EVT VT = N->getValueType(0);
17687       // Return a load from the stack slot.
17688       if (StackSlot.getNode())
17689         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
17690                                       MachinePointerInfo(),
17691                                       false, false, false, 0));
17692       else
17693         Results.push_back(FIST);
17694     }
17695     return;
17696   }
17697   case ISD::UINT_TO_FP: {
17698     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
17699     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
17700         N->getValueType(0) != MVT::v2f32)
17701       return;
17702     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
17703                                  N->getOperand(0));
17704     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
17705                                      MVT::f64);
17706     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
17707     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
17708                              DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
17709     Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
17710     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
17711     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
17712     return;
17713   }
17714   case ISD::FP_ROUND: {
17715     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
17716         return;
17717     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
17718     Results.push_back(V);
17719     return;
17720   }
17721   case ISD::FP_EXTEND: {
17722     // Right now, only MVT::v2f32 has OperationAction for FP_EXTEND.
17723     // No other ValueType for FP_EXTEND should reach this point.
17724     assert(N->getValueType(0) == MVT::v2f32 &&
17725            "Do not know how to legalize this Node");
17726     return;
17727   }
17728   case ISD::INTRINSIC_W_CHAIN: {
17729     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
17730     switch (IntNo) {
17731     default : llvm_unreachable("Do not know how to custom type "
17732                                "legalize this intrinsic operation!");
17733     case Intrinsic::x86_rdtsc:
17734       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
17735                                      Results);
17736     case Intrinsic::x86_rdtscp:
17737       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
17738                                      Results);
17739     case Intrinsic::x86_rdpmc:
17740       return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
17741     }
17742   }
17743   case ISD::READCYCLECOUNTER: {
17744     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
17745                                    Results);
17746   }
17747   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
17748     EVT T = N->getValueType(0);
17749     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
17750     bool Regs64bit = T == MVT::i128;
17751     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
17752     SDValue cpInL, cpInH;
17753     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
17754                         DAG.getConstant(0, dl, HalfT));
17755     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
17756                         DAG.getConstant(1, dl, HalfT));
17757     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
17758                              Regs64bit ? X86::RAX : X86::EAX,
17759                              cpInL, SDValue());
17760     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
17761                              Regs64bit ? X86::RDX : X86::EDX,
17762                              cpInH, cpInL.getValue(1));
17763     SDValue swapInL, swapInH;
17764     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
17765                           DAG.getConstant(0, dl, HalfT));
17766     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
17767                           DAG.getConstant(1, dl, HalfT));
17768     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
17769                                Regs64bit ? X86::RBX : X86::EBX,
17770                                swapInL, cpInH.getValue(1));
17771     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
17772                                Regs64bit ? X86::RCX : X86::ECX,
17773                                swapInH, swapInL.getValue(1));
17774     SDValue Ops[] = { swapInH.getValue(0),
17775                       N->getOperand(1),
17776                       swapInH.getValue(1) };
17777     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
17778     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
17779     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
17780                                   X86ISD::LCMPXCHG8_DAG;
17781     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
17782     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
17783                                         Regs64bit ? X86::RAX : X86::EAX,
17784                                         HalfT, Result.getValue(1));
17785     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
17786                                         Regs64bit ? X86::RDX : X86::EDX,
17787                                         HalfT, cpOutL.getValue(2));
17788     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
17789
17790     SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
17791                                         MVT::i32, cpOutH.getValue(2));
17792     SDValue Success =
17793         DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17794                     DAG.getConstant(X86::COND_E, dl, MVT::i8), EFLAGS);
17795     Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
17796
17797     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
17798     Results.push_back(Success);
17799     Results.push_back(EFLAGS.getValue(1));
17800     return;
17801   }
17802   case ISD::ATOMIC_SWAP:
17803   case ISD::ATOMIC_LOAD_ADD:
17804   case ISD::ATOMIC_LOAD_SUB:
17805   case ISD::ATOMIC_LOAD_AND:
17806   case ISD::ATOMIC_LOAD_OR:
17807   case ISD::ATOMIC_LOAD_XOR:
17808   case ISD::ATOMIC_LOAD_NAND:
17809   case ISD::ATOMIC_LOAD_MIN:
17810   case ISD::ATOMIC_LOAD_MAX:
17811   case ISD::ATOMIC_LOAD_UMIN:
17812   case ISD::ATOMIC_LOAD_UMAX:
17813   case ISD::ATOMIC_LOAD: {
17814     // Delegate to generic TypeLegalization. Situations we can really handle
17815     // should have already been dealt with by AtomicExpandPass.cpp.
17816     break;
17817   }
17818   case ISD::BITCAST: {
17819     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
17820     EVT DstVT = N->getValueType(0);
17821     EVT SrcVT = N->getOperand(0)->getValueType(0);
17822
17823     if (SrcVT != MVT::f64 ||
17824         (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
17825       return;
17826
17827     unsigned NumElts = DstVT.getVectorNumElements();
17828     EVT SVT = DstVT.getVectorElementType();
17829     EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
17830     SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
17831                                    MVT::v2f64, N->getOperand(0));
17832     SDValue ToVecInt = DAG.getNode(ISD::BITCAST, dl, WiderVT, Expanded);
17833
17834     if (ExperimentalVectorWideningLegalization) {
17835       // If we are legalizing vectors by widening, we already have the desired
17836       // legal vector type, just return it.
17837       Results.push_back(ToVecInt);
17838       return;
17839     }
17840
17841     SmallVector<SDValue, 8> Elts;
17842     for (unsigned i = 0, e = NumElts; i != e; ++i)
17843       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
17844                                    ToVecInt, DAG.getIntPtrConstant(i, dl)));
17845
17846     Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
17847   }
17848   }
17849 }
17850
17851 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
17852   switch ((X86ISD::NodeType)Opcode) {
17853   case X86ISD::FIRST_NUMBER:       break;
17854   case X86ISD::BSF:                return "X86ISD::BSF";
17855   case X86ISD::BSR:                return "X86ISD::BSR";
17856   case X86ISD::SHLD:               return "X86ISD::SHLD";
17857   case X86ISD::SHRD:               return "X86ISD::SHRD";
17858   case X86ISD::FAND:               return "X86ISD::FAND";
17859   case X86ISD::FANDN:              return "X86ISD::FANDN";
17860   case X86ISD::FOR:                return "X86ISD::FOR";
17861   case X86ISD::FXOR:               return "X86ISD::FXOR";
17862   case X86ISD::FSRL:               return "X86ISD::FSRL";
17863   case X86ISD::FILD:               return "X86ISD::FILD";
17864   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
17865   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
17866   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
17867   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
17868   case X86ISD::FLD:                return "X86ISD::FLD";
17869   case X86ISD::FST:                return "X86ISD::FST";
17870   case X86ISD::CALL:               return "X86ISD::CALL";
17871   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
17872   case X86ISD::RDTSCP_DAG:         return "X86ISD::RDTSCP_DAG";
17873   case X86ISD::RDPMC_DAG:          return "X86ISD::RDPMC_DAG";
17874   case X86ISD::BT:                 return "X86ISD::BT";
17875   case X86ISD::CMP:                return "X86ISD::CMP";
17876   case X86ISD::COMI:               return "X86ISD::COMI";
17877   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
17878   case X86ISD::CMPM:               return "X86ISD::CMPM";
17879   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
17880   case X86ISD::CMPM_RND:           return "X86ISD::CMPM_RND";
17881   case X86ISD::SETCC:              return "X86ISD::SETCC";
17882   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
17883   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
17884   case X86ISD::FGETSIGNx86:        return "X86ISD::FGETSIGNx86";
17885   case X86ISD::CMOV:               return "X86ISD::CMOV";
17886   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
17887   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
17888   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
17889   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
17890   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
17891   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
17892   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
17893   case X86ISD::MOVDQ2Q:            return "X86ISD::MOVDQ2Q";
17894   case X86ISD::MMX_MOVD2W:         return "X86ISD::MMX_MOVD2W";
17895   case X86ISD::MMX_MOVW2D:         return "X86ISD::MMX_MOVW2D";
17896   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
17897   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
17898   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
17899   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
17900   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
17901   case X86ISD::MMX_PINSRW:         return "X86ISD::MMX_PINSRW";
17902   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
17903   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
17904   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
17905   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
17906   case X86ISD::SHRUNKBLEND:        return "X86ISD::SHRUNKBLEND";
17907   case X86ISD::ADDUS:              return "X86ISD::ADDUS";
17908   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
17909   case X86ISD::HADD:               return "X86ISD::HADD";
17910   case X86ISD::HSUB:               return "X86ISD::HSUB";
17911   case X86ISD::FHADD:              return "X86ISD::FHADD";
17912   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
17913   case X86ISD::UMAX:               return "X86ISD::UMAX";
17914   case X86ISD::UMIN:               return "X86ISD::UMIN";
17915   case X86ISD::SMAX:               return "X86ISD::SMAX";
17916   case X86ISD::SMIN:               return "X86ISD::SMIN";
17917   case X86ISD::FMAX:               return "X86ISD::FMAX";
17918   case X86ISD::FMAX_RND:           return "X86ISD::FMAX_RND";
17919   case X86ISD::FMIN:               return "X86ISD::FMIN";
17920   case X86ISD::FMIN_RND:           return "X86ISD::FMIN_RND";
17921   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
17922   case X86ISD::FMINC:              return "X86ISD::FMINC";
17923   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
17924   case X86ISD::FRCP:               return "X86ISD::FRCP";
17925   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
17926   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
17927   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
17928   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
17929   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
17930   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
17931   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
17932   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
17933   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
17934   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
17935   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
17936   case X86ISD::LCMPXCHG16_DAG:     return "X86ISD::LCMPXCHG16_DAG";
17937   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
17938   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
17939   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
17940   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
17941   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
17942   case X86ISD::VTRUNCM:            return "X86ISD::VTRUNCM";
17943   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
17944   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
17945   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
17946   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
17947   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
17948   case X86ISD::VSHL:               return "X86ISD::VSHL";
17949   case X86ISD::VSRL:               return "X86ISD::VSRL";
17950   case X86ISD::VSRA:               return "X86ISD::VSRA";
17951   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
17952   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
17953   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
17954   case X86ISD::CMPP:               return "X86ISD::CMPP";
17955   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
17956   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
17957   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
17958   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
17959   case X86ISD::ADD:                return "X86ISD::ADD";
17960   case X86ISD::SUB:                return "X86ISD::SUB";
17961   case X86ISD::ADC:                return "X86ISD::ADC";
17962   case X86ISD::SBB:                return "X86ISD::SBB";
17963   case X86ISD::SMUL:               return "X86ISD::SMUL";
17964   case X86ISD::UMUL:               return "X86ISD::UMUL";
17965   case X86ISD::SMUL8:              return "X86ISD::SMUL8";
17966   case X86ISD::UMUL8:              return "X86ISD::UMUL8";
17967   case X86ISD::SDIVREM8_SEXT_HREG: return "X86ISD::SDIVREM8_SEXT_HREG";
17968   case X86ISD::UDIVREM8_ZEXT_HREG: return "X86ISD::UDIVREM8_ZEXT_HREG";
17969   case X86ISD::INC:                return "X86ISD::INC";
17970   case X86ISD::DEC:                return "X86ISD::DEC";
17971   case X86ISD::OR:                 return "X86ISD::OR";
17972   case X86ISD::XOR:                return "X86ISD::XOR";
17973   case X86ISD::AND:                return "X86ISD::AND";
17974   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
17975   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
17976   case X86ISD::PTEST:              return "X86ISD::PTEST";
17977   case X86ISD::TESTP:              return "X86ISD::TESTP";
17978   case X86ISD::TESTM:              return "X86ISD::TESTM";
17979   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
17980   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
17981   case X86ISD::PACKSS:             return "X86ISD::PACKSS";
17982   case X86ISD::PACKUS:             return "X86ISD::PACKUS";
17983   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
17984   case X86ISD::VALIGN:             return "X86ISD::VALIGN";
17985   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
17986   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
17987   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
17988   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
17989   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
17990   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
17991   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
17992   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
17993   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
17994   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
17995   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
17996   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
17997   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
17998   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
17999   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
18000   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
18001   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
18002   case X86ISD::SUBV_BROADCAST:     return "X86ISD::SUBV_BROADCAST";
18003   case X86ISD::VEXTRACT:           return "X86ISD::VEXTRACT";
18004   case X86ISD::VPERMILPV:          return "X86ISD::VPERMILPV";
18005   case X86ISD::VPERMILPI:          return "X86ISD::VPERMILPI";
18006   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
18007   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
18008   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
18009   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
18010   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
18011   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
18012   case X86ISD::PMULDQ:             return "X86ISD::PMULDQ";
18013   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
18014   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
18015   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
18016   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
18017   case X86ISD::MFENCE:             return "X86ISD::MFENCE";
18018   case X86ISD::SFENCE:             return "X86ISD::SFENCE";
18019   case X86ISD::LFENCE:             return "X86ISD::LFENCE";
18020   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
18021   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
18022   case X86ISD::SAHF:               return "X86ISD::SAHF";
18023   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
18024   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
18025   case X86ISD::FMADD:              return "X86ISD::FMADD";
18026   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
18027   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
18028   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
18029   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
18030   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
18031   case X86ISD::FMADD_RND:          return "X86ISD::FMADD_RND";
18032   case X86ISD::FNMADD_RND:         return "X86ISD::FNMADD_RND";
18033   case X86ISD::FMSUB_RND:          return "X86ISD::FMSUB_RND";
18034   case X86ISD::FNMSUB_RND:         return "X86ISD::FNMSUB_RND";
18035   case X86ISD::FMADDSUB_RND:       return "X86ISD::FMADDSUB_RND";
18036   case X86ISD::FMSUBADD_RND:       return "X86ISD::FMSUBADD_RND";
18037   case X86ISD::RNDSCALE:           return "X86ISD::RNDSCALE";
18038   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
18039   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
18040   case X86ISD::XTEST:              return "X86ISD::XTEST";
18041   case X86ISD::COMPRESS:           return "X86ISD::COMPRESS";
18042   case X86ISD::EXPAND:             return "X86ISD::EXPAND";
18043   case X86ISD::SELECT:             return "X86ISD::SELECT";
18044   case X86ISD::ADDSUB:             return "X86ISD::ADDSUB";
18045   case X86ISD::RCP28:              return "X86ISD::RCP28";
18046   case X86ISD::EXP2:               return "X86ISD::EXP2";
18047   case X86ISD::RSQRT28:            return "X86ISD::RSQRT28";
18048   case X86ISD::FADD_RND:           return "X86ISD::FADD_RND";
18049   case X86ISD::FSUB_RND:           return "X86ISD::FSUB_RND";
18050   case X86ISD::FMUL_RND:           return "X86ISD::FMUL_RND";
18051   case X86ISD::FDIV_RND:           return "X86ISD::FDIV_RND";
18052   case X86ISD::ADDS:               return "X86ISD::ADDS";
18053   case X86ISD::SUBS:               return "X86ISD::SUBS";
18054   }
18055   return nullptr;
18056 }
18057
18058 // isLegalAddressingMode - Return true if the addressing mode represented
18059 // by AM is legal for this target, for a load/store of the specified type.
18060 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
18061                                               Type *Ty) const {
18062   // X86 supports extremely general addressing modes.
18063   CodeModel::Model M = getTargetMachine().getCodeModel();
18064   Reloc::Model R = getTargetMachine().getRelocationModel();
18065
18066   // X86 allows a sign-extended 32-bit immediate field as a displacement.
18067   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
18068     return false;
18069
18070   if (AM.BaseGV) {
18071     unsigned GVFlags =
18072       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
18073
18074     // If a reference to this global requires an extra load, we can't fold it.
18075     if (isGlobalStubReference(GVFlags))
18076       return false;
18077
18078     // If BaseGV requires a register for the PIC base, we cannot also have a
18079     // BaseReg specified.
18080     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
18081       return false;
18082
18083     // If lower 4G is not available, then we must use rip-relative addressing.
18084     if ((M != CodeModel::Small || R != Reloc::Static) &&
18085         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
18086       return false;
18087   }
18088
18089   switch (AM.Scale) {
18090   case 0:
18091   case 1:
18092   case 2:
18093   case 4:
18094   case 8:
18095     // These scales always work.
18096     break;
18097   case 3:
18098   case 5:
18099   case 9:
18100     // These scales are formed with basereg+scalereg.  Only accept if there is
18101     // no basereg yet.
18102     if (AM.HasBaseReg)
18103       return false;
18104     break;
18105   default:  // Other stuff never works.
18106     return false;
18107   }
18108
18109   return true;
18110 }
18111
18112 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
18113   unsigned Bits = Ty->getScalarSizeInBits();
18114
18115   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
18116   // particularly cheaper than those without.
18117   if (Bits == 8)
18118     return false;
18119
18120   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
18121   // variable shifts just as cheap as scalar ones.
18122   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
18123     return false;
18124
18125   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
18126   // fully general vector.
18127   return true;
18128 }
18129
18130 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
18131   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
18132     return false;
18133   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
18134   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
18135   return NumBits1 > NumBits2;
18136 }
18137
18138 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
18139   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
18140     return false;
18141
18142   if (!isTypeLegal(EVT::getEVT(Ty1)))
18143     return false;
18144
18145   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
18146
18147   // Assuming the caller doesn't have a zeroext or signext return parameter,
18148   // truncation all the way down to i1 is valid.
18149   return true;
18150 }
18151
18152 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
18153   return isInt<32>(Imm);
18154 }
18155
18156 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
18157   // Can also use sub to handle negated immediates.
18158   return isInt<32>(Imm);
18159 }
18160
18161 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
18162   if (!VT1.isInteger() || !VT2.isInteger())
18163     return false;
18164   unsigned NumBits1 = VT1.getSizeInBits();
18165   unsigned NumBits2 = VT2.getSizeInBits();
18166   return NumBits1 > NumBits2;
18167 }
18168
18169 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
18170   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
18171   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
18172 }
18173
18174 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
18175   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
18176   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
18177 }
18178
18179 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
18180   EVT VT1 = Val.getValueType();
18181   if (isZExtFree(VT1, VT2))
18182     return true;
18183
18184   if (Val.getOpcode() != ISD::LOAD)
18185     return false;
18186
18187   if (!VT1.isSimple() || !VT1.isInteger() ||
18188       !VT2.isSimple() || !VT2.isInteger())
18189     return false;
18190
18191   switch (VT1.getSimpleVT().SimpleTy) {
18192   default: break;
18193   case MVT::i8:
18194   case MVT::i16:
18195   case MVT::i32:
18196     // X86 has 8, 16, and 32-bit zero-extending loads.
18197     return true;
18198   }
18199
18200   return false;
18201 }
18202
18203 bool X86TargetLowering::isVectorLoadExtDesirable(SDValue) const { return true; }
18204
18205 bool
18206 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
18207   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
18208     return false;
18209
18210   VT = VT.getScalarType();
18211
18212   if (!VT.isSimple())
18213     return false;
18214
18215   switch (VT.getSimpleVT().SimpleTy) {
18216   case MVT::f32:
18217   case MVT::f64:
18218     return true;
18219   default:
18220     break;
18221   }
18222
18223   return false;
18224 }
18225
18226 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
18227   // i16 instructions are longer (0x66 prefix) and potentially slower.
18228   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
18229 }
18230
18231 /// isShuffleMaskLegal - Targets can use this to indicate that they only
18232 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
18233 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
18234 /// are assumed to be legal.
18235 bool
18236 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
18237                                       EVT VT) const {
18238   if (!VT.isSimple())
18239     return false;
18240
18241   // Not for i1 vectors
18242   if (VT.getScalarType() == MVT::i1)
18243     return false;
18244
18245   // Very little shuffling can be done for 64-bit vectors right now.
18246   if (VT.getSizeInBits() == 64)
18247     return false;
18248
18249   // We only care that the types being shuffled are legal. The lowering can
18250   // handle any possible shuffle mask that results.
18251   return isTypeLegal(VT.getSimpleVT());
18252 }
18253
18254 bool
18255 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
18256                                           EVT VT) const {
18257   // Just delegate to the generic legality, clear masks aren't special.
18258   return isShuffleMaskLegal(Mask, VT);
18259 }
18260
18261 //===----------------------------------------------------------------------===//
18262 //                           X86 Scheduler Hooks
18263 //===----------------------------------------------------------------------===//
18264
18265 /// Utility function to emit xbegin specifying the start of an RTM region.
18266 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
18267                                      const TargetInstrInfo *TII) {
18268   DebugLoc DL = MI->getDebugLoc();
18269
18270   const BasicBlock *BB = MBB->getBasicBlock();
18271   MachineFunction::iterator I = MBB;
18272   ++I;
18273
18274   // For the v = xbegin(), we generate
18275   //
18276   // thisMBB:
18277   //  xbegin sinkMBB
18278   //
18279   // mainMBB:
18280   //  eax = -1
18281   //
18282   // sinkMBB:
18283   //  v = eax
18284
18285   MachineBasicBlock *thisMBB = MBB;
18286   MachineFunction *MF = MBB->getParent();
18287   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
18288   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
18289   MF->insert(I, mainMBB);
18290   MF->insert(I, sinkMBB);
18291
18292   // Transfer the remainder of BB and its successor edges to sinkMBB.
18293   sinkMBB->splice(sinkMBB->begin(), MBB,
18294                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
18295   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
18296
18297   // thisMBB:
18298   //  xbegin sinkMBB
18299   //  # fallthrough to mainMBB
18300   //  # abortion to sinkMBB
18301   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
18302   thisMBB->addSuccessor(mainMBB);
18303   thisMBB->addSuccessor(sinkMBB);
18304
18305   // mainMBB:
18306   //  EAX = -1
18307   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
18308   mainMBB->addSuccessor(sinkMBB);
18309
18310   // sinkMBB:
18311   // EAX is live into the sinkMBB
18312   sinkMBB->addLiveIn(X86::EAX);
18313   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
18314           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
18315     .addReg(X86::EAX);
18316
18317   MI->eraseFromParent();
18318   return sinkMBB;
18319 }
18320
18321 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
18322 // or XMM0_V32I8 in AVX all of this code can be replaced with that
18323 // in the .td file.
18324 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
18325                                        const TargetInstrInfo *TII) {
18326   unsigned Opc;
18327   switch (MI->getOpcode()) {
18328   default: llvm_unreachable("illegal opcode!");
18329   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
18330   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
18331   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
18332   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
18333   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
18334   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
18335   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
18336   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
18337   }
18338
18339   DebugLoc dl = MI->getDebugLoc();
18340   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
18341
18342   unsigned NumArgs = MI->getNumOperands();
18343   for (unsigned i = 1; i < NumArgs; ++i) {
18344     MachineOperand &Op = MI->getOperand(i);
18345     if (!(Op.isReg() && Op.isImplicit()))
18346       MIB.addOperand(Op);
18347   }
18348   if (MI->hasOneMemOperand())
18349     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
18350
18351   BuildMI(*BB, MI, dl,
18352     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
18353     .addReg(X86::XMM0);
18354
18355   MI->eraseFromParent();
18356   return BB;
18357 }
18358
18359 // FIXME: Custom handling because TableGen doesn't support multiple implicit
18360 // defs in an instruction pattern
18361 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
18362                                        const TargetInstrInfo *TII) {
18363   unsigned Opc;
18364   switch (MI->getOpcode()) {
18365   default: llvm_unreachable("illegal opcode!");
18366   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
18367   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
18368   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
18369   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
18370   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
18371   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
18372   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
18373   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
18374   }
18375
18376   DebugLoc dl = MI->getDebugLoc();
18377   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
18378
18379   unsigned NumArgs = MI->getNumOperands(); // remove the results
18380   for (unsigned i = 1; i < NumArgs; ++i) {
18381     MachineOperand &Op = MI->getOperand(i);
18382     if (!(Op.isReg() && Op.isImplicit()))
18383       MIB.addOperand(Op);
18384   }
18385   if (MI->hasOneMemOperand())
18386     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
18387
18388   BuildMI(*BB, MI, dl,
18389     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
18390     .addReg(X86::ECX);
18391
18392   MI->eraseFromParent();
18393   return BB;
18394 }
18395
18396 static MachineBasicBlock *EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
18397                                       const X86Subtarget *Subtarget) {
18398   DebugLoc dl = MI->getDebugLoc();
18399   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18400   // Address into RAX/EAX, other two args into ECX, EDX.
18401   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
18402   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
18403   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
18404   for (int i = 0; i < X86::AddrNumOperands; ++i)
18405     MIB.addOperand(MI->getOperand(i));
18406
18407   unsigned ValOps = X86::AddrNumOperands;
18408   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
18409     .addReg(MI->getOperand(ValOps).getReg());
18410   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
18411     .addReg(MI->getOperand(ValOps+1).getReg());
18412
18413   // The instruction doesn't actually take any operands though.
18414   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
18415
18416   MI->eraseFromParent(); // The pseudo is gone now.
18417   return BB;
18418 }
18419
18420 MachineBasicBlock *
18421 X86TargetLowering::EmitVAARG64WithCustomInserter(MachineInstr *MI,
18422                                                  MachineBasicBlock *MBB) const {
18423   // Emit va_arg instruction on X86-64.
18424
18425   // Operands to this pseudo-instruction:
18426   // 0  ) Output        : destination address (reg)
18427   // 1-5) Input         : va_list address (addr, i64mem)
18428   // 6  ) ArgSize       : Size (in bytes) of vararg type
18429   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
18430   // 8  ) Align         : Alignment of type
18431   // 9  ) EFLAGS (implicit-def)
18432
18433   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
18434   static_assert(X86::AddrNumOperands == 5,
18435                 "VAARG_64 assumes 5 address operands");
18436
18437   unsigned DestReg = MI->getOperand(0).getReg();
18438   MachineOperand &Base = MI->getOperand(1);
18439   MachineOperand &Scale = MI->getOperand(2);
18440   MachineOperand &Index = MI->getOperand(3);
18441   MachineOperand &Disp = MI->getOperand(4);
18442   MachineOperand &Segment = MI->getOperand(5);
18443   unsigned ArgSize = MI->getOperand(6).getImm();
18444   unsigned ArgMode = MI->getOperand(7).getImm();
18445   unsigned Align = MI->getOperand(8).getImm();
18446
18447   // Memory Reference
18448   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
18449   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
18450   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
18451
18452   // Machine Information
18453   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18454   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
18455   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
18456   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
18457   DebugLoc DL = MI->getDebugLoc();
18458
18459   // struct va_list {
18460   //   i32   gp_offset
18461   //   i32   fp_offset
18462   //   i64   overflow_area (address)
18463   //   i64   reg_save_area (address)
18464   // }
18465   // sizeof(va_list) = 24
18466   // alignment(va_list) = 8
18467
18468   unsigned TotalNumIntRegs = 6;
18469   unsigned TotalNumXMMRegs = 8;
18470   bool UseGPOffset = (ArgMode == 1);
18471   bool UseFPOffset = (ArgMode == 2);
18472   unsigned MaxOffset = TotalNumIntRegs * 8 +
18473                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
18474
18475   /* Align ArgSize to a multiple of 8 */
18476   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
18477   bool NeedsAlign = (Align > 8);
18478
18479   MachineBasicBlock *thisMBB = MBB;
18480   MachineBasicBlock *overflowMBB;
18481   MachineBasicBlock *offsetMBB;
18482   MachineBasicBlock *endMBB;
18483
18484   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
18485   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
18486   unsigned OffsetReg = 0;
18487
18488   if (!UseGPOffset && !UseFPOffset) {
18489     // If we only pull from the overflow region, we don't create a branch.
18490     // We don't need to alter control flow.
18491     OffsetDestReg = 0; // unused
18492     OverflowDestReg = DestReg;
18493
18494     offsetMBB = nullptr;
18495     overflowMBB = thisMBB;
18496     endMBB = thisMBB;
18497   } else {
18498     // First emit code to check if gp_offset (or fp_offset) is below the bound.
18499     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
18500     // If not, pull from overflow_area. (branch to overflowMBB)
18501     //
18502     //       thisMBB
18503     //         |     .
18504     //         |        .
18505     //     offsetMBB   overflowMBB
18506     //         |        .
18507     //         |     .
18508     //        endMBB
18509
18510     // Registers for the PHI in endMBB
18511     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
18512     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
18513
18514     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
18515     MachineFunction *MF = MBB->getParent();
18516     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18517     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18518     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18519
18520     MachineFunction::iterator MBBIter = MBB;
18521     ++MBBIter;
18522
18523     // Insert the new basic blocks
18524     MF->insert(MBBIter, offsetMBB);
18525     MF->insert(MBBIter, overflowMBB);
18526     MF->insert(MBBIter, endMBB);
18527
18528     // Transfer the remainder of MBB and its successor edges to endMBB.
18529     endMBB->splice(endMBB->begin(), thisMBB,
18530                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
18531     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
18532
18533     // Make offsetMBB and overflowMBB successors of thisMBB
18534     thisMBB->addSuccessor(offsetMBB);
18535     thisMBB->addSuccessor(overflowMBB);
18536
18537     // endMBB is a successor of both offsetMBB and overflowMBB
18538     offsetMBB->addSuccessor(endMBB);
18539     overflowMBB->addSuccessor(endMBB);
18540
18541     // Load the offset value into a register
18542     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
18543     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
18544       .addOperand(Base)
18545       .addOperand(Scale)
18546       .addOperand(Index)
18547       .addDisp(Disp, UseFPOffset ? 4 : 0)
18548       .addOperand(Segment)
18549       .setMemRefs(MMOBegin, MMOEnd);
18550
18551     // Check if there is enough room left to pull this argument.
18552     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
18553       .addReg(OffsetReg)
18554       .addImm(MaxOffset + 8 - ArgSizeA8);
18555
18556     // Branch to "overflowMBB" if offset >= max
18557     // Fall through to "offsetMBB" otherwise
18558     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
18559       .addMBB(overflowMBB);
18560   }
18561
18562   // In offsetMBB, emit code to use the reg_save_area.
18563   if (offsetMBB) {
18564     assert(OffsetReg != 0);
18565
18566     // Read the reg_save_area address.
18567     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
18568     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
18569       .addOperand(Base)
18570       .addOperand(Scale)
18571       .addOperand(Index)
18572       .addDisp(Disp, 16)
18573       .addOperand(Segment)
18574       .setMemRefs(MMOBegin, MMOEnd);
18575
18576     // Zero-extend the offset
18577     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
18578       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
18579         .addImm(0)
18580         .addReg(OffsetReg)
18581         .addImm(X86::sub_32bit);
18582
18583     // Add the offset to the reg_save_area to get the final address.
18584     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
18585       .addReg(OffsetReg64)
18586       .addReg(RegSaveReg);
18587
18588     // Compute the offset for the next argument
18589     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
18590     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
18591       .addReg(OffsetReg)
18592       .addImm(UseFPOffset ? 16 : 8);
18593
18594     // Store it back into the va_list.
18595     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
18596       .addOperand(Base)
18597       .addOperand(Scale)
18598       .addOperand(Index)
18599       .addDisp(Disp, UseFPOffset ? 4 : 0)
18600       .addOperand(Segment)
18601       .addReg(NextOffsetReg)
18602       .setMemRefs(MMOBegin, MMOEnd);
18603
18604     // Jump to endMBB
18605     BuildMI(offsetMBB, DL, TII->get(X86::JMP_1))
18606       .addMBB(endMBB);
18607   }
18608
18609   //
18610   // Emit code to use overflow area
18611   //
18612
18613   // Load the overflow_area address into a register.
18614   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
18615   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
18616     .addOperand(Base)
18617     .addOperand(Scale)
18618     .addOperand(Index)
18619     .addDisp(Disp, 8)
18620     .addOperand(Segment)
18621     .setMemRefs(MMOBegin, MMOEnd);
18622
18623   // If we need to align it, do so. Otherwise, just copy the address
18624   // to OverflowDestReg.
18625   if (NeedsAlign) {
18626     // Align the overflow address
18627     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
18628     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
18629
18630     // aligned_addr = (addr + (align-1)) & ~(align-1)
18631     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
18632       .addReg(OverflowAddrReg)
18633       .addImm(Align-1);
18634
18635     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
18636       .addReg(TmpReg)
18637       .addImm(~(uint64_t)(Align-1));
18638   } else {
18639     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
18640       .addReg(OverflowAddrReg);
18641   }
18642
18643   // Compute the next overflow address after this argument.
18644   // (the overflow address should be kept 8-byte aligned)
18645   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
18646   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
18647     .addReg(OverflowDestReg)
18648     .addImm(ArgSizeA8);
18649
18650   // Store the new overflow address.
18651   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
18652     .addOperand(Base)
18653     .addOperand(Scale)
18654     .addOperand(Index)
18655     .addDisp(Disp, 8)
18656     .addOperand(Segment)
18657     .addReg(NextAddrReg)
18658     .setMemRefs(MMOBegin, MMOEnd);
18659
18660   // If we branched, emit the PHI to the front of endMBB.
18661   if (offsetMBB) {
18662     BuildMI(*endMBB, endMBB->begin(), DL,
18663             TII->get(X86::PHI), DestReg)
18664       .addReg(OffsetDestReg).addMBB(offsetMBB)
18665       .addReg(OverflowDestReg).addMBB(overflowMBB);
18666   }
18667
18668   // Erase the pseudo instruction
18669   MI->eraseFromParent();
18670
18671   return endMBB;
18672 }
18673
18674 MachineBasicBlock *
18675 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
18676                                                  MachineInstr *MI,
18677                                                  MachineBasicBlock *MBB) const {
18678   // Emit code to save XMM registers to the stack. The ABI says that the
18679   // number of registers to save is given in %al, so it's theoretically
18680   // possible to do an indirect jump trick to avoid saving all of them,
18681   // however this code takes a simpler approach and just executes all
18682   // of the stores if %al is non-zero. It's less code, and it's probably
18683   // easier on the hardware branch predictor, and stores aren't all that
18684   // expensive anyway.
18685
18686   // Create the new basic blocks. One block contains all the XMM stores,
18687   // and one block is the final destination regardless of whether any
18688   // stores were performed.
18689   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
18690   MachineFunction *F = MBB->getParent();
18691   MachineFunction::iterator MBBIter = MBB;
18692   ++MBBIter;
18693   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
18694   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
18695   F->insert(MBBIter, XMMSaveMBB);
18696   F->insert(MBBIter, EndMBB);
18697
18698   // Transfer the remainder of MBB and its successor edges to EndMBB.
18699   EndMBB->splice(EndMBB->begin(), MBB,
18700                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
18701   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
18702
18703   // The original block will now fall through to the XMM save block.
18704   MBB->addSuccessor(XMMSaveMBB);
18705   // The XMMSaveMBB will fall through to the end block.
18706   XMMSaveMBB->addSuccessor(EndMBB);
18707
18708   // Now add the instructions.
18709   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18710   DebugLoc DL = MI->getDebugLoc();
18711
18712   unsigned CountReg = MI->getOperand(0).getReg();
18713   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
18714   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
18715
18716   if (!Subtarget->isTargetWin64()) {
18717     // If %al is 0, branch around the XMM save block.
18718     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
18719     BuildMI(MBB, DL, TII->get(X86::JE_1)).addMBB(EndMBB);
18720     MBB->addSuccessor(EndMBB);
18721   }
18722
18723   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
18724   // that was just emitted, but clearly shouldn't be "saved".
18725   assert((MI->getNumOperands() <= 3 ||
18726           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
18727           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
18728          && "Expected last argument to be EFLAGS");
18729   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
18730   // In the XMM save block, save all the XMM argument registers.
18731   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
18732     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
18733     MachineMemOperand *MMO =
18734       F->getMachineMemOperand(
18735           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
18736         MachineMemOperand::MOStore,
18737         /*Size=*/16, /*Align=*/16);
18738     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
18739       .addFrameIndex(RegSaveFrameIndex)
18740       .addImm(/*Scale=*/1)
18741       .addReg(/*IndexReg=*/0)
18742       .addImm(/*Disp=*/Offset)
18743       .addReg(/*Segment=*/0)
18744       .addReg(MI->getOperand(i).getReg())
18745       .addMemOperand(MMO);
18746   }
18747
18748   MI->eraseFromParent();   // The pseudo instruction is gone now.
18749
18750   return EndMBB;
18751 }
18752
18753 // The EFLAGS operand of SelectItr might be missing a kill marker
18754 // because there were multiple uses of EFLAGS, and ISel didn't know
18755 // which to mark. Figure out whether SelectItr should have had a
18756 // kill marker, and set it if it should. Returns the correct kill
18757 // marker value.
18758 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
18759                                      MachineBasicBlock* BB,
18760                                      const TargetRegisterInfo* TRI) {
18761   // Scan forward through BB for a use/def of EFLAGS.
18762   MachineBasicBlock::iterator miI(std::next(SelectItr));
18763   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
18764     const MachineInstr& mi = *miI;
18765     if (mi.readsRegister(X86::EFLAGS))
18766       return false;
18767     if (mi.definesRegister(X86::EFLAGS))
18768       break; // Should have kill-flag - update below.
18769   }
18770
18771   // If we hit the end of the block, check whether EFLAGS is live into a
18772   // successor.
18773   if (miI == BB->end()) {
18774     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
18775                                           sEnd = BB->succ_end();
18776          sItr != sEnd; ++sItr) {
18777       MachineBasicBlock* succ = *sItr;
18778       if (succ->isLiveIn(X86::EFLAGS))
18779         return false;
18780     }
18781   }
18782
18783   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
18784   // out. SelectMI should have a kill flag on EFLAGS.
18785   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
18786   return true;
18787 }
18788
18789 MachineBasicBlock *
18790 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
18791                                      MachineBasicBlock *BB) const {
18792   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18793   DebugLoc DL = MI->getDebugLoc();
18794
18795   // To "insert" a SELECT_CC instruction, we actually have to insert the
18796   // diamond control-flow pattern.  The incoming instruction knows the
18797   // destination vreg to set, the condition code register to branch on, the
18798   // true/false values to select between, and a branch opcode to use.
18799   const BasicBlock *LLVM_BB = BB->getBasicBlock();
18800   MachineFunction::iterator It = BB;
18801   ++It;
18802
18803   //  thisMBB:
18804   //  ...
18805   //   TrueVal = ...
18806   //   cmpTY ccX, r1, r2
18807   //   bCC copy1MBB
18808   //   fallthrough --> copy0MBB
18809   MachineBasicBlock *thisMBB = BB;
18810   MachineFunction *F = BB->getParent();
18811
18812   // We also lower double CMOVs:
18813   //   (CMOV (CMOV F, T, cc1), T, cc2)
18814   // to two successives branches.  For that, we look for another CMOV as the
18815   // following instruction.
18816   //
18817   // Without this, we would add a PHI between the two jumps, which ends up
18818   // creating a few copies all around. For instance, for
18819   //
18820   //    (sitofp (zext (fcmp une)))
18821   //
18822   // we would generate:
18823   //
18824   //         ucomiss %xmm1, %xmm0
18825   //         movss  <1.0f>, %xmm0
18826   //         movaps  %xmm0, %xmm1
18827   //         jne     .LBB5_2
18828   //         xorps   %xmm1, %xmm1
18829   // .LBB5_2:
18830   //         jp      .LBB5_4
18831   //         movaps  %xmm1, %xmm0
18832   // .LBB5_4:
18833   //         retq
18834   //
18835   // because this custom-inserter would have generated:
18836   //
18837   //   A
18838   //   | \
18839   //   |  B
18840   //   | /
18841   //   C
18842   //   | \
18843   //   |  D
18844   //   | /
18845   //   E
18846   //
18847   // A: X = ...; Y = ...
18848   // B: empty
18849   // C: Z = PHI [X, A], [Y, B]
18850   // D: empty
18851   // E: PHI [X, C], [Z, D]
18852   //
18853   // If we lower both CMOVs in a single step, we can instead generate:
18854   //
18855   //   A
18856   //   | \
18857   //   |  C
18858   //   | /|
18859   //   |/ |
18860   //   |  |
18861   //   |  D
18862   //   | /
18863   //   E
18864   //
18865   // A: X = ...; Y = ...
18866   // D: empty
18867   // E: PHI [X, A], [X, C], [Y, D]
18868   //
18869   // Which, in our sitofp/fcmp example, gives us something like:
18870   //
18871   //         ucomiss %xmm1, %xmm0
18872   //         movss  <1.0f>, %xmm0
18873   //         jne     .LBB5_4
18874   //         jp      .LBB5_4
18875   //         xorps   %xmm0, %xmm0
18876   // .LBB5_4:
18877   //         retq
18878   //
18879   MachineInstr *NextCMOV = nullptr;
18880   MachineBasicBlock::iterator NextMIIt =
18881       std::next(MachineBasicBlock::iterator(MI));
18882   if (NextMIIt != BB->end() && NextMIIt->getOpcode() == MI->getOpcode() &&
18883       NextMIIt->getOperand(2).getReg() == MI->getOperand(2).getReg() &&
18884       NextMIIt->getOperand(1).getReg() == MI->getOperand(0).getReg())
18885     NextCMOV = &*NextMIIt;
18886
18887   MachineBasicBlock *jcc1MBB = nullptr;
18888
18889   // If we have a double CMOV, we lower it to two successive branches to
18890   // the same block.  EFLAGS is used by both, so mark it as live in the second.
18891   if (NextCMOV) {
18892     jcc1MBB = F->CreateMachineBasicBlock(LLVM_BB);
18893     F->insert(It, jcc1MBB);
18894     jcc1MBB->addLiveIn(X86::EFLAGS);
18895   }
18896
18897   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
18898   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
18899   F->insert(It, copy0MBB);
18900   F->insert(It, sinkMBB);
18901
18902   // If the EFLAGS register isn't dead in the terminator, then claim that it's
18903   // live into the sink and copy blocks.
18904   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
18905
18906   MachineInstr *LastEFLAGSUser = NextCMOV ? NextCMOV : MI;
18907   if (!LastEFLAGSUser->killsRegister(X86::EFLAGS) &&
18908       !checkAndUpdateEFLAGSKill(LastEFLAGSUser, BB, TRI)) {
18909     copy0MBB->addLiveIn(X86::EFLAGS);
18910     sinkMBB->addLiveIn(X86::EFLAGS);
18911   }
18912
18913   // Transfer the remainder of BB and its successor edges to sinkMBB.
18914   sinkMBB->splice(sinkMBB->begin(), BB,
18915                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
18916   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
18917
18918   // Add the true and fallthrough blocks as its successors.
18919   if (NextCMOV) {
18920     // The fallthrough block may be jcc1MBB, if we have a double CMOV.
18921     BB->addSuccessor(jcc1MBB);
18922
18923     // In that case, jcc1MBB will itself fallthrough the copy0MBB, and
18924     // jump to the sinkMBB.
18925     jcc1MBB->addSuccessor(copy0MBB);
18926     jcc1MBB->addSuccessor(sinkMBB);
18927   } else {
18928     BB->addSuccessor(copy0MBB);
18929   }
18930
18931   // The true block target of the first (or only) branch is always sinkMBB.
18932   BB->addSuccessor(sinkMBB);
18933
18934   // Create the conditional branch instruction.
18935   unsigned Opc =
18936     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
18937   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
18938
18939   if (NextCMOV) {
18940     unsigned Opc2 = X86::GetCondBranchFromCond(
18941         (X86::CondCode)NextCMOV->getOperand(3).getImm());
18942     BuildMI(jcc1MBB, DL, TII->get(Opc2)).addMBB(sinkMBB);
18943   }
18944
18945   //  copy0MBB:
18946   //   %FalseValue = ...
18947   //   # fallthrough to sinkMBB
18948   copy0MBB->addSuccessor(sinkMBB);
18949
18950   //  sinkMBB:
18951   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
18952   //  ...
18953   MachineInstrBuilder MIB =
18954       BuildMI(*sinkMBB, sinkMBB->begin(), DL, TII->get(X86::PHI),
18955               MI->getOperand(0).getReg())
18956           .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
18957           .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
18958
18959   // If we have a double CMOV, the second Jcc provides the same incoming
18960   // value as the first Jcc (the True operand of the SELECT_CC/CMOV nodes).
18961   if (NextCMOV) {
18962     MIB.addReg(MI->getOperand(2).getReg()).addMBB(jcc1MBB);
18963     // Copy the PHI result to the register defined by the second CMOV.
18964     BuildMI(*sinkMBB, std::next(MachineBasicBlock::iterator(MIB.getInstr())),
18965             DL, TII->get(TargetOpcode::COPY), NextCMOV->getOperand(0).getReg())
18966         .addReg(MI->getOperand(0).getReg());
18967     NextCMOV->eraseFromParent();
18968   }
18969
18970   MI->eraseFromParent();   // The pseudo instruction is gone now.
18971   return sinkMBB;
18972 }
18973
18974 MachineBasicBlock *
18975 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI,
18976                                         MachineBasicBlock *BB) const {
18977   MachineFunction *MF = BB->getParent();
18978   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18979   DebugLoc DL = MI->getDebugLoc();
18980   const BasicBlock *LLVM_BB = BB->getBasicBlock();
18981
18982   assert(MF->shouldSplitStack());
18983
18984   const bool Is64Bit = Subtarget->is64Bit();
18985   const bool IsLP64 = Subtarget->isTarget64BitLP64();
18986
18987   const unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
18988   const unsigned TlsOffset = IsLP64 ? 0x70 : Is64Bit ? 0x40 : 0x30;
18989
18990   // BB:
18991   //  ... [Till the alloca]
18992   // If stacklet is not large enough, jump to mallocMBB
18993   //
18994   // bumpMBB:
18995   //  Allocate by subtracting from RSP
18996   //  Jump to continueMBB
18997   //
18998   // mallocMBB:
18999   //  Allocate by call to runtime
19000   //
19001   // continueMBB:
19002   //  ...
19003   //  [rest of original BB]
19004   //
19005
19006   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19007   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19008   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19009
19010   MachineRegisterInfo &MRI = MF->getRegInfo();
19011   const TargetRegisterClass *AddrRegClass =
19012     getRegClassFor(getPointerTy());
19013
19014   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
19015     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
19016     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
19017     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
19018     sizeVReg = MI->getOperand(1).getReg(),
19019     physSPReg = IsLP64 || Subtarget->isTargetNaCl64() ? X86::RSP : X86::ESP;
19020
19021   MachineFunction::iterator MBBIter = BB;
19022   ++MBBIter;
19023
19024   MF->insert(MBBIter, bumpMBB);
19025   MF->insert(MBBIter, mallocMBB);
19026   MF->insert(MBBIter, continueMBB);
19027
19028   continueMBB->splice(continueMBB->begin(), BB,
19029                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
19030   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
19031
19032   // Add code to the main basic block to check if the stack limit has been hit,
19033   // and if so, jump to mallocMBB otherwise to bumpMBB.
19034   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
19035   BuildMI(BB, DL, TII->get(IsLP64 ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
19036     .addReg(tmpSPVReg).addReg(sizeVReg);
19037   BuildMI(BB, DL, TII->get(IsLP64 ? X86::CMP64mr:X86::CMP32mr))
19038     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
19039     .addReg(SPLimitVReg);
19040   BuildMI(BB, DL, TII->get(X86::JG_1)).addMBB(mallocMBB);
19041
19042   // bumpMBB simply decreases the stack pointer, since we know the current
19043   // stacklet has enough space.
19044   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
19045     .addReg(SPLimitVReg);
19046   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
19047     .addReg(SPLimitVReg);
19048   BuildMI(bumpMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
19049
19050   // Calls into a routine in libgcc to allocate more space from the heap.
19051   const uint32_t *RegMask =
19052       Subtarget->getRegisterInfo()->getCallPreservedMask(*MF, CallingConv::C);
19053   if (IsLP64) {
19054     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
19055       .addReg(sizeVReg);
19056     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
19057       .addExternalSymbol("__morestack_allocate_stack_space")
19058       .addRegMask(RegMask)
19059       .addReg(X86::RDI, RegState::Implicit)
19060       .addReg(X86::RAX, RegState::ImplicitDefine);
19061   } else if (Is64Bit) {
19062     BuildMI(mallocMBB, DL, TII->get(X86::MOV32rr), X86::EDI)
19063       .addReg(sizeVReg);
19064     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
19065       .addExternalSymbol("__morestack_allocate_stack_space")
19066       .addRegMask(RegMask)
19067       .addReg(X86::EDI, RegState::Implicit)
19068       .addReg(X86::EAX, RegState::ImplicitDefine);
19069   } else {
19070     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
19071       .addImm(12);
19072     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
19073     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
19074       .addExternalSymbol("__morestack_allocate_stack_space")
19075       .addRegMask(RegMask)
19076       .addReg(X86::EAX, RegState::ImplicitDefine);
19077   }
19078
19079   if (!Is64Bit)
19080     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
19081       .addImm(16);
19082
19083   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
19084     .addReg(IsLP64 ? X86::RAX : X86::EAX);
19085   BuildMI(mallocMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
19086
19087   // Set up the CFG correctly.
19088   BB->addSuccessor(bumpMBB);
19089   BB->addSuccessor(mallocMBB);
19090   mallocMBB->addSuccessor(continueMBB);
19091   bumpMBB->addSuccessor(continueMBB);
19092
19093   // Take care of the PHI nodes.
19094   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
19095           MI->getOperand(0).getReg())
19096     .addReg(mallocPtrVReg).addMBB(mallocMBB)
19097     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
19098
19099   // Delete the original pseudo instruction.
19100   MI->eraseFromParent();
19101
19102   // And we're done.
19103   return continueMBB;
19104 }
19105
19106 MachineBasicBlock *
19107 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
19108                                         MachineBasicBlock *BB) const {
19109   DebugLoc DL = MI->getDebugLoc();
19110
19111   assert(!Subtarget->isTargetMachO());
19112
19113   X86FrameLowering::emitStackProbeCall(*BB->getParent(), *BB, MI, DL);
19114
19115   MI->eraseFromParent();   // The pseudo instruction is gone now.
19116   return BB;
19117 }
19118
19119 MachineBasicBlock *
19120 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
19121                                       MachineBasicBlock *BB) const {
19122   // This is pretty easy.  We're taking the value that we received from
19123   // our load from the relocation, sticking it in either RDI (x86-64)
19124   // or EAX and doing an indirect call.  The return value will then
19125   // be in the normal return register.
19126   MachineFunction *F = BB->getParent();
19127   const X86InstrInfo *TII = Subtarget->getInstrInfo();
19128   DebugLoc DL = MI->getDebugLoc();
19129
19130   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
19131   assert(MI->getOperand(3).isGlobal() && "This should be a global");
19132
19133   // Get a register mask for the lowered call.
19134   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
19135   // proper register mask.
19136   const uint32_t *RegMask =
19137       Subtarget->getRegisterInfo()->getCallPreservedMask(*F, CallingConv::C);
19138   if (Subtarget->is64Bit()) {
19139     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
19140                                       TII->get(X86::MOV64rm), X86::RDI)
19141     .addReg(X86::RIP)
19142     .addImm(0).addReg(0)
19143     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
19144                       MI->getOperand(3).getTargetFlags())
19145     .addReg(0);
19146     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
19147     addDirectMem(MIB, X86::RDI);
19148     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
19149   } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
19150     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
19151                                       TII->get(X86::MOV32rm), X86::EAX)
19152     .addReg(0)
19153     .addImm(0).addReg(0)
19154     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
19155                       MI->getOperand(3).getTargetFlags())
19156     .addReg(0);
19157     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
19158     addDirectMem(MIB, X86::EAX);
19159     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
19160   } else {
19161     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
19162                                       TII->get(X86::MOV32rm), X86::EAX)
19163     .addReg(TII->getGlobalBaseReg(F))
19164     .addImm(0).addReg(0)
19165     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
19166                       MI->getOperand(3).getTargetFlags())
19167     .addReg(0);
19168     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
19169     addDirectMem(MIB, X86::EAX);
19170     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
19171   }
19172
19173   MI->eraseFromParent(); // The pseudo instruction is gone now.
19174   return BB;
19175 }
19176
19177 MachineBasicBlock *
19178 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
19179                                     MachineBasicBlock *MBB) const {
19180   DebugLoc DL = MI->getDebugLoc();
19181   MachineFunction *MF = MBB->getParent();
19182   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19183   MachineRegisterInfo &MRI = MF->getRegInfo();
19184
19185   const BasicBlock *BB = MBB->getBasicBlock();
19186   MachineFunction::iterator I = MBB;
19187   ++I;
19188
19189   // Memory Reference
19190   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
19191   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
19192
19193   unsigned DstReg;
19194   unsigned MemOpndSlot = 0;
19195
19196   unsigned CurOp = 0;
19197
19198   DstReg = MI->getOperand(CurOp++).getReg();
19199   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
19200   assert(RC->hasType(MVT::i32) && "Invalid destination!");
19201   unsigned mainDstReg = MRI.createVirtualRegister(RC);
19202   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
19203
19204   MemOpndSlot = CurOp;
19205
19206   MVT PVT = getPointerTy();
19207   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
19208          "Invalid Pointer Size!");
19209
19210   // For v = setjmp(buf), we generate
19211   //
19212   // thisMBB:
19213   //  buf[LabelOffset] = restoreMBB
19214   //  SjLjSetup restoreMBB
19215   //
19216   // mainMBB:
19217   //  v_main = 0
19218   //
19219   // sinkMBB:
19220   //  v = phi(main, restore)
19221   //
19222   // restoreMBB:
19223   //  if base pointer being used, load it from frame
19224   //  v_restore = 1
19225
19226   MachineBasicBlock *thisMBB = MBB;
19227   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
19228   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
19229   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
19230   MF->insert(I, mainMBB);
19231   MF->insert(I, sinkMBB);
19232   MF->push_back(restoreMBB);
19233
19234   MachineInstrBuilder MIB;
19235
19236   // Transfer the remainder of BB and its successor edges to sinkMBB.
19237   sinkMBB->splice(sinkMBB->begin(), MBB,
19238                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
19239   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
19240
19241   // thisMBB:
19242   unsigned PtrStoreOpc = 0;
19243   unsigned LabelReg = 0;
19244   const int64_t LabelOffset = 1 * PVT.getStoreSize();
19245   Reloc::Model RM = MF->getTarget().getRelocationModel();
19246   bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
19247                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
19248
19249   // Prepare IP either in reg or imm.
19250   if (!UseImmLabel) {
19251     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
19252     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
19253     LabelReg = MRI.createVirtualRegister(PtrRC);
19254     if (Subtarget->is64Bit()) {
19255       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
19256               .addReg(X86::RIP)
19257               .addImm(0)
19258               .addReg(0)
19259               .addMBB(restoreMBB)
19260               .addReg(0);
19261     } else {
19262       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
19263       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
19264               .addReg(XII->getGlobalBaseReg(MF))
19265               .addImm(0)
19266               .addReg(0)
19267               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
19268               .addReg(0);
19269     }
19270   } else
19271     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
19272   // Store IP
19273   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
19274   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
19275     if (i == X86::AddrDisp)
19276       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
19277     else
19278       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
19279   }
19280   if (!UseImmLabel)
19281     MIB.addReg(LabelReg);
19282   else
19283     MIB.addMBB(restoreMBB);
19284   MIB.setMemRefs(MMOBegin, MMOEnd);
19285   // Setup
19286   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
19287           .addMBB(restoreMBB);
19288
19289   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
19290   MIB.addRegMask(RegInfo->getNoPreservedMask());
19291   thisMBB->addSuccessor(mainMBB);
19292   thisMBB->addSuccessor(restoreMBB);
19293
19294   // mainMBB:
19295   //  EAX = 0
19296   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
19297   mainMBB->addSuccessor(sinkMBB);
19298
19299   // sinkMBB:
19300   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
19301           TII->get(X86::PHI), DstReg)
19302     .addReg(mainDstReg).addMBB(mainMBB)
19303     .addReg(restoreDstReg).addMBB(restoreMBB);
19304
19305   // restoreMBB:
19306   if (RegInfo->hasBasePointer(*MF)) {
19307     const bool Uses64BitFramePtr =
19308         Subtarget->isTarget64BitLP64() || Subtarget->isTargetNaCl64();
19309     X86MachineFunctionInfo *X86FI = MF->getInfo<X86MachineFunctionInfo>();
19310     X86FI->setRestoreBasePointer(MF);
19311     unsigned FramePtr = RegInfo->getFrameRegister(*MF);
19312     unsigned BasePtr = RegInfo->getBaseRegister();
19313     unsigned Opm = Uses64BitFramePtr ? X86::MOV64rm : X86::MOV32rm;
19314     addRegOffset(BuildMI(restoreMBB, DL, TII->get(Opm), BasePtr),
19315                  FramePtr, true, X86FI->getRestoreBasePointerOffset())
19316       .setMIFlag(MachineInstr::FrameSetup);
19317   }
19318   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
19319   BuildMI(restoreMBB, DL, TII->get(X86::JMP_1)).addMBB(sinkMBB);
19320   restoreMBB->addSuccessor(sinkMBB);
19321
19322   MI->eraseFromParent();
19323   return sinkMBB;
19324 }
19325
19326 MachineBasicBlock *
19327 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
19328                                      MachineBasicBlock *MBB) const {
19329   DebugLoc DL = MI->getDebugLoc();
19330   MachineFunction *MF = MBB->getParent();
19331   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19332   MachineRegisterInfo &MRI = MF->getRegInfo();
19333
19334   // Memory Reference
19335   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
19336   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
19337
19338   MVT PVT = getPointerTy();
19339   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
19340          "Invalid Pointer Size!");
19341
19342   const TargetRegisterClass *RC =
19343     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
19344   unsigned Tmp = MRI.createVirtualRegister(RC);
19345   // Since FP is only updated here but NOT referenced, it's treated as GPR.
19346   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
19347   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
19348   unsigned SP = RegInfo->getStackRegister();
19349
19350   MachineInstrBuilder MIB;
19351
19352   const int64_t LabelOffset = 1 * PVT.getStoreSize();
19353   const int64_t SPOffset = 2 * PVT.getStoreSize();
19354
19355   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
19356   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
19357
19358   // Reload FP
19359   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
19360   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
19361     MIB.addOperand(MI->getOperand(i));
19362   MIB.setMemRefs(MMOBegin, MMOEnd);
19363   // Reload IP
19364   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
19365   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
19366     if (i == X86::AddrDisp)
19367       MIB.addDisp(MI->getOperand(i), LabelOffset);
19368     else
19369       MIB.addOperand(MI->getOperand(i));
19370   }
19371   MIB.setMemRefs(MMOBegin, MMOEnd);
19372   // Reload SP
19373   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
19374   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
19375     if (i == X86::AddrDisp)
19376       MIB.addDisp(MI->getOperand(i), SPOffset);
19377     else
19378       MIB.addOperand(MI->getOperand(i));
19379   }
19380   MIB.setMemRefs(MMOBegin, MMOEnd);
19381   // Jump
19382   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
19383
19384   MI->eraseFromParent();
19385   return MBB;
19386 }
19387
19388 // Replace 213-type (isel default) FMA3 instructions with 231-type for
19389 // accumulator loops. Writing back to the accumulator allows the coalescer
19390 // to remove extra copies in the loop.
19391 MachineBasicBlock *
19392 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
19393                                  MachineBasicBlock *MBB) const {
19394   MachineOperand &AddendOp = MI->getOperand(3);
19395
19396   // Bail out early if the addend isn't a register - we can't switch these.
19397   if (!AddendOp.isReg())
19398     return MBB;
19399
19400   MachineFunction &MF = *MBB->getParent();
19401   MachineRegisterInfo &MRI = MF.getRegInfo();
19402
19403   // Check whether the addend is defined by a PHI:
19404   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
19405   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
19406   if (!AddendDef.isPHI())
19407     return MBB;
19408
19409   // Look for the following pattern:
19410   // loop:
19411   //   %addend = phi [%entry, 0], [%loop, %result]
19412   //   ...
19413   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
19414
19415   // Replace with:
19416   //   loop:
19417   //   %addend = phi [%entry, 0], [%loop, %result]
19418   //   ...
19419   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
19420
19421   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
19422     assert(AddendDef.getOperand(i).isReg());
19423     MachineOperand PHISrcOp = AddendDef.getOperand(i);
19424     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
19425     if (&PHISrcInst == MI) {
19426       // Found a matching instruction.
19427       unsigned NewFMAOpc = 0;
19428       switch (MI->getOpcode()) {
19429         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
19430         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
19431         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
19432         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
19433         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
19434         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
19435         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
19436         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
19437         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
19438         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
19439         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
19440         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
19441         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
19442         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
19443         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
19444         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
19445         case X86::VFMADDSUBPDr213r: NewFMAOpc = X86::VFMADDSUBPDr231r; break;
19446         case X86::VFMADDSUBPSr213r: NewFMAOpc = X86::VFMADDSUBPSr231r; break;
19447         case X86::VFMSUBADDPDr213r: NewFMAOpc = X86::VFMSUBADDPDr231r; break;
19448         case X86::VFMSUBADDPSr213r: NewFMAOpc = X86::VFMSUBADDPSr231r; break;
19449
19450         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
19451         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
19452         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
19453         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
19454         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
19455         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
19456         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
19457         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
19458         case X86::VFMADDSUBPDr213rY: NewFMAOpc = X86::VFMADDSUBPDr231rY; break;
19459         case X86::VFMADDSUBPSr213rY: NewFMAOpc = X86::VFMADDSUBPSr231rY; break;
19460         case X86::VFMSUBADDPDr213rY: NewFMAOpc = X86::VFMSUBADDPDr231rY; break;
19461         case X86::VFMSUBADDPSr213rY: NewFMAOpc = X86::VFMSUBADDPSr231rY; break;
19462         default: llvm_unreachable("Unrecognized FMA variant.");
19463       }
19464
19465       const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
19466       MachineInstrBuilder MIB =
19467         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
19468         .addOperand(MI->getOperand(0))
19469         .addOperand(MI->getOperand(3))
19470         .addOperand(MI->getOperand(2))
19471         .addOperand(MI->getOperand(1));
19472       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
19473       MI->eraseFromParent();
19474     }
19475   }
19476
19477   return MBB;
19478 }
19479
19480 MachineBasicBlock *
19481 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
19482                                                MachineBasicBlock *BB) const {
19483   switch (MI->getOpcode()) {
19484   default: llvm_unreachable("Unexpected instr type to insert");
19485   case X86::TAILJMPd64:
19486   case X86::TAILJMPr64:
19487   case X86::TAILJMPm64:
19488   case X86::TAILJMPd64_REX:
19489   case X86::TAILJMPr64_REX:
19490   case X86::TAILJMPm64_REX:
19491     llvm_unreachable("TAILJMP64 would not be touched here.");
19492   case X86::TCRETURNdi64:
19493   case X86::TCRETURNri64:
19494   case X86::TCRETURNmi64:
19495     return BB;
19496   case X86::WIN_ALLOCA:
19497     return EmitLoweredWinAlloca(MI, BB);
19498   case X86::SEG_ALLOCA_32:
19499   case X86::SEG_ALLOCA_64:
19500     return EmitLoweredSegAlloca(MI, BB);
19501   case X86::TLSCall_32:
19502   case X86::TLSCall_64:
19503     return EmitLoweredTLSCall(MI, BB);
19504   case X86::CMOV_GR8:
19505   case X86::CMOV_FR32:
19506   case X86::CMOV_FR64:
19507   case X86::CMOV_V4F32:
19508   case X86::CMOV_V2F64:
19509   case X86::CMOV_V2I64:
19510   case X86::CMOV_V8F32:
19511   case X86::CMOV_V4F64:
19512   case X86::CMOV_V4I64:
19513   case X86::CMOV_V16F32:
19514   case X86::CMOV_V8F64:
19515   case X86::CMOV_V8I64:
19516   case X86::CMOV_GR16:
19517   case X86::CMOV_GR32:
19518   case X86::CMOV_RFP32:
19519   case X86::CMOV_RFP64:
19520   case X86::CMOV_RFP80:
19521   case X86::CMOV_V8I1:
19522   case X86::CMOV_V16I1:
19523   case X86::CMOV_V32I1:
19524   case X86::CMOV_V64I1:
19525     return EmitLoweredSelect(MI, BB);
19526
19527   case X86::FP32_TO_INT16_IN_MEM:
19528   case X86::FP32_TO_INT32_IN_MEM:
19529   case X86::FP32_TO_INT64_IN_MEM:
19530   case X86::FP64_TO_INT16_IN_MEM:
19531   case X86::FP64_TO_INT32_IN_MEM:
19532   case X86::FP64_TO_INT64_IN_MEM:
19533   case X86::FP80_TO_INT16_IN_MEM:
19534   case X86::FP80_TO_INT32_IN_MEM:
19535   case X86::FP80_TO_INT64_IN_MEM: {
19536     MachineFunction *F = BB->getParent();
19537     const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19538     DebugLoc DL = MI->getDebugLoc();
19539
19540     // Change the floating point control register to use "round towards zero"
19541     // mode when truncating to an integer value.
19542     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
19543     addFrameReference(BuildMI(*BB, MI, DL,
19544                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
19545
19546     // Load the old value of the high byte of the control word...
19547     unsigned OldCW =
19548       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
19549     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
19550                       CWFrameIdx);
19551
19552     // Set the high part to be round to zero...
19553     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
19554       .addImm(0xC7F);
19555
19556     // Reload the modified control word now...
19557     addFrameReference(BuildMI(*BB, MI, DL,
19558                               TII->get(X86::FLDCW16m)), CWFrameIdx);
19559
19560     // Restore the memory image of control word to original value
19561     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
19562       .addReg(OldCW);
19563
19564     // Get the X86 opcode to use.
19565     unsigned Opc;
19566     switch (MI->getOpcode()) {
19567     default: llvm_unreachable("illegal opcode!");
19568     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
19569     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
19570     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
19571     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
19572     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
19573     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
19574     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
19575     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
19576     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
19577     }
19578
19579     X86AddressMode AM;
19580     MachineOperand &Op = MI->getOperand(0);
19581     if (Op.isReg()) {
19582       AM.BaseType = X86AddressMode::RegBase;
19583       AM.Base.Reg = Op.getReg();
19584     } else {
19585       AM.BaseType = X86AddressMode::FrameIndexBase;
19586       AM.Base.FrameIndex = Op.getIndex();
19587     }
19588     Op = MI->getOperand(1);
19589     if (Op.isImm())
19590       AM.Scale = Op.getImm();
19591     Op = MI->getOperand(2);
19592     if (Op.isImm())
19593       AM.IndexReg = Op.getImm();
19594     Op = MI->getOperand(3);
19595     if (Op.isGlobal()) {
19596       AM.GV = Op.getGlobal();
19597     } else {
19598       AM.Disp = Op.getImm();
19599     }
19600     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
19601                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
19602
19603     // Reload the original control word now.
19604     addFrameReference(BuildMI(*BB, MI, DL,
19605                               TII->get(X86::FLDCW16m)), CWFrameIdx);
19606
19607     MI->eraseFromParent();   // The pseudo instruction is gone now.
19608     return BB;
19609   }
19610     // String/text processing lowering.
19611   case X86::PCMPISTRM128REG:
19612   case X86::VPCMPISTRM128REG:
19613   case X86::PCMPISTRM128MEM:
19614   case X86::VPCMPISTRM128MEM:
19615   case X86::PCMPESTRM128REG:
19616   case X86::VPCMPESTRM128REG:
19617   case X86::PCMPESTRM128MEM:
19618   case X86::VPCMPESTRM128MEM:
19619     assert(Subtarget->hasSSE42() &&
19620            "Target must have SSE4.2 or AVX features enabled");
19621     return EmitPCMPSTRM(MI, BB, Subtarget->getInstrInfo());
19622
19623   // String/text processing lowering.
19624   case X86::PCMPISTRIREG:
19625   case X86::VPCMPISTRIREG:
19626   case X86::PCMPISTRIMEM:
19627   case X86::VPCMPISTRIMEM:
19628   case X86::PCMPESTRIREG:
19629   case X86::VPCMPESTRIREG:
19630   case X86::PCMPESTRIMEM:
19631   case X86::VPCMPESTRIMEM:
19632     assert(Subtarget->hasSSE42() &&
19633            "Target must have SSE4.2 or AVX features enabled");
19634     return EmitPCMPSTRI(MI, BB, Subtarget->getInstrInfo());
19635
19636   // Thread synchronization.
19637   case X86::MONITOR:
19638     return EmitMonitor(MI, BB, Subtarget);
19639
19640   // xbegin
19641   case X86::XBEGIN:
19642     return EmitXBegin(MI, BB, Subtarget->getInstrInfo());
19643
19644   case X86::VASTART_SAVE_XMM_REGS:
19645     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
19646
19647   case X86::VAARG_64:
19648     return EmitVAARG64WithCustomInserter(MI, BB);
19649
19650   case X86::EH_SjLj_SetJmp32:
19651   case X86::EH_SjLj_SetJmp64:
19652     return emitEHSjLjSetJmp(MI, BB);
19653
19654   case X86::EH_SjLj_LongJmp32:
19655   case X86::EH_SjLj_LongJmp64:
19656     return emitEHSjLjLongJmp(MI, BB);
19657
19658   case TargetOpcode::STATEPOINT:
19659     // As an implementation detail, STATEPOINT shares the STACKMAP format at
19660     // this point in the process.  We diverge later.
19661     return emitPatchPoint(MI, BB);
19662
19663   case TargetOpcode::STACKMAP:
19664   case TargetOpcode::PATCHPOINT:
19665     return emitPatchPoint(MI, BB);
19666
19667   case X86::VFMADDPDr213r:
19668   case X86::VFMADDPSr213r:
19669   case X86::VFMADDSDr213r:
19670   case X86::VFMADDSSr213r:
19671   case X86::VFMSUBPDr213r:
19672   case X86::VFMSUBPSr213r:
19673   case X86::VFMSUBSDr213r:
19674   case X86::VFMSUBSSr213r:
19675   case X86::VFNMADDPDr213r:
19676   case X86::VFNMADDPSr213r:
19677   case X86::VFNMADDSDr213r:
19678   case X86::VFNMADDSSr213r:
19679   case X86::VFNMSUBPDr213r:
19680   case X86::VFNMSUBPSr213r:
19681   case X86::VFNMSUBSDr213r:
19682   case X86::VFNMSUBSSr213r:
19683   case X86::VFMADDSUBPDr213r:
19684   case X86::VFMADDSUBPSr213r:
19685   case X86::VFMSUBADDPDr213r:
19686   case X86::VFMSUBADDPSr213r:
19687   case X86::VFMADDPDr213rY:
19688   case X86::VFMADDPSr213rY:
19689   case X86::VFMSUBPDr213rY:
19690   case X86::VFMSUBPSr213rY:
19691   case X86::VFNMADDPDr213rY:
19692   case X86::VFNMADDPSr213rY:
19693   case X86::VFNMSUBPDr213rY:
19694   case X86::VFNMSUBPSr213rY:
19695   case X86::VFMADDSUBPDr213rY:
19696   case X86::VFMADDSUBPSr213rY:
19697   case X86::VFMSUBADDPDr213rY:
19698   case X86::VFMSUBADDPSr213rY:
19699     return emitFMA3Instr(MI, BB);
19700   }
19701 }
19702
19703 //===----------------------------------------------------------------------===//
19704 //                           X86 Optimization Hooks
19705 //===----------------------------------------------------------------------===//
19706
19707 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
19708                                                       APInt &KnownZero,
19709                                                       APInt &KnownOne,
19710                                                       const SelectionDAG &DAG,
19711                                                       unsigned Depth) const {
19712   unsigned BitWidth = KnownZero.getBitWidth();
19713   unsigned Opc = Op.getOpcode();
19714   assert((Opc >= ISD::BUILTIN_OP_END ||
19715           Opc == ISD::INTRINSIC_WO_CHAIN ||
19716           Opc == ISD::INTRINSIC_W_CHAIN ||
19717           Opc == ISD::INTRINSIC_VOID) &&
19718          "Should use MaskedValueIsZero if you don't know whether Op"
19719          " is a target node!");
19720
19721   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
19722   switch (Opc) {
19723   default: break;
19724   case X86ISD::ADD:
19725   case X86ISD::SUB:
19726   case X86ISD::ADC:
19727   case X86ISD::SBB:
19728   case X86ISD::SMUL:
19729   case X86ISD::UMUL:
19730   case X86ISD::INC:
19731   case X86ISD::DEC:
19732   case X86ISD::OR:
19733   case X86ISD::XOR:
19734   case X86ISD::AND:
19735     // These nodes' second result is a boolean.
19736     if (Op.getResNo() == 0)
19737       break;
19738     // Fallthrough
19739   case X86ISD::SETCC:
19740     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
19741     break;
19742   case ISD::INTRINSIC_WO_CHAIN: {
19743     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
19744     unsigned NumLoBits = 0;
19745     switch (IntId) {
19746     default: break;
19747     case Intrinsic::x86_sse_movmsk_ps:
19748     case Intrinsic::x86_avx_movmsk_ps_256:
19749     case Intrinsic::x86_sse2_movmsk_pd:
19750     case Intrinsic::x86_avx_movmsk_pd_256:
19751     case Intrinsic::x86_mmx_pmovmskb:
19752     case Intrinsic::x86_sse2_pmovmskb_128:
19753     case Intrinsic::x86_avx2_pmovmskb: {
19754       // High bits of movmskp{s|d}, pmovmskb are known zero.
19755       switch (IntId) {
19756         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
19757         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
19758         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
19759         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
19760         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
19761         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
19762         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
19763         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
19764       }
19765       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
19766       break;
19767     }
19768     }
19769     break;
19770   }
19771   }
19772 }
19773
19774 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
19775   SDValue Op,
19776   const SelectionDAG &,
19777   unsigned Depth) const {
19778   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
19779   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
19780     return Op.getValueType().getScalarType().getSizeInBits();
19781
19782   // Fallback case.
19783   return 1;
19784 }
19785
19786 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
19787 /// node is a GlobalAddress + offset.
19788 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
19789                                        const GlobalValue* &GA,
19790                                        int64_t &Offset) const {
19791   if (N->getOpcode() == X86ISD::Wrapper) {
19792     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
19793       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
19794       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
19795       return true;
19796     }
19797   }
19798   return TargetLowering::isGAPlusOffset(N, GA, Offset);
19799 }
19800
19801 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
19802 /// same as extracting the high 128-bit part of 256-bit vector and then
19803 /// inserting the result into the low part of a new 256-bit vector
19804 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
19805   EVT VT = SVOp->getValueType(0);
19806   unsigned NumElems = VT.getVectorNumElements();
19807
19808   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
19809   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
19810     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
19811         SVOp->getMaskElt(j) >= 0)
19812       return false;
19813
19814   return true;
19815 }
19816
19817 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
19818 /// same as extracting the low 128-bit part of 256-bit vector and then
19819 /// inserting the result into the high part of a new 256-bit vector
19820 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
19821   EVT VT = SVOp->getValueType(0);
19822   unsigned NumElems = VT.getVectorNumElements();
19823
19824   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
19825   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
19826     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
19827         SVOp->getMaskElt(j) >= 0)
19828       return false;
19829
19830   return true;
19831 }
19832
19833 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
19834 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
19835                                         TargetLowering::DAGCombinerInfo &DCI,
19836                                         const X86Subtarget* Subtarget) {
19837   SDLoc dl(N);
19838   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
19839   SDValue V1 = SVOp->getOperand(0);
19840   SDValue V2 = SVOp->getOperand(1);
19841   EVT VT = SVOp->getValueType(0);
19842   unsigned NumElems = VT.getVectorNumElements();
19843
19844   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
19845       V2.getOpcode() == ISD::CONCAT_VECTORS) {
19846     //
19847     //                   0,0,0,...
19848     //                      |
19849     //    V      UNDEF    BUILD_VECTOR    UNDEF
19850     //     \      /           \           /
19851     //  CONCAT_VECTOR         CONCAT_VECTOR
19852     //         \                  /
19853     //          \                /
19854     //          RESULT: V + zero extended
19855     //
19856     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
19857         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
19858         V1.getOperand(1).getOpcode() != ISD::UNDEF)
19859       return SDValue();
19860
19861     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
19862       return SDValue();
19863
19864     // To match the shuffle mask, the first half of the mask should
19865     // be exactly the first vector, and all the rest a splat with the
19866     // first element of the second one.
19867     for (unsigned i = 0; i != NumElems/2; ++i)
19868       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
19869           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
19870         return SDValue();
19871
19872     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
19873     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
19874       if (Ld->hasNUsesOfValue(1, 0)) {
19875         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
19876         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
19877         SDValue ResNode =
19878           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
19879                                   Ld->getMemoryVT(),
19880                                   Ld->getPointerInfo(),
19881                                   Ld->getAlignment(),
19882                                   false/*isVolatile*/, true/*ReadMem*/,
19883                                   false/*WriteMem*/);
19884
19885         // Make sure the newly-created LOAD is in the same position as Ld in
19886         // terms of dependency. We create a TokenFactor for Ld and ResNode,
19887         // and update uses of Ld's output chain to use the TokenFactor.
19888         if (Ld->hasAnyUseOfValue(1)) {
19889           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
19890                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
19891           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
19892           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
19893                                  SDValue(ResNode.getNode(), 1));
19894         }
19895
19896         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
19897       }
19898     }
19899
19900     // Emit a zeroed vector and insert the desired subvector on its
19901     // first half.
19902     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
19903     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
19904     return DCI.CombineTo(N, InsV);
19905   }
19906
19907   //===--------------------------------------------------------------------===//
19908   // Combine some shuffles into subvector extracts and inserts:
19909   //
19910
19911   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
19912   if (isShuffleHigh128VectorInsertLow(SVOp)) {
19913     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
19914     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
19915     return DCI.CombineTo(N, InsV);
19916   }
19917
19918   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
19919   if (isShuffleLow128VectorInsertHigh(SVOp)) {
19920     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
19921     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
19922     return DCI.CombineTo(N, InsV);
19923   }
19924
19925   return SDValue();
19926 }
19927
19928 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
19929 /// possible.
19930 ///
19931 /// This is the leaf of the recursive combinine below. When we have found some
19932 /// chain of single-use x86 shuffle instructions and accumulated the combined
19933 /// shuffle mask represented by them, this will try to pattern match that mask
19934 /// into either a single instruction if there is a special purpose instruction
19935 /// for this operation, or into a PSHUFB instruction which is a fully general
19936 /// instruction but should only be used to replace chains over a certain depth.
19937 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
19938                                    int Depth, bool HasPSHUFB, SelectionDAG &DAG,
19939                                    TargetLowering::DAGCombinerInfo &DCI,
19940                                    const X86Subtarget *Subtarget) {
19941   assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
19942
19943   // Find the operand that enters the chain. Note that multiple uses are OK
19944   // here, we're not going to remove the operand we find.
19945   SDValue Input = Op.getOperand(0);
19946   while (Input.getOpcode() == ISD::BITCAST)
19947     Input = Input.getOperand(0);
19948
19949   MVT VT = Input.getSimpleValueType();
19950   MVT RootVT = Root.getSimpleValueType();
19951   SDLoc DL(Root);
19952
19953   // Just remove no-op shuffle masks.
19954   if (Mask.size() == 1) {
19955     DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Input),
19956                   /*AddTo*/ true);
19957     return true;
19958   }
19959
19960   // Use the float domain if the operand type is a floating point type.
19961   bool FloatDomain = VT.isFloatingPoint();
19962
19963   // For floating point shuffles, we don't have free copies in the shuffle
19964   // instructions or the ability to load as part of the instruction, so
19965   // canonicalize their shuffles to UNPCK or MOV variants.
19966   //
19967   // Note that even with AVX we prefer the PSHUFD form of shuffle for integer
19968   // vectors because it can have a load folded into it that UNPCK cannot. This
19969   // doesn't preclude something switching to the shorter encoding post-RA.
19970   //
19971   // FIXME: Should teach these routines about AVX vector widths.
19972   if (FloatDomain && VT.getSizeInBits() == 128) {
19973     if (Mask.equals({0, 0}) || Mask.equals({1, 1})) {
19974       bool Lo = Mask.equals({0, 0});
19975       unsigned Shuffle;
19976       MVT ShuffleVT;
19977       // Check if we have SSE3 which will let us use MOVDDUP. That instruction
19978       // is no slower than UNPCKLPD but has the option to fold the input operand
19979       // into even an unaligned memory load.
19980       if (Lo && Subtarget->hasSSE3()) {
19981         Shuffle = X86ISD::MOVDDUP;
19982         ShuffleVT = MVT::v2f64;
19983       } else {
19984         // We have MOVLHPS and MOVHLPS throughout SSE and they encode smaller
19985         // than the UNPCK variants.
19986         Shuffle = Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS;
19987         ShuffleVT = MVT::v4f32;
19988       }
19989       if (Depth == 1 && Root->getOpcode() == Shuffle)
19990         return false; // Nothing to do!
19991       Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19992       DCI.AddToWorklist(Op.getNode());
19993       if (Shuffle == X86ISD::MOVDDUP)
19994         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
19995       else
19996         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
19997       DCI.AddToWorklist(Op.getNode());
19998       DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19999                     /*AddTo*/ true);
20000       return true;
20001     }
20002     if (Subtarget->hasSSE3() &&
20003         (Mask.equals({0, 0, 2, 2}) || Mask.equals({1, 1, 3, 3}))) {
20004       bool Lo = Mask.equals({0, 0, 2, 2});
20005       unsigned Shuffle = Lo ? X86ISD::MOVSLDUP : X86ISD::MOVSHDUP;
20006       MVT ShuffleVT = MVT::v4f32;
20007       if (Depth == 1 && Root->getOpcode() == Shuffle)
20008         return false; // Nothing to do!
20009       Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
20010       DCI.AddToWorklist(Op.getNode());
20011       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
20012       DCI.AddToWorklist(Op.getNode());
20013       DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
20014                     /*AddTo*/ true);
20015       return true;
20016     }
20017     if (Mask.equals({0, 0, 1, 1}) || Mask.equals({2, 2, 3, 3})) {
20018       bool Lo = Mask.equals({0, 0, 1, 1});
20019       unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
20020       MVT ShuffleVT = MVT::v4f32;
20021       if (Depth == 1 && Root->getOpcode() == Shuffle)
20022         return false; // Nothing to do!
20023       Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
20024       DCI.AddToWorklist(Op.getNode());
20025       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
20026       DCI.AddToWorklist(Op.getNode());
20027       DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
20028                     /*AddTo*/ true);
20029       return true;
20030     }
20031   }
20032
20033   // We always canonicalize the 8 x i16 and 16 x i8 shuffles into their UNPCK
20034   // variants as none of these have single-instruction variants that are
20035   // superior to the UNPCK formulation.
20036   if (!FloatDomain && VT.getSizeInBits() == 128 &&
20037       (Mask.equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
20038        Mask.equals({4, 4, 5, 5, 6, 6, 7, 7}) ||
20039        Mask.equals({0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7}) ||
20040        Mask.equals(
20041            {8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15}))) {
20042     bool Lo = Mask[0] == 0;
20043     unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
20044     if (Depth == 1 && Root->getOpcode() == Shuffle)
20045       return false; // Nothing to do!
20046     MVT ShuffleVT;
20047     switch (Mask.size()) {
20048     case 8:
20049       ShuffleVT = MVT::v8i16;
20050       break;
20051     case 16:
20052       ShuffleVT = MVT::v16i8;
20053       break;
20054     default:
20055       llvm_unreachable("Impossible mask size!");
20056     };
20057     Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
20058     DCI.AddToWorklist(Op.getNode());
20059     Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
20060     DCI.AddToWorklist(Op.getNode());
20061     DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
20062                   /*AddTo*/ true);
20063     return true;
20064   }
20065
20066   // Don't try to re-form single instruction chains under any circumstances now
20067   // that we've done encoding canonicalization for them.
20068   if (Depth < 2)
20069     return false;
20070
20071   // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
20072   // can replace them with a single PSHUFB instruction profitably. Intel's
20073   // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
20074   // in practice PSHUFB tends to be *very* fast so we're more aggressive.
20075   if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
20076     SmallVector<SDValue, 16> PSHUFBMask;
20077     int NumBytes = VT.getSizeInBits() / 8;
20078     int Ratio = NumBytes / Mask.size();
20079     for (int i = 0; i < NumBytes; ++i) {
20080       if (Mask[i / Ratio] == SM_SentinelUndef) {
20081         PSHUFBMask.push_back(DAG.getUNDEF(MVT::i8));
20082         continue;
20083       }
20084       int M = Mask[i / Ratio] != SM_SentinelZero
20085                   ? Ratio * Mask[i / Ratio] + i % Ratio
20086                   : 255;
20087       PSHUFBMask.push_back(DAG.getConstant(M, DL, MVT::i8));
20088     }
20089     MVT ByteVT = MVT::getVectorVT(MVT::i8, NumBytes);
20090     Op = DAG.getNode(ISD::BITCAST, DL, ByteVT, Input);
20091     DCI.AddToWorklist(Op.getNode());
20092     SDValue PSHUFBMaskOp =
20093         DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVT, PSHUFBMask);
20094     DCI.AddToWorklist(PSHUFBMaskOp.getNode());
20095     Op = DAG.getNode(X86ISD::PSHUFB, DL, ByteVT, Op, PSHUFBMaskOp);
20096     DCI.AddToWorklist(Op.getNode());
20097     DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
20098                   /*AddTo*/ true);
20099     return true;
20100   }
20101
20102   // Failed to find any combines.
20103   return false;
20104 }
20105
20106 /// \brief Fully generic combining of x86 shuffle instructions.
20107 ///
20108 /// This should be the last combine run over the x86 shuffle instructions. Once
20109 /// they have been fully optimized, this will recursively consider all chains
20110 /// of single-use shuffle instructions, build a generic model of the cumulative
20111 /// shuffle operation, and check for simpler instructions which implement this
20112 /// operation. We use this primarily for two purposes:
20113 ///
20114 /// 1) Collapse generic shuffles to specialized single instructions when
20115 ///    equivalent. In most cases, this is just an encoding size win, but
20116 ///    sometimes we will collapse multiple generic shuffles into a single
20117 ///    special-purpose shuffle.
20118 /// 2) Look for sequences of shuffle instructions with 3 or more total
20119 ///    instructions, and replace them with the slightly more expensive SSSE3
20120 ///    PSHUFB instruction if available. We do this as the last combining step
20121 ///    to ensure we avoid using PSHUFB if we can implement the shuffle with
20122 ///    a suitable short sequence of other instructions. The PHUFB will either
20123 ///    use a register or have to read from memory and so is slightly (but only
20124 ///    slightly) more expensive than the other shuffle instructions.
20125 ///
20126 /// Because this is inherently a quadratic operation (for each shuffle in
20127 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
20128 /// This should never be an issue in practice as the shuffle lowering doesn't
20129 /// produce sequences of more than 8 instructions.
20130 ///
20131 /// FIXME: We will currently miss some cases where the redundant shuffling
20132 /// would simplify under the threshold for PSHUFB formation because of
20133 /// combine-ordering. To fix this, we should do the redundant instruction
20134 /// combining in this recursive walk.
20135 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
20136                                           ArrayRef<int> RootMask,
20137                                           int Depth, bool HasPSHUFB,
20138                                           SelectionDAG &DAG,
20139                                           TargetLowering::DAGCombinerInfo &DCI,
20140                                           const X86Subtarget *Subtarget) {
20141   // Bound the depth of our recursive combine because this is ultimately
20142   // quadratic in nature.
20143   if (Depth > 8)
20144     return false;
20145
20146   // Directly rip through bitcasts to find the underlying operand.
20147   while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
20148     Op = Op.getOperand(0);
20149
20150   MVT VT = Op.getSimpleValueType();
20151   if (!VT.isVector())
20152     return false; // Bail if we hit a non-vector.
20153
20154   assert(Root.getSimpleValueType().isVector() &&
20155          "Shuffles operate on vector types!");
20156   assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
20157          "Can only combine shuffles of the same vector register size.");
20158
20159   if (!isTargetShuffle(Op.getOpcode()))
20160     return false;
20161   SmallVector<int, 16> OpMask;
20162   bool IsUnary;
20163   bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, OpMask, IsUnary);
20164   // We only can combine unary shuffles which we can decode the mask for.
20165   if (!HaveMask || !IsUnary)
20166     return false;
20167
20168   assert(VT.getVectorNumElements() == OpMask.size() &&
20169          "Different mask size from vector size!");
20170   assert(((RootMask.size() > OpMask.size() &&
20171            RootMask.size() % OpMask.size() == 0) ||
20172           (OpMask.size() > RootMask.size() &&
20173            OpMask.size() % RootMask.size() == 0) ||
20174           OpMask.size() == RootMask.size()) &&
20175          "The smaller number of elements must divide the larger.");
20176   int RootRatio = std::max<int>(1, OpMask.size() / RootMask.size());
20177   int OpRatio = std::max<int>(1, RootMask.size() / OpMask.size());
20178   assert(((RootRatio == 1 && OpRatio == 1) ||
20179           (RootRatio == 1) != (OpRatio == 1)) &&
20180          "Must not have a ratio for both incoming and op masks!");
20181
20182   SmallVector<int, 16> Mask;
20183   Mask.reserve(std::max(OpMask.size(), RootMask.size()));
20184
20185   // Merge this shuffle operation's mask into our accumulated mask. Note that
20186   // this shuffle's mask will be the first applied to the input, followed by the
20187   // root mask to get us all the way to the root value arrangement. The reason
20188   // for this order is that we are recursing up the operation chain.
20189   for (int i = 0, e = std::max(OpMask.size(), RootMask.size()); i < e; ++i) {
20190     int RootIdx = i / RootRatio;
20191     if (RootMask[RootIdx] < 0) {
20192       // This is a zero or undef lane, we're done.
20193       Mask.push_back(RootMask[RootIdx]);
20194       continue;
20195     }
20196
20197     int RootMaskedIdx = RootMask[RootIdx] * RootRatio + i % RootRatio;
20198     int OpIdx = RootMaskedIdx / OpRatio;
20199     if (OpMask[OpIdx] < 0) {
20200       // The incoming lanes are zero or undef, it doesn't matter which ones we
20201       // are using.
20202       Mask.push_back(OpMask[OpIdx]);
20203       continue;
20204     }
20205
20206     // Ok, we have non-zero lanes, map them through.
20207     Mask.push_back(OpMask[OpIdx] * OpRatio +
20208                    RootMaskedIdx % OpRatio);
20209   }
20210
20211   // See if we can recurse into the operand to combine more things.
20212   switch (Op.getOpcode()) {
20213     case X86ISD::PSHUFB:
20214       HasPSHUFB = true;
20215     case X86ISD::PSHUFD:
20216     case X86ISD::PSHUFHW:
20217     case X86ISD::PSHUFLW:
20218       if (Op.getOperand(0).hasOneUse() &&
20219           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
20220                                         HasPSHUFB, DAG, DCI, Subtarget))
20221         return true;
20222       break;
20223
20224     case X86ISD::UNPCKL:
20225     case X86ISD::UNPCKH:
20226       assert(Op.getOperand(0) == Op.getOperand(1) && "We only combine unary shuffles!");
20227       // We can't check for single use, we have to check that this shuffle is the only user.
20228       if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
20229           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
20230                                         HasPSHUFB, DAG, DCI, Subtarget))
20231           return true;
20232       break;
20233   }
20234
20235   // Minor canonicalization of the accumulated shuffle mask to make it easier
20236   // to match below. All this does is detect masks with squential pairs of
20237   // elements, and shrink them to the half-width mask. It does this in a loop
20238   // so it will reduce the size of the mask to the minimal width mask which
20239   // performs an equivalent shuffle.
20240   SmallVector<int, 16> WidenedMask;
20241   while (Mask.size() > 1 && canWidenShuffleElements(Mask, WidenedMask)) {
20242     Mask = std::move(WidenedMask);
20243     WidenedMask.clear();
20244   }
20245
20246   return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
20247                                 Subtarget);
20248 }
20249
20250 /// \brief Get the PSHUF-style mask from PSHUF node.
20251 ///
20252 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
20253 /// PSHUF-style masks that can be reused with such instructions.
20254 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
20255   MVT VT = N.getSimpleValueType();
20256   SmallVector<int, 4> Mask;
20257   bool IsUnary;
20258   bool HaveMask = getTargetShuffleMask(N.getNode(), VT, Mask, IsUnary);
20259   (void)HaveMask;
20260   assert(HaveMask);
20261
20262   // If we have more than 128-bits, only the low 128-bits of shuffle mask
20263   // matter. Check that the upper masks are repeats and remove them.
20264   if (VT.getSizeInBits() > 128) {
20265     int LaneElts = 128 / VT.getScalarSizeInBits();
20266 #ifndef NDEBUG
20267     for (int i = 1, NumLanes = VT.getSizeInBits() / 128; i < NumLanes; ++i)
20268       for (int j = 0; j < LaneElts; ++j)
20269         assert(Mask[j] == Mask[i * LaneElts + j] - LaneElts &&
20270                "Mask doesn't repeat in high 128-bit lanes!");
20271 #endif
20272     Mask.resize(LaneElts);
20273   }
20274
20275   switch (N.getOpcode()) {
20276   case X86ISD::PSHUFD:
20277     return Mask;
20278   case X86ISD::PSHUFLW:
20279     Mask.resize(4);
20280     return Mask;
20281   case X86ISD::PSHUFHW:
20282     Mask.erase(Mask.begin(), Mask.begin() + 4);
20283     for (int &M : Mask)
20284       M -= 4;
20285     return Mask;
20286   default:
20287     llvm_unreachable("No valid shuffle instruction found!");
20288   }
20289 }
20290
20291 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
20292 ///
20293 /// We walk up the chain and look for a combinable shuffle, skipping over
20294 /// shuffles that we could hoist this shuffle's transformation past without
20295 /// altering anything.
20296 static SDValue
20297 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
20298                              SelectionDAG &DAG,
20299                              TargetLowering::DAGCombinerInfo &DCI) {
20300   assert(N.getOpcode() == X86ISD::PSHUFD &&
20301          "Called with something other than an x86 128-bit half shuffle!");
20302   SDLoc DL(N);
20303
20304   // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
20305   // of the shuffles in the chain so that we can form a fresh chain to replace
20306   // this one.
20307   SmallVector<SDValue, 8> Chain;
20308   SDValue V = N.getOperand(0);
20309   for (; V.hasOneUse(); V = V.getOperand(0)) {
20310     switch (V.getOpcode()) {
20311     default:
20312       return SDValue(); // Nothing combined!
20313
20314     case ISD::BITCAST:
20315       // Skip bitcasts as we always know the type for the target specific
20316       // instructions.
20317       continue;
20318
20319     case X86ISD::PSHUFD:
20320       // Found another dword shuffle.
20321       break;
20322
20323     case X86ISD::PSHUFLW:
20324       // Check that the low words (being shuffled) are the identity in the
20325       // dword shuffle, and the high words are self-contained.
20326       if (Mask[0] != 0 || Mask[1] != 1 ||
20327           !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
20328         return SDValue();
20329
20330       Chain.push_back(V);
20331       continue;
20332
20333     case X86ISD::PSHUFHW:
20334       // Check that the high words (being shuffled) are the identity in the
20335       // dword shuffle, and the low words are self-contained.
20336       if (Mask[2] != 2 || Mask[3] != 3 ||
20337           !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
20338         return SDValue();
20339
20340       Chain.push_back(V);
20341       continue;
20342
20343     case X86ISD::UNPCKL:
20344     case X86ISD::UNPCKH:
20345       // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
20346       // shuffle into a preceding word shuffle.
20347       if (V.getSimpleValueType().getScalarType() != MVT::i8 &&
20348           V.getSimpleValueType().getScalarType() != MVT::i16)
20349         return SDValue();
20350
20351       // Search for a half-shuffle which we can combine with.
20352       unsigned CombineOp =
20353           V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
20354       if (V.getOperand(0) != V.getOperand(1) ||
20355           !V->isOnlyUserOf(V.getOperand(0).getNode()))
20356         return SDValue();
20357       Chain.push_back(V);
20358       V = V.getOperand(0);
20359       do {
20360         switch (V.getOpcode()) {
20361         default:
20362           return SDValue(); // Nothing to combine.
20363
20364         case X86ISD::PSHUFLW:
20365         case X86ISD::PSHUFHW:
20366           if (V.getOpcode() == CombineOp)
20367             break;
20368
20369           Chain.push_back(V);
20370
20371           // Fallthrough!
20372         case ISD::BITCAST:
20373           V = V.getOperand(0);
20374           continue;
20375         }
20376         break;
20377       } while (V.hasOneUse());
20378       break;
20379     }
20380     // Break out of the loop if we break out of the switch.
20381     break;
20382   }
20383
20384   if (!V.hasOneUse())
20385     // We fell out of the loop without finding a viable combining instruction.
20386     return SDValue();
20387
20388   // Merge this node's mask and our incoming mask.
20389   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
20390   for (int &M : Mask)
20391     M = VMask[M];
20392   V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
20393                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
20394
20395   // Rebuild the chain around this new shuffle.
20396   while (!Chain.empty()) {
20397     SDValue W = Chain.pop_back_val();
20398
20399     if (V.getValueType() != W.getOperand(0).getValueType())
20400       V = DAG.getNode(ISD::BITCAST, DL, W.getOperand(0).getValueType(), V);
20401
20402     switch (W.getOpcode()) {
20403     default:
20404       llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
20405
20406     case X86ISD::UNPCKL:
20407     case X86ISD::UNPCKH:
20408       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
20409       break;
20410
20411     case X86ISD::PSHUFD:
20412     case X86ISD::PSHUFLW:
20413     case X86ISD::PSHUFHW:
20414       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
20415       break;
20416     }
20417   }
20418   if (V.getValueType() != N.getValueType())
20419     V = DAG.getNode(ISD::BITCAST, DL, N.getValueType(), V);
20420
20421   // Return the new chain to replace N.
20422   return V;
20423 }
20424
20425 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or pshufhw.
20426 ///
20427 /// We walk up the chain, skipping shuffles of the other half and looking
20428 /// through shuffles which switch halves trying to find a shuffle of the same
20429 /// pair of dwords.
20430 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
20431                                         SelectionDAG &DAG,
20432                                         TargetLowering::DAGCombinerInfo &DCI) {
20433   assert(
20434       (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
20435       "Called with something other than an x86 128-bit half shuffle!");
20436   SDLoc DL(N);
20437   unsigned CombineOpcode = N.getOpcode();
20438
20439   // Walk up a single-use chain looking for a combinable shuffle.
20440   SDValue V = N.getOperand(0);
20441   for (; V.hasOneUse(); V = V.getOperand(0)) {
20442     switch (V.getOpcode()) {
20443     default:
20444       return false; // Nothing combined!
20445
20446     case ISD::BITCAST:
20447       // Skip bitcasts as we always know the type for the target specific
20448       // instructions.
20449       continue;
20450
20451     case X86ISD::PSHUFLW:
20452     case X86ISD::PSHUFHW:
20453       if (V.getOpcode() == CombineOpcode)
20454         break;
20455
20456       // Other-half shuffles are no-ops.
20457       continue;
20458     }
20459     // Break out of the loop if we break out of the switch.
20460     break;
20461   }
20462
20463   if (!V.hasOneUse())
20464     // We fell out of the loop without finding a viable combining instruction.
20465     return false;
20466
20467   // Combine away the bottom node as its shuffle will be accumulated into
20468   // a preceding shuffle.
20469   DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
20470
20471   // Record the old value.
20472   SDValue Old = V;
20473
20474   // Merge this node's mask and our incoming mask (adjusted to account for all
20475   // the pshufd instructions encountered).
20476   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
20477   for (int &M : Mask)
20478     M = VMask[M];
20479   V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
20480                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
20481
20482   // Check that the shuffles didn't cancel each other out. If not, we need to
20483   // combine to the new one.
20484   if (Old != V)
20485     // Replace the combinable shuffle with the combined one, updating all users
20486     // so that we re-evaluate the chain here.
20487     DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
20488
20489   return true;
20490 }
20491
20492 /// \brief Try to combine x86 target specific shuffles.
20493 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
20494                                            TargetLowering::DAGCombinerInfo &DCI,
20495                                            const X86Subtarget *Subtarget) {
20496   SDLoc DL(N);
20497   MVT VT = N.getSimpleValueType();
20498   SmallVector<int, 4> Mask;
20499
20500   switch (N.getOpcode()) {
20501   case X86ISD::PSHUFD:
20502   case X86ISD::PSHUFLW:
20503   case X86ISD::PSHUFHW:
20504     Mask = getPSHUFShuffleMask(N);
20505     assert(Mask.size() == 4);
20506     break;
20507   default:
20508     return SDValue();
20509   }
20510
20511   // Nuke no-op shuffles that show up after combining.
20512   if (isNoopShuffleMask(Mask))
20513     return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
20514
20515   // Look for simplifications involving one or two shuffle instructions.
20516   SDValue V = N.getOperand(0);
20517   switch (N.getOpcode()) {
20518   default:
20519     break;
20520   case X86ISD::PSHUFLW:
20521   case X86ISD::PSHUFHW:
20522     assert(VT.getScalarType() == MVT::i16 && "Bad word shuffle type!");
20523
20524     if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
20525       return SDValue(); // We combined away this shuffle, so we're done.
20526
20527     // See if this reduces to a PSHUFD which is no more expensive and can
20528     // combine with more operations. Note that it has to at least flip the
20529     // dwords as otherwise it would have been removed as a no-op.
20530     if (makeArrayRef(Mask).equals({2, 3, 0, 1})) {
20531       int DMask[] = {0, 1, 2, 3};
20532       int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
20533       DMask[DOffset + 0] = DOffset + 1;
20534       DMask[DOffset + 1] = DOffset + 0;
20535       MVT DVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
20536       V = DAG.getNode(ISD::BITCAST, DL, DVT, V);
20537       DCI.AddToWorklist(V.getNode());
20538       V = DAG.getNode(X86ISD::PSHUFD, DL, DVT, V,
20539                       getV4X86ShuffleImm8ForMask(DMask, DL, DAG));
20540       DCI.AddToWorklist(V.getNode());
20541       return DAG.getNode(ISD::BITCAST, DL, VT, V);
20542     }
20543
20544     // Look for shuffle patterns which can be implemented as a single unpack.
20545     // FIXME: This doesn't handle the location of the PSHUFD generically, and
20546     // only works when we have a PSHUFD followed by two half-shuffles.
20547     if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
20548         (V.getOpcode() == X86ISD::PSHUFLW ||
20549          V.getOpcode() == X86ISD::PSHUFHW) &&
20550         V.getOpcode() != N.getOpcode() &&
20551         V.hasOneUse()) {
20552       SDValue D = V.getOperand(0);
20553       while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
20554         D = D.getOperand(0);
20555       if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
20556         SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
20557         SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
20558         int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
20559         int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
20560         int WordMask[8];
20561         for (int i = 0; i < 4; ++i) {
20562           WordMask[i + NOffset] = Mask[i] + NOffset;
20563           WordMask[i + VOffset] = VMask[i] + VOffset;
20564         }
20565         // Map the word mask through the DWord mask.
20566         int MappedMask[8];
20567         for (int i = 0; i < 8; ++i)
20568           MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
20569         if (makeArrayRef(MappedMask).equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
20570             makeArrayRef(MappedMask).equals({4, 4, 5, 5, 6, 6, 7, 7})) {
20571           // We can replace all three shuffles with an unpack.
20572           V = DAG.getNode(ISD::BITCAST, DL, VT, D.getOperand(0));
20573           DCI.AddToWorklist(V.getNode());
20574           return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
20575                                                 : X86ISD::UNPCKH,
20576                              DL, VT, V, V);
20577         }
20578       }
20579     }
20580
20581     break;
20582
20583   case X86ISD::PSHUFD:
20584     if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG, DCI))
20585       return NewN;
20586
20587     break;
20588   }
20589
20590   return SDValue();
20591 }
20592
20593 /// \brief Try to combine a shuffle into a target-specific add-sub node.
20594 ///
20595 /// We combine this directly on the abstract vector shuffle nodes so it is
20596 /// easier to generically match. We also insert dummy vector shuffle nodes for
20597 /// the operands which explicitly discard the lanes which are unused by this
20598 /// operation to try to flow through the rest of the combiner the fact that
20599 /// they're unused.
20600 static SDValue combineShuffleToAddSub(SDNode *N, SelectionDAG &DAG) {
20601   SDLoc DL(N);
20602   EVT VT = N->getValueType(0);
20603
20604   // We only handle target-independent shuffles.
20605   // FIXME: It would be easy and harmless to use the target shuffle mask
20606   // extraction tool to support more.
20607   if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
20608     return SDValue();
20609
20610   auto *SVN = cast<ShuffleVectorSDNode>(N);
20611   ArrayRef<int> Mask = SVN->getMask();
20612   SDValue V1 = N->getOperand(0);
20613   SDValue V2 = N->getOperand(1);
20614
20615   // We require the first shuffle operand to be the SUB node, and the second to
20616   // be the ADD node.
20617   // FIXME: We should support the commuted patterns.
20618   if (V1->getOpcode() != ISD::FSUB || V2->getOpcode() != ISD::FADD)
20619     return SDValue();
20620
20621   // If there are other uses of these operations we can't fold them.
20622   if (!V1->hasOneUse() || !V2->hasOneUse())
20623     return SDValue();
20624
20625   // Ensure that both operations have the same operands. Note that we can
20626   // commute the FADD operands.
20627   SDValue LHS = V1->getOperand(0), RHS = V1->getOperand(1);
20628   if ((V2->getOperand(0) != LHS || V2->getOperand(1) != RHS) &&
20629       (V2->getOperand(0) != RHS || V2->getOperand(1) != LHS))
20630     return SDValue();
20631
20632   // We're looking for blends between FADD and FSUB nodes. We insist on these
20633   // nodes being lined up in a specific expected pattern.
20634   if (!(isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
20635         isShuffleEquivalent(V1, V2, Mask, {0, 5, 2, 7}) ||
20636         isShuffleEquivalent(V1, V2, Mask, {0, 9, 2, 11, 4, 13, 6, 15})))
20637     return SDValue();
20638
20639   // Only specific types are legal at this point, assert so we notice if and
20640   // when these change.
20641   assert((VT == MVT::v4f32 || VT == MVT::v2f64 || VT == MVT::v8f32 ||
20642           VT == MVT::v4f64) &&
20643          "Unknown vector type encountered!");
20644
20645   return DAG.getNode(X86ISD::ADDSUB, DL, VT, LHS, RHS);
20646 }
20647
20648 /// PerformShuffleCombine - Performs several different shuffle combines.
20649 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
20650                                      TargetLowering::DAGCombinerInfo &DCI,
20651                                      const X86Subtarget *Subtarget) {
20652   SDLoc dl(N);
20653   SDValue N0 = N->getOperand(0);
20654   SDValue N1 = N->getOperand(1);
20655   EVT VT = N->getValueType(0);
20656
20657   // Don't create instructions with illegal types after legalize types has run.
20658   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20659   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
20660     return SDValue();
20661
20662   // If we have legalized the vector types, look for blends of FADD and FSUB
20663   // nodes that we can fuse into an ADDSUB node.
20664   if (TLI.isTypeLegal(VT) && Subtarget->hasSSE3())
20665     if (SDValue AddSub = combineShuffleToAddSub(N, DAG))
20666       return AddSub;
20667
20668   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
20669   if (Subtarget->hasFp256() && VT.is256BitVector() &&
20670       N->getOpcode() == ISD::VECTOR_SHUFFLE)
20671     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
20672
20673   // During Type Legalization, when promoting illegal vector types,
20674   // the backend might introduce new shuffle dag nodes and bitcasts.
20675   //
20676   // This code performs the following transformation:
20677   // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
20678   //       (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
20679   //
20680   // We do this only if both the bitcast and the BINOP dag nodes have
20681   // one use. Also, perform this transformation only if the new binary
20682   // operation is legal. This is to avoid introducing dag nodes that
20683   // potentially need to be further expanded (or custom lowered) into a
20684   // less optimal sequence of dag nodes.
20685   if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
20686       N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
20687       N0.getOpcode() == ISD::BITCAST) {
20688     SDValue BC0 = N0.getOperand(0);
20689     EVT SVT = BC0.getValueType();
20690     unsigned Opcode = BC0.getOpcode();
20691     unsigned NumElts = VT.getVectorNumElements();
20692
20693     if (BC0.hasOneUse() && SVT.isVector() &&
20694         SVT.getVectorNumElements() * 2 == NumElts &&
20695         TLI.isOperationLegal(Opcode, VT)) {
20696       bool CanFold = false;
20697       switch (Opcode) {
20698       default : break;
20699       case ISD::ADD :
20700       case ISD::FADD :
20701       case ISD::SUB :
20702       case ISD::FSUB :
20703       case ISD::MUL :
20704       case ISD::FMUL :
20705         CanFold = true;
20706       }
20707
20708       unsigned SVTNumElts = SVT.getVectorNumElements();
20709       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
20710       for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
20711         CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
20712       for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
20713         CanFold = SVOp->getMaskElt(i) < 0;
20714
20715       if (CanFold) {
20716         SDValue BC00 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(0));
20717         SDValue BC01 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(1));
20718         SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
20719         return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
20720       }
20721     }
20722   }
20723
20724   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
20725   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
20726   // consecutive, non-overlapping, and in the right order.
20727   SmallVector<SDValue, 16> Elts;
20728   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
20729     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
20730
20731   SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
20732   if (LD.getNode())
20733     return LD;
20734
20735   if (isTargetShuffle(N->getOpcode())) {
20736     SDValue Shuffle =
20737         PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
20738     if (Shuffle.getNode())
20739       return Shuffle;
20740
20741     // Try recursively combining arbitrary sequences of x86 shuffle
20742     // instructions into higher-order shuffles. We do this after combining
20743     // specific PSHUF instruction sequences into their minimal form so that we
20744     // can evaluate how many specialized shuffle instructions are involved in
20745     // a particular chain.
20746     SmallVector<int, 1> NonceMask; // Just a placeholder.
20747     NonceMask.push_back(0);
20748     if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
20749                                       /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
20750                                       DCI, Subtarget))
20751       return SDValue(); // This routine will use CombineTo to replace N.
20752   }
20753
20754   return SDValue();
20755 }
20756
20757 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
20758 /// specific shuffle of a load can be folded into a single element load.
20759 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
20760 /// shuffles have been custom lowered so we need to handle those here.
20761 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
20762                                          TargetLowering::DAGCombinerInfo &DCI) {
20763   if (DCI.isBeforeLegalizeOps())
20764     return SDValue();
20765
20766   SDValue InVec = N->getOperand(0);
20767   SDValue EltNo = N->getOperand(1);
20768
20769   if (!isa<ConstantSDNode>(EltNo))
20770     return SDValue();
20771
20772   EVT OriginalVT = InVec.getValueType();
20773
20774   if (InVec.getOpcode() == ISD::BITCAST) {
20775     // Don't duplicate a load with other uses.
20776     if (!InVec.hasOneUse())
20777       return SDValue();
20778     EVT BCVT = InVec.getOperand(0).getValueType();
20779     if (!BCVT.isVector() || 
20780         BCVT.getVectorNumElements() != OriginalVT.getVectorNumElements())
20781       return SDValue();
20782     InVec = InVec.getOperand(0);
20783   }
20784
20785   EVT CurrentVT = InVec.getValueType();
20786
20787   if (!isTargetShuffle(InVec.getOpcode()))
20788     return SDValue();
20789
20790   // Don't duplicate a load with other uses.
20791   if (!InVec.hasOneUse())
20792     return SDValue();
20793
20794   SmallVector<int, 16> ShuffleMask;
20795   bool UnaryShuffle;
20796   if (!getTargetShuffleMask(InVec.getNode(), CurrentVT.getSimpleVT(),
20797                             ShuffleMask, UnaryShuffle))
20798     return SDValue();
20799
20800   // Select the input vector, guarding against out of range extract vector.
20801   unsigned NumElems = CurrentVT.getVectorNumElements();
20802   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
20803   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
20804   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
20805                                          : InVec.getOperand(1);
20806
20807   // If inputs to shuffle are the same for both ops, then allow 2 uses
20808   unsigned AllowedUses = InVec.getNumOperands() > 1 &&
20809                          InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
20810
20811   if (LdNode.getOpcode() == ISD::BITCAST) {
20812     // Don't duplicate a load with other uses.
20813     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
20814       return SDValue();
20815
20816     AllowedUses = 1; // only allow 1 load use if we have a bitcast
20817     LdNode = LdNode.getOperand(0);
20818   }
20819
20820   if (!ISD::isNormalLoad(LdNode.getNode()))
20821     return SDValue();
20822
20823   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
20824
20825   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
20826     return SDValue();
20827
20828   EVT EltVT = N->getValueType(0);
20829   // If there's a bitcast before the shuffle, check if the load type and
20830   // alignment is valid.
20831   unsigned Align = LN0->getAlignment();
20832   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20833   unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
20834       EltVT.getTypeForEVT(*DAG.getContext()));
20835
20836   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, EltVT))
20837     return SDValue();
20838
20839   // All checks match so transform back to vector_shuffle so that DAG combiner
20840   // can finish the job
20841   SDLoc dl(N);
20842
20843   // Create shuffle node taking into account the case that its a unary shuffle
20844   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(CurrentVT)
20845                                    : InVec.getOperand(1);
20846   Shuffle = DAG.getVectorShuffle(CurrentVT, dl,
20847                                  InVec.getOperand(0), Shuffle,
20848                                  &ShuffleMask[0]);
20849   Shuffle = DAG.getNode(ISD::BITCAST, dl, OriginalVT, Shuffle);
20850   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
20851                      EltNo);
20852 }
20853
20854 /// \brief Detect bitcasts between i32 to x86mmx low word. Since MMX types are
20855 /// special and don't usually play with other vector types, it's better to
20856 /// handle them early to be sure we emit efficient code by avoiding
20857 /// store-load conversions.
20858 static SDValue PerformBITCASTCombine(SDNode *N, SelectionDAG &DAG) {
20859   if (N->getValueType(0) != MVT::x86mmx ||
20860       N->getOperand(0)->getOpcode() != ISD::BUILD_VECTOR ||
20861       N->getOperand(0)->getValueType(0) != MVT::v2i32)
20862     return SDValue();
20863
20864   SDValue V = N->getOperand(0);
20865   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V.getOperand(1));
20866   if (C && C->getZExtValue() == 0 && V.getOperand(0).getValueType() == MVT::i32)
20867     return DAG.getNode(X86ISD::MMX_MOVW2D, SDLoc(V.getOperand(0)),
20868                        N->getValueType(0), V.getOperand(0));
20869
20870   return SDValue();
20871 }
20872
20873 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
20874 /// generation and convert it from being a bunch of shuffles and extracts
20875 /// into a somewhat faster sequence. For i686, the best sequence is apparently
20876 /// storing the value and loading scalars back, while for x64 we should
20877 /// use 64-bit extracts and shifts.
20878 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
20879                                          TargetLowering::DAGCombinerInfo &DCI) {
20880   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
20881   if (NewOp.getNode())
20882     return NewOp;
20883
20884   SDValue InputVector = N->getOperand(0);
20885   SDLoc dl(InputVector);
20886   // Detect mmx to i32 conversion through a v2i32 elt extract.
20887   if (InputVector.getOpcode() == ISD::BITCAST && InputVector.hasOneUse() &&
20888       N->getValueType(0) == MVT::i32 &&
20889       InputVector.getValueType() == MVT::v2i32) {
20890
20891     // The bitcast source is a direct mmx result.
20892     SDValue MMXSrc = InputVector.getNode()->getOperand(0);
20893     if (MMXSrc.getValueType() == MVT::x86mmx)
20894       return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
20895                          N->getValueType(0),
20896                          InputVector.getNode()->getOperand(0));
20897
20898     // The mmx is indirect: (i64 extract_elt (v1i64 bitcast (x86mmx ...))).
20899     SDValue MMXSrcOp = MMXSrc.getOperand(0);
20900     if (MMXSrc.getOpcode() == ISD::EXTRACT_VECTOR_ELT && MMXSrc.hasOneUse() &&
20901         MMXSrc.getValueType() == MVT::i64 && MMXSrcOp.hasOneUse() &&
20902         MMXSrcOp.getOpcode() == ISD::BITCAST &&
20903         MMXSrcOp.getValueType() == MVT::v1i64 &&
20904         MMXSrcOp.getOperand(0).getValueType() == MVT::x86mmx)
20905       return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
20906                          N->getValueType(0),
20907                          MMXSrcOp.getOperand(0));
20908   }
20909
20910   EVT VT = N->getValueType(0);
20911   
20912   if (VT == MVT::i1 && dyn_cast<ConstantSDNode>(N->getOperand(1)) &&
20913       InputVector.getOpcode() == ISD::BITCAST &&
20914       dyn_cast<ConstantSDNode>(InputVector.getOperand(0))) {
20915     uint64_t ExtractedElt =
20916           cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
20917     uint64_t InputValue =
20918           cast<ConstantSDNode>(InputVector.getOperand(0))->getZExtValue();
20919     uint64_t Res = (InputValue >> ExtractedElt) & 1;
20920     return DAG.getConstant(Res, dl, MVT::i1);
20921   }
20922   // Only operate on vectors of 4 elements, where the alternative shuffling
20923   // gets to be more expensive.
20924   if (InputVector.getValueType() != MVT::v4i32)
20925     return SDValue();
20926
20927   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
20928   // single use which is a sign-extend or zero-extend, and all elements are
20929   // used.
20930   SmallVector<SDNode *, 4> Uses;
20931   unsigned ExtractedElements = 0;
20932   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
20933        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
20934     if (UI.getUse().getResNo() != InputVector.getResNo())
20935       return SDValue();
20936
20937     SDNode *Extract = *UI;
20938     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
20939       return SDValue();
20940
20941     if (Extract->getValueType(0) != MVT::i32)
20942       return SDValue();
20943     if (!Extract->hasOneUse())
20944       return SDValue();
20945     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
20946         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
20947       return SDValue();
20948     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
20949       return SDValue();
20950
20951     // Record which element was extracted.
20952     ExtractedElements |=
20953       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
20954
20955     Uses.push_back(Extract);
20956   }
20957
20958   // If not all the elements were used, this may not be worthwhile.
20959   if (ExtractedElements != 15)
20960     return SDValue();
20961
20962   // Ok, we've now decided to do the transformation.
20963   // If 64-bit shifts are legal, use the extract-shift sequence,
20964   // otherwise bounce the vector off the cache.
20965   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20966   SDValue Vals[4];
20967
20968   if (TLI.isOperationLegal(ISD::SRA, MVT::i64)) {
20969     SDValue Cst = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, InputVector);
20970     EVT VecIdxTy = DAG.getTargetLoweringInfo().getVectorIdxTy();
20971     SDValue BottomHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
20972       DAG.getConstant(0, dl, VecIdxTy));
20973     SDValue TopHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
20974       DAG.getConstant(1, dl, VecIdxTy));
20975
20976     SDValue ShAmt = DAG.getConstant(32, dl,
20977       DAG.getTargetLoweringInfo().getShiftAmountTy(MVT::i64));
20978     Vals[0] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BottomHalf);
20979     Vals[1] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
20980       DAG.getNode(ISD::SRA, dl, MVT::i64, BottomHalf, ShAmt));
20981     Vals[2] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, TopHalf);
20982     Vals[3] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
20983       DAG.getNode(ISD::SRA, dl, MVT::i64, TopHalf, ShAmt));
20984   } else {
20985     // Store the value to a temporary stack slot.
20986     SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
20987     SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
20988       MachinePointerInfo(), false, false, 0);
20989
20990     EVT ElementType = InputVector.getValueType().getVectorElementType();
20991     unsigned EltSize = ElementType.getSizeInBits() / 8;
20992
20993     // Replace each use (extract) with a load of the appropriate element.
20994     for (unsigned i = 0; i < 4; ++i) {
20995       uint64_t Offset = EltSize * i;
20996       SDValue OffsetVal = DAG.getConstant(Offset, dl, TLI.getPointerTy());
20997
20998       SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
20999                                        StackPtr, OffsetVal);
21000
21001       // Load the scalar.
21002       Vals[i] = DAG.getLoad(ElementType, dl, Ch,
21003                             ScalarAddr, MachinePointerInfo(),
21004                             false, false, false, 0);
21005
21006     }
21007   }
21008
21009   // Replace the extracts
21010   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
21011     UE = Uses.end(); UI != UE; ++UI) {
21012     SDNode *Extract = *UI;
21013
21014     SDValue Idx = Extract->getOperand(1);
21015     uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
21016     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), Vals[IdxVal]);
21017   }
21018
21019   // The replacement was made in place; don't return anything.
21020   return SDValue();
21021 }
21022
21023 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
21024 static std::pair<unsigned, bool>
21025 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
21026                    SelectionDAG &DAG, const X86Subtarget *Subtarget) {
21027   if (!VT.isVector())
21028     return std::make_pair(0, false);
21029
21030   bool NeedSplit = false;
21031   switch (VT.getSimpleVT().SimpleTy) {
21032   default: return std::make_pair(0, false);
21033   case MVT::v4i64:
21034   case MVT::v2i64:
21035     if (!Subtarget->hasVLX())
21036       return std::make_pair(0, false);
21037     break;
21038   case MVT::v64i8:
21039   case MVT::v32i16:
21040     if (!Subtarget->hasBWI())
21041       return std::make_pair(0, false);
21042     break;
21043   case MVT::v16i32:
21044   case MVT::v8i64:
21045     if (!Subtarget->hasAVX512())
21046       return std::make_pair(0, false);
21047     break;
21048   case MVT::v32i8:
21049   case MVT::v16i16:
21050   case MVT::v8i32:
21051     if (!Subtarget->hasAVX2())
21052       NeedSplit = true;
21053     if (!Subtarget->hasAVX())
21054       return std::make_pair(0, false);
21055     break;
21056   case MVT::v16i8:
21057   case MVT::v8i16:
21058   case MVT::v4i32:
21059     if (!Subtarget->hasSSE2())
21060       return std::make_pair(0, false);
21061   }
21062
21063   // SSE2 has only a small subset of the operations.
21064   bool hasUnsigned = Subtarget->hasSSE41() ||
21065                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
21066   bool hasSigned = Subtarget->hasSSE41() ||
21067                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
21068
21069   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
21070
21071   unsigned Opc = 0;
21072   // Check for x CC y ? x : y.
21073   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
21074       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
21075     switch (CC) {
21076     default: break;
21077     case ISD::SETULT:
21078     case ISD::SETULE:
21079       Opc = hasUnsigned ? X86ISD::UMIN : 0u; break;
21080     case ISD::SETUGT:
21081     case ISD::SETUGE:
21082       Opc = hasUnsigned ? X86ISD::UMAX : 0u; break;
21083     case ISD::SETLT:
21084     case ISD::SETLE:
21085       Opc = hasSigned ? X86ISD::SMIN : 0u; break;
21086     case ISD::SETGT:
21087     case ISD::SETGE:
21088       Opc = hasSigned ? X86ISD::SMAX : 0u; break;
21089     }
21090   // Check for x CC y ? y : x -- a min/max with reversed arms.
21091   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
21092              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
21093     switch (CC) {
21094     default: break;
21095     case ISD::SETULT:
21096     case ISD::SETULE:
21097       Opc = hasUnsigned ? X86ISD::UMAX : 0u; break;
21098     case ISD::SETUGT:
21099     case ISD::SETUGE:
21100       Opc = hasUnsigned ? X86ISD::UMIN : 0u; break;
21101     case ISD::SETLT:
21102     case ISD::SETLE:
21103       Opc = hasSigned ? X86ISD::SMAX : 0u; break;
21104     case ISD::SETGT:
21105     case ISD::SETGE:
21106       Opc = hasSigned ? X86ISD::SMIN : 0u; break;
21107     }
21108   }
21109
21110   return std::make_pair(Opc, NeedSplit);
21111 }
21112
21113 static SDValue
21114 transformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
21115                                       const X86Subtarget *Subtarget) {
21116   SDLoc dl(N);
21117   SDValue Cond = N->getOperand(0);
21118   SDValue LHS = N->getOperand(1);
21119   SDValue RHS = N->getOperand(2);
21120
21121   if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
21122     SDValue CondSrc = Cond->getOperand(0);
21123     if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
21124       Cond = CondSrc->getOperand(0);
21125   }
21126
21127   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
21128     return SDValue();
21129
21130   // A vselect where all conditions and data are constants can be optimized into
21131   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
21132   if (ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
21133       ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
21134     return SDValue();
21135
21136   unsigned MaskValue = 0;
21137   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
21138     return SDValue();
21139
21140   MVT VT = N->getSimpleValueType(0);
21141   unsigned NumElems = VT.getVectorNumElements();
21142   SmallVector<int, 8> ShuffleMask(NumElems, -1);
21143   for (unsigned i = 0; i < NumElems; ++i) {
21144     // Be sure we emit undef where we can.
21145     if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
21146       ShuffleMask[i] = -1;
21147     else
21148       ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
21149   }
21150
21151   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21152   if (!TLI.isShuffleMaskLegal(ShuffleMask, VT))
21153     return SDValue();
21154   return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
21155 }
21156
21157 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
21158 /// nodes.
21159 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
21160                                     TargetLowering::DAGCombinerInfo &DCI,
21161                                     const X86Subtarget *Subtarget) {
21162   SDLoc DL(N);
21163   SDValue Cond = N->getOperand(0);
21164   // Get the LHS/RHS of the select.
21165   SDValue LHS = N->getOperand(1);
21166   SDValue RHS = N->getOperand(2);
21167   EVT VT = LHS.getValueType();
21168   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21169
21170   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
21171   // instructions match the semantics of the common C idiom x<y?x:y but not
21172   // x<=y?x:y, because of how they handle negative zero (which can be
21173   // ignored in unsafe-math mode).
21174   // We also try to create v2f32 min/max nodes, which we later widen to v4f32.
21175   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
21176       VT != MVT::f80 && (TLI.isTypeLegal(VT) || VT == MVT::v2f32) &&
21177       (Subtarget->hasSSE2() ||
21178        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
21179     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
21180
21181     unsigned Opcode = 0;
21182     // Check for x CC y ? x : y.
21183     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
21184         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
21185       switch (CC) {
21186       default: break;
21187       case ISD::SETULT:
21188         // Converting this to a min would handle NaNs incorrectly, and swapping
21189         // the operands would cause it to handle comparisons between positive
21190         // and negative zero incorrectly.
21191         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
21192           if (!DAG.getTarget().Options.UnsafeFPMath &&
21193               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
21194             break;
21195           std::swap(LHS, RHS);
21196         }
21197         Opcode = X86ISD::FMIN;
21198         break;
21199       case ISD::SETOLE:
21200         // Converting this to a min would handle comparisons between positive
21201         // and negative zero incorrectly.
21202         if (!DAG.getTarget().Options.UnsafeFPMath &&
21203             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
21204           break;
21205         Opcode = X86ISD::FMIN;
21206         break;
21207       case ISD::SETULE:
21208         // Converting this to a min would handle both negative zeros and NaNs
21209         // incorrectly, but we can swap the operands to fix both.
21210         std::swap(LHS, RHS);
21211       case ISD::SETOLT:
21212       case ISD::SETLT:
21213       case ISD::SETLE:
21214         Opcode = X86ISD::FMIN;
21215         break;
21216
21217       case ISD::SETOGE:
21218         // Converting this to a max would handle comparisons between positive
21219         // and negative zero incorrectly.
21220         if (!DAG.getTarget().Options.UnsafeFPMath &&
21221             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
21222           break;
21223         Opcode = X86ISD::FMAX;
21224         break;
21225       case ISD::SETUGT:
21226         // Converting this to a max would handle NaNs incorrectly, and swapping
21227         // the operands would cause it to handle comparisons between positive
21228         // and negative zero incorrectly.
21229         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
21230           if (!DAG.getTarget().Options.UnsafeFPMath &&
21231               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
21232             break;
21233           std::swap(LHS, RHS);
21234         }
21235         Opcode = X86ISD::FMAX;
21236         break;
21237       case ISD::SETUGE:
21238         // Converting this to a max would handle both negative zeros and NaNs
21239         // incorrectly, but we can swap the operands to fix both.
21240         std::swap(LHS, RHS);
21241       case ISD::SETOGT:
21242       case ISD::SETGT:
21243       case ISD::SETGE:
21244         Opcode = X86ISD::FMAX;
21245         break;
21246       }
21247     // Check for x CC y ? y : x -- a min/max with reversed arms.
21248     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
21249                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
21250       switch (CC) {
21251       default: break;
21252       case ISD::SETOGE:
21253         // Converting this to a min would handle comparisons between positive
21254         // and negative zero incorrectly, and swapping the operands would
21255         // cause it to handle NaNs incorrectly.
21256         if (!DAG.getTarget().Options.UnsafeFPMath &&
21257             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
21258           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
21259             break;
21260           std::swap(LHS, RHS);
21261         }
21262         Opcode = X86ISD::FMIN;
21263         break;
21264       case ISD::SETUGT:
21265         // Converting this to a min would handle NaNs incorrectly.
21266         if (!DAG.getTarget().Options.UnsafeFPMath &&
21267             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
21268           break;
21269         Opcode = X86ISD::FMIN;
21270         break;
21271       case ISD::SETUGE:
21272         // Converting this to a min would handle both negative zeros and NaNs
21273         // incorrectly, but we can swap the operands to fix both.
21274         std::swap(LHS, RHS);
21275       case ISD::SETOGT:
21276       case ISD::SETGT:
21277       case ISD::SETGE:
21278         Opcode = X86ISD::FMIN;
21279         break;
21280
21281       case ISD::SETULT:
21282         // Converting this to a max would handle NaNs incorrectly.
21283         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
21284           break;
21285         Opcode = X86ISD::FMAX;
21286         break;
21287       case ISD::SETOLE:
21288         // Converting this to a max would handle comparisons between positive
21289         // and negative zero incorrectly, and swapping the operands would
21290         // cause it to handle NaNs incorrectly.
21291         if (!DAG.getTarget().Options.UnsafeFPMath &&
21292             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
21293           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
21294             break;
21295           std::swap(LHS, RHS);
21296         }
21297         Opcode = X86ISD::FMAX;
21298         break;
21299       case ISD::SETULE:
21300         // Converting this to a max would handle both negative zeros and NaNs
21301         // incorrectly, but we can swap the operands to fix both.
21302         std::swap(LHS, RHS);
21303       case ISD::SETOLT:
21304       case ISD::SETLT:
21305       case ISD::SETLE:
21306         Opcode = X86ISD::FMAX;
21307         break;
21308       }
21309     }
21310
21311     if (Opcode)
21312       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
21313   }
21314
21315   EVT CondVT = Cond.getValueType();
21316   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
21317       CondVT.getVectorElementType() == MVT::i1) {
21318     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
21319     // lowering on KNL. In this case we convert it to
21320     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
21321     // The same situation for all 128 and 256-bit vectors of i8 and i16.
21322     // Since SKX these selects have a proper lowering.
21323     EVT OpVT = LHS.getValueType();
21324     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
21325         (OpVT.getVectorElementType() == MVT::i8 ||
21326          OpVT.getVectorElementType() == MVT::i16) &&
21327         !(Subtarget->hasBWI() && Subtarget->hasVLX())) {
21328       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
21329       DCI.AddToWorklist(Cond.getNode());
21330       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
21331     }
21332   }
21333   // If this is a select between two integer constants, try to do some
21334   // optimizations.
21335   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
21336     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
21337       // Don't do this for crazy integer types.
21338       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
21339         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
21340         // so that TrueC (the true value) is larger than FalseC.
21341         bool NeedsCondInvert = false;
21342
21343         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
21344             // Efficiently invertible.
21345             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
21346              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
21347               isa<ConstantSDNode>(Cond.getOperand(1))))) {
21348           NeedsCondInvert = true;
21349           std::swap(TrueC, FalseC);
21350         }
21351
21352         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
21353         if (FalseC->getAPIntValue() == 0 &&
21354             TrueC->getAPIntValue().isPowerOf2()) {
21355           if (NeedsCondInvert) // Invert the condition if needed.
21356             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
21357                                DAG.getConstant(1, DL, Cond.getValueType()));
21358
21359           // Zero extend the condition if needed.
21360           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
21361
21362           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
21363           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
21364                              DAG.getConstant(ShAmt, DL, MVT::i8));
21365         }
21366
21367         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
21368         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
21369           if (NeedsCondInvert) // Invert the condition if needed.
21370             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
21371                                DAG.getConstant(1, DL, Cond.getValueType()));
21372
21373           // Zero extend the condition if needed.
21374           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
21375                              FalseC->getValueType(0), Cond);
21376           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
21377                              SDValue(FalseC, 0));
21378         }
21379
21380         // Optimize cases that will turn into an LEA instruction.  This requires
21381         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
21382         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
21383           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
21384           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
21385
21386           bool isFastMultiplier = false;
21387           if (Diff < 10) {
21388             switch ((unsigned char)Diff) {
21389               default: break;
21390               case 1:  // result = add base, cond
21391               case 2:  // result = lea base(    , cond*2)
21392               case 3:  // result = lea base(cond, cond*2)
21393               case 4:  // result = lea base(    , cond*4)
21394               case 5:  // result = lea base(cond, cond*4)
21395               case 8:  // result = lea base(    , cond*8)
21396               case 9:  // result = lea base(cond, cond*8)
21397                 isFastMultiplier = true;
21398                 break;
21399             }
21400           }
21401
21402           if (isFastMultiplier) {
21403             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
21404             if (NeedsCondInvert) // Invert the condition if needed.
21405               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
21406                                  DAG.getConstant(1, DL, Cond.getValueType()));
21407
21408             // Zero extend the condition if needed.
21409             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
21410                                Cond);
21411             // Scale the condition by the difference.
21412             if (Diff != 1)
21413               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
21414                                  DAG.getConstant(Diff, DL,
21415                                                  Cond.getValueType()));
21416
21417             // Add the base if non-zero.
21418             if (FalseC->getAPIntValue() != 0)
21419               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
21420                                  SDValue(FalseC, 0));
21421             return Cond;
21422           }
21423         }
21424       }
21425   }
21426
21427   // Canonicalize max and min:
21428   // (x > y) ? x : y -> (x >= y) ? x : y
21429   // (x < y) ? x : y -> (x <= y) ? x : y
21430   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
21431   // the need for an extra compare
21432   // against zero. e.g.
21433   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
21434   // subl   %esi, %edi
21435   // testl  %edi, %edi
21436   // movl   $0, %eax
21437   // cmovgl %edi, %eax
21438   // =>
21439   // xorl   %eax, %eax
21440   // subl   %esi, $edi
21441   // cmovsl %eax, %edi
21442   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
21443       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
21444       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
21445     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
21446     switch (CC) {
21447     default: break;
21448     case ISD::SETLT:
21449     case ISD::SETGT: {
21450       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
21451       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
21452                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
21453       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
21454     }
21455     }
21456   }
21457
21458   // Early exit check
21459   if (!TLI.isTypeLegal(VT))
21460     return SDValue();
21461
21462   // Match VSELECTs into subs with unsigned saturation.
21463   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
21464       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
21465       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
21466        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
21467     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
21468
21469     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
21470     // left side invert the predicate to simplify logic below.
21471     SDValue Other;
21472     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
21473       Other = RHS;
21474       CC = ISD::getSetCCInverse(CC, true);
21475     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
21476       Other = LHS;
21477     }
21478
21479     if (Other.getNode() && Other->getNumOperands() == 2 &&
21480         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
21481       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
21482       SDValue CondRHS = Cond->getOperand(1);
21483
21484       // Look for a general sub with unsigned saturation first.
21485       // x >= y ? x-y : 0 --> subus x, y
21486       // x >  y ? x-y : 0 --> subus x, y
21487       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
21488           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
21489         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
21490
21491       if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
21492         if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
21493           if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
21494             if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
21495               // If the RHS is a constant we have to reverse the const
21496               // canonicalization.
21497               // x > C-1 ? x+-C : 0 --> subus x, C
21498               if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
21499                   CondRHSConst->getAPIntValue() ==
21500                       (-OpRHSConst->getAPIntValue() - 1))
21501                 return DAG.getNode(
21502                     X86ISD::SUBUS, DL, VT, OpLHS,
21503                     DAG.getConstant(-OpRHSConst->getAPIntValue(), DL, VT));
21504
21505           // Another special case: If C was a sign bit, the sub has been
21506           // canonicalized into a xor.
21507           // FIXME: Would it be better to use computeKnownBits to determine
21508           //        whether it's safe to decanonicalize the xor?
21509           // x s< 0 ? x^C : 0 --> subus x, C
21510           if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
21511               ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
21512               OpRHSConst->getAPIntValue().isSignBit())
21513             // Note that we have to rebuild the RHS constant here to ensure we
21514             // don't rely on particular values of undef lanes.
21515             return DAG.getNode(
21516                 X86ISD::SUBUS, DL, VT, OpLHS,
21517                 DAG.getConstant(OpRHSConst->getAPIntValue(), DL, VT));
21518         }
21519     }
21520   }
21521
21522   // Try to match a min/max vector operation.
21523   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
21524     std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
21525     unsigned Opc = ret.first;
21526     bool NeedSplit = ret.second;
21527
21528     if (Opc && NeedSplit) {
21529       unsigned NumElems = VT.getVectorNumElements();
21530       // Extract the LHS vectors
21531       SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
21532       SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
21533
21534       // Extract the RHS vectors
21535       SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
21536       SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
21537
21538       // Create min/max for each subvector
21539       LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
21540       RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
21541
21542       // Merge the result
21543       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
21544     } else if (Opc)
21545       return DAG.getNode(Opc, DL, VT, LHS, RHS);
21546   }
21547
21548   // Simplify vector selection if condition value type matches vselect
21549   // operand type
21550   if (N->getOpcode() == ISD::VSELECT && CondVT == VT) {
21551     assert(Cond.getValueType().isVector() &&
21552            "vector select expects a vector selector!");
21553
21554     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
21555     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
21556
21557     // Try invert the condition if true value is not all 1s and false value
21558     // is not all 0s.
21559     if (!TValIsAllOnes && !FValIsAllZeros &&
21560         // Check if the selector will be produced by CMPP*/PCMP*
21561         Cond.getOpcode() == ISD::SETCC &&
21562         // Check if SETCC has already been promoted
21563         TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT) {
21564       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
21565       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
21566
21567       if (TValIsAllZeros || FValIsAllOnes) {
21568         SDValue CC = Cond.getOperand(2);
21569         ISD::CondCode NewCC =
21570           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
21571                                Cond.getOperand(0).getValueType().isInteger());
21572         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
21573         std::swap(LHS, RHS);
21574         TValIsAllOnes = FValIsAllOnes;
21575         FValIsAllZeros = TValIsAllZeros;
21576       }
21577     }
21578
21579     if (TValIsAllOnes || FValIsAllZeros) {
21580       SDValue Ret;
21581
21582       if (TValIsAllOnes && FValIsAllZeros)
21583         Ret = Cond;
21584       else if (TValIsAllOnes)
21585         Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
21586                           DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
21587       else if (FValIsAllZeros)
21588         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
21589                           DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
21590
21591       return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
21592     }
21593   }
21594
21595   // We should generate an X86ISD::BLENDI from a vselect if its argument
21596   // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
21597   // constants. This specific pattern gets generated when we split a
21598   // selector for a 512 bit vector in a machine without AVX512 (but with
21599   // 256-bit vectors), during legalization:
21600   //
21601   // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
21602   //
21603   // Iff we find this pattern and the build_vectors are built from
21604   // constants, we translate the vselect into a shuffle_vector that we
21605   // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
21606   if ((N->getOpcode() == ISD::VSELECT ||
21607        N->getOpcode() == X86ISD::SHRUNKBLEND) &&
21608       !DCI.isBeforeLegalize()) {
21609     SDValue Shuffle = transformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
21610     if (Shuffle.getNode())
21611       return Shuffle;
21612   }
21613
21614   // If this is a *dynamic* select (non-constant condition) and we can match
21615   // this node with one of the variable blend instructions, restructure the
21616   // condition so that the blends can use the high bit of each element and use
21617   // SimplifyDemandedBits to simplify the condition operand.
21618   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
21619       !DCI.isBeforeLegalize() &&
21620       !ISD::isBuildVectorOfConstantSDNodes(Cond.getNode())) {
21621     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
21622
21623     // Don't optimize vector selects that map to mask-registers.
21624     if (BitWidth == 1)
21625       return SDValue();
21626
21627     // We can only handle the cases where VSELECT is directly legal on the
21628     // subtarget. We custom lower VSELECT nodes with constant conditions and
21629     // this makes it hard to see whether a dynamic VSELECT will correctly
21630     // lower, so we both check the operation's status and explicitly handle the
21631     // cases where a *dynamic* blend will fail even though a constant-condition
21632     // blend could be custom lowered.
21633     // FIXME: We should find a better way to handle this class of problems.
21634     // Potentially, we should combine constant-condition vselect nodes
21635     // pre-legalization into shuffles and not mark as many types as custom
21636     // lowered.
21637     if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
21638       return SDValue();
21639     // FIXME: We don't support i16-element blends currently. We could and
21640     // should support them by making *all* the bits in the condition be set
21641     // rather than just the high bit and using an i8-element blend.
21642     if (VT.getScalarType() == MVT::i16)
21643       return SDValue();
21644     // Dynamic blending was only available from SSE4.1 onward.
21645     if (VT.getSizeInBits() == 128 && !Subtarget->hasSSE41())
21646       return SDValue();
21647     // Byte blends are only available in AVX2
21648     if (VT.getSizeInBits() == 256 && VT.getScalarType() == MVT::i8 &&
21649         !Subtarget->hasAVX2())
21650       return SDValue();
21651
21652     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
21653     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
21654
21655     APInt KnownZero, KnownOne;
21656     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
21657                                           DCI.isBeforeLegalizeOps());
21658     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
21659         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne,
21660                                  TLO)) {
21661       // If we changed the computation somewhere in the DAG, this change
21662       // will affect all users of Cond.
21663       // Make sure it is fine and update all the nodes so that we do not
21664       // use the generic VSELECT anymore. Otherwise, we may perform
21665       // wrong optimizations as we messed up with the actual expectation
21666       // for the vector boolean values.
21667       if (Cond != TLO.Old) {
21668         // Check all uses of that condition operand to check whether it will be
21669         // consumed by non-BLEND instructions, which may depend on all bits are
21670         // set properly.
21671         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
21672              I != E; ++I)
21673           if (I->getOpcode() != ISD::VSELECT)
21674             // TODO: Add other opcodes eventually lowered into BLEND.
21675             return SDValue();
21676
21677         // Update all the users of the condition, before committing the change,
21678         // so that the VSELECT optimizations that expect the correct vector
21679         // boolean value will not be triggered.
21680         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
21681              I != E; ++I)
21682           DAG.ReplaceAllUsesOfValueWith(
21683               SDValue(*I, 0),
21684               DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(*I), I->getValueType(0),
21685                           Cond, I->getOperand(1), I->getOperand(2)));
21686         DCI.CommitTargetLoweringOpt(TLO);
21687         return SDValue();
21688       }
21689       // At this point, only Cond is changed. Change the condition
21690       // just for N to keep the opportunity to optimize all other
21691       // users their own way.
21692       DAG.ReplaceAllUsesOfValueWith(
21693           SDValue(N, 0),
21694           DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(N), N->getValueType(0),
21695                       TLO.New, N->getOperand(1), N->getOperand(2)));
21696       return SDValue();
21697     }
21698   }
21699
21700   return SDValue();
21701 }
21702
21703 // Check whether a boolean test is testing a boolean value generated by
21704 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
21705 // code.
21706 //
21707 // Simplify the following patterns:
21708 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
21709 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
21710 // to (Op EFLAGS Cond)
21711 //
21712 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
21713 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
21714 // to (Op EFLAGS !Cond)
21715 //
21716 // where Op could be BRCOND or CMOV.
21717 //
21718 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
21719   // Quit if not CMP and SUB with its value result used.
21720   if (Cmp.getOpcode() != X86ISD::CMP &&
21721       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
21722       return SDValue();
21723
21724   // Quit if not used as a boolean value.
21725   if (CC != X86::COND_E && CC != X86::COND_NE)
21726     return SDValue();
21727
21728   // Check CMP operands. One of them should be 0 or 1 and the other should be
21729   // an SetCC or extended from it.
21730   SDValue Op1 = Cmp.getOperand(0);
21731   SDValue Op2 = Cmp.getOperand(1);
21732
21733   SDValue SetCC;
21734   const ConstantSDNode* C = nullptr;
21735   bool needOppositeCond = (CC == X86::COND_E);
21736   bool checkAgainstTrue = false; // Is it a comparison against 1?
21737
21738   if ((C = dyn_cast<ConstantSDNode>(Op1)))
21739     SetCC = Op2;
21740   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
21741     SetCC = Op1;
21742   else // Quit if all operands are not constants.
21743     return SDValue();
21744
21745   if (C->getZExtValue() == 1) {
21746     needOppositeCond = !needOppositeCond;
21747     checkAgainstTrue = true;
21748   } else if (C->getZExtValue() != 0)
21749     // Quit if the constant is neither 0 or 1.
21750     return SDValue();
21751
21752   bool truncatedToBoolWithAnd = false;
21753   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
21754   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
21755          SetCC.getOpcode() == ISD::TRUNCATE ||
21756          SetCC.getOpcode() == ISD::AND) {
21757     if (SetCC.getOpcode() == ISD::AND) {
21758       int OpIdx = -1;
21759       ConstantSDNode *CS;
21760       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
21761           CS->getZExtValue() == 1)
21762         OpIdx = 1;
21763       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
21764           CS->getZExtValue() == 1)
21765         OpIdx = 0;
21766       if (OpIdx == -1)
21767         break;
21768       SetCC = SetCC.getOperand(OpIdx);
21769       truncatedToBoolWithAnd = true;
21770     } else
21771       SetCC = SetCC.getOperand(0);
21772   }
21773
21774   switch (SetCC.getOpcode()) {
21775   case X86ISD::SETCC_CARRY:
21776     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
21777     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
21778     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
21779     // truncated to i1 using 'and'.
21780     if (checkAgainstTrue && !truncatedToBoolWithAnd)
21781       break;
21782     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
21783            "Invalid use of SETCC_CARRY!");
21784     // FALL THROUGH
21785   case X86ISD::SETCC:
21786     // Set the condition code or opposite one if necessary.
21787     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
21788     if (needOppositeCond)
21789       CC = X86::GetOppositeBranchCondition(CC);
21790     return SetCC.getOperand(1);
21791   case X86ISD::CMOV: {
21792     // Check whether false/true value has canonical one, i.e. 0 or 1.
21793     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
21794     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
21795     // Quit if true value is not a constant.
21796     if (!TVal)
21797       return SDValue();
21798     // Quit if false value is not a constant.
21799     if (!FVal) {
21800       SDValue Op = SetCC.getOperand(0);
21801       // Skip 'zext' or 'trunc' node.
21802       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
21803           Op.getOpcode() == ISD::TRUNCATE)
21804         Op = Op.getOperand(0);
21805       // A special case for rdrand/rdseed, where 0 is set if false cond is
21806       // found.
21807       if ((Op.getOpcode() != X86ISD::RDRAND &&
21808            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
21809         return SDValue();
21810     }
21811     // Quit if false value is not the constant 0 or 1.
21812     bool FValIsFalse = true;
21813     if (FVal && FVal->getZExtValue() != 0) {
21814       if (FVal->getZExtValue() != 1)
21815         return SDValue();
21816       // If FVal is 1, opposite cond is needed.
21817       needOppositeCond = !needOppositeCond;
21818       FValIsFalse = false;
21819     }
21820     // Quit if TVal is not the constant opposite of FVal.
21821     if (FValIsFalse && TVal->getZExtValue() != 1)
21822       return SDValue();
21823     if (!FValIsFalse && TVal->getZExtValue() != 0)
21824       return SDValue();
21825     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
21826     if (needOppositeCond)
21827       CC = X86::GetOppositeBranchCondition(CC);
21828     return SetCC.getOperand(3);
21829   }
21830   }
21831
21832   return SDValue();
21833 }
21834
21835 /// Check whether Cond is an AND/OR of SETCCs off of the same EFLAGS.
21836 /// Match:
21837 ///   (X86or (X86setcc) (X86setcc))
21838 ///   (X86cmp (and (X86setcc) (X86setcc)), 0)
21839 static bool checkBoolTestAndOrSetCCCombine(SDValue Cond, X86::CondCode &CC0,
21840                                            X86::CondCode &CC1, SDValue &Flags,
21841                                            bool &isAnd) {
21842   if (Cond->getOpcode() == X86ISD::CMP) {
21843     ConstantSDNode *CondOp1C = dyn_cast<ConstantSDNode>(Cond->getOperand(1));
21844     if (!CondOp1C || !CondOp1C->isNullValue())
21845       return false;
21846
21847     Cond = Cond->getOperand(0);
21848   }
21849
21850   isAnd = false;
21851
21852   SDValue SetCC0, SetCC1;
21853   switch (Cond->getOpcode()) {
21854   default: return false;
21855   case ISD::AND:
21856   case X86ISD::AND:
21857     isAnd = true;
21858     // fallthru
21859   case ISD::OR:
21860   case X86ISD::OR:
21861     SetCC0 = Cond->getOperand(0);
21862     SetCC1 = Cond->getOperand(1);
21863     break;
21864   };
21865
21866   // Make sure we have SETCC nodes, using the same flags value.
21867   if (SetCC0.getOpcode() != X86ISD::SETCC ||
21868       SetCC1.getOpcode() != X86ISD::SETCC ||
21869       SetCC0->getOperand(1) != SetCC1->getOperand(1))
21870     return false;
21871
21872   CC0 = (X86::CondCode)SetCC0->getConstantOperandVal(0);
21873   CC1 = (X86::CondCode)SetCC1->getConstantOperandVal(0);
21874   Flags = SetCC0->getOperand(1);
21875   return true;
21876 }
21877
21878 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
21879 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
21880                                   TargetLowering::DAGCombinerInfo &DCI,
21881                                   const X86Subtarget *Subtarget) {
21882   SDLoc DL(N);
21883
21884   // If the flag operand isn't dead, don't touch this CMOV.
21885   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
21886     return SDValue();
21887
21888   SDValue FalseOp = N->getOperand(0);
21889   SDValue TrueOp = N->getOperand(1);
21890   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
21891   SDValue Cond = N->getOperand(3);
21892
21893   if (CC == X86::COND_E || CC == X86::COND_NE) {
21894     switch (Cond.getOpcode()) {
21895     default: break;
21896     case X86ISD::BSR:
21897     case X86ISD::BSF:
21898       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
21899       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
21900         return (CC == X86::COND_E) ? FalseOp : TrueOp;
21901     }
21902   }
21903
21904   SDValue Flags;
21905
21906   Flags = checkBoolTestSetCCCombine(Cond, CC);
21907   if (Flags.getNode() &&
21908       // Extra check as FCMOV only supports a subset of X86 cond.
21909       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
21910     SDValue Ops[] = { FalseOp, TrueOp,
21911                       DAG.getConstant(CC, DL, MVT::i8), Flags };
21912     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
21913   }
21914
21915   // If this is a select between two integer constants, try to do some
21916   // optimizations.  Note that the operands are ordered the opposite of SELECT
21917   // operands.
21918   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
21919     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
21920       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
21921       // larger than FalseC (the false value).
21922       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
21923         CC = X86::GetOppositeBranchCondition(CC);
21924         std::swap(TrueC, FalseC);
21925         std::swap(TrueOp, FalseOp);
21926       }
21927
21928       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
21929       // This is efficient for any integer data type (including i8/i16) and
21930       // shift amount.
21931       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
21932         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
21933                            DAG.getConstant(CC, DL, MVT::i8), Cond);
21934
21935         // Zero extend the condition if needed.
21936         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
21937
21938         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
21939         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
21940                            DAG.getConstant(ShAmt, DL, MVT::i8));
21941         if (N->getNumValues() == 2)  // Dead flag value?
21942           return DCI.CombineTo(N, Cond, SDValue());
21943         return Cond;
21944       }
21945
21946       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
21947       // for any integer data type, including i8/i16.
21948       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
21949         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
21950                            DAG.getConstant(CC, DL, MVT::i8), Cond);
21951
21952         // Zero extend the condition if needed.
21953         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
21954                            FalseC->getValueType(0), Cond);
21955         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
21956                            SDValue(FalseC, 0));
21957
21958         if (N->getNumValues() == 2)  // Dead flag value?
21959           return DCI.CombineTo(N, Cond, SDValue());
21960         return Cond;
21961       }
21962
21963       // Optimize cases that will turn into an LEA instruction.  This requires
21964       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
21965       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
21966         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
21967         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
21968
21969         bool isFastMultiplier = false;
21970         if (Diff < 10) {
21971           switch ((unsigned char)Diff) {
21972           default: break;
21973           case 1:  // result = add base, cond
21974           case 2:  // result = lea base(    , cond*2)
21975           case 3:  // result = lea base(cond, cond*2)
21976           case 4:  // result = lea base(    , cond*4)
21977           case 5:  // result = lea base(cond, cond*4)
21978           case 8:  // result = lea base(    , cond*8)
21979           case 9:  // result = lea base(cond, cond*8)
21980             isFastMultiplier = true;
21981             break;
21982           }
21983         }
21984
21985         if (isFastMultiplier) {
21986           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
21987           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
21988                              DAG.getConstant(CC, DL, MVT::i8), Cond);
21989           // Zero extend the condition if needed.
21990           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
21991                              Cond);
21992           // Scale the condition by the difference.
21993           if (Diff != 1)
21994             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
21995                                DAG.getConstant(Diff, DL, Cond.getValueType()));
21996
21997           // Add the base if non-zero.
21998           if (FalseC->getAPIntValue() != 0)
21999             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
22000                                SDValue(FalseC, 0));
22001           if (N->getNumValues() == 2)  // Dead flag value?
22002             return DCI.CombineTo(N, Cond, SDValue());
22003           return Cond;
22004         }
22005       }
22006     }
22007   }
22008
22009   // Handle these cases:
22010   //   (select (x != c), e, c) -> select (x != c), e, x),
22011   //   (select (x == c), c, e) -> select (x == c), x, e)
22012   // where the c is an integer constant, and the "select" is the combination
22013   // of CMOV and CMP.
22014   //
22015   // The rationale for this change is that the conditional-move from a constant
22016   // needs two instructions, however, conditional-move from a register needs
22017   // only one instruction.
22018   //
22019   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
22020   //  some instruction-combining opportunities. This opt needs to be
22021   //  postponed as late as possible.
22022   //
22023   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
22024     // the DCI.xxxx conditions are provided to postpone the optimization as
22025     // late as possible.
22026
22027     ConstantSDNode *CmpAgainst = nullptr;
22028     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
22029         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
22030         !isa<ConstantSDNode>(Cond.getOperand(0))) {
22031
22032       if (CC == X86::COND_NE &&
22033           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
22034         CC = X86::GetOppositeBranchCondition(CC);
22035         std::swap(TrueOp, FalseOp);
22036       }
22037
22038       if (CC == X86::COND_E &&
22039           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
22040         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
22041                           DAG.getConstant(CC, DL, MVT::i8), Cond };
22042         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
22043       }
22044     }
22045   }
22046
22047   // Fold and/or of setcc's to double CMOV:
22048   //   (CMOV F, T, ((cc1 | cc2) != 0)) -> (CMOV (CMOV F, T, cc1), T, cc2)
22049   //   (CMOV F, T, ((cc1 & cc2) != 0)) -> (CMOV (CMOV T, F, !cc1), F, !cc2)
22050   //
22051   // This combine lets us generate:
22052   //   cmovcc1 (jcc1 if we don't have CMOV)
22053   //   cmovcc2 (same)
22054   // instead of:
22055   //   setcc1
22056   //   setcc2
22057   //   and/or
22058   //   cmovne (jne if we don't have CMOV)
22059   // When we can't use the CMOV instruction, it might increase branch
22060   // mispredicts.
22061   // When we can use CMOV, or when there is no mispredict, this improves
22062   // throughput and reduces register pressure.
22063   //
22064   if (CC == X86::COND_NE) {
22065     SDValue Flags;
22066     X86::CondCode CC0, CC1;
22067     bool isAndSetCC;
22068     if (checkBoolTestAndOrSetCCCombine(Cond, CC0, CC1, Flags, isAndSetCC)) {
22069       if (isAndSetCC) {
22070         std::swap(FalseOp, TrueOp);
22071         CC0 = X86::GetOppositeBranchCondition(CC0);
22072         CC1 = X86::GetOppositeBranchCondition(CC1);
22073       }
22074
22075       SDValue LOps[] = {FalseOp, TrueOp, DAG.getConstant(CC0, DL, MVT::i8),
22076         Flags};
22077       SDValue LCMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), LOps);
22078       SDValue Ops[] = {LCMOV, TrueOp, DAG.getConstant(CC1, DL, MVT::i8), Flags};
22079       SDValue CMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
22080       DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SDValue(CMOV.getNode(), 1));
22081       return CMOV;
22082     }
22083   }
22084
22085   return SDValue();
22086 }
22087
22088 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
22089                                                 const X86Subtarget *Subtarget) {
22090   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
22091   switch (IntNo) {
22092   default: return SDValue();
22093   // SSE/AVX/AVX2 blend intrinsics.
22094   case Intrinsic::x86_avx2_pblendvb:
22095     // Don't try to simplify this intrinsic if we don't have AVX2.
22096     if (!Subtarget->hasAVX2())
22097       return SDValue();
22098     // FALL-THROUGH
22099   case Intrinsic::x86_avx_blendv_pd_256:
22100   case Intrinsic::x86_avx_blendv_ps_256:
22101     // Don't try to simplify this intrinsic if we don't have AVX.
22102     if (!Subtarget->hasAVX())
22103       return SDValue();
22104     // FALL-THROUGH
22105   case Intrinsic::x86_sse41_blendvps:
22106   case Intrinsic::x86_sse41_blendvpd:
22107   case Intrinsic::x86_sse41_pblendvb: {
22108     SDValue Op0 = N->getOperand(1);
22109     SDValue Op1 = N->getOperand(2);
22110     SDValue Mask = N->getOperand(3);
22111
22112     // Don't try to simplify this intrinsic if we don't have SSE4.1.
22113     if (!Subtarget->hasSSE41())
22114       return SDValue();
22115
22116     // fold (blend A, A, Mask) -> A
22117     if (Op0 == Op1)
22118       return Op0;
22119     // fold (blend A, B, allZeros) -> A
22120     if (ISD::isBuildVectorAllZeros(Mask.getNode()))
22121       return Op0;
22122     // fold (blend A, B, allOnes) -> B
22123     if (ISD::isBuildVectorAllOnes(Mask.getNode()))
22124       return Op1;
22125
22126     // Simplify the case where the mask is a constant i32 value.
22127     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
22128       if (C->isNullValue())
22129         return Op0;
22130       if (C->isAllOnesValue())
22131         return Op1;
22132     }
22133
22134     return SDValue();
22135   }
22136
22137   // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
22138   case Intrinsic::x86_sse2_psrai_w:
22139   case Intrinsic::x86_sse2_psrai_d:
22140   case Intrinsic::x86_avx2_psrai_w:
22141   case Intrinsic::x86_avx2_psrai_d:
22142   case Intrinsic::x86_sse2_psra_w:
22143   case Intrinsic::x86_sse2_psra_d:
22144   case Intrinsic::x86_avx2_psra_w:
22145   case Intrinsic::x86_avx2_psra_d: {
22146     SDValue Op0 = N->getOperand(1);
22147     SDValue Op1 = N->getOperand(2);
22148     EVT VT = Op0.getValueType();
22149     assert(VT.isVector() && "Expected a vector type!");
22150
22151     if (isa<BuildVectorSDNode>(Op1))
22152       Op1 = Op1.getOperand(0);
22153
22154     if (!isa<ConstantSDNode>(Op1))
22155       return SDValue();
22156
22157     EVT SVT = VT.getVectorElementType();
22158     unsigned SVTBits = SVT.getSizeInBits();
22159
22160     ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
22161     const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
22162     uint64_t ShAmt = C.getZExtValue();
22163
22164     // Don't try to convert this shift into a ISD::SRA if the shift
22165     // count is bigger than or equal to the element size.
22166     if (ShAmt >= SVTBits)
22167       return SDValue();
22168
22169     // Trivial case: if the shift count is zero, then fold this
22170     // into the first operand.
22171     if (ShAmt == 0)
22172       return Op0;
22173
22174     // Replace this packed shift intrinsic with a target independent
22175     // shift dag node.
22176     SDLoc DL(N);
22177     SDValue Splat = DAG.getConstant(C, DL, VT);
22178     return DAG.getNode(ISD::SRA, DL, VT, Op0, Splat);
22179   }
22180   }
22181 }
22182
22183 /// PerformMulCombine - Optimize a single multiply with constant into two
22184 /// in order to implement it with two cheaper instructions, e.g.
22185 /// LEA + SHL, LEA + LEA.
22186 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
22187                                  TargetLowering::DAGCombinerInfo &DCI) {
22188   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
22189     return SDValue();
22190
22191   EVT VT = N->getValueType(0);
22192   if (VT != MVT::i64 && VT != MVT::i32)
22193     return SDValue();
22194
22195   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
22196   if (!C)
22197     return SDValue();
22198   uint64_t MulAmt = C->getZExtValue();
22199   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
22200     return SDValue();
22201
22202   uint64_t MulAmt1 = 0;
22203   uint64_t MulAmt2 = 0;
22204   if ((MulAmt % 9) == 0) {
22205     MulAmt1 = 9;
22206     MulAmt2 = MulAmt / 9;
22207   } else if ((MulAmt % 5) == 0) {
22208     MulAmt1 = 5;
22209     MulAmt2 = MulAmt / 5;
22210   } else if ((MulAmt % 3) == 0) {
22211     MulAmt1 = 3;
22212     MulAmt2 = MulAmt / 3;
22213   }
22214   if (MulAmt2 &&
22215       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
22216     SDLoc DL(N);
22217
22218     if (isPowerOf2_64(MulAmt2) &&
22219         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
22220       // If second multiplifer is pow2, issue it first. We want the multiply by
22221       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
22222       // is an add.
22223       std::swap(MulAmt1, MulAmt2);
22224
22225     SDValue NewMul;
22226     if (isPowerOf2_64(MulAmt1))
22227       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
22228                            DAG.getConstant(Log2_64(MulAmt1), DL, MVT::i8));
22229     else
22230       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
22231                            DAG.getConstant(MulAmt1, DL, VT));
22232
22233     if (isPowerOf2_64(MulAmt2))
22234       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
22235                            DAG.getConstant(Log2_64(MulAmt2), DL, MVT::i8));
22236     else
22237       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
22238                            DAG.getConstant(MulAmt2, DL, VT));
22239
22240     // Do not add new nodes to DAG combiner worklist.
22241     DCI.CombineTo(N, NewMul, false);
22242   }
22243   return SDValue();
22244 }
22245
22246 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
22247   SDValue N0 = N->getOperand(0);
22248   SDValue N1 = N->getOperand(1);
22249   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
22250   EVT VT = N0.getValueType();
22251
22252   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
22253   // since the result of setcc_c is all zero's or all ones.
22254   if (VT.isInteger() && !VT.isVector() &&
22255       N1C && N0.getOpcode() == ISD::AND &&
22256       N0.getOperand(1).getOpcode() == ISD::Constant) {
22257     SDValue N00 = N0.getOperand(0);
22258     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
22259         ((N00.getOpcode() == ISD::ANY_EXTEND ||
22260           N00.getOpcode() == ISD::ZERO_EXTEND) &&
22261          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
22262       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
22263       APInt ShAmt = N1C->getAPIntValue();
22264       Mask = Mask.shl(ShAmt);
22265       if (Mask != 0) {
22266         SDLoc DL(N);
22267         return DAG.getNode(ISD::AND, DL, VT,
22268                            N00, DAG.getConstant(Mask, DL, VT));
22269       }
22270     }
22271   }
22272
22273   // Hardware support for vector shifts is sparse which makes us scalarize the
22274   // vector operations in many cases. Also, on sandybridge ADD is faster than
22275   // shl.
22276   // (shl V, 1) -> add V,V
22277   if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
22278     if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
22279       assert(N0.getValueType().isVector() && "Invalid vector shift type");
22280       // We shift all of the values by one. In many cases we do not have
22281       // hardware support for this operation. This is better expressed as an ADD
22282       // of two values.
22283       if (N1SplatC->getZExtValue() == 1)
22284         return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
22285     }
22286
22287   return SDValue();
22288 }
22289
22290 /// \brief Returns a vector of 0s if the node in input is a vector logical
22291 /// shift by a constant amount which is known to be bigger than or equal
22292 /// to the vector element size in bits.
22293 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
22294                                       const X86Subtarget *Subtarget) {
22295   EVT VT = N->getValueType(0);
22296
22297   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
22298       (!Subtarget->hasInt256() ||
22299        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
22300     return SDValue();
22301
22302   SDValue Amt = N->getOperand(1);
22303   SDLoc DL(N);
22304   if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
22305     if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
22306       APInt ShiftAmt = AmtSplat->getAPIntValue();
22307       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
22308
22309       // SSE2/AVX2 logical shifts always return a vector of 0s
22310       // if the shift amount is bigger than or equal to
22311       // the element size. The constant shift amount will be
22312       // encoded as a 8-bit immediate.
22313       if (ShiftAmt.trunc(8).uge(MaxAmount))
22314         return getZeroVector(VT, Subtarget, DAG, DL);
22315     }
22316
22317   return SDValue();
22318 }
22319
22320 /// PerformShiftCombine - Combine shifts.
22321 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
22322                                    TargetLowering::DAGCombinerInfo &DCI,
22323                                    const X86Subtarget *Subtarget) {
22324   if (N->getOpcode() == ISD::SHL) {
22325     SDValue V = PerformSHLCombine(N, DAG);
22326     if (V.getNode()) return V;
22327   }
22328
22329   if (N->getOpcode() != ISD::SRA) {
22330     // Try to fold this logical shift into a zero vector.
22331     SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
22332     if (V.getNode()) return V;
22333   }
22334
22335   return SDValue();
22336 }
22337
22338 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
22339 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
22340 // and friends.  Likewise for OR -> CMPNEQSS.
22341 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
22342                             TargetLowering::DAGCombinerInfo &DCI,
22343                             const X86Subtarget *Subtarget) {
22344   unsigned opcode;
22345
22346   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
22347   // we're requiring SSE2 for both.
22348   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
22349     SDValue N0 = N->getOperand(0);
22350     SDValue N1 = N->getOperand(1);
22351     SDValue CMP0 = N0->getOperand(1);
22352     SDValue CMP1 = N1->getOperand(1);
22353     SDLoc DL(N);
22354
22355     // The SETCCs should both refer to the same CMP.
22356     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
22357       return SDValue();
22358
22359     SDValue CMP00 = CMP0->getOperand(0);
22360     SDValue CMP01 = CMP0->getOperand(1);
22361     EVT     VT    = CMP00.getValueType();
22362
22363     if (VT == MVT::f32 || VT == MVT::f64) {
22364       bool ExpectingFlags = false;
22365       // Check for any users that want flags:
22366       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
22367            !ExpectingFlags && UI != UE; ++UI)
22368         switch (UI->getOpcode()) {
22369         default:
22370         case ISD::BR_CC:
22371         case ISD::BRCOND:
22372         case ISD::SELECT:
22373           ExpectingFlags = true;
22374           break;
22375         case ISD::CopyToReg:
22376         case ISD::SIGN_EXTEND:
22377         case ISD::ZERO_EXTEND:
22378         case ISD::ANY_EXTEND:
22379           break;
22380         }
22381
22382       if (!ExpectingFlags) {
22383         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
22384         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
22385
22386         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
22387           X86::CondCode tmp = cc0;
22388           cc0 = cc1;
22389           cc1 = tmp;
22390         }
22391
22392         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
22393             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
22394           // FIXME: need symbolic constants for these magic numbers.
22395           // See X86ATTInstPrinter.cpp:printSSECC().
22396           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
22397           if (Subtarget->hasAVX512()) {
22398             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
22399                                          CMP01,
22400                                          DAG.getConstant(x86cc, DL, MVT::i8));
22401             if (N->getValueType(0) != MVT::i1)
22402               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
22403                                  FSetCC);
22404             return FSetCC;
22405           }
22406           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
22407                                               CMP00.getValueType(), CMP00, CMP01,
22408                                               DAG.getConstant(x86cc, DL,
22409                                                               MVT::i8));
22410
22411           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
22412           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
22413
22414           if (is64BitFP && !Subtarget->is64Bit()) {
22415             // On a 32-bit target, we cannot bitcast the 64-bit float to a
22416             // 64-bit integer, since that's not a legal type. Since
22417             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
22418             // bits, but can do this little dance to extract the lowest 32 bits
22419             // and work with those going forward.
22420             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
22421                                            OnesOrZeroesF);
22422             SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
22423                                            Vector64);
22424             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
22425                                         Vector32, DAG.getIntPtrConstant(0, DL));
22426             IntVT = MVT::i32;
22427           }
22428
22429           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT,
22430                                               OnesOrZeroesF);
22431           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
22432                                       DAG.getConstant(1, DL, IntVT));
22433           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8,
22434                                               ANDed);
22435           return OneBitOfTruth;
22436         }
22437       }
22438     }
22439   }
22440   return SDValue();
22441 }
22442
22443 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
22444 /// so it can be folded inside ANDNP.
22445 static bool CanFoldXORWithAllOnes(const SDNode *N) {
22446   EVT VT = N->getValueType(0);
22447
22448   // Match direct AllOnes for 128 and 256-bit vectors
22449   if (ISD::isBuildVectorAllOnes(N))
22450     return true;
22451
22452   // Look through a bit convert.
22453   if (N->getOpcode() == ISD::BITCAST)
22454     N = N->getOperand(0).getNode();
22455
22456   // Sometimes the operand may come from a insert_subvector building a 256-bit
22457   // allones vector
22458   if (VT.is256BitVector() &&
22459       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
22460     SDValue V1 = N->getOperand(0);
22461     SDValue V2 = N->getOperand(1);
22462
22463     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
22464         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
22465         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
22466         ISD::isBuildVectorAllOnes(V2.getNode()))
22467       return true;
22468   }
22469
22470   return false;
22471 }
22472
22473 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
22474 // register. In most cases we actually compare or select YMM-sized registers
22475 // and mixing the two types creates horrible code. This method optimizes
22476 // some of the transition sequences.
22477 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
22478                                  TargetLowering::DAGCombinerInfo &DCI,
22479                                  const X86Subtarget *Subtarget) {
22480   EVT VT = N->getValueType(0);
22481   if (!VT.is256BitVector())
22482     return SDValue();
22483
22484   assert((N->getOpcode() == ISD::ANY_EXTEND ||
22485           N->getOpcode() == ISD::ZERO_EXTEND ||
22486           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
22487
22488   SDValue Narrow = N->getOperand(0);
22489   EVT NarrowVT = Narrow->getValueType(0);
22490   if (!NarrowVT.is128BitVector())
22491     return SDValue();
22492
22493   if (Narrow->getOpcode() != ISD::XOR &&
22494       Narrow->getOpcode() != ISD::AND &&
22495       Narrow->getOpcode() != ISD::OR)
22496     return SDValue();
22497
22498   SDValue N0  = Narrow->getOperand(0);
22499   SDValue N1  = Narrow->getOperand(1);
22500   SDLoc DL(Narrow);
22501
22502   // The Left side has to be a trunc.
22503   if (N0.getOpcode() != ISD::TRUNCATE)
22504     return SDValue();
22505
22506   // The type of the truncated inputs.
22507   EVT WideVT = N0->getOperand(0)->getValueType(0);
22508   if (WideVT != VT)
22509     return SDValue();
22510
22511   // The right side has to be a 'trunc' or a constant vector.
22512   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
22513   ConstantSDNode *RHSConstSplat = nullptr;
22514   if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
22515     RHSConstSplat = RHSBV->getConstantSplatNode();
22516   if (!RHSTrunc && !RHSConstSplat)
22517     return SDValue();
22518
22519   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22520
22521   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
22522     return SDValue();
22523
22524   // Set N0 and N1 to hold the inputs to the new wide operation.
22525   N0 = N0->getOperand(0);
22526   if (RHSConstSplat) {
22527     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
22528                      SDValue(RHSConstSplat, 0));
22529     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
22530     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
22531   } else if (RHSTrunc) {
22532     N1 = N1->getOperand(0);
22533   }
22534
22535   // Generate the wide operation.
22536   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
22537   unsigned Opcode = N->getOpcode();
22538   switch (Opcode) {
22539   case ISD::ANY_EXTEND:
22540     return Op;
22541   case ISD::ZERO_EXTEND: {
22542     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
22543     APInt Mask = APInt::getAllOnesValue(InBits);
22544     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
22545     return DAG.getNode(ISD::AND, DL, VT,
22546                        Op, DAG.getConstant(Mask, DL, VT));
22547   }
22548   case ISD::SIGN_EXTEND:
22549     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
22550                        Op, DAG.getValueType(NarrowVT));
22551   default:
22552     llvm_unreachable("Unexpected opcode");
22553   }
22554 }
22555
22556 static SDValue VectorZextCombine(SDNode *N, SelectionDAG &DAG,
22557                                  TargetLowering::DAGCombinerInfo &DCI,
22558                                  const X86Subtarget *Subtarget) {
22559   SDValue N0 = N->getOperand(0);
22560   SDValue N1 = N->getOperand(1);
22561   SDLoc DL(N);
22562
22563   // A vector zext_in_reg may be represented as a shuffle,
22564   // feeding into a bitcast (this represents anyext) feeding into
22565   // an and with a mask.
22566   // We'd like to try to combine that into a shuffle with zero
22567   // plus a bitcast, removing the and.
22568   if (N0.getOpcode() != ISD::BITCAST ||
22569       N0.getOperand(0).getOpcode() != ISD::VECTOR_SHUFFLE)
22570     return SDValue();
22571
22572   // The other side of the AND should be a splat of 2^C, where C
22573   // is the number of bits in the source type.
22574   if (N1.getOpcode() == ISD::BITCAST)
22575     N1 = N1.getOperand(0);
22576   if (N1.getOpcode() != ISD::BUILD_VECTOR)
22577     return SDValue();
22578   BuildVectorSDNode *Vector = cast<BuildVectorSDNode>(N1);
22579
22580   ShuffleVectorSDNode *Shuffle = cast<ShuffleVectorSDNode>(N0.getOperand(0));
22581   EVT SrcType = Shuffle->getValueType(0);
22582
22583   // We expect a single-source shuffle
22584   if (Shuffle->getOperand(1)->getOpcode() != ISD::UNDEF)
22585     return SDValue();
22586
22587   unsigned SrcSize = SrcType.getScalarSizeInBits();
22588
22589   APInt SplatValue, SplatUndef;
22590   unsigned SplatBitSize;
22591   bool HasAnyUndefs;
22592   if (!Vector->isConstantSplat(SplatValue, SplatUndef,
22593                                 SplatBitSize, HasAnyUndefs))
22594     return SDValue();
22595
22596   unsigned ResSize = N1.getValueType().getScalarSizeInBits();
22597   // Make sure the splat matches the mask we expect
22598   if (SplatBitSize > ResSize ||
22599       (SplatValue + 1).exactLogBase2() != (int)SrcSize)
22600     return SDValue();
22601
22602   // Make sure the input and output size make sense
22603   if (SrcSize >= ResSize || ResSize % SrcSize)
22604     return SDValue();
22605
22606   // We expect a shuffle of the form <0, u, u, u, 1, u, u, u...>
22607   // The number of u's between each two values depends on the ratio between
22608   // the source and dest type.
22609   unsigned ZextRatio = ResSize / SrcSize;
22610   bool IsZext = true;
22611   for (unsigned i = 0; i < SrcType.getVectorNumElements(); ++i) {
22612     if (i % ZextRatio) {
22613       if (Shuffle->getMaskElt(i) > 0) {
22614         // Expected undef
22615         IsZext = false;
22616         break;
22617       }
22618     } else {
22619       if (Shuffle->getMaskElt(i) != (int)(i / ZextRatio)) {
22620         // Expected element number
22621         IsZext = false;
22622         break;
22623       }
22624     }
22625   }
22626
22627   if (!IsZext)
22628     return SDValue();
22629
22630   // Ok, perform the transformation - replace the shuffle with
22631   // a shuffle of the form <0, k, k, k, 1, k, k, k> with zero
22632   // (instead of undef) where the k elements come from the zero vector.
22633   SmallVector<int, 8> Mask;
22634   unsigned NumElems = SrcType.getVectorNumElements();
22635   for (unsigned i = 0; i < NumElems; ++i)
22636     if (i % ZextRatio)
22637       Mask.push_back(NumElems);
22638     else
22639       Mask.push_back(i / ZextRatio);
22640
22641   SDValue NewShuffle = DAG.getVectorShuffle(Shuffle->getValueType(0), DL,
22642     Shuffle->getOperand(0), DAG.getConstant(0, DL, SrcType), Mask);
22643   return DAG.getNode(ISD::BITCAST, DL, N0.getValueType(), NewShuffle);
22644 }
22645
22646 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
22647                                  TargetLowering::DAGCombinerInfo &DCI,
22648                                  const X86Subtarget *Subtarget) {
22649   if (DCI.isBeforeLegalizeOps())
22650     return SDValue();
22651
22652   if (SDValue Zext = VectorZextCombine(N, DAG, DCI, Subtarget))
22653     return Zext;
22654
22655   if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
22656     return R;
22657
22658   EVT VT = N->getValueType(0);
22659   SDValue N0 = N->getOperand(0);
22660   SDValue N1 = N->getOperand(1);
22661   SDLoc DL(N);
22662
22663   // Create BEXTR instructions
22664   // BEXTR is ((X >> imm) & (2**size-1))
22665   if (VT == MVT::i32 || VT == MVT::i64) {
22666     // Check for BEXTR.
22667     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
22668         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
22669       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
22670       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
22671       if (MaskNode && ShiftNode) {
22672         uint64_t Mask = MaskNode->getZExtValue();
22673         uint64_t Shift = ShiftNode->getZExtValue();
22674         if (isMask_64(Mask)) {
22675           uint64_t MaskSize = countPopulation(Mask);
22676           if (Shift + MaskSize <= VT.getSizeInBits())
22677             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
22678                                DAG.getConstant(Shift | (MaskSize << 8), DL,
22679                                                VT));
22680         }
22681       }
22682     } // BEXTR
22683
22684     return SDValue();
22685   }
22686
22687   // Want to form ANDNP nodes:
22688   // 1) In the hopes of then easily combining them with OR and AND nodes
22689   //    to form PBLEND/PSIGN.
22690   // 2) To match ANDN packed intrinsics
22691   if (VT != MVT::v2i64 && VT != MVT::v4i64)
22692     return SDValue();
22693
22694   // Check LHS for vnot
22695   if (N0.getOpcode() == ISD::XOR &&
22696       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
22697       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
22698     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
22699
22700   // Check RHS for vnot
22701   if (N1.getOpcode() == ISD::XOR &&
22702       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
22703       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
22704     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
22705
22706   return SDValue();
22707 }
22708
22709 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
22710                                 TargetLowering::DAGCombinerInfo &DCI,
22711                                 const X86Subtarget *Subtarget) {
22712   if (DCI.isBeforeLegalizeOps())
22713     return SDValue();
22714
22715   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
22716   if (R.getNode())
22717     return R;
22718
22719   SDValue N0 = N->getOperand(0);
22720   SDValue N1 = N->getOperand(1);
22721   EVT VT = N->getValueType(0);
22722
22723   // look for psign/blend
22724   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
22725     if (!Subtarget->hasSSSE3() ||
22726         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
22727       return SDValue();
22728
22729     // Canonicalize pandn to RHS
22730     if (N0.getOpcode() == X86ISD::ANDNP)
22731       std::swap(N0, N1);
22732     // or (and (m, y), (pandn m, x))
22733     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
22734       SDValue Mask = N1.getOperand(0);
22735       SDValue X    = N1.getOperand(1);
22736       SDValue Y;
22737       if (N0.getOperand(0) == Mask)
22738         Y = N0.getOperand(1);
22739       if (N0.getOperand(1) == Mask)
22740         Y = N0.getOperand(0);
22741
22742       // Check to see if the mask appeared in both the AND and ANDNP and
22743       if (!Y.getNode())
22744         return SDValue();
22745
22746       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
22747       // Look through mask bitcast.
22748       if (Mask.getOpcode() == ISD::BITCAST)
22749         Mask = Mask.getOperand(0);
22750       if (X.getOpcode() == ISD::BITCAST)
22751         X = X.getOperand(0);
22752       if (Y.getOpcode() == ISD::BITCAST)
22753         Y = Y.getOperand(0);
22754
22755       EVT MaskVT = Mask.getValueType();
22756
22757       // Validate that the Mask operand is a vector sra node.
22758       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
22759       // there is no psrai.b
22760       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
22761       unsigned SraAmt = ~0;
22762       if (Mask.getOpcode() == ISD::SRA) {
22763         if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
22764           if (auto *AmtConst = AmtBV->getConstantSplatNode())
22765             SraAmt = AmtConst->getZExtValue();
22766       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
22767         SDValue SraC = Mask.getOperand(1);
22768         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
22769       }
22770       if ((SraAmt + 1) != EltBits)
22771         return SDValue();
22772
22773       SDLoc DL(N);
22774
22775       // Now we know we at least have a plendvb with the mask val.  See if
22776       // we can form a psignb/w/d.
22777       // psign = x.type == y.type == mask.type && y = sub(0, x);
22778       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
22779           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
22780           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
22781         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
22782                "Unsupported VT for PSIGN");
22783         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
22784         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
22785       }
22786       // PBLENDVB only available on SSE 4.1
22787       if (!Subtarget->hasSSE41())
22788         return SDValue();
22789
22790       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
22791
22792       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
22793       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
22794       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
22795       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
22796       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
22797     }
22798   }
22799
22800   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
22801     return SDValue();
22802
22803   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
22804   MachineFunction &MF = DAG.getMachineFunction();
22805   bool OptForSize =
22806       MF.getFunction()->hasFnAttribute(Attribute::OptimizeForSize);
22807
22808   // SHLD/SHRD instructions have lower register pressure, but on some
22809   // platforms they have higher latency than the equivalent
22810   // series of shifts/or that would otherwise be generated.
22811   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
22812   // have higher latencies and we are not optimizing for size.
22813   if (!OptForSize && Subtarget->isSHLDSlow())
22814     return SDValue();
22815
22816   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
22817     std::swap(N0, N1);
22818   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
22819     return SDValue();
22820   if (!N0.hasOneUse() || !N1.hasOneUse())
22821     return SDValue();
22822
22823   SDValue ShAmt0 = N0.getOperand(1);
22824   if (ShAmt0.getValueType() != MVT::i8)
22825     return SDValue();
22826   SDValue ShAmt1 = N1.getOperand(1);
22827   if (ShAmt1.getValueType() != MVT::i8)
22828     return SDValue();
22829   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
22830     ShAmt0 = ShAmt0.getOperand(0);
22831   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
22832     ShAmt1 = ShAmt1.getOperand(0);
22833
22834   SDLoc DL(N);
22835   unsigned Opc = X86ISD::SHLD;
22836   SDValue Op0 = N0.getOperand(0);
22837   SDValue Op1 = N1.getOperand(0);
22838   if (ShAmt0.getOpcode() == ISD::SUB) {
22839     Opc = X86ISD::SHRD;
22840     std::swap(Op0, Op1);
22841     std::swap(ShAmt0, ShAmt1);
22842   }
22843
22844   unsigned Bits = VT.getSizeInBits();
22845   if (ShAmt1.getOpcode() == ISD::SUB) {
22846     SDValue Sum = ShAmt1.getOperand(0);
22847     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
22848       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
22849       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
22850         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
22851       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
22852         return DAG.getNode(Opc, DL, VT,
22853                            Op0, Op1,
22854                            DAG.getNode(ISD::TRUNCATE, DL,
22855                                        MVT::i8, ShAmt0));
22856     }
22857   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
22858     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
22859     if (ShAmt0C &&
22860         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
22861       return DAG.getNode(Opc, DL, VT,
22862                          N0.getOperand(0), N1.getOperand(0),
22863                          DAG.getNode(ISD::TRUNCATE, DL,
22864                                        MVT::i8, ShAmt0));
22865   }
22866
22867   return SDValue();
22868 }
22869
22870 // Generate NEG and CMOV for integer abs.
22871 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
22872   EVT VT = N->getValueType(0);
22873
22874   // Since X86 does not have CMOV for 8-bit integer, we don't convert
22875   // 8-bit integer abs to NEG and CMOV.
22876   if (VT.isInteger() && VT.getSizeInBits() == 8)
22877     return SDValue();
22878
22879   SDValue N0 = N->getOperand(0);
22880   SDValue N1 = N->getOperand(1);
22881   SDLoc DL(N);
22882
22883   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
22884   // and change it to SUB and CMOV.
22885   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
22886       N0.getOpcode() == ISD::ADD &&
22887       N0.getOperand(1) == N1 &&
22888       N1.getOpcode() == ISD::SRA &&
22889       N1.getOperand(0) == N0.getOperand(0))
22890     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
22891       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
22892         // Generate SUB & CMOV.
22893         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
22894                                   DAG.getConstant(0, DL, VT), N0.getOperand(0));
22895
22896         SDValue Ops[] = { N0.getOperand(0), Neg,
22897                           DAG.getConstant(X86::COND_GE, DL, MVT::i8),
22898                           SDValue(Neg.getNode(), 1) };
22899         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
22900       }
22901   return SDValue();
22902 }
22903
22904 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
22905 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
22906                                  TargetLowering::DAGCombinerInfo &DCI,
22907                                  const X86Subtarget *Subtarget) {
22908   if (DCI.isBeforeLegalizeOps())
22909     return SDValue();
22910
22911   if (Subtarget->hasCMov()) {
22912     SDValue RV = performIntegerAbsCombine(N, DAG);
22913     if (RV.getNode())
22914       return RV;
22915   }
22916
22917   return SDValue();
22918 }
22919
22920 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
22921 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
22922                                   TargetLowering::DAGCombinerInfo &DCI,
22923                                   const X86Subtarget *Subtarget) {
22924   LoadSDNode *Ld = cast<LoadSDNode>(N);
22925   EVT RegVT = Ld->getValueType(0);
22926   EVT MemVT = Ld->getMemoryVT();
22927   SDLoc dl(Ld);
22928   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22929
22930   // For chips with slow 32-byte unaligned loads, break the 32-byte operation
22931   // into two 16-byte operations.
22932   ISD::LoadExtType Ext = Ld->getExtensionType();
22933   unsigned Alignment = Ld->getAlignment();
22934   bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
22935   if (RegVT.is256BitVector() && Subtarget->isUnalignedMem32Slow() &&
22936       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
22937     unsigned NumElems = RegVT.getVectorNumElements();
22938     if (NumElems < 2)
22939       return SDValue();
22940
22941     SDValue Ptr = Ld->getBasePtr();
22942     SDValue Increment = DAG.getConstant(16, dl, TLI.getPointerTy());
22943
22944     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
22945                                   NumElems/2);
22946     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
22947                                 Ld->getPointerInfo(), Ld->isVolatile(),
22948                                 Ld->isNonTemporal(), Ld->isInvariant(),
22949                                 Alignment);
22950     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
22951     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
22952                                 Ld->getPointerInfo(), Ld->isVolatile(),
22953                                 Ld->isNonTemporal(), Ld->isInvariant(),
22954                                 std::min(16U, Alignment));
22955     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
22956                              Load1.getValue(1),
22957                              Load2.getValue(1));
22958
22959     SDValue NewVec = DAG.getUNDEF(RegVT);
22960     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
22961     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
22962     return DCI.CombineTo(N, NewVec, TF, true);
22963   }
22964
22965   return SDValue();
22966 }
22967
22968 /// PerformMLOADCombine - Resolve extending loads
22969 static SDValue PerformMLOADCombine(SDNode *N, SelectionDAG &DAG,
22970                                    TargetLowering::DAGCombinerInfo &DCI,
22971                                    const X86Subtarget *Subtarget) {
22972   MaskedLoadSDNode *Mld = cast<MaskedLoadSDNode>(N);
22973   if (Mld->getExtensionType() != ISD::SEXTLOAD)
22974     return SDValue();
22975
22976   EVT VT = Mld->getValueType(0);
22977   unsigned NumElems = VT.getVectorNumElements();
22978   EVT LdVT = Mld->getMemoryVT();
22979   SDLoc dl(Mld);
22980
22981   assert(LdVT != VT && "Cannot extend to the same type");
22982   unsigned ToSz = VT.getVectorElementType().getSizeInBits();
22983   unsigned FromSz = LdVT.getVectorElementType().getSizeInBits();
22984   // From, To sizes and ElemCount must be pow of two
22985   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
22986     "Unexpected size for extending masked load");
22987
22988   unsigned SizeRatio  = ToSz / FromSz;
22989   assert(SizeRatio * NumElems * FromSz == VT.getSizeInBits());
22990
22991   // Create a type on which we perform the shuffle
22992   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
22993           LdVT.getScalarType(), NumElems*SizeRatio);
22994   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
22995
22996   // Convert Src0 value
22997   SDValue WideSrc0 = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mld->getSrc0());
22998   if (Mld->getSrc0().getOpcode() != ISD::UNDEF) {
22999     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
23000     for (unsigned i = 0; i != NumElems; ++i)
23001       ShuffleVec[i] = i * SizeRatio;
23002
23003     // Can't shuffle using an illegal type.
23004     assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
23005             && "WideVecVT should be legal");
23006     WideSrc0 = DAG.getVectorShuffle(WideVecVT, dl, WideSrc0,
23007                                     DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
23008   }
23009   // Prepare the new mask
23010   SDValue NewMask;
23011   SDValue Mask = Mld->getMask();
23012   if (Mask.getValueType() == VT) {
23013     // Mask and original value have the same type
23014     NewMask = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mask);
23015     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
23016     for (unsigned i = 0; i != NumElems; ++i)
23017       ShuffleVec[i] = i * SizeRatio;
23018     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
23019       ShuffleVec[i] = NumElems*SizeRatio;
23020     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
23021                                    DAG.getConstant(0, dl, WideVecVT),
23022                                    &ShuffleVec[0]);
23023   }
23024   else {
23025     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
23026     unsigned WidenNumElts = NumElems*SizeRatio;
23027     unsigned MaskNumElts = VT.getVectorNumElements();
23028     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
23029                                      WidenNumElts);
23030
23031     unsigned NumConcat = WidenNumElts / MaskNumElts;
23032     SmallVector<SDValue, 16> Ops(NumConcat);
23033     SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
23034     Ops[0] = Mask;
23035     for (unsigned i = 1; i != NumConcat; ++i)
23036       Ops[i] = ZeroVal;
23037
23038     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
23039   }
23040
23041   SDValue WideLd = DAG.getMaskedLoad(WideVecVT, dl, Mld->getChain(),
23042                                      Mld->getBasePtr(), NewMask, WideSrc0,
23043                                      Mld->getMemoryVT(), Mld->getMemOperand(),
23044                                      ISD::NON_EXTLOAD);
23045   SDValue NewVec = DAG.getNode(X86ISD::VSEXT, dl, VT, WideLd);
23046   return DCI.CombineTo(N, NewVec, WideLd.getValue(1), true);
23047
23048 }
23049 /// PerformMSTORECombine - Resolve truncating stores
23050 static SDValue PerformMSTORECombine(SDNode *N, SelectionDAG &DAG,
23051                                     const X86Subtarget *Subtarget) {
23052   MaskedStoreSDNode *Mst = cast<MaskedStoreSDNode>(N);
23053   if (!Mst->isTruncatingStore())
23054     return SDValue();
23055
23056   EVT VT = Mst->getValue().getValueType();
23057   unsigned NumElems = VT.getVectorNumElements();
23058   EVT StVT = Mst->getMemoryVT();
23059   SDLoc dl(Mst);
23060
23061   assert(StVT != VT && "Cannot truncate to the same type");
23062   unsigned FromSz = VT.getVectorElementType().getSizeInBits();
23063   unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
23064
23065   // From, To sizes and ElemCount must be pow of two
23066   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
23067     "Unexpected size for truncating masked store");
23068   // We are going to use the original vector elt for storing.
23069   // Accumulated smaller vector elements must be a multiple of the store size.
23070   assert (((NumElems * FromSz) % ToSz) == 0 &&
23071           "Unexpected ratio for truncating masked store");
23072
23073   unsigned SizeRatio  = FromSz / ToSz;
23074   assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
23075
23076   // Create a type on which we perform the shuffle
23077   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
23078           StVT.getScalarType(), NumElems*SizeRatio);
23079
23080   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
23081
23082   SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mst->getValue());
23083   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
23084   for (unsigned i = 0; i != NumElems; ++i)
23085     ShuffleVec[i] = i * SizeRatio;
23086
23087   // Can't shuffle using an illegal type.
23088   assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
23089           && "WideVecVT should be legal");
23090
23091   SDValue TruncatedVal = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
23092                                         DAG.getUNDEF(WideVecVT),
23093                                         &ShuffleVec[0]);
23094
23095   SDValue NewMask;
23096   SDValue Mask = Mst->getMask();
23097   if (Mask.getValueType() == VT) {
23098     // Mask and original value have the same type
23099     NewMask = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mask);
23100     for (unsigned i = 0; i != NumElems; ++i)
23101       ShuffleVec[i] = i * SizeRatio;
23102     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
23103       ShuffleVec[i] = NumElems*SizeRatio;
23104     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
23105                                    DAG.getConstant(0, dl, WideVecVT),
23106                                    &ShuffleVec[0]);
23107   }
23108   else {
23109     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
23110     unsigned WidenNumElts = NumElems*SizeRatio;
23111     unsigned MaskNumElts = VT.getVectorNumElements();
23112     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
23113                                      WidenNumElts);
23114
23115     unsigned NumConcat = WidenNumElts / MaskNumElts;
23116     SmallVector<SDValue, 16> Ops(NumConcat);
23117     SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
23118     Ops[0] = Mask;
23119     for (unsigned i = 1; i != NumConcat; ++i)
23120       Ops[i] = ZeroVal;
23121
23122     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
23123   }
23124
23125   return DAG.getMaskedStore(Mst->getChain(), dl, TruncatedVal, Mst->getBasePtr(),
23126                             NewMask, StVT, Mst->getMemOperand(), false);
23127 }
23128 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
23129 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
23130                                    const X86Subtarget *Subtarget) {
23131   StoreSDNode *St = cast<StoreSDNode>(N);
23132   EVT VT = St->getValue().getValueType();
23133   EVT StVT = St->getMemoryVT();
23134   SDLoc dl(St);
23135   SDValue StoredVal = St->getOperand(1);
23136   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23137
23138   // If we are saving a concatenation of two XMM registers and 32-byte stores
23139   // are slow, such as on Sandy Bridge, perform two 16-byte stores.
23140   unsigned Alignment = St->getAlignment();
23141   bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
23142   if (VT.is256BitVector() && Subtarget->isUnalignedMem32Slow() &&
23143       StVT == VT && !IsAligned) {
23144     unsigned NumElems = VT.getVectorNumElements();
23145     if (NumElems < 2)
23146       return SDValue();
23147
23148     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
23149     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
23150
23151     SDValue Stride = DAG.getConstant(16, dl, TLI.getPointerTy());
23152     SDValue Ptr0 = St->getBasePtr();
23153     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
23154
23155     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
23156                                 St->getPointerInfo(), St->isVolatile(),
23157                                 St->isNonTemporal(), Alignment);
23158     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
23159                                 St->getPointerInfo(), St->isVolatile(),
23160                                 St->isNonTemporal(),
23161                                 std::min(16U, Alignment));
23162     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
23163   }
23164
23165   // Optimize trunc store (of multiple scalars) to shuffle and store.
23166   // First, pack all of the elements in one place. Next, store to memory
23167   // in fewer chunks.
23168   if (St->isTruncatingStore() && VT.isVector()) {
23169     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23170     unsigned NumElems = VT.getVectorNumElements();
23171     assert(StVT != VT && "Cannot truncate to the same type");
23172     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
23173     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
23174
23175     // From, To sizes and ElemCount must be pow of two
23176     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
23177     // We are going to use the original vector elt for storing.
23178     // Accumulated smaller vector elements must be a multiple of the store size.
23179     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
23180
23181     unsigned SizeRatio  = FromSz / ToSz;
23182
23183     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
23184
23185     // Create a type on which we perform the shuffle
23186     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
23187             StVT.getScalarType(), NumElems*SizeRatio);
23188
23189     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
23190
23191     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
23192     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
23193     for (unsigned i = 0; i != NumElems; ++i)
23194       ShuffleVec[i] = i * SizeRatio;
23195
23196     // Can't shuffle using an illegal type.
23197     if (!TLI.isTypeLegal(WideVecVT))
23198       return SDValue();
23199
23200     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
23201                                          DAG.getUNDEF(WideVecVT),
23202                                          &ShuffleVec[0]);
23203     // At this point all of the data is stored at the bottom of the
23204     // register. We now need to save it to mem.
23205
23206     // Find the largest store unit
23207     MVT StoreType = MVT::i8;
23208     for (MVT Tp : MVT::integer_valuetypes()) {
23209       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
23210         StoreType = Tp;
23211     }
23212
23213     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
23214     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
23215         (64 <= NumElems * ToSz))
23216       StoreType = MVT::f64;
23217
23218     // Bitcast the original vector into a vector of store-size units
23219     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
23220             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
23221     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
23222     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
23223     SmallVector<SDValue, 8> Chains;
23224     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8, dl,
23225                                         TLI.getPointerTy());
23226     SDValue Ptr = St->getBasePtr();
23227
23228     // Perform one or more big stores into memory.
23229     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
23230       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
23231                                    StoreType, ShuffWide,
23232                                    DAG.getIntPtrConstant(i, dl));
23233       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
23234                                 St->getPointerInfo(), St->isVolatile(),
23235                                 St->isNonTemporal(), St->getAlignment());
23236       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
23237       Chains.push_back(Ch);
23238     }
23239
23240     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
23241   }
23242
23243   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
23244   // the FP state in cases where an emms may be missing.
23245   // A preferable solution to the general problem is to figure out the right
23246   // places to insert EMMS.  This qualifies as a quick hack.
23247
23248   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
23249   if (VT.getSizeInBits() != 64)
23250     return SDValue();
23251
23252   const Function *F = DAG.getMachineFunction().getFunction();
23253   bool NoImplicitFloatOps = F->hasFnAttribute(Attribute::NoImplicitFloat);
23254   bool F64IsLegal =
23255       !Subtarget->useSoftFloat() && !NoImplicitFloatOps && Subtarget->hasSSE2();
23256   if ((VT.isVector() ||
23257        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
23258       isa<LoadSDNode>(St->getValue()) &&
23259       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
23260       St->getChain().hasOneUse() && !St->isVolatile()) {
23261     SDNode* LdVal = St->getValue().getNode();
23262     LoadSDNode *Ld = nullptr;
23263     int TokenFactorIndex = -1;
23264     SmallVector<SDValue, 8> Ops;
23265     SDNode* ChainVal = St->getChain().getNode();
23266     // Must be a store of a load.  We currently handle two cases:  the load
23267     // is a direct child, and it's under an intervening TokenFactor.  It is
23268     // possible to dig deeper under nested TokenFactors.
23269     if (ChainVal == LdVal)
23270       Ld = cast<LoadSDNode>(St->getChain());
23271     else if (St->getValue().hasOneUse() &&
23272              ChainVal->getOpcode() == ISD::TokenFactor) {
23273       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
23274         if (ChainVal->getOperand(i).getNode() == LdVal) {
23275           TokenFactorIndex = i;
23276           Ld = cast<LoadSDNode>(St->getValue());
23277         } else
23278           Ops.push_back(ChainVal->getOperand(i));
23279       }
23280     }
23281
23282     if (!Ld || !ISD::isNormalLoad(Ld))
23283       return SDValue();
23284
23285     // If this is not the MMX case, i.e. we are just turning i64 load/store
23286     // into f64 load/store, avoid the transformation if there are multiple
23287     // uses of the loaded value.
23288     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
23289       return SDValue();
23290
23291     SDLoc LdDL(Ld);
23292     SDLoc StDL(N);
23293     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
23294     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
23295     // pair instead.
23296     if (Subtarget->is64Bit() || F64IsLegal) {
23297       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
23298       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
23299                                   Ld->getPointerInfo(), Ld->isVolatile(),
23300                                   Ld->isNonTemporal(), Ld->isInvariant(),
23301                                   Ld->getAlignment());
23302       SDValue NewChain = NewLd.getValue(1);
23303       if (TokenFactorIndex != -1) {
23304         Ops.push_back(NewChain);
23305         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
23306       }
23307       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
23308                           St->getPointerInfo(),
23309                           St->isVolatile(), St->isNonTemporal(),
23310                           St->getAlignment());
23311     }
23312
23313     // Otherwise, lower to two pairs of 32-bit loads / stores.
23314     SDValue LoAddr = Ld->getBasePtr();
23315     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
23316                                  DAG.getConstant(4, LdDL, MVT::i32));
23317
23318     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
23319                                Ld->getPointerInfo(),
23320                                Ld->isVolatile(), Ld->isNonTemporal(),
23321                                Ld->isInvariant(), Ld->getAlignment());
23322     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
23323                                Ld->getPointerInfo().getWithOffset(4),
23324                                Ld->isVolatile(), Ld->isNonTemporal(),
23325                                Ld->isInvariant(),
23326                                MinAlign(Ld->getAlignment(), 4));
23327
23328     SDValue NewChain = LoLd.getValue(1);
23329     if (TokenFactorIndex != -1) {
23330       Ops.push_back(LoLd);
23331       Ops.push_back(HiLd);
23332       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
23333     }
23334
23335     LoAddr = St->getBasePtr();
23336     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
23337                          DAG.getConstant(4, StDL, MVT::i32));
23338
23339     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
23340                                 St->getPointerInfo(),
23341                                 St->isVolatile(), St->isNonTemporal(),
23342                                 St->getAlignment());
23343     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
23344                                 St->getPointerInfo().getWithOffset(4),
23345                                 St->isVolatile(),
23346                                 St->isNonTemporal(),
23347                                 MinAlign(St->getAlignment(), 4));
23348     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
23349   }
23350
23351   // This is similar to the above case, but here we handle a scalar 64-bit
23352   // integer store that is extracted from a vector on a 32-bit target.
23353   // If we have SSE2, then we can treat it like a floating-point double
23354   // to get past legalization. The execution dependencies fixup pass will
23355   // choose the optimal machine instruction for the store if this really is
23356   // an integer or v2f32 rather than an f64.
23357   if (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit() &&
23358       St->getOperand(1).getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
23359     SDValue OldExtract = St->getOperand(1);
23360     SDValue ExtOp0 = OldExtract.getOperand(0);
23361     unsigned VecSize = ExtOp0.getValueSizeInBits();
23362     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, VecSize / 64);
23363     SDValue BitCast = DAG.getNode(ISD::BITCAST, dl, VecVT, ExtOp0);
23364     SDValue NewExtract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
23365                                      BitCast, OldExtract.getOperand(1));
23366     return DAG.getStore(St->getChain(), dl, NewExtract, St->getBasePtr(),
23367                         St->getPointerInfo(), St->isVolatile(),
23368                         St->isNonTemporal(), St->getAlignment());
23369   }
23370
23371   return SDValue();
23372 }
23373
23374 /// Return 'true' if this vector operation is "horizontal"
23375 /// and return the operands for the horizontal operation in LHS and RHS.  A
23376 /// horizontal operation performs the binary operation on successive elements
23377 /// of its first operand, then on successive elements of its second operand,
23378 /// returning the resulting values in a vector.  For example, if
23379 ///   A = < float a0, float a1, float a2, float a3 >
23380 /// and
23381 ///   B = < float b0, float b1, float b2, float b3 >
23382 /// then the result of doing a horizontal operation on A and B is
23383 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
23384 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
23385 /// A horizontal-op B, for some already available A and B, and if so then LHS is
23386 /// set to A, RHS to B, and the routine returns 'true'.
23387 /// Note that the binary operation should have the property that if one of the
23388 /// operands is UNDEF then the result is UNDEF.
23389 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
23390   // Look for the following pattern: if
23391   //   A = < float a0, float a1, float a2, float a3 >
23392   //   B = < float b0, float b1, float b2, float b3 >
23393   // and
23394   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
23395   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
23396   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
23397   // which is A horizontal-op B.
23398
23399   // At least one of the operands should be a vector shuffle.
23400   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
23401       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
23402     return false;
23403
23404   MVT VT = LHS.getSimpleValueType();
23405
23406   assert((VT.is128BitVector() || VT.is256BitVector()) &&
23407          "Unsupported vector type for horizontal add/sub");
23408
23409   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
23410   // operate independently on 128-bit lanes.
23411   unsigned NumElts = VT.getVectorNumElements();
23412   unsigned NumLanes = VT.getSizeInBits()/128;
23413   unsigned NumLaneElts = NumElts / NumLanes;
23414   assert((NumLaneElts % 2 == 0) &&
23415          "Vector type should have an even number of elements in each lane");
23416   unsigned HalfLaneElts = NumLaneElts/2;
23417
23418   // View LHS in the form
23419   //   LHS = VECTOR_SHUFFLE A, B, LMask
23420   // If LHS is not a shuffle then pretend it is the shuffle
23421   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
23422   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
23423   // type VT.
23424   SDValue A, B;
23425   SmallVector<int, 16> LMask(NumElts);
23426   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
23427     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
23428       A = LHS.getOperand(0);
23429     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
23430       B = LHS.getOperand(1);
23431     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
23432     std::copy(Mask.begin(), Mask.end(), LMask.begin());
23433   } else {
23434     if (LHS.getOpcode() != ISD::UNDEF)
23435       A = LHS;
23436     for (unsigned i = 0; i != NumElts; ++i)
23437       LMask[i] = i;
23438   }
23439
23440   // Likewise, view RHS in the form
23441   //   RHS = VECTOR_SHUFFLE C, D, RMask
23442   SDValue C, D;
23443   SmallVector<int, 16> RMask(NumElts);
23444   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
23445     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
23446       C = RHS.getOperand(0);
23447     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
23448       D = RHS.getOperand(1);
23449     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
23450     std::copy(Mask.begin(), Mask.end(), RMask.begin());
23451   } else {
23452     if (RHS.getOpcode() != ISD::UNDEF)
23453       C = RHS;
23454     for (unsigned i = 0; i != NumElts; ++i)
23455       RMask[i] = i;
23456   }
23457
23458   // Check that the shuffles are both shuffling the same vectors.
23459   if (!(A == C && B == D) && !(A == D && B == C))
23460     return false;
23461
23462   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
23463   if (!A.getNode() && !B.getNode())
23464     return false;
23465
23466   // If A and B occur in reverse order in RHS, then "swap" them (which means
23467   // rewriting the mask).
23468   if (A != C)
23469     ShuffleVectorSDNode::commuteMask(RMask);
23470
23471   // At this point LHS and RHS are equivalent to
23472   //   LHS = VECTOR_SHUFFLE A, B, LMask
23473   //   RHS = VECTOR_SHUFFLE A, B, RMask
23474   // Check that the masks correspond to performing a horizontal operation.
23475   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
23476     for (unsigned i = 0; i != NumLaneElts; ++i) {
23477       int LIdx = LMask[i+l], RIdx = RMask[i+l];
23478
23479       // Ignore any UNDEF components.
23480       if (LIdx < 0 || RIdx < 0 ||
23481           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
23482           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
23483         continue;
23484
23485       // Check that successive elements are being operated on.  If not, this is
23486       // not a horizontal operation.
23487       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
23488       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
23489       if (!(LIdx == Index && RIdx == Index + 1) &&
23490           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
23491         return false;
23492     }
23493   }
23494
23495   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
23496   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
23497   return true;
23498 }
23499
23500 /// Do target-specific dag combines on floating point adds.
23501 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
23502                                   const X86Subtarget *Subtarget) {
23503   EVT VT = N->getValueType(0);
23504   SDValue LHS = N->getOperand(0);
23505   SDValue RHS = N->getOperand(1);
23506
23507   // Try to synthesize horizontal adds from adds of shuffles.
23508   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
23509        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
23510       isHorizontalBinOp(LHS, RHS, true))
23511     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
23512   return SDValue();
23513 }
23514
23515 /// Do target-specific dag combines on floating point subs.
23516 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
23517                                   const X86Subtarget *Subtarget) {
23518   EVT VT = N->getValueType(0);
23519   SDValue LHS = N->getOperand(0);
23520   SDValue RHS = N->getOperand(1);
23521
23522   // Try to synthesize horizontal subs from subs of shuffles.
23523   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
23524        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
23525       isHorizontalBinOp(LHS, RHS, false))
23526     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
23527   return SDValue();
23528 }
23529
23530 /// Do target-specific dag combines on X86ISD::FOR and X86ISD::FXOR nodes.
23531 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
23532   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
23533
23534   // F[X]OR(0.0, x) -> x
23535   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
23536     if (C->getValueAPF().isPosZero())
23537       return N->getOperand(1);
23538
23539   // F[X]OR(x, 0.0) -> x
23540   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
23541     if (C->getValueAPF().isPosZero())
23542       return N->getOperand(0);
23543   return SDValue();
23544 }
23545
23546 /// Do target-specific dag combines on X86ISD::FMIN and X86ISD::FMAX nodes.
23547 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
23548   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
23549
23550   // Only perform optimizations if UnsafeMath is used.
23551   if (!DAG.getTarget().Options.UnsafeFPMath)
23552     return SDValue();
23553
23554   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
23555   // into FMINC and FMAXC, which are Commutative operations.
23556   unsigned NewOp = 0;
23557   switch (N->getOpcode()) {
23558     default: llvm_unreachable("unknown opcode");
23559     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
23560     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
23561   }
23562
23563   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
23564                      N->getOperand(0), N->getOperand(1));
23565 }
23566
23567 /// Do target-specific dag combines on X86ISD::FAND nodes.
23568 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
23569   // FAND(0.0, x) -> 0.0
23570   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
23571     if (C->getValueAPF().isPosZero())
23572       return N->getOperand(0);
23573
23574   // FAND(x, 0.0) -> 0.0
23575   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
23576     if (C->getValueAPF().isPosZero())
23577       return N->getOperand(1);
23578
23579   return SDValue();
23580 }
23581
23582 /// Do target-specific dag combines on X86ISD::FANDN nodes
23583 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
23584   // FANDN(0.0, x) -> x
23585   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
23586     if (C->getValueAPF().isPosZero())
23587       return N->getOperand(1);
23588
23589   // FANDN(x, 0.0) -> 0.0
23590   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
23591     if (C->getValueAPF().isPosZero())
23592       return N->getOperand(1);
23593
23594   return SDValue();
23595 }
23596
23597 static SDValue PerformBTCombine(SDNode *N,
23598                                 SelectionDAG &DAG,
23599                                 TargetLowering::DAGCombinerInfo &DCI) {
23600   // BT ignores high bits in the bit index operand.
23601   SDValue Op1 = N->getOperand(1);
23602   if (Op1.hasOneUse()) {
23603     unsigned BitWidth = Op1.getValueSizeInBits();
23604     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
23605     APInt KnownZero, KnownOne;
23606     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
23607                                           !DCI.isBeforeLegalizeOps());
23608     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23609     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
23610         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
23611       DCI.CommitTargetLoweringOpt(TLO);
23612   }
23613   return SDValue();
23614 }
23615
23616 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
23617   SDValue Op = N->getOperand(0);
23618   if (Op.getOpcode() == ISD::BITCAST)
23619     Op = Op.getOperand(0);
23620   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
23621   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
23622       VT.getVectorElementType().getSizeInBits() ==
23623       OpVT.getVectorElementType().getSizeInBits()) {
23624     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
23625   }
23626   return SDValue();
23627 }
23628
23629 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
23630                                                const X86Subtarget *Subtarget) {
23631   EVT VT = N->getValueType(0);
23632   if (!VT.isVector())
23633     return SDValue();
23634
23635   SDValue N0 = N->getOperand(0);
23636   SDValue N1 = N->getOperand(1);
23637   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
23638   SDLoc dl(N);
23639
23640   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
23641   // both SSE and AVX2 since there is no sign-extended shift right
23642   // operation on a vector with 64-bit elements.
23643   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
23644   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
23645   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
23646       N0.getOpcode() == ISD::SIGN_EXTEND)) {
23647     SDValue N00 = N0.getOperand(0);
23648
23649     // EXTLOAD has a better solution on AVX2,
23650     // it may be replaced with X86ISD::VSEXT node.
23651     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
23652       if (!ISD::isNormalLoad(N00.getNode()))
23653         return SDValue();
23654
23655     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
23656         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
23657                                   N00, N1);
23658       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
23659     }
23660   }
23661   return SDValue();
23662 }
23663
23664 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
23665                                   TargetLowering::DAGCombinerInfo &DCI,
23666                                   const X86Subtarget *Subtarget) {
23667   SDValue N0 = N->getOperand(0);
23668   EVT VT = N->getValueType(0);
23669   SDLoc dl(N);
23670
23671   // (i8,i32 sext (sdivrem (i8 x, i8 y)) ->
23672   // (i8,i32 (sdivrem_sext_hreg (i8 x, i8 y)
23673   // This exposes the sext to the sdivrem lowering, so that it directly extends
23674   // from AH (which we otherwise need to do contortions to access).
23675   if (N0.getOpcode() == ISD::SDIVREM && N0.getResNo() == 1 &&
23676       N0.getValueType() == MVT::i8 && VT == MVT::i32) {
23677     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
23678     SDValue R = DAG.getNode(X86ISD::SDIVREM8_SEXT_HREG, dl, NodeTys,
23679                             N0.getOperand(0), N0.getOperand(1));
23680     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
23681     return R.getValue(1);
23682   }
23683
23684   if (!DCI.isBeforeLegalizeOps()) {
23685     if (N0.getValueType() == MVT::i1) {
23686       SDValue Zero = DAG.getConstant(0, dl, VT);
23687       SDValue AllOnes =
23688         DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl, VT);
23689       return DAG.getNode(ISD::SELECT, dl, VT, N0, AllOnes, Zero);
23690     }
23691     return SDValue();
23692   }
23693
23694   if (!Subtarget->hasFp256())
23695     return SDValue();
23696
23697   if (VT.isVector() && VT.getSizeInBits() == 256) {
23698     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
23699     if (R.getNode())
23700       return R;
23701   }
23702
23703   return SDValue();
23704 }
23705
23706 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
23707                                  const X86Subtarget* Subtarget) {
23708   SDLoc dl(N);
23709   EVT VT = N->getValueType(0);
23710
23711   // Let legalize expand this if it isn't a legal type yet.
23712   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
23713     return SDValue();
23714
23715   EVT ScalarVT = VT.getScalarType();
23716   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
23717       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
23718     return SDValue();
23719
23720   SDValue A = N->getOperand(0);
23721   SDValue B = N->getOperand(1);
23722   SDValue C = N->getOperand(2);
23723
23724   bool NegA = (A.getOpcode() == ISD::FNEG);
23725   bool NegB = (B.getOpcode() == ISD::FNEG);
23726   bool NegC = (C.getOpcode() == ISD::FNEG);
23727
23728   // Negative multiplication when NegA xor NegB
23729   bool NegMul = (NegA != NegB);
23730   if (NegA)
23731     A = A.getOperand(0);
23732   if (NegB)
23733     B = B.getOperand(0);
23734   if (NegC)
23735     C = C.getOperand(0);
23736
23737   unsigned Opcode;
23738   if (!NegMul)
23739     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
23740   else
23741     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
23742
23743   return DAG.getNode(Opcode, dl, VT, A, B, C);
23744 }
23745
23746 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
23747                                   TargetLowering::DAGCombinerInfo &DCI,
23748                                   const X86Subtarget *Subtarget) {
23749   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
23750   //           (and (i32 x86isd::setcc_carry), 1)
23751   // This eliminates the zext. This transformation is necessary because
23752   // ISD::SETCC is always legalized to i8.
23753   SDLoc dl(N);
23754   SDValue N0 = N->getOperand(0);
23755   EVT VT = N->getValueType(0);
23756
23757   if (N0.getOpcode() == ISD::AND &&
23758       N0.hasOneUse() &&
23759       N0.getOperand(0).hasOneUse()) {
23760     SDValue N00 = N0.getOperand(0);
23761     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
23762       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
23763       if (!C || C->getZExtValue() != 1)
23764         return SDValue();
23765       return DAG.getNode(ISD::AND, dl, VT,
23766                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
23767                                      N00.getOperand(0), N00.getOperand(1)),
23768                          DAG.getConstant(1, dl, VT));
23769     }
23770   }
23771
23772   if (N0.getOpcode() == ISD::TRUNCATE &&
23773       N0.hasOneUse() &&
23774       N0.getOperand(0).hasOneUse()) {
23775     SDValue N00 = N0.getOperand(0);
23776     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
23777       return DAG.getNode(ISD::AND, dl, VT,
23778                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
23779                                      N00.getOperand(0), N00.getOperand(1)),
23780                          DAG.getConstant(1, dl, VT));
23781     }
23782   }
23783   if (VT.is256BitVector()) {
23784     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
23785     if (R.getNode())
23786       return R;
23787   }
23788
23789   // (i8,i32 zext (udivrem (i8 x, i8 y)) ->
23790   // (i8,i32 (udivrem_zext_hreg (i8 x, i8 y)
23791   // This exposes the zext to the udivrem lowering, so that it directly extends
23792   // from AH (which we otherwise need to do contortions to access).
23793   if (N0.getOpcode() == ISD::UDIVREM &&
23794       N0.getResNo() == 1 && N0.getValueType() == MVT::i8 &&
23795       (VT == MVT::i32 || VT == MVT::i64)) {
23796     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
23797     SDValue R = DAG.getNode(X86ISD::UDIVREM8_ZEXT_HREG, dl, NodeTys,
23798                             N0.getOperand(0), N0.getOperand(1));
23799     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
23800     return R.getValue(1);
23801   }
23802
23803   return SDValue();
23804 }
23805
23806 // Optimize x == -y --> x+y == 0
23807 //          x != -y --> x+y != 0
23808 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
23809                                       const X86Subtarget* Subtarget) {
23810   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
23811   SDValue LHS = N->getOperand(0);
23812   SDValue RHS = N->getOperand(1);
23813   EVT VT = N->getValueType(0);
23814   SDLoc DL(N);
23815
23816   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
23817     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
23818       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
23819         SDValue addV = DAG.getNode(ISD::ADD, DL, LHS.getValueType(), RHS,
23820                                    LHS.getOperand(1));
23821         return DAG.getSetCC(DL, N->getValueType(0), addV,
23822                             DAG.getConstant(0, DL, addV.getValueType()), CC);
23823       }
23824   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
23825     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
23826       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
23827         SDValue addV = DAG.getNode(ISD::ADD, DL, RHS.getValueType(), LHS,
23828                                    RHS.getOperand(1));
23829         return DAG.getSetCC(DL, N->getValueType(0), addV,
23830                             DAG.getConstant(0, DL, addV.getValueType()), CC);
23831       }
23832
23833   if (VT.getScalarType() == MVT::i1 &&
23834       (CC == ISD::SETNE || CC == ISD::SETEQ || ISD::isSignedIntSetCC(CC))) {
23835     bool IsSEXT0 =
23836         (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
23837         (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
23838     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
23839
23840     if (!IsSEXT0 || !IsVZero1) {
23841       // Swap the operands and update the condition code.
23842       std::swap(LHS, RHS);
23843       CC = ISD::getSetCCSwappedOperands(CC);
23844
23845       IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
23846                 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
23847       IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
23848     }
23849
23850     if (IsSEXT0 && IsVZero1) {
23851       assert(VT == LHS.getOperand(0).getValueType() &&
23852              "Uexpected operand type");
23853       if (CC == ISD::SETGT)
23854         return DAG.getConstant(0, DL, VT);
23855       if (CC == ISD::SETLE)
23856         return DAG.getConstant(1, DL, VT);
23857       if (CC == ISD::SETEQ || CC == ISD::SETGE)
23858         return DAG.getNOT(DL, LHS.getOperand(0), VT);
23859
23860       assert((CC == ISD::SETNE || CC == ISD::SETLT) &&
23861              "Unexpected condition code!");
23862       return LHS.getOperand(0);
23863     }
23864   }
23865
23866   return SDValue();
23867 }
23868
23869 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
23870                                          SelectionDAG &DAG) {
23871   SDLoc dl(Load);
23872   MVT VT = Load->getSimpleValueType(0);
23873   MVT EVT = VT.getVectorElementType();
23874   SDValue Addr = Load->getOperand(1);
23875   SDValue NewAddr = DAG.getNode(
23876       ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
23877       DAG.getConstant(Index * EVT.getStoreSize(), dl,
23878                       Addr.getSimpleValueType()));
23879
23880   SDValue NewLoad =
23881       DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
23882                   DAG.getMachineFunction().getMachineMemOperand(
23883                       Load->getMemOperand(), 0, EVT.getStoreSize()));
23884   return NewLoad;
23885 }
23886
23887 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
23888                                       const X86Subtarget *Subtarget) {
23889   SDLoc dl(N);
23890   MVT VT = N->getOperand(1)->getSimpleValueType(0);
23891   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
23892          "X86insertps is only defined for v4x32");
23893
23894   SDValue Ld = N->getOperand(1);
23895   if (MayFoldLoad(Ld)) {
23896     // Extract the countS bits from the immediate so we can get the proper
23897     // address when narrowing the vector load to a specific element.
23898     // When the second source op is a memory address, insertps doesn't use
23899     // countS and just gets an f32 from that address.
23900     unsigned DestIndex =
23901         cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
23902
23903     Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
23904
23905     // Create this as a scalar to vector to match the instruction pattern.
23906     SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
23907     // countS bits are ignored when loading from memory on insertps, which
23908     // means we don't need to explicitly set them to 0.
23909     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
23910                        LoadScalarToVector, N->getOperand(2));
23911   }
23912   return SDValue();
23913 }
23914
23915 static SDValue PerformBLENDICombine(SDNode *N, SelectionDAG &DAG) {
23916   SDValue V0 = N->getOperand(0);
23917   SDValue V1 = N->getOperand(1);
23918   SDLoc DL(N);
23919   EVT VT = N->getValueType(0);
23920
23921   // Canonicalize a v2f64 blend with a mask of 2 by swapping the vector
23922   // operands and changing the mask to 1. This saves us a bunch of
23923   // pattern-matching possibilities related to scalar math ops in SSE/AVX.
23924   // x86InstrInfo knows how to commute this back after instruction selection
23925   // if it would help register allocation.
23926
23927   // TODO: If optimizing for size or a processor that doesn't suffer from
23928   // partial register update stalls, this should be transformed into a MOVSD
23929   // instruction because a MOVSD is 1-2 bytes smaller than a BLENDPD.
23930
23931   if (VT == MVT::v2f64)
23932     if (auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(2)))
23933       if (Mask->getZExtValue() == 2 && !isShuffleFoldableLoad(V0)) {
23934         SDValue NewMask = DAG.getConstant(1, DL, MVT::i8);
23935         return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V0, NewMask);
23936       }
23937
23938   return SDValue();
23939 }
23940
23941 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
23942 // as "sbb reg,reg", since it can be extended without zext and produces
23943 // an all-ones bit which is more useful than 0/1 in some cases.
23944 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
23945                                MVT VT) {
23946   if (VT == MVT::i8)
23947     return DAG.getNode(ISD::AND, DL, VT,
23948                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
23949                                    DAG.getConstant(X86::COND_B, DL, MVT::i8),
23950                                    EFLAGS),
23951                        DAG.getConstant(1, DL, VT));
23952   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
23953   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
23954                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
23955                                  DAG.getConstant(X86::COND_B, DL, MVT::i8),
23956                                  EFLAGS));
23957 }
23958
23959 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
23960 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
23961                                    TargetLowering::DAGCombinerInfo &DCI,
23962                                    const X86Subtarget *Subtarget) {
23963   SDLoc DL(N);
23964   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
23965   SDValue EFLAGS = N->getOperand(1);
23966
23967   if (CC == X86::COND_A) {
23968     // Try to convert COND_A into COND_B in an attempt to facilitate
23969     // materializing "setb reg".
23970     //
23971     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
23972     // cannot take an immediate as its first operand.
23973     //
23974     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
23975         EFLAGS.getValueType().isInteger() &&
23976         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
23977       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
23978                                    EFLAGS.getNode()->getVTList(),
23979                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
23980       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
23981       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
23982     }
23983   }
23984
23985   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
23986   // a zext and produces an all-ones bit which is more useful than 0/1 in some
23987   // cases.
23988   if (CC == X86::COND_B)
23989     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
23990
23991   SDValue Flags;
23992
23993   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
23994   if (Flags.getNode()) {
23995     SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
23996     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
23997   }
23998
23999   return SDValue();
24000 }
24001
24002 // Optimize branch condition evaluation.
24003 //
24004 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
24005                                     TargetLowering::DAGCombinerInfo &DCI,
24006                                     const X86Subtarget *Subtarget) {
24007   SDLoc DL(N);
24008   SDValue Chain = N->getOperand(0);
24009   SDValue Dest = N->getOperand(1);
24010   SDValue EFLAGS = N->getOperand(3);
24011   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
24012
24013   SDValue Flags;
24014
24015   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
24016   if (Flags.getNode()) {
24017     SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
24018     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
24019                        Flags);
24020   }
24021
24022   return SDValue();
24023 }
24024
24025 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
24026                                                          SelectionDAG &DAG) {
24027   // Take advantage of vector comparisons producing 0 or -1 in each lane to
24028   // optimize away operation when it's from a constant.
24029   //
24030   // The general transformation is:
24031   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
24032   //       AND(VECTOR_CMP(x,y), constant2)
24033   //    constant2 = UNARYOP(constant)
24034
24035   // Early exit if this isn't a vector operation, the operand of the
24036   // unary operation isn't a bitwise AND, or if the sizes of the operations
24037   // aren't the same.
24038   EVT VT = N->getValueType(0);
24039   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
24040       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
24041       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
24042     return SDValue();
24043
24044   // Now check that the other operand of the AND is a constant. We could
24045   // make the transformation for non-constant splats as well, but it's unclear
24046   // that would be a benefit as it would not eliminate any operations, just
24047   // perform one more step in scalar code before moving to the vector unit.
24048   if (BuildVectorSDNode *BV =
24049           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
24050     // Bail out if the vector isn't a constant.
24051     if (!BV->isConstant())
24052       return SDValue();
24053
24054     // Everything checks out. Build up the new and improved node.
24055     SDLoc DL(N);
24056     EVT IntVT = BV->getValueType(0);
24057     // Create a new constant of the appropriate type for the transformed
24058     // DAG.
24059     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
24060     // The AND node needs bitcasts to/from an integer vector type around it.
24061     SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
24062     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
24063                                  N->getOperand(0)->getOperand(0), MaskConst);
24064     SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
24065     return Res;
24066   }
24067
24068   return SDValue();
24069 }
24070
24071 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
24072                                         const X86Subtarget *Subtarget) {
24073   // First try to optimize away the conversion entirely when it's
24074   // conditionally from a constant. Vectors only.
24075   SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG);
24076   if (Res != SDValue())
24077     return Res;
24078
24079   // Now move on to more general possibilities.
24080   SDValue Op0 = N->getOperand(0);
24081   EVT InVT = Op0->getValueType(0);
24082
24083   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
24084   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
24085     SDLoc dl(N);
24086     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
24087     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
24088     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
24089   }
24090
24091   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
24092   // a 32-bit target where SSE doesn't support i64->FP operations.
24093   if (Op0.getOpcode() == ISD::LOAD) {
24094     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
24095     EVT VT = Ld->getValueType(0);
24096
24097     // This transformation is not supported if the result type is f16
24098     if (N->getValueType(0) == MVT::f16)
24099       return SDValue();
24100
24101     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
24102         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
24103         !Subtarget->is64Bit() && VT == MVT::i64) {
24104       SDValue FILDChain = Subtarget->getTargetLowering()->BuildFILD(
24105           SDValue(N, 0), Ld->getValueType(0), Ld->getChain(), Op0, DAG);
24106       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
24107       return FILDChain;
24108     }
24109   }
24110   return SDValue();
24111 }
24112
24113 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
24114 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
24115                                  X86TargetLowering::DAGCombinerInfo &DCI) {
24116   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
24117   // the result is either zero or one (depending on the input carry bit).
24118   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
24119   if (X86::isZeroNode(N->getOperand(0)) &&
24120       X86::isZeroNode(N->getOperand(1)) &&
24121       // We don't have a good way to replace an EFLAGS use, so only do this when
24122       // dead right now.
24123       SDValue(N, 1).use_empty()) {
24124     SDLoc DL(N);
24125     EVT VT = N->getValueType(0);
24126     SDValue CarryOut = DAG.getConstant(0, DL, N->getValueType(1));
24127     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
24128                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
24129                                            DAG.getConstant(X86::COND_B, DL,
24130                                                            MVT::i8),
24131                                            N->getOperand(2)),
24132                                DAG.getConstant(1, DL, VT));
24133     return DCI.CombineTo(N, Res1, CarryOut);
24134   }
24135
24136   return SDValue();
24137 }
24138
24139 // fold (add Y, (sete  X, 0)) -> adc  0, Y
24140 //      (add Y, (setne X, 0)) -> sbb -1, Y
24141 //      (sub (sete  X, 0), Y) -> sbb  0, Y
24142 //      (sub (setne X, 0), Y) -> adc -1, Y
24143 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
24144   SDLoc DL(N);
24145
24146   // Look through ZExts.
24147   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
24148   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
24149     return SDValue();
24150
24151   SDValue SetCC = Ext.getOperand(0);
24152   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
24153     return SDValue();
24154
24155   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
24156   if (CC != X86::COND_E && CC != X86::COND_NE)
24157     return SDValue();
24158
24159   SDValue Cmp = SetCC.getOperand(1);
24160   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
24161       !X86::isZeroNode(Cmp.getOperand(1)) ||
24162       !Cmp.getOperand(0).getValueType().isInteger())
24163     return SDValue();
24164
24165   SDValue CmpOp0 = Cmp.getOperand(0);
24166   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
24167                                DAG.getConstant(1, DL, CmpOp0.getValueType()));
24168
24169   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
24170   if (CC == X86::COND_NE)
24171     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
24172                        DL, OtherVal.getValueType(), OtherVal,
24173                        DAG.getConstant(-1ULL, DL, OtherVal.getValueType()),
24174                        NewCmp);
24175   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
24176                      DL, OtherVal.getValueType(), OtherVal,
24177                      DAG.getConstant(0, DL, OtherVal.getValueType()), NewCmp);
24178 }
24179
24180 /// PerformADDCombine - Do target-specific dag combines on integer adds.
24181 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
24182                                  const X86Subtarget *Subtarget) {
24183   EVT VT = N->getValueType(0);
24184   SDValue Op0 = N->getOperand(0);
24185   SDValue Op1 = N->getOperand(1);
24186
24187   // Try to synthesize horizontal adds from adds of shuffles.
24188   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
24189        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
24190       isHorizontalBinOp(Op0, Op1, true))
24191     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
24192
24193   return OptimizeConditionalInDecrement(N, DAG);
24194 }
24195
24196 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
24197                                  const X86Subtarget *Subtarget) {
24198   SDValue Op0 = N->getOperand(0);
24199   SDValue Op1 = N->getOperand(1);
24200
24201   // X86 can't encode an immediate LHS of a sub. See if we can push the
24202   // negation into a preceding instruction.
24203   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
24204     // If the RHS of the sub is a XOR with one use and a constant, invert the
24205     // immediate. Then add one to the LHS of the sub so we can turn
24206     // X-Y -> X+~Y+1, saving one register.
24207     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
24208         isa<ConstantSDNode>(Op1.getOperand(1))) {
24209       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
24210       EVT VT = Op0.getValueType();
24211       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
24212                                    Op1.getOperand(0),
24213                                    DAG.getConstant(~XorC, SDLoc(Op1), VT));
24214       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
24215                          DAG.getConstant(C->getAPIntValue() + 1, SDLoc(N), VT));
24216     }
24217   }
24218
24219   // Try to synthesize horizontal adds from adds of shuffles.
24220   EVT VT = N->getValueType(0);
24221   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
24222        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
24223       isHorizontalBinOp(Op0, Op1, true))
24224     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
24225
24226   return OptimizeConditionalInDecrement(N, DAG);
24227 }
24228
24229 /// performVZEXTCombine - Performs build vector combines
24230 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
24231                                    TargetLowering::DAGCombinerInfo &DCI,
24232                                    const X86Subtarget *Subtarget) {
24233   SDLoc DL(N);
24234   MVT VT = N->getSimpleValueType(0);
24235   SDValue Op = N->getOperand(0);
24236   MVT OpVT = Op.getSimpleValueType();
24237   MVT OpEltVT = OpVT.getVectorElementType();
24238   unsigned InputBits = OpEltVT.getSizeInBits() * VT.getVectorNumElements();
24239
24240   // (vzext (bitcast (vzext (x)) -> (vzext x)
24241   SDValue V = Op;
24242   while (V.getOpcode() == ISD::BITCAST)
24243     V = V.getOperand(0);
24244
24245   if (V != Op && V.getOpcode() == X86ISD::VZEXT) {
24246     MVT InnerVT = V.getSimpleValueType();
24247     MVT InnerEltVT = InnerVT.getVectorElementType();
24248
24249     // If the element sizes match exactly, we can just do one larger vzext. This
24250     // is always an exact type match as vzext operates on integer types.
24251     if (OpEltVT == InnerEltVT) {
24252       assert(OpVT == InnerVT && "Types must match for vzext!");
24253       return DAG.getNode(X86ISD::VZEXT, DL, VT, V.getOperand(0));
24254     }
24255
24256     // The only other way we can combine them is if only a single element of the
24257     // inner vzext is used in the input to the outer vzext.
24258     if (InnerEltVT.getSizeInBits() < InputBits)
24259       return SDValue();
24260
24261     // In this case, the inner vzext is completely dead because we're going to
24262     // only look at bits inside of the low element. Just do the outer vzext on
24263     // a bitcast of the input to the inner.
24264     return DAG.getNode(X86ISD::VZEXT, DL, VT,
24265                        DAG.getNode(ISD::BITCAST, DL, OpVT, V));
24266   }
24267
24268   // Check if we can bypass extracting and re-inserting an element of an input
24269   // vector. Essentialy:
24270   // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
24271   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR &&
24272       V.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
24273       V.getOperand(0).getSimpleValueType().getSizeInBits() == InputBits) {
24274     SDValue ExtractedV = V.getOperand(0);
24275     SDValue OrigV = ExtractedV.getOperand(0);
24276     if (auto *ExtractIdx = dyn_cast<ConstantSDNode>(ExtractedV.getOperand(1)))
24277       if (ExtractIdx->getZExtValue() == 0) {
24278         MVT OrigVT = OrigV.getSimpleValueType();
24279         // Extract a subvector if necessary...
24280         if (OrigVT.getSizeInBits() > OpVT.getSizeInBits()) {
24281           int Ratio = OrigVT.getSizeInBits() / OpVT.getSizeInBits();
24282           OrigVT = MVT::getVectorVT(OrigVT.getVectorElementType(),
24283                                     OrigVT.getVectorNumElements() / Ratio);
24284           OrigV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigVT, OrigV,
24285                               DAG.getIntPtrConstant(0, DL));
24286         }
24287         Op = DAG.getNode(ISD::BITCAST, DL, OpVT, OrigV);
24288         return DAG.getNode(X86ISD::VZEXT, DL, VT, Op);
24289       }
24290   }
24291
24292   return SDValue();
24293 }
24294
24295 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
24296                                              DAGCombinerInfo &DCI) const {
24297   SelectionDAG &DAG = DCI.DAG;
24298   switch (N->getOpcode()) {
24299   default: break;
24300   case ISD::EXTRACT_VECTOR_ELT:
24301     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
24302   case ISD::VSELECT:
24303   case ISD::SELECT:
24304   case X86ISD::SHRUNKBLEND:
24305     return PerformSELECTCombine(N, DAG, DCI, Subtarget);
24306   case ISD::BITCAST:        return PerformBITCASTCombine(N, DAG);
24307   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
24308   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
24309   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
24310   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
24311   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
24312   case ISD::SHL:
24313   case ISD::SRA:
24314   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
24315   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
24316   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
24317   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
24318   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
24319   case ISD::MLOAD:          return PerformMLOADCombine(N, DAG, DCI, Subtarget);
24320   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
24321   case ISD::MSTORE:         return PerformMSTORECombine(N, DAG, Subtarget);
24322   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, Subtarget);
24323   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
24324   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
24325   case X86ISD::FXOR:
24326   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
24327   case X86ISD::FMIN:
24328   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
24329   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
24330   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
24331   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
24332   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
24333   case ISD::ANY_EXTEND:
24334   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
24335   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
24336   case ISD::SIGN_EXTEND_INREG:
24337     return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
24338   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
24339   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
24340   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
24341   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
24342   case X86ISD::SHUFP:       // Handle all target specific shuffles
24343   case X86ISD::PALIGNR:
24344   case X86ISD::UNPCKH:
24345   case X86ISD::UNPCKL:
24346   case X86ISD::MOVHLPS:
24347   case X86ISD::MOVLHPS:
24348   case X86ISD::PSHUFB:
24349   case X86ISD::PSHUFD:
24350   case X86ISD::PSHUFHW:
24351   case X86ISD::PSHUFLW:
24352   case X86ISD::MOVSS:
24353   case X86ISD::MOVSD:
24354   case X86ISD::VPERMILPI:
24355   case X86ISD::VPERM2X128:
24356   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
24357   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
24358   case ISD::INTRINSIC_WO_CHAIN:
24359     return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
24360   case X86ISD::INSERTPS: {
24361     if (getTargetMachine().getOptLevel() > CodeGenOpt::None)
24362       return PerformINSERTPSCombine(N, DAG, Subtarget);
24363     break;
24364   }
24365   case X86ISD::BLENDI:    return PerformBLENDICombine(N, DAG);
24366   }
24367
24368   return SDValue();
24369 }
24370
24371 /// isTypeDesirableForOp - Return true if the target has native support for
24372 /// the specified value type and it is 'desirable' to use the type for the
24373 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
24374 /// instruction encodings are longer and some i16 instructions are slow.
24375 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
24376   if (!isTypeLegal(VT))
24377     return false;
24378   if (VT != MVT::i16)
24379     return true;
24380
24381   switch (Opc) {
24382   default:
24383     return true;
24384   case ISD::LOAD:
24385   case ISD::SIGN_EXTEND:
24386   case ISD::ZERO_EXTEND:
24387   case ISD::ANY_EXTEND:
24388   case ISD::SHL:
24389   case ISD::SRL:
24390   case ISD::SUB:
24391   case ISD::ADD:
24392   case ISD::MUL:
24393   case ISD::AND:
24394   case ISD::OR:
24395   case ISD::XOR:
24396     return false;
24397   }
24398 }
24399
24400 /// IsDesirableToPromoteOp - This method query the target whether it is
24401 /// beneficial for dag combiner to promote the specified node. If true, it
24402 /// should return the desired promotion type by reference.
24403 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
24404   EVT VT = Op.getValueType();
24405   if (VT != MVT::i16)
24406     return false;
24407
24408   bool Promote = false;
24409   bool Commute = false;
24410   switch (Op.getOpcode()) {
24411   default: break;
24412   case ISD::LOAD: {
24413     LoadSDNode *LD = cast<LoadSDNode>(Op);
24414     // If the non-extending load has a single use and it's not live out, then it
24415     // might be folded.
24416     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
24417                                                      Op.hasOneUse()*/) {
24418       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
24419              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
24420         // The only case where we'd want to promote LOAD (rather then it being
24421         // promoted as an operand is when it's only use is liveout.
24422         if (UI->getOpcode() != ISD::CopyToReg)
24423           return false;
24424       }
24425     }
24426     Promote = true;
24427     break;
24428   }
24429   case ISD::SIGN_EXTEND:
24430   case ISD::ZERO_EXTEND:
24431   case ISD::ANY_EXTEND:
24432     Promote = true;
24433     break;
24434   case ISD::SHL:
24435   case ISD::SRL: {
24436     SDValue N0 = Op.getOperand(0);
24437     // Look out for (store (shl (load), x)).
24438     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
24439       return false;
24440     Promote = true;
24441     break;
24442   }
24443   case ISD::ADD:
24444   case ISD::MUL:
24445   case ISD::AND:
24446   case ISD::OR:
24447   case ISD::XOR:
24448     Commute = true;
24449     // fallthrough
24450   case ISD::SUB: {
24451     SDValue N0 = Op.getOperand(0);
24452     SDValue N1 = Op.getOperand(1);
24453     if (!Commute && MayFoldLoad(N1))
24454       return false;
24455     // Avoid disabling potential load folding opportunities.
24456     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
24457       return false;
24458     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
24459       return false;
24460     Promote = true;
24461   }
24462   }
24463
24464   PVT = MVT::i32;
24465   return Promote;
24466 }
24467
24468 //===----------------------------------------------------------------------===//
24469 //                           X86 Inline Assembly Support
24470 //===----------------------------------------------------------------------===//
24471
24472 // Helper to match a string separated by whitespace.
24473 static bool matchAsm(StringRef S, ArrayRef<const char *> Pieces) {
24474   S = S.substr(S.find_first_not_of(" \t")); // Skip leading whitespace.
24475
24476   for (StringRef Piece : Pieces) {
24477     if (!S.startswith(Piece)) // Check if the piece matches.
24478       return false;
24479
24480     S = S.substr(Piece.size());
24481     StringRef::size_type Pos = S.find_first_not_of(" \t");
24482     if (Pos == 0) // We matched a prefix.
24483       return false;
24484
24485     S = S.substr(Pos);
24486   }
24487
24488   return S.empty();
24489 }
24490
24491 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
24492
24493   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
24494     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
24495         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
24496         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
24497
24498       if (AsmPieces.size() == 3)
24499         return true;
24500       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
24501         return true;
24502     }
24503   }
24504   return false;
24505 }
24506
24507 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
24508   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
24509
24510   std::string AsmStr = IA->getAsmString();
24511
24512   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
24513   if (!Ty || Ty->getBitWidth() % 16 != 0)
24514     return false;
24515
24516   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
24517   SmallVector<StringRef, 4> AsmPieces;
24518   SplitString(AsmStr, AsmPieces, ";\n");
24519
24520   switch (AsmPieces.size()) {
24521   default: return false;
24522   case 1:
24523     // FIXME: this should verify that we are targeting a 486 or better.  If not,
24524     // we will turn this bswap into something that will be lowered to logical
24525     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
24526     // lower so don't worry about this.
24527     // bswap $0
24528     if (matchAsm(AsmPieces[0], {"bswap", "$0"}) ||
24529         matchAsm(AsmPieces[0], {"bswapl", "$0"}) ||
24530         matchAsm(AsmPieces[0], {"bswapq", "$0"}) ||
24531         matchAsm(AsmPieces[0], {"bswap", "${0:q}"}) ||
24532         matchAsm(AsmPieces[0], {"bswapl", "${0:q}"}) ||
24533         matchAsm(AsmPieces[0], {"bswapq", "${0:q}"})) {
24534       // No need to check constraints, nothing other than the equivalent of
24535       // "=r,0" would be valid here.
24536       return IntrinsicLowering::LowerToByteSwap(CI);
24537     }
24538
24539     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
24540     if (CI->getType()->isIntegerTy(16) &&
24541         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
24542         (matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) ||
24543          matchAsm(AsmPieces[0], {"rolw", "$$8,", "${0:w}"}))) {
24544       AsmPieces.clear();
24545       const std::string &ConstraintsStr = IA->getConstraintString();
24546       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
24547       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
24548       if (clobbersFlagRegisters(AsmPieces))
24549         return IntrinsicLowering::LowerToByteSwap(CI);
24550     }
24551     break;
24552   case 3:
24553     if (CI->getType()->isIntegerTy(32) &&
24554         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
24555         matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) &&
24556         matchAsm(AsmPieces[1], {"rorl", "$$16,", "$0"}) &&
24557         matchAsm(AsmPieces[2], {"rorw", "$$8,", "${0:w}"})) {
24558       AsmPieces.clear();
24559       const std::string &ConstraintsStr = IA->getConstraintString();
24560       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
24561       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
24562       if (clobbersFlagRegisters(AsmPieces))
24563         return IntrinsicLowering::LowerToByteSwap(CI);
24564     }
24565
24566     if (CI->getType()->isIntegerTy(64)) {
24567       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
24568       if (Constraints.size() >= 2 &&
24569           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
24570           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
24571         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
24572         if (matchAsm(AsmPieces[0], {"bswap", "%eax"}) &&
24573             matchAsm(AsmPieces[1], {"bswap", "%edx"}) &&
24574             matchAsm(AsmPieces[2], {"xchgl", "%eax,", "%edx"}))
24575           return IntrinsicLowering::LowerToByteSwap(CI);
24576       }
24577     }
24578     break;
24579   }
24580   return false;
24581 }
24582
24583 /// getConstraintType - Given a constraint letter, return the type of
24584 /// constraint it is for this target.
24585 X86TargetLowering::ConstraintType
24586 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
24587   if (Constraint.size() == 1) {
24588     switch (Constraint[0]) {
24589     case 'R':
24590     case 'q':
24591     case 'Q':
24592     case 'f':
24593     case 't':
24594     case 'u':
24595     case 'y':
24596     case 'x':
24597     case 'Y':
24598     case 'l':
24599       return C_RegisterClass;
24600     case 'a':
24601     case 'b':
24602     case 'c':
24603     case 'd':
24604     case 'S':
24605     case 'D':
24606     case 'A':
24607       return C_Register;
24608     case 'I':
24609     case 'J':
24610     case 'K':
24611     case 'L':
24612     case 'M':
24613     case 'N':
24614     case 'G':
24615     case 'C':
24616     case 'e':
24617     case 'Z':
24618       return C_Other;
24619     default:
24620       break;
24621     }
24622   }
24623   return TargetLowering::getConstraintType(Constraint);
24624 }
24625
24626 /// Examine constraint type and operand type and determine a weight value.
24627 /// This object must already have been set up with the operand type
24628 /// and the current alternative constraint selected.
24629 TargetLowering::ConstraintWeight
24630   X86TargetLowering::getSingleConstraintMatchWeight(
24631     AsmOperandInfo &info, const char *constraint) const {
24632   ConstraintWeight weight = CW_Invalid;
24633   Value *CallOperandVal = info.CallOperandVal;
24634     // If we don't have a value, we can't do a match,
24635     // but allow it at the lowest weight.
24636   if (!CallOperandVal)
24637     return CW_Default;
24638   Type *type = CallOperandVal->getType();
24639   // Look at the constraint type.
24640   switch (*constraint) {
24641   default:
24642     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
24643   case 'R':
24644   case 'q':
24645   case 'Q':
24646   case 'a':
24647   case 'b':
24648   case 'c':
24649   case 'd':
24650   case 'S':
24651   case 'D':
24652   case 'A':
24653     if (CallOperandVal->getType()->isIntegerTy())
24654       weight = CW_SpecificReg;
24655     break;
24656   case 'f':
24657   case 't':
24658   case 'u':
24659     if (type->isFloatingPointTy())
24660       weight = CW_SpecificReg;
24661     break;
24662   case 'y':
24663     if (type->isX86_MMXTy() && Subtarget->hasMMX())
24664       weight = CW_SpecificReg;
24665     break;
24666   case 'x':
24667   case 'Y':
24668     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
24669         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
24670       weight = CW_Register;
24671     break;
24672   case 'I':
24673     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
24674       if (C->getZExtValue() <= 31)
24675         weight = CW_Constant;
24676     }
24677     break;
24678   case 'J':
24679     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24680       if (C->getZExtValue() <= 63)
24681         weight = CW_Constant;
24682     }
24683     break;
24684   case 'K':
24685     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24686       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
24687         weight = CW_Constant;
24688     }
24689     break;
24690   case 'L':
24691     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24692       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
24693         weight = CW_Constant;
24694     }
24695     break;
24696   case 'M':
24697     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24698       if (C->getZExtValue() <= 3)
24699         weight = CW_Constant;
24700     }
24701     break;
24702   case 'N':
24703     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24704       if (C->getZExtValue() <= 0xff)
24705         weight = CW_Constant;
24706     }
24707     break;
24708   case 'G':
24709   case 'C':
24710     if (isa<ConstantFP>(CallOperandVal)) {
24711       weight = CW_Constant;
24712     }
24713     break;
24714   case 'e':
24715     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24716       if ((C->getSExtValue() >= -0x80000000LL) &&
24717           (C->getSExtValue() <= 0x7fffffffLL))
24718         weight = CW_Constant;
24719     }
24720     break;
24721   case 'Z':
24722     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24723       if (C->getZExtValue() <= 0xffffffff)
24724         weight = CW_Constant;
24725     }
24726     break;
24727   }
24728   return weight;
24729 }
24730
24731 /// LowerXConstraint - try to replace an X constraint, which matches anything,
24732 /// with another that has more specific requirements based on the type of the
24733 /// corresponding operand.
24734 const char *X86TargetLowering::
24735 LowerXConstraint(EVT ConstraintVT) const {
24736   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
24737   // 'f' like normal targets.
24738   if (ConstraintVT.isFloatingPoint()) {
24739     if (Subtarget->hasSSE2())
24740       return "Y";
24741     if (Subtarget->hasSSE1())
24742       return "x";
24743   }
24744
24745   return TargetLowering::LowerXConstraint(ConstraintVT);
24746 }
24747
24748 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
24749 /// vector.  If it is invalid, don't add anything to Ops.
24750 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
24751                                                      std::string &Constraint,
24752                                                      std::vector<SDValue>&Ops,
24753                                                      SelectionDAG &DAG) const {
24754   SDValue Result;
24755
24756   // Only support length 1 constraints for now.
24757   if (Constraint.length() > 1) return;
24758
24759   char ConstraintLetter = Constraint[0];
24760   switch (ConstraintLetter) {
24761   default: break;
24762   case 'I':
24763     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24764       if (C->getZExtValue() <= 31) {
24765         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24766                                        Op.getValueType());
24767         break;
24768       }
24769     }
24770     return;
24771   case 'J':
24772     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24773       if (C->getZExtValue() <= 63) {
24774         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24775                                        Op.getValueType());
24776         break;
24777       }
24778     }
24779     return;
24780   case 'K':
24781     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24782       if (isInt<8>(C->getSExtValue())) {
24783         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24784                                        Op.getValueType());
24785         break;
24786       }
24787     }
24788     return;
24789   case 'L':
24790     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24791       if (C->getZExtValue() == 0xff || C->getZExtValue() == 0xffff ||
24792           (Subtarget->is64Bit() && C->getZExtValue() == 0xffffffff)) {
24793         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op),
24794                                        Op.getValueType());
24795         break;
24796       }
24797     }
24798     return;
24799   case 'M':
24800     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24801       if (C->getZExtValue() <= 3) {
24802         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24803                                        Op.getValueType());
24804         break;
24805       }
24806     }
24807     return;
24808   case 'N':
24809     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24810       if (C->getZExtValue() <= 255) {
24811         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24812                                        Op.getValueType());
24813         break;
24814       }
24815     }
24816     return;
24817   case 'O':
24818     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24819       if (C->getZExtValue() <= 127) {
24820         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24821                                        Op.getValueType());
24822         break;
24823       }
24824     }
24825     return;
24826   case 'e': {
24827     // 32-bit signed value
24828     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24829       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
24830                                            C->getSExtValue())) {
24831         // Widen to 64 bits here to get it sign extended.
24832         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op), MVT::i64);
24833         break;
24834       }
24835     // FIXME gcc accepts some relocatable values here too, but only in certain
24836     // memory models; it's complicated.
24837     }
24838     return;
24839   }
24840   case 'Z': {
24841     // 32-bit unsigned value
24842     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24843       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
24844                                            C->getZExtValue())) {
24845         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24846                                        Op.getValueType());
24847         break;
24848       }
24849     }
24850     // FIXME gcc accepts some relocatable values here too, but only in certain
24851     // memory models; it's complicated.
24852     return;
24853   }
24854   case 'i': {
24855     // Literal immediates are always ok.
24856     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
24857       // Widen to 64 bits here to get it sign extended.
24858       Result = DAG.getTargetConstant(CST->getSExtValue(), SDLoc(Op), MVT::i64);
24859       break;
24860     }
24861
24862     // In any sort of PIC mode addresses need to be computed at runtime by
24863     // adding in a register or some sort of table lookup.  These can't
24864     // be used as immediates.
24865     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
24866       return;
24867
24868     // If we are in non-pic codegen mode, we allow the address of a global (with
24869     // an optional displacement) to be used with 'i'.
24870     GlobalAddressSDNode *GA = nullptr;
24871     int64_t Offset = 0;
24872
24873     // Match either (GA), (GA+C), (GA+C1+C2), etc.
24874     while (1) {
24875       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
24876         Offset += GA->getOffset();
24877         break;
24878       } else if (Op.getOpcode() == ISD::ADD) {
24879         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
24880           Offset += C->getZExtValue();
24881           Op = Op.getOperand(0);
24882           continue;
24883         }
24884       } else if (Op.getOpcode() == ISD::SUB) {
24885         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
24886           Offset += -C->getZExtValue();
24887           Op = Op.getOperand(0);
24888           continue;
24889         }
24890       }
24891
24892       // Otherwise, this isn't something we can handle, reject it.
24893       return;
24894     }
24895
24896     const GlobalValue *GV = GA->getGlobal();
24897     // If we require an extra load to get this address, as in PIC mode, we
24898     // can't accept it.
24899     if (isGlobalStubReference(
24900             Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
24901       return;
24902
24903     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
24904                                         GA->getValueType(0), Offset);
24905     break;
24906   }
24907   }
24908
24909   if (Result.getNode()) {
24910     Ops.push_back(Result);
24911     return;
24912   }
24913   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
24914 }
24915
24916 std::pair<unsigned, const TargetRegisterClass *>
24917 X86TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
24918                                                 const std::string &Constraint,
24919                                                 MVT VT) const {
24920   // First, see if this is a constraint that directly corresponds to an LLVM
24921   // register class.
24922   if (Constraint.size() == 1) {
24923     // GCC Constraint Letters
24924     switch (Constraint[0]) {
24925     default: break;
24926       // TODO: Slight differences here in allocation order and leaving
24927       // RIP in the class. Do they matter any more here than they do
24928       // in the normal allocation?
24929     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
24930       if (Subtarget->is64Bit()) {
24931         if (VT == MVT::i32 || VT == MVT::f32)
24932           return std::make_pair(0U, &X86::GR32RegClass);
24933         if (VT == MVT::i16)
24934           return std::make_pair(0U, &X86::GR16RegClass);
24935         if (VT == MVT::i8 || VT == MVT::i1)
24936           return std::make_pair(0U, &X86::GR8RegClass);
24937         if (VT == MVT::i64 || VT == MVT::f64)
24938           return std::make_pair(0U, &X86::GR64RegClass);
24939         break;
24940       }
24941       // 32-bit fallthrough
24942     case 'Q':   // Q_REGS
24943       if (VT == MVT::i32 || VT == MVT::f32)
24944         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
24945       if (VT == MVT::i16)
24946         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
24947       if (VT == MVT::i8 || VT == MVT::i1)
24948         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
24949       if (VT == MVT::i64)
24950         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
24951       break;
24952     case 'r':   // GENERAL_REGS
24953     case 'l':   // INDEX_REGS
24954       if (VT == MVT::i8 || VT == MVT::i1)
24955         return std::make_pair(0U, &X86::GR8RegClass);
24956       if (VT == MVT::i16)
24957         return std::make_pair(0U, &X86::GR16RegClass);
24958       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
24959         return std::make_pair(0U, &X86::GR32RegClass);
24960       return std::make_pair(0U, &X86::GR64RegClass);
24961     case 'R':   // LEGACY_REGS
24962       if (VT == MVT::i8 || VT == MVT::i1)
24963         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
24964       if (VT == MVT::i16)
24965         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
24966       if (VT == MVT::i32 || !Subtarget->is64Bit())
24967         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
24968       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
24969     case 'f':  // FP Stack registers.
24970       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
24971       // value to the correct fpstack register class.
24972       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
24973         return std::make_pair(0U, &X86::RFP32RegClass);
24974       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
24975         return std::make_pair(0U, &X86::RFP64RegClass);
24976       return std::make_pair(0U, &X86::RFP80RegClass);
24977     case 'y':   // MMX_REGS if MMX allowed.
24978       if (!Subtarget->hasMMX()) break;
24979       return std::make_pair(0U, &X86::VR64RegClass);
24980     case 'Y':   // SSE_REGS if SSE2 allowed
24981       if (!Subtarget->hasSSE2()) break;
24982       // FALL THROUGH.
24983     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
24984       if (!Subtarget->hasSSE1()) break;
24985
24986       switch (VT.SimpleTy) {
24987       default: break;
24988       // Scalar SSE types.
24989       case MVT::f32:
24990       case MVT::i32:
24991         return std::make_pair(0U, &X86::FR32RegClass);
24992       case MVT::f64:
24993       case MVT::i64:
24994         return std::make_pair(0U, &X86::FR64RegClass);
24995       // Vector types.
24996       case MVT::v16i8:
24997       case MVT::v8i16:
24998       case MVT::v4i32:
24999       case MVT::v2i64:
25000       case MVT::v4f32:
25001       case MVT::v2f64:
25002         return std::make_pair(0U, &X86::VR128RegClass);
25003       // AVX types.
25004       case MVT::v32i8:
25005       case MVT::v16i16:
25006       case MVT::v8i32:
25007       case MVT::v4i64:
25008       case MVT::v8f32:
25009       case MVT::v4f64:
25010         return std::make_pair(0U, &X86::VR256RegClass);
25011       case MVT::v8f64:
25012       case MVT::v16f32:
25013       case MVT::v16i32:
25014       case MVT::v8i64:
25015         return std::make_pair(0U, &X86::VR512RegClass);
25016       }
25017       break;
25018     }
25019   }
25020
25021   // Use the default implementation in TargetLowering to convert the register
25022   // constraint into a member of a register class.
25023   std::pair<unsigned, const TargetRegisterClass*> Res;
25024   Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
25025
25026   // Not found as a standard register?
25027   if (!Res.second) {
25028     // Map st(0) -> st(7) -> ST0
25029     if (Constraint.size() == 7 && Constraint[0] == '{' &&
25030         tolower(Constraint[1]) == 's' &&
25031         tolower(Constraint[2]) == 't' &&
25032         Constraint[3] == '(' &&
25033         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
25034         Constraint[5] == ')' &&
25035         Constraint[6] == '}') {
25036
25037       Res.first = X86::FP0+Constraint[4]-'0';
25038       Res.second = &X86::RFP80RegClass;
25039       return Res;
25040     }
25041
25042     // GCC allows "st(0)" to be called just plain "st".
25043     if (StringRef("{st}").equals_lower(Constraint)) {
25044       Res.first = X86::FP0;
25045       Res.second = &X86::RFP80RegClass;
25046       return Res;
25047     }
25048
25049     // flags -> EFLAGS
25050     if (StringRef("{flags}").equals_lower(Constraint)) {
25051       Res.first = X86::EFLAGS;
25052       Res.second = &X86::CCRRegClass;
25053       return Res;
25054     }
25055
25056     // 'A' means EAX + EDX.
25057     if (Constraint == "A") {
25058       Res.first = X86::EAX;
25059       Res.second = &X86::GR32_ADRegClass;
25060       return Res;
25061     }
25062     return Res;
25063   }
25064
25065   // Otherwise, check to see if this is a register class of the wrong value
25066   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
25067   // turn into {ax},{dx}.
25068   if (Res.second->hasType(VT))
25069     return Res;   // Correct type already, nothing to do.
25070
25071   // All of the single-register GCC register classes map their values onto
25072   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
25073   // really want an 8-bit or 32-bit register, map to the appropriate register
25074   // class and return the appropriate register.
25075   if (Res.second == &X86::GR16RegClass) {
25076     if (VT == MVT::i8 || VT == MVT::i1) {
25077       unsigned DestReg = 0;
25078       switch (Res.first) {
25079       default: break;
25080       case X86::AX: DestReg = X86::AL; break;
25081       case X86::DX: DestReg = X86::DL; break;
25082       case X86::CX: DestReg = X86::CL; break;
25083       case X86::BX: DestReg = X86::BL; break;
25084       }
25085       if (DestReg) {
25086         Res.first = DestReg;
25087         Res.second = &X86::GR8RegClass;
25088       }
25089     } else if (VT == MVT::i32 || VT == MVT::f32) {
25090       unsigned DestReg = 0;
25091       switch (Res.first) {
25092       default: break;
25093       case X86::AX: DestReg = X86::EAX; break;
25094       case X86::DX: DestReg = X86::EDX; break;
25095       case X86::CX: DestReg = X86::ECX; break;
25096       case X86::BX: DestReg = X86::EBX; break;
25097       case X86::SI: DestReg = X86::ESI; break;
25098       case X86::DI: DestReg = X86::EDI; break;
25099       case X86::BP: DestReg = X86::EBP; break;
25100       case X86::SP: DestReg = X86::ESP; break;
25101       }
25102       if (DestReg) {
25103         Res.first = DestReg;
25104         Res.second = &X86::GR32RegClass;
25105       }
25106     } else if (VT == MVT::i64 || VT == MVT::f64) {
25107       unsigned DestReg = 0;
25108       switch (Res.first) {
25109       default: break;
25110       case X86::AX: DestReg = X86::RAX; break;
25111       case X86::DX: DestReg = X86::RDX; break;
25112       case X86::CX: DestReg = X86::RCX; break;
25113       case X86::BX: DestReg = X86::RBX; break;
25114       case X86::SI: DestReg = X86::RSI; break;
25115       case X86::DI: DestReg = X86::RDI; break;
25116       case X86::BP: DestReg = X86::RBP; break;
25117       case X86::SP: DestReg = X86::RSP; break;
25118       }
25119       if (DestReg) {
25120         Res.first = DestReg;
25121         Res.second = &X86::GR64RegClass;
25122       }
25123     }
25124   } else if (Res.second == &X86::FR32RegClass ||
25125              Res.second == &X86::FR64RegClass ||
25126              Res.second == &X86::VR128RegClass ||
25127              Res.second == &X86::VR256RegClass ||
25128              Res.second == &X86::FR32XRegClass ||
25129              Res.second == &X86::FR64XRegClass ||
25130              Res.second == &X86::VR128XRegClass ||
25131              Res.second == &X86::VR256XRegClass ||
25132              Res.second == &X86::VR512RegClass) {
25133     // Handle references to XMM physical registers that got mapped into the
25134     // wrong class.  This can happen with constraints like {xmm0} where the
25135     // target independent register mapper will just pick the first match it can
25136     // find, ignoring the required type.
25137
25138     if (VT == MVT::f32 || VT == MVT::i32)
25139       Res.second = &X86::FR32RegClass;
25140     else if (VT == MVT::f64 || VT == MVT::i64)
25141       Res.second = &X86::FR64RegClass;
25142     else if (X86::VR128RegClass.hasType(VT))
25143       Res.second = &X86::VR128RegClass;
25144     else if (X86::VR256RegClass.hasType(VT))
25145       Res.second = &X86::VR256RegClass;
25146     else if (X86::VR512RegClass.hasType(VT))
25147       Res.second = &X86::VR512RegClass;
25148   }
25149
25150   return Res;
25151 }
25152
25153 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
25154                                             Type *Ty) const {
25155   // Scaling factors are not free at all.
25156   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
25157   // will take 2 allocations in the out of order engine instead of 1
25158   // for plain addressing mode, i.e. inst (reg1).
25159   // E.g.,
25160   // vaddps (%rsi,%drx), %ymm0, %ymm1
25161   // Requires two allocations (one for the load, one for the computation)
25162   // whereas:
25163   // vaddps (%rsi), %ymm0, %ymm1
25164   // Requires just 1 allocation, i.e., freeing allocations for other operations
25165   // and having less micro operations to execute.
25166   //
25167   // For some X86 architectures, this is even worse because for instance for
25168   // stores, the complex addressing mode forces the instruction to use the
25169   // "load" ports instead of the dedicated "store" port.
25170   // E.g., on Haswell:
25171   // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
25172   // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
25173   if (isLegalAddressingMode(AM, Ty))
25174     // Scale represents reg2 * scale, thus account for 1
25175     // as soon as we use a second register.
25176     return AM.Scale != 0;
25177   return -1;
25178 }
25179
25180 bool X86TargetLowering::isTargetFTOL() const {
25181   return Subtarget->isTargetKnownWindowsMSVC() && !Subtarget->is64Bit();
25182 }