Revert r237828 "[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       Op = New;
12741     }
12742     break;
12743
12744   case ISD::AND:
12745     // If the primary and result isn't used, don't bother using X86ISD::AND,
12746     // because a TEST instruction will be better.
12747     if (!hasNonFlagsUse(Op))
12748       break;
12749     // FALL THROUGH
12750   case ISD::SUB:
12751   case ISD::OR:
12752   case ISD::XOR:
12753     // Due to the ISEL shortcoming noted above, be conservative if this op is
12754     // likely to be selected as part of a load-modify-store instruction.
12755     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12756            UE = Op.getNode()->use_end(); UI != UE; ++UI)
12757       if (UI->getOpcode() == ISD::STORE)
12758         goto default_case;
12759
12760     // Otherwise use a regular EFLAGS-setting instruction.
12761     switch (ArithOp.getOpcode()) {
12762     default: llvm_unreachable("unexpected operator!");
12763     case ISD::SUB: Opcode = X86ISD::SUB; break;
12764     case ISD::XOR: Opcode = X86ISD::XOR; break;
12765     case ISD::AND: Opcode = X86ISD::AND; break;
12766     case ISD::OR: {
12767       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
12768         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
12769         if (EFLAGS.getNode())
12770           return EFLAGS;
12771       }
12772       Opcode = X86ISD::OR;
12773       break;
12774     }
12775     }
12776
12777     NumOperands = 2;
12778     break;
12779   case X86ISD::ADD:
12780   case X86ISD::SUB:
12781   case X86ISD::INC:
12782   case X86ISD::DEC:
12783   case X86ISD::OR:
12784   case X86ISD::XOR:
12785   case X86ISD::AND:
12786     return SDValue(Op.getNode(), 1);
12787   default:
12788   default_case:
12789     break;
12790   }
12791
12792   // If we found that truncation is beneficial, perform the truncation and
12793   // update 'Op'.
12794   if (NeedTruncation) {
12795     EVT VT = Op.getValueType();
12796     SDValue WideVal = Op->getOperand(0);
12797     EVT WideVT = WideVal.getValueType();
12798     unsigned ConvertedOp = 0;
12799     // Use a target machine opcode to prevent further DAGCombine
12800     // optimizations that may separate the arithmetic operations
12801     // from the setcc node.
12802     switch (WideVal.getOpcode()) {
12803       default: break;
12804       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
12805       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
12806       case ISD::AND: ConvertedOp = X86ISD::AND; break;
12807       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
12808       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
12809     }
12810
12811     if (ConvertedOp) {
12812       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12813       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
12814         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
12815         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
12816         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
12817       }
12818     }
12819   }
12820
12821   if (Opcode == 0)
12822     // Emit a CMP with 0, which is the TEST pattern.
12823     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12824                        DAG.getConstant(0, dl, Op.getValueType()));
12825
12826   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12827   SmallVector<SDValue, 4> Ops(Op->op_begin(), Op->op_begin() + NumOperands);
12828
12829   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
12830   DAG.ReplaceAllUsesWith(Op, New);
12831   return SDValue(New.getNode(), 1);
12832 }
12833
12834 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
12835 /// equivalent.
12836 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
12837                                    SDLoc dl, SelectionDAG &DAG) const {
12838   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
12839     if (C->getAPIntValue() == 0)
12840       return EmitTest(Op0, X86CC, dl, DAG);
12841
12842      if (Op0.getValueType() == MVT::i1)
12843        llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
12844   }
12845
12846   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
12847        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
12848     // Do the comparison at i32 if it's smaller, besides the Atom case.
12849     // This avoids subregister aliasing issues. Keep the smaller reference
12850     // if we're optimizing for size, however, as that'll allow better folding
12851     // of memory operations.
12852     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
12853         !DAG.getMachineFunction().getFunction()->hasFnAttribute(
12854             Attribute::MinSize) &&
12855         !Subtarget->isAtom()) {
12856       unsigned ExtendOp =
12857           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
12858       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
12859       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
12860     }
12861     // Use SUB instead of CMP to enable CSE between SUB and CMP.
12862     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
12863     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
12864                               Op0, Op1);
12865     return SDValue(Sub.getNode(), 1);
12866   }
12867   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
12868 }
12869
12870 /// Convert a comparison if required by the subtarget.
12871 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
12872                                                  SelectionDAG &DAG) const {
12873   // If the subtarget does not support the FUCOMI instruction, floating-point
12874   // comparisons have to be converted.
12875   if (Subtarget->hasCMov() ||
12876       Cmp.getOpcode() != X86ISD::CMP ||
12877       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
12878       !Cmp.getOperand(1).getValueType().isFloatingPoint())
12879     return Cmp;
12880
12881   // The instruction selector will select an FUCOM instruction instead of
12882   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
12883   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
12884   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
12885   SDLoc dl(Cmp);
12886   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
12887   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
12888   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
12889                             DAG.getConstant(8, dl, MVT::i8));
12890   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
12891   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
12892 }
12893
12894 /// The minimum architected relative accuracy is 2^-12. We need one
12895 /// Newton-Raphson step to have a good float result (24 bits of precision).
12896 SDValue X86TargetLowering::getRsqrtEstimate(SDValue Op,
12897                                             DAGCombinerInfo &DCI,
12898                                             unsigned &RefinementSteps,
12899                                             bool &UseOneConstNR) const {
12900   // FIXME: We should use instruction latency models to calculate the cost of
12901   // each potential sequence, but this is very hard to do reliably because
12902   // at least Intel's Core* chips have variable timing based on the number of
12903   // significant digits in the divisor and/or sqrt operand.
12904   if (!Subtarget->useSqrtEst())
12905     return SDValue();
12906
12907   EVT VT = Op.getValueType();
12908
12909   // SSE1 has rsqrtss and rsqrtps.
12910   // TODO: Add support for AVX512 (v16f32).
12911   // It is likely not profitable to do this for f64 because a double-precision
12912   // rsqrt estimate with refinement on x86 prior to FMA requires at least 16
12913   // instructions: convert to single, rsqrtss, convert back to double, refine
12914   // (3 steps = at least 13 insts). If an 'rsqrtsd' variant was added to the ISA
12915   // along with FMA, this could be a throughput win.
12916   if ((Subtarget->hasSSE1() && (VT == MVT::f32 || VT == MVT::v4f32)) ||
12917       (Subtarget->hasAVX() && VT == MVT::v8f32)) {
12918     RefinementSteps = 1;
12919     UseOneConstNR = false;
12920     return DCI.DAG.getNode(X86ISD::FRSQRT, SDLoc(Op), VT, Op);
12921   }
12922   return SDValue();
12923 }
12924
12925 /// The minimum architected relative accuracy is 2^-12. We need one
12926 /// Newton-Raphson step to have a good float result (24 bits of precision).
12927 SDValue X86TargetLowering::getRecipEstimate(SDValue Op,
12928                                             DAGCombinerInfo &DCI,
12929                                             unsigned &RefinementSteps) const {
12930   // FIXME: We should use instruction latency models to calculate the cost of
12931   // each potential sequence, but this is very hard to do reliably because
12932   // at least Intel's Core* chips have variable timing based on the number of
12933   // significant digits in the divisor.
12934   if (!Subtarget->useReciprocalEst())
12935     return SDValue();
12936
12937   EVT VT = Op.getValueType();
12938
12939   // SSE1 has rcpss and rcpps. AVX adds a 256-bit variant for rcpps.
12940   // TODO: Add support for AVX512 (v16f32).
12941   // It is likely not profitable to do this for f64 because a double-precision
12942   // reciprocal estimate with refinement on x86 prior to FMA requires
12943   // 15 instructions: convert to single, rcpss, convert back to double, refine
12944   // (3 steps = 12 insts). If an 'rcpsd' variant was added to the ISA
12945   // along with FMA, this could be a throughput win.
12946   if ((Subtarget->hasSSE1() && (VT == MVT::f32 || VT == MVT::v4f32)) ||
12947       (Subtarget->hasAVX() && VT == MVT::v8f32)) {
12948     RefinementSteps = ReciprocalEstimateRefinementSteps;
12949     return DCI.DAG.getNode(X86ISD::FRCP, SDLoc(Op), VT, Op);
12950   }
12951   return SDValue();
12952 }
12953
12954 /// If we have at least two divisions that use the same divisor, convert to
12955 /// multplication by a reciprocal. This may need to be adjusted for a given
12956 /// CPU if a division's cost is not at least twice the cost of a multiplication.
12957 /// This is because we still need one division to calculate the reciprocal and
12958 /// then we need two multiplies by that reciprocal as replacements for the
12959 /// original divisions.
12960 bool X86TargetLowering::combineRepeatedFPDivisors(unsigned NumUsers) const {
12961   return NumUsers > 1;
12962 }
12963
12964 static bool isAllOnes(SDValue V) {
12965   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
12966   return C && C->isAllOnesValue();
12967 }
12968
12969 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
12970 /// if it's possible.
12971 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
12972                                      SDLoc dl, SelectionDAG &DAG) const {
12973   SDValue Op0 = And.getOperand(0);
12974   SDValue Op1 = And.getOperand(1);
12975   if (Op0.getOpcode() == ISD::TRUNCATE)
12976     Op0 = Op0.getOperand(0);
12977   if (Op1.getOpcode() == ISD::TRUNCATE)
12978     Op1 = Op1.getOperand(0);
12979
12980   SDValue LHS, RHS;
12981   if (Op1.getOpcode() == ISD::SHL)
12982     std::swap(Op0, Op1);
12983   if (Op0.getOpcode() == ISD::SHL) {
12984     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
12985       if (And00C->getZExtValue() == 1) {
12986         // If we looked past a truncate, check that it's only truncating away
12987         // known zeros.
12988         unsigned BitWidth = Op0.getValueSizeInBits();
12989         unsigned AndBitWidth = And.getValueSizeInBits();
12990         if (BitWidth > AndBitWidth) {
12991           APInt Zeros, Ones;
12992           DAG.computeKnownBits(Op0, Zeros, Ones);
12993           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
12994             return SDValue();
12995         }
12996         LHS = Op1;
12997         RHS = Op0.getOperand(1);
12998       }
12999   } else if (Op1.getOpcode() == ISD::Constant) {
13000     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
13001     uint64_t AndRHSVal = AndRHS->getZExtValue();
13002     SDValue AndLHS = Op0;
13003
13004     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
13005       LHS = AndLHS.getOperand(0);
13006       RHS = AndLHS.getOperand(1);
13007     }
13008
13009     // Use BT if the immediate can't be encoded in a TEST instruction.
13010     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
13011       LHS = AndLHS;
13012       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), dl, LHS.getValueType());
13013     }
13014   }
13015
13016   if (LHS.getNode()) {
13017     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
13018     // instruction.  Since the shift amount is in-range-or-undefined, we know
13019     // that doing a bittest on the i32 value is ok.  We extend to i32 because
13020     // the encoding for the i16 version is larger than the i32 version.
13021     // Also promote i16 to i32 for performance / code size reason.
13022     if (LHS.getValueType() == MVT::i8 ||
13023         LHS.getValueType() == MVT::i16)
13024       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
13025
13026     // If the operand types disagree, extend the shift amount to match.  Since
13027     // BT ignores high bits (like shifts) we can use anyextend.
13028     if (LHS.getValueType() != RHS.getValueType())
13029       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
13030
13031     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
13032     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
13033     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13034                        DAG.getConstant(Cond, dl, MVT::i8), BT);
13035   }
13036
13037   return SDValue();
13038 }
13039
13040 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
13041 /// mask CMPs.
13042 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
13043                               SDValue &Op1) {
13044   unsigned SSECC;
13045   bool Swap = false;
13046
13047   // SSE Condition code mapping:
13048   //  0 - EQ
13049   //  1 - LT
13050   //  2 - LE
13051   //  3 - UNORD
13052   //  4 - NEQ
13053   //  5 - NLT
13054   //  6 - NLE
13055   //  7 - ORD
13056   switch (SetCCOpcode) {
13057   default: llvm_unreachable("Unexpected SETCC condition");
13058   case ISD::SETOEQ:
13059   case ISD::SETEQ:  SSECC = 0; break;
13060   case ISD::SETOGT:
13061   case ISD::SETGT:  Swap = true; // Fallthrough
13062   case ISD::SETLT:
13063   case ISD::SETOLT: SSECC = 1; break;
13064   case ISD::SETOGE:
13065   case ISD::SETGE:  Swap = true; // Fallthrough
13066   case ISD::SETLE:
13067   case ISD::SETOLE: SSECC = 2; break;
13068   case ISD::SETUO:  SSECC = 3; break;
13069   case ISD::SETUNE:
13070   case ISD::SETNE:  SSECC = 4; break;
13071   case ISD::SETULE: Swap = true; // Fallthrough
13072   case ISD::SETUGE: SSECC = 5; break;
13073   case ISD::SETULT: Swap = true; // Fallthrough
13074   case ISD::SETUGT: SSECC = 6; break;
13075   case ISD::SETO:   SSECC = 7; break;
13076   case ISD::SETUEQ:
13077   case ISD::SETONE: SSECC = 8; break;
13078   }
13079   if (Swap)
13080     std::swap(Op0, Op1);
13081
13082   return SSECC;
13083 }
13084
13085 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
13086 // ones, and then concatenate the result back.
13087 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
13088   MVT VT = Op.getSimpleValueType();
13089
13090   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
13091          "Unsupported value type for operation");
13092
13093   unsigned NumElems = VT.getVectorNumElements();
13094   SDLoc dl(Op);
13095   SDValue CC = Op.getOperand(2);
13096
13097   // Extract the LHS vectors
13098   SDValue LHS = Op.getOperand(0);
13099   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13100   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13101
13102   // Extract the RHS vectors
13103   SDValue RHS = Op.getOperand(1);
13104   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
13105   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
13106
13107   // Issue the operation on the smaller types and concatenate the result back
13108   MVT EltVT = VT.getVectorElementType();
13109   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13110   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
13111                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
13112                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
13113 }
13114
13115 static SDValue LowerBoolVSETCC_AVX512(SDValue Op, SelectionDAG &DAG) {
13116   SDValue Op0 = Op.getOperand(0);
13117   SDValue Op1 = Op.getOperand(1);
13118   SDValue CC = Op.getOperand(2);
13119   MVT VT = Op.getSimpleValueType();
13120   SDLoc dl(Op);
13121
13122   assert(Op0.getValueType().getVectorElementType() == MVT::i1 &&
13123          "Unexpected type for boolean compare operation");
13124   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13125   SDValue NotOp0 = DAG.getNode(ISD::XOR, dl, VT, Op0,
13126                                DAG.getConstant(-1, dl, VT));
13127   SDValue NotOp1 = DAG.getNode(ISD::XOR, dl, VT, Op1,
13128                                DAG.getConstant(-1, dl, VT));
13129   switch (SetCCOpcode) {
13130   default: llvm_unreachable("Unexpected SETCC condition");
13131   case ISD::SETNE:
13132     // (x != y) -> ~(x ^ y)
13133     return DAG.getNode(ISD::XOR, dl, VT,
13134                        DAG.getNode(ISD::XOR, dl, VT, Op0, Op1),
13135                        DAG.getConstant(-1, dl, VT));
13136   case ISD::SETEQ:
13137     // (x == y) -> (x ^ y)
13138     return DAG.getNode(ISD::XOR, dl, VT, Op0, Op1);
13139   case ISD::SETUGT:
13140   case ISD::SETGT:
13141     // (x > y) -> (x & ~y)
13142     return DAG.getNode(ISD::AND, dl, VT, Op0, NotOp1);
13143   case ISD::SETULT:
13144   case ISD::SETLT:
13145     // (x < y) -> (~x & y)
13146     return DAG.getNode(ISD::AND, dl, VT, NotOp0, Op1);
13147   case ISD::SETULE:
13148   case ISD::SETLE:
13149     // (x <= y) -> (~x | y)
13150     return DAG.getNode(ISD::OR, dl, VT, NotOp0, Op1);
13151   case ISD::SETUGE:
13152   case ISD::SETGE:
13153     // (x >=y) -> (x | ~y)
13154     return DAG.getNode(ISD::OR, dl, VT, Op0, NotOp1);
13155   }
13156 }
13157
13158 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
13159                                      const X86Subtarget *Subtarget) {
13160   SDValue Op0 = Op.getOperand(0);
13161   SDValue Op1 = Op.getOperand(1);
13162   SDValue CC = Op.getOperand(2);
13163   MVT VT = Op.getSimpleValueType();
13164   SDLoc dl(Op);
13165
13166   assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 8 &&
13167          Op.getValueType().getScalarType() == MVT::i1 &&
13168          "Cannot set masked compare for this operation");
13169
13170   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13171   unsigned  Opc = 0;
13172   bool Unsigned = false;
13173   bool Swap = false;
13174   unsigned SSECC;
13175   switch (SetCCOpcode) {
13176   default: llvm_unreachable("Unexpected SETCC condition");
13177   case ISD::SETNE:  SSECC = 4; break;
13178   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
13179   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
13180   case ISD::SETLT:  Swap = true; //fall-through
13181   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
13182   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
13183   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
13184   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
13185   case ISD::SETULE: Unsigned = true; //fall-through
13186   case ISD::SETLE:  SSECC = 2; break;
13187   }
13188
13189   if (Swap)
13190     std::swap(Op0, Op1);
13191   if (Opc)
13192     return DAG.getNode(Opc, dl, VT, Op0, Op1);
13193   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
13194   return DAG.getNode(Opc, dl, VT, Op0, Op1,
13195                      DAG.getConstant(SSECC, dl, MVT::i8));
13196 }
13197
13198 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
13199 /// operand \p Op1.  If non-trivial (for example because it's not constant)
13200 /// return an empty value.
13201 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
13202 {
13203   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
13204   if (!BV)
13205     return SDValue();
13206
13207   MVT VT = Op1.getSimpleValueType();
13208   MVT EVT = VT.getVectorElementType();
13209   unsigned n = VT.getVectorNumElements();
13210   SmallVector<SDValue, 8> ULTOp1;
13211
13212   for (unsigned i = 0; i < n; ++i) {
13213     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
13214     if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
13215       return SDValue();
13216
13217     // Avoid underflow.
13218     APInt Val = Elt->getAPIntValue();
13219     if (Val == 0)
13220       return SDValue();
13221
13222     ULTOp1.push_back(DAG.getConstant(Val - 1, dl, EVT));
13223   }
13224
13225   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
13226 }
13227
13228 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
13229                            SelectionDAG &DAG) {
13230   SDValue Op0 = Op.getOperand(0);
13231   SDValue Op1 = Op.getOperand(1);
13232   SDValue CC = Op.getOperand(2);
13233   MVT VT = Op.getSimpleValueType();
13234   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13235   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
13236   SDLoc dl(Op);
13237
13238   if (isFP) {
13239 #ifndef NDEBUG
13240     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
13241     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
13242 #endif
13243
13244     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
13245     unsigned Opc = X86ISD::CMPP;
13246     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
13247       assert(VT.getVectorNumElements() <= 16);
13248       Opc = X86ISD::CMPM;
13249     }
13250     // In the two special cases we can't handle, emit two comparisons.
13251     if (SSECC == 8) {
13252       unsigned CC0, CC1;
13253       unsigned CombineOpc;
13254       if (SetCCOpcode == ISD::SETUEQ) {
13255         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
13256       } else {
13257         assert(SetCCOpcode == ISD::SETONE);
13258         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
13259       }
13260
13261       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13262                                  DAG.getConstant(CC0, dl, MVT::i8));
13263       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13264                                  DAG.getConstant(CC1, dl, MVT::i8));
13265       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
13266     }
13267     // Handle all other FP comparisons here.
13268     return DAG.getNode(Opc, dl, VT, Op0, Op1,
13269                        DAG.getConstant(SSECC, dl, MVT::i8));
13270   }
13271
13272   // Break 256-bit integer vector compare into smaller ones.
13273   if (VT.is256BitVector() && !Subtarget->hasInt256())
13274     return Lower256IntVSETCC(Op, DAG);
13275
13276   EVT OpVT = Op1.getValueType();
13277   if (OpVT.getVectorElementType() == MVT::i1)
13278     return LowerBoolVSETCC_AVX512(Op, DAG);
13279
13280   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
13281   if (Subtarget->hasAVX512()) {
13282     if (Op1.getValueType().is512BitVector() ||
13283         (Subtarget->hasBWI() && Subtarget->hasVLX()) ||
13284         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
13285       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
13286
13287     // In AVX-512 architecture setcc returns mask with i1 elements,
13288     // But there is no compare instruction for i8 and i16 elements in KNL.
13289     // We are not talking about 512-bit operands in this case, these
13290     // types are illegal.
13291     if (MaskResult &&
13292         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
13293          OpVT.getVectorElementType().getSizeInBits() >= 8))
13294       return DAG.getNode(ISD::TRUNCATE, dl, VT,
13295                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
13296   }
13297
13298   // We are handling one of the integer comparisons here.  Since SSE only has
13299   // GT and EQ comparisons for integer, swapping operands and multiple
13300   // operations may be required for some comparisons.
13301   unsigned Opc;
13302   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
13303   bool Subus = false;
13304
13305   switch (SetCCOpcode) {
13306   default: llvm_unreachable("Unexpected SETCC condition");
13307   case ISD::SETNE:  Invert = true;
13308   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
13309   case ISD::SETLT:  Swap = true;
13310   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
13311   case ISD::SETGE:  Swap = true;
13312   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
13313                     Invert = true; break;
13314   case ISD::SETULT: Swap = true;
13315   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
13316                     FlipSigns = true; break;
13317   case ISD::SETUGE: Swap = true;
13318   case ISD::SETULE: Opc = X86ISD::PCMPGT;
13319                     FlipSigns = true; Invert = true; break;
13320   }
13321
13322   // Special case: Use min/max operations for SETULE/SETUGE
13323   MVT VET = VT.getVectorElementType();
13324   bool hasMinMax =
13325        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
13326     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
13327
13328   if (hasMinMax) {
13329     switch (SetCCOpcode) {
13330     default: break;
13331     case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
13332     case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
13333     }
13334
13335     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
13336   }
13337
13338   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
13339   if (!MinMax && hasSubus) {
13340     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
13341     // Op0 u<= Op1:
13342     //   t = psubus Op0, Op1
13343     //   pcmpeq t, <0..0>
13344     switch (SetCCOpcode) {
13345     default: break;
13346     case ISD::SETULT: {
13347       // If the comparison is against a constant we can turn this into a
13348       // setule.  With psubus, setule does not require a swap.  This is
13349       // beneficial because the constant in the register is no longer
13350       // destructed as the destination so it can be hoisted out of a loop.
13351       // Only do this pre-AVX since vpcmp* is no longer destructive.
13352       if (Subtarget->hasAVX())
13353         break;
13354       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
13355       if (ULEOp1.getNode()) {
13356         Op1 = ULEOp1;
13357         Subus = true; Invert = false; Swap = false;
13358       }
13359       break;
13360     }
13361     // Psubus is better than flip-sign because it requires no inversion.
13362     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
13363     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
13364     }
13365
13366     if (Subus) {
13367       Opc = X86ISD::SUBUS;
13368       FlipSigns = false;
13369     }
13370   }
13371
13372   if (Swap)
13373     std::swap(Op0, Op1);
13374
13375   // Check that the operation in question is available (most are plain SSE2,
13376   // but PCMPGTQ and PCMPEQQ have different requirements).
13377   if (VT == MVT::v2i64) {
13378     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
13379       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
13380
13381       // First cast everything to the right type.
13382       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
13383       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
13384
13385       // Since SSE has no unsigned integer comparisons, we need to flip the sign
13386       // bits of the inputs before performing those operations. The lower
13387       // compare is always unsigned.
13388       SDValue SB;
13389       if (FlipSigns) {
13390         SB = DAG.getConstant(0x80000000U, dl, MVT::v4i32);
13391       } else {
13392         SDValue Sign = DAG.getConstant(0x80000000U, dl, MVT::i32);
13393         SDValue Zero = DAG.getConstant(0x00000000U, dl, MVT::i32);
13394         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
13395                          Sign, Zero, Sign, Zero);
13396       }
13397       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
13398       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
13399
13400       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
13401       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
13402       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
13403
13404       // Create masks for only the low parts/high parts of the 64 bit integers.
13405       static const int MaskHi[] = { 1, 1, 3, 3 };
13406       static const int MaskLo[] = { 0, 0, 2, 2 };
13407       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
13408       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
13409       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
13410
13411       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
13412       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
13413
13414       if (Invert)
13415         Result = DAG.getNOT(dl, Result, MVT::v4i32);
13416
13417       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
13418     }
13419
13420     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
13421       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
13422       // pcmpeqd + pshufd + pand.
13423       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
13424
13425       // First cast everything to the right type.
13426       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
13427       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
13428
13429       // Do the compare.
13430       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
13431
13432       // Make sure the lower and upper halves are both all-ones.
13433       static const int Mask[] = { 1, 0, 3, 2 };
13434       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
13435       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
13436
13437       if (Invert)
13438         Result = DAG.getNOT(dl, Result, MVT::v4i32);
13439
13440       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
13441     }
13442   }
13443
13444   // Since SSE has no unsigned integer comparisons, we need to flip the sign
13445   // bits of the inputs before performing those operations.
13446   if (FlipSigns) {
13447     EVT EltVT = VT.getVectorElementType();
13448     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), dl,
13449                                  VT);
13450     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
13451     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
13452   }
13453
13454   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
13455
13456   // If the logical-not of the result is required, perform that now.
13457   if (Invert)
13458     Result = DAG.getNOT(dl, Result, VT);
13459
13460   if (MinMax)
13461     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
13462
13463   if (Subus)
13464     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
13465                          getZeroVector(VT, Subtarget, DAG, dl));
13466
13467   return Result;
13468 }
13469
13470 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
13471
13472   MVT VT = Op.getSimpleValueType();
13473
13474   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
13475
13476   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
13477          && "SetCC type must be 8-bit or 1-bit integer");
13478   SDValue Op0 = Op.getOperand(0);
13479   SDValue Op1 = Op.getOperand(1);
13480   SDLoc dl(Op);
13481   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
13482
13483   // Optimize to BT if possible.
13484   // Lower (X & (1 << N)) == 0 to BT(X, N).
13485   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
13486   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
13487   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
13488       Op1.getOpcode() == ISD::Constant &&
13489       cast<ConstantSDNode>(Op1)->isNullValue() &&
13490       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13491     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
13492     if (NewSetCC.getNode()) {
13493       if (VT == MVT::i1)
13494         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewSetCC);
13495       return NewSetCC;
13496     }
13497   }
13498
13499   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
13500   // these.
13501   if (Op1.getOpcode() == ISD::Constant &&
13502       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
13503        cast<ConstantSDNode>(Op1)->isNullValue()) &&
13504       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13505
13506     // If the input is a setcc, then reuse the input setcc or use a new one with
13507     // the inverted condition.
13508     if (Op0.getOpcode() == X86ISD::SETCC) {
13509       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
13510       bool Invert = (CC == ISD::SETNE) ^
13511         cast<ConstantSDNode>(Op1)->isNullValue();
13512       if (!Invert)
13513         return Op0;
13514
13515       CCode = X86::GetOppositeBranchCondition(CCode);
13516       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13517                                   DAG.getConstant(CCode, dl, MVT::i8),
13518                                   Op0.getOperand(1));
13519       if (VT == MVT::i1)
13520         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13521       return SetCC;
13522     }
13523   }
13524   if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
13525       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
13526       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13527
13528     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
13529     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, dl, MVT::i1), NewCC);
13530   }
13531
13532   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
13533   unsigned X86CC = TranslateX86CC(CC, dl, isFP, Op0, Op1, DAG);
13534   if (X86CC == X86::COND_INVALID)
13535     return SDValue();
13536
13537   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
13538   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
13539   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13540                               DAG.getConstant(X86CC, dl, MVT::i8), EFLAGS);
13541   if (VT == MVT::i1)
13542     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13543   return SetCC;
13544 }
13545
13546 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
13547 static bool isX86LogicalCmp(SDValue Op) {
13548   unsigned Opc = Op.getNode()->getOpcode();
13549   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
13550       Opc == X86ISD::SAHF)
13551     return true;
13552   if (Op.getResNo() == 1 &&
13553       (Opc == X86ISD::ADD ||
13554        Opc == X86ISD::SUB ||
13555        Opc == X86ISD::ADC ||
13556        Opc == X86ISD::SBB ||
13557        Opc == X86ISD::SMUL ||
13558        Opc == X86ISD::UMUL ||
13559        Opc == X86ISD::INC ||
13560        Opc == X86ISD::DEC ||
13561        Opc == X86ISD::OR ||
13562        Opc == X86ISD::XOR ||
13563        Opc == X86ISD::AND))
13564     return true;
13565
13566   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
13567     return true;
13568
13569   return false;
13570 }
13571
13572 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
13573   if (V.getOpcode() != ISD::TRUNCATE)
13574     return false;
13575
13576   SDValue VOp0 = V.getOperand(0);
13577   unsigned InBits = VOp0.getValueSizeInBits();
13578   unsigned Bits = V.getValueSizeInBits();
13579   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
13580 }
13581
13582 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
13583   bool addTest = true;
13584   SDValue Cond  = Op.getOperand(0);
13585   SDValue Op1 = Op.getOperand(1);
13586   SDValue Op2 = Op.getOperand(2);
13587   SDLoc DL(Op);
13588   EVT VT = Op1.getValueType();
13589   SDValue CC;
13590
13591   // Lower FP selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
13592   // are available or VBLENDV if AVX is available.
13593   // Otherwise FP cmovs get lowered into a less efficient branch sequence later.
13594   if (Cond.getOpcode() == ISD::SETCC &&
13595       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
13596        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
13597       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
13598     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
13599     int SSECC = translateX86FSETCC(
13600         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
13601
13602     if (SSECC != 8) {
13603       if (Subtarget->hasAVX512()) {
13604         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
13605                                   DAG.getConstant(SSECC, DL, MVT::i8));
13606         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
13607       }
13608
13609       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
13610                                 DAG.getConstant(SSECC, DL, MVT::i8));
13611
13612       // If we have AVX, we can use a variable vector select (VBLENDV) instead
13613       // of 3 logic instructions for size savings and potentially speed.
13614       // Unfortunately, there is no scalar form of VBLENDV.
13615
13616       // If either operand is a constant, don't try this. We can expect to
13617       // optimize away at least one of the logic instructions later in that
13618       // case, so that sequence would be faster than a variable blend.
13619
13620       // BLENDV was introduced with SSE 4.1, but the 2 register form implicitly
13621       // uses XMM0 as the selection register. That may need just as many
13622       // instructions as the AND/ANDN/OR sequence due to register moves, so
13623       // don't bother.
13624
13625       if (Subtarget->hasAVX() &&
13626           !isa<ConstantFPSDNode>(Op1) && !isa<ConstantFPSDNode>(Op2)) {
13627
13628         // Convert to vectors, do a VSELECT, and convert back to scalar.
13629         // All of the conversions should be optimized away.
13630
13631         EVT VecVT = VT == MVT::f32 ? MVT::v4f32 : MVT::v2f64;
13632         SDValue VOp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op1);
13633         SDValue VOp2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op2);
13634         SDValue VCmp = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Cmp);
13635
13636         EVT VCmpVT = VT == MVT::f32 ? MVT::v4i32 : MVT::v2i64;
13637         VCmp = DAG.getNode(ISD::BITCAST, DL, VCmpVT, VCmp);
13638
13639         SDValue VSel = DAG.getNode(ISD::VSELECT, DL, VecVT, VCmp, VOp1, VOp2);
13640
13641         return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
13642                            VSel, DAG.getIntPtrConstant(0, DL));
13643       }
13644       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
13645       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
13646       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
13647     }
13648   }
13649
13650     if (VT.isVector() && VT.getScalarType() == MVT::i1) {
13651       SDValue Op1Scalar;
13652       if (ISD::isBuildVectorOfConstantSDNodes(Op1.getNode()))
13653         Op1Scalar = ConvertI1VectorToInterger(Op1, DAG);
13654       else if (Op1.getOpcode() == ISD::BITCAST && Op1.getOperand(0))
13655         Op1Scalar = Op1.getOperand(0);
13656       SDValue Op2Scalar;
13657       if (ISD::isBuildVectorOfConstantSDNodes(Op2.getNode()))
13658         Op2Scalar = ConvertI1VectorToInterger(Op2, DAG);
13659       else if (Op2.getOpcode() == ISD::BITCAST && Op2.getOperand(0))
13660         Op2Scalar = Op2.getOperand(0);
13661       if (Op1Scalar.getNode() && Op2Scalar.getNode()) {
13662         SDValue newSelect = DAG.getNode(ISD::SELECT, DL, 
13663                                         Op1Scalar.getValueType(),
13664                                         Cond, Op1Scalar, Op2Scalar);
13665         if (newSelect.getValueSizeInBits() == VT.getSizeInBits())
13666           return DAG.getNode(ISD::BITCAST, DL, VT, newSelect);
13667         SDValue ExtVec = DAG.getNode(ISD::BITCAST, DL, MVT::v8i1, newSelect);
13668         return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, ExtVec,
13669                            DAG.getIntPtrConstant(0, DL));
13670     }
13671   }
13672
13673   if (VT == MVT::v4i1 || VT == MVT::v2i1) {
13674     SDValue zeroConst = DAG.getIntPtrConstant(0, DL);
13675     Op1 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
13676                       DAG.getUNDEF(MVT::v8i1), Op1, zeroConst);
13677     Op2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
13678                       DAG.getUNDEF(MVT::v8i1), Op2, zeroConst);
13679     SDValue newSelect = DAG.getNode(ISD::SELECT, DL, MVT::v8i1,
13680                                     Cond, Op1, Op2);
13681     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, newSelect, zeroConst);
13682   }
13683
13684   if (Cond.getOpcode() == ISD::SETCC) {
13685     SDValue NewCond = LowerSETCC(Cond, DAG);
13686     if (NewCond.getNode())
13687       Cond = NewCond;
13688   }
13689
13690   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
13691   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
13692   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
13693   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
13694   if (Cond.getOpcode() == X86ISD::SETCC &&
13695       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
13696       isZero(Cond.getOperand(1).getOperand(1))) {
13697     SDValue Cmp = Cond.getOperand(1);
13698
13699     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
13700
13701     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
13702         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
13703       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
13704
13705       SDValue CmpOp0 = Cmp.getOperand(0);
13706       // Apply further optimizations for special cases
13707       // (select (x != 0), -1, 0) -> neg & sbb
13708       // (select (x == 0), 0, -1) -> neg & sbb
13709       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
13710         if (YC->isNullValue() &&
13711             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
13712           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
13713           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
13714                                     DAG.getConstant(0, DL,
13715                                                     CmpOp0.getValueType()),
13716                                     CmpOp0);
13717           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13718                                     DAG.getConstant(X86::COND_B, DL, MVT::i8),
13719                                     SDValue(Neg.getNode(), 1));
13720           return Res;
13721         }
13722
13723       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
13724                         CmpOp0, DAG.getConstant(1, DL, CmpOp0.getValueType()));
13725       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
13726
13727       SDValue Res =   // Res = 0 or -1.
13728         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13729                     DAG.getConstant(X86::COND_B, DL, MVT::i8), Cmp);
13730
13731       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
13732         Res = DAG.getNOT(DL, Res, Res.getValueType());
13733
13734       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
13735       if (!N2C || !N2C->isNullValue())
13736         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
13737       return Res;
13738     }
13739   }
13740
13741   // Look past (and (setcc_carry (cmp ...)), 1).
13742   if (Cond.getOpcode() == ISD::AND &&
13743       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
13744     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
13745     if (C && C->getAPIntValue() == 1)
13746       Cond = Cond.getOperand(0);
13747   }
13748
13749   // If condition flag is set by a X86ISD::CMP, then use it as the condition
13750   // setting operand in place of the X86ISD::SETCC.
13751   unsigned CondOpcode = Cond.getOpcode();
13752   if (CondOpcode == X86ISD::SETCC ||
13753       CondOpcode == X86ISD::SETCC_CARRY) {
13754     CC = Cond.getOperand(0);
13755
13756     SDValue Cmp = Cond.getOperand(1);
13757     unsigned Opc = Cmp.getOpcode();
13758     MVT VT = Op.getSimpleValueType();
13759
13760     bool IllegalFPCMov = false;
13761     if (VT.isFloatingPoint() && !VT.isVector() &&
13762         !isScalarFPTypeInSSEReg(VT))  // FPStack?
13763       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
13764
13765     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
13766         Opc == X86ISD::BT) { // FIXME
13767       Cond = Cmp;
13768       addTest = false;
13769     }
13770   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
13771              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
13772              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
13773               Cond.getOperand(0).getValueType() != MVT::i8)) {
13774     SDValue LHS = Cond.getOperand(0);
13775     SDValue RHS = Cond.getOperand(1);
13776     unsigned X86Opcode;
13777     unsigned X86Cond;
13778     SDVTList VTs;
13779     switch (CondOpcode) {
13780     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
13781     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
13782     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
13783     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
13784     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
13785     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
13786     default: llvm_unreachable("unexpected overflowing operator");
13787     }
13788     if (CondOpcode == ISD::UMULO)
13789       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
13790                           MVT::i32);
13791     else
13792       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
13793
13794     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
13795
13796     if (CondOpcode == ISD::UMULO)
13797       Cond = X86Op.getValue(2);
13798     else
13799       Cond = X86Op.getValue(1);
13800
13801     CC = DAG.getConstant(X86Cond, DL, MVT::i8);
13802     addTest = false;
13803   }
13804
13805   if (addTest) {
13806     // Look pass the truncate if the high bits are known zero.
13807     if (isTruncWithZeroHighBitsInput(Cond, DAG))
13808         Cond = Cond.getOperand(0);
13809
13810     // We know the result of AND is compared against zero. Try to match
13811     // it to BT.
13812     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
13813       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
13814       if (NewSetCC.getNode()) {
13815         CC = NewSetCC.getOperand(0);
13816         Cond = NewSetCC.getOperand(1);
13817         addTest = false;
13818       }
13819     }
13820   }
13821
13822   if (addTest) {
13823     CC = DAG.getConstant(X86::COND_NE, DL, MVT::i8);
13824     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
13825   }
13826
13827   // a <  b ? -1 :  0 -> RES = ~setcc_carry
13828   // a <  b ?  0 : -1 -> RES = setcc_carry
13829   // a >= b ? -1 :  0 -> RES = setcc_carry
13830   // a >= b ?  0 : -1 -> RES = ~setcc_carry
13831   if (Cond.getOpcode() == X86ISD::SUB) {
13832     Cond = ConvertCmpIfNecessary(Cond, DAG);
13833     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
13834
13835     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
13836         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
13837       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13838                                 DAG.getConstant(X86::COND_B, DL, MVT::i8),
13839                                 Cond);
13840       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
13841         return DAG.getNOT(DL, Res, Res.getValueType());
13842       return Res;
13843     }
13844   }
13845
13846   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
13847   // widen the cmov and push the truncate through. This avoids introducing a new
13848   // branch during isel and doesn't add any extensions.
13849   if (Op.getValueType() == MVT::i8 &&
13850       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
13851     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
13852     if (T1.getValueType() == T2.getValueType() &&
13853         // Blacklist CopyFromReg to avoid partial register stalls.
13854         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
13855       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
13856       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
13857       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
13858     }
13859   }
13860
13861   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
13862   // condition is true.
13863   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
13864   SDValue Ops[] = { Op2, Op1, CC, Cond };
13865   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
13866 }
13867
13868 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, const X86Subtarget *Subtarget,
13869                                        SelectionDAG &DAG) {
13870   MVT VT = Op->getSimpleValueType(0);
13871   SDValue In = Op->getOperand(0);
13872   MVT InVT = In.getSimpleValueType();
13873   MVT VTElt = VT.getVectorElementType();
13874   MVT InVTElt = InVT.getVectorElementType();
13875   SDLoc dl(Op);
13876
13877   // SKX processor
13878   if ((InVTElt == MVT::i1) &&
13879       (((Subtarget->hasBWI() && Subtarget->hasVLX() &&
13880         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() <= 16)) ||
13881
13882        ((Subtarget->hasBWI() && VT.is512BitVector() &&
13883         VTElt.getSizeInBits() <= 16)) ||
13884
13885        ((Subtarget->hasDQI() && Subtarget->hasVLX() &&
13886         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() >= 32)) ||
13887
13888        ((Subtarget->hasDQI() && VT.is512BitVector() &&
13889         VTElt.getSizeInBits() >= 32))))
13890     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13891
13892   unsigned int NumElts = VT.getVectorNumElements();
13893
13894   if (NumElts != 8 && NumElts != 16)
13895     return SDValue();
13896
13897   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1) {
13898     if (In.getOpcode() == X86ISD::VSEXT || In.getOpcode() == X86ISD::VZEXT)
13899       return DAG.getNode(In.getOpcode(), dl, VT, In.getOperand(0));
13900     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13901   }
13902
13903   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
13904   MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
13905   SDValue NegOne =
13906    DAG.getConstant(APInt::getAllOnesValue(ExtVT.getScalarSizeInBits()), dl,
13907                    ExtVT);
13908   SDValue Zero =
13909    DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), dl, ExtVT);
13910
13911   SDValue V = DAG.getNode(ISD::VSELECT, dl, ExtVT, In, NegOne, Zero);
13912   if (VT.is512BitVector())
13913     return V;
13914   return DAG.getNode(X86ISD::VTRUNC, dl, VT, V);
13915 }
13916
13917 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
13918                                 SelectionDAG &DAG) {
13919   MVT VT = Op->getSimpleValueType(0);
13920   SDValue In = Op->getOperand(0);
13921   MVT InVT = In.getSimpleValueType();
13922   SDLoc dl(Op);
13923
13924   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
13925     return LowerSIGN_EXTEND_AVX512(Op, Subtarget, DAG);
13926
13927   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
13928       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
13929       (VT != MVT::v16i16 || InVT != MVT::v16i8))
13930     return SDValue();
13931
13932   if (Subtarget->hasInt256())
13933     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13934
13935   // Optimize vectors in AVX mode
13936   // Sign extend  v8i16 to v8i32 and
13937   //              v4i32 to v4i64
13938   //
13939   // Divide input vector into two parts
13940   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
13941   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
13942   // concat the vectors to original VT
13943
13944   unsigned NumElems = InVT.getVectorNumElements();
13945   SDValue Undef = DAG.getUNDEF(InVT);
13946
13947   SmallVector<int,8> ShufMask1(NumElems, -1);
13948   for (unsigned i = 0; i != NumElems/2; ++i)
13949     ShufMask1[i] = i;
13950
13951   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
13952
13953   SmallVector<int,8> ShufMask2(NumElems, -1);
13954   for (unsigned i = 0; i != NumElems/2; ++i)
13955     ShufMask2[i] = i + NumElems/2;
13956
13957   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
13958
13959   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
13960                                 VT.getVectorNumElements()/2);
13961
13962   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
13963   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
13964
13965   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
13966 }
13967
13968 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
13969 // may emit an illegal shuffle but the expansion is still better than scalar
13970 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
13971 // we'll emit a shuffle and a arithmetic shift.
13972 // FIXME: Is the expansion actually better than scalar code? It doesn't seem so.
13973 // TODO: It is possible to support ZExt by zeroing the undef values during
13974 // the shuffle phase or after the shuffle.
13975 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
13976                                  SelectionDAG &DAG) {
13977   MVT RegVT = Op.getSimpleValueType();
13978   assert(RegVT.isVector() && "We only custom lower vector sext loads.");
13979   assert(RegVT.isInteger() &&
13980          "We only custom lower integer vector sext loads.");
13981
13982   // Nothing useful we can do without SSE2 shuffles.
13983   assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
13984
13985   LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
13986   SDLoc dl(Ld);
13987   EVT MemVT = Ld->getMemoryVT();
13988   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13989   unsigned RegSz = RegVT.getSizeInBits();
13990
13991   ISD::LoadExtType Ext = Ld->getExtensionType();
13992
13993   assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
13994          && "Only anyext and sext are currently implemented.");
13995   assert(MemVT != RegVT && "Cannot extend to the same type");
13996   assert(MemVT.isVector() && "Must load a vector from memory");
13997
13998   unsigned NumElems = RegVT.getVectorNumElements();
13999   unsigned MemSz = MemVT.getSizeInBits();
14000   assert(RegSz > MemSz && "Register size must be greater than the mem size");
14001
14002   if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
14003     // The only way in which we have a legal 256-bit vector result but not the
14004     // integer 256-bit operations needed to directly lower a sextload is if we
14005     // have AVX1 but not AVX2. In that case, we can always emit a sextload to
14006     // a 128-bit vector and a normal sign_extend to 256-bits that should get
14007     // correctly legalized. We do this late to allow the canonical form of
14008     // sextload to persist throughout the rest of the DAG combiner -- it wants
14009     // to fold together any extensions it can, and so will fuse a sign_extend
14010     // of an sextload into a sextload targeting a wider value.
14011     SDValue Load;
14012     if (MemSz == 128) {
14013       // Just switch this to a normal load.
14014       assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
14015                                        "it must be a legal 128-bit vector "
14016                                        "type!");
14017       Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
14018                   Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
14019                   Ld->isInvariant(), Ld->getAlignment());
14020     } else {
14021       assert(MemSz < 128 &&
14022              "Can't extend a type wider than 128 bits to a 256 bit vector!");
14023       // Do an sext load to a 128-bit vector type. We want to use the same
14024       // number of elements, but elements half as wide. This will end up being
14025       // recursively lowered by this routine, but will succeed as we definitely
14026       // have all the necessary features if we're using AVX1.
14027       EVT HalfEltVT =
14028           EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
14029       EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
14030       Load =
14031           DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
14032                          Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
14033                          Ld->isNonTemporal(), Ld->isInvariant(),
14034                          Ld->getAlignment());
14035     }
14036
14037     // Replace chain users with the new chain.
14038     assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
14039     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
14040
14041     // Finally, do a normal sign-extend to the desired register.
14042     return DAG.getSExtOrTrunc(Load, dl, RegVT);
14043   }
14044
14045   // All sizes must be a power of two.
14046   assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
14047          "Non-power-of-two elements are not custom lowered!");
14048
14049   // Attempt to load the original value using scalar loads.
14050   // Find the largest scalar type that divides the total loaded size.
14051   MVT SclrLoadTy = MVT::i8;
14052   for (MVT Tp : MVT::integer_valuetypes()) {
14053     if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
14054       SclrLoadTy = Tp;
14055     }
14056   }
14057
14058   // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
14059   if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
14060       (64 <= MemSz))
14061     SclrLoadTy = MVT::f64;
14062
14063   // Calculate the number of scalar loads that we need to perform
14064   // in order to load our vector from memory.
14065   unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
14066
14067   assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
14068          "Can only lower sext loads with a single scalar load!");
14069
14070   unsigned loadRegZize = RegSz;
14071   if (Ext == ISD::SEXTLOAD && RegSz >= 256)
14072     loadRegZize = 128;
14073
14074   // Represent our vector as a sequence of elements which are the
14075   // largest scalar that we can load.
14076   EVT LoadUnitVecVT = EVT::getVectorVT(
14077       *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
14078
14079   // Represent the data using the same element type that is stored in
14080   // memory. In practice, we ''widen'' MemVT.
14081   EVT WideVecVT =
14082       EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
14083                        loadRegZize / MemVT.getScalarType().getSizeInBits());
14084
14085   assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
14086          "Invalid vector type");
14087
14088   // We can't shuffle using an illegal type.
14089   assert(TLI.isTypeLegal(WideVecVT) &&
14090          "We only lower types that form legal widened vector types");
14091
14092   SmallVector<SDValue, 8> Chains;
14093   SDValue Ptr = Ld->getBasePtr();
14094   SDValue Increment =
14095       DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, dl, TLI.getPointerTy());
14096   SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
14097
14098   for (unsigned i = 0; i < NumLoads; ++i) {
14099     // Perform a single load.
14100     SDValue ScalarLoad =
14101         DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
14102                     Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
14103                     Ld->getAlignment());
14104     Chains.push_back(ScalarLoad.getValue(1));
14105     // Create the first element type using SCALAR_TO_VECTOR in order to avoid
14106     // another round of DAGCombining.
14107     if (i == 0)
14108       Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
14109     else
14110       Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
14111                         ScalarLoad, DAG.getIntPtrConstant(i, dl));
14112
14113     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
14114   }
14115
14116   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
14117
14118   // Bitcast the loaded value to a vector of the original element type, in
14119   // the size of the target vector type.
14120   SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
14121   unsigned SizeRatio = RegSz / MemSz;
14122
14123   if (Ext == ISD::SEXTLOAD) {
14124     // If we have SSE4.1, we can directly emit a VSEXT node.
14125     if (Subtarget->hasSSE41()) {
14126       SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
14127       DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14128       return Sext;
14129     }
14130
14131     // Otherwise we'll shuffle the small elements in the high bits of the
14132     // larger type and perform an arithmetic shift. If the shift is not legal
14133     // it's better to scalarize.
14134     assert(TLI.isOperationLegalOrCustom(ISD::SRA, RegVT) &&
14135            "We can't implement a sext load without an arithmetic right shift!");
14136
14137     // Redistribute the loaded elements into the different locations.
14138     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
14139     for (unsigned i = 0; i != NumElems; ++i)
14140       ShuffleVec[i * SizeRatio + SizeRatio - 1] = i;
14141
14142     SDValue Shuff = DAG.getVectorShuffle(
14143         WideVecVT, dl, SlicedVec, DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
14144
14145     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
14146
14147     // Build the arithmetic shift.
14148     unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
14149                    MemVT.getVectorElementType().getSizeInBits();
14150     Shuff =
14151         DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
14152                     DAG.getConstant(Amt, dl, RegVT));
14153
14154     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14155     return Shuff;
14156   }
14157
14158   // Redistribute the loaded elements into the different locations.
14159   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
14160   for (unsigned i = 0; i != NumElems; ++i)
14161     ShuffleVec[i * SizeRatio] = i;
14162
14163   SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
14164                                        DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
14165
14166   // Bitcast to the requested type.
14167   Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
14168   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14169   return Shuff;
14170 }
14171
14172 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
14173 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
14174 // from the AND / OR.
14175 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
14176   Opc = Op.getOpcode();
14177   if (Opc != ISD::OR && Opc != ISD::AND)
14178     return false;
14179   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
14180           Op.getOperand(0).hasOneUse() &&
14181           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
14182           Op.getOperand(1).hasOneUse());
14183 }
14184
14185 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
14186 // 1 and that the SETCC node has a single use.
14187 static bool isXor1OfSetCC(SDValue Op) {
14188   if (Op.getOpcode() != ISD::XOR)
14189     return false;
14190   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
14191   if (N1C && N1C->getAPIntValue() == 1) {
14192     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
14193       Op.getOperand(0).hasOneUse();
14194   }
14195   return false;
14196 }
14197
14198 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
14199   bool addTest = true;
14200   SDValue Chain = Op.getOperand(0);
14201   SDValue Cond  = Op.getOperand(1);
14202   SDValue Dest  = Op.getOperand(2);
14203   SDLoc dl(Op);
14204   SDValue CC;
14205   bool Inverted = false;
14206
14207   if (Cond.getOpcode() == ISD::SETCC) {
14208     // Check for setcc([su]{add,sub,mul}o == 0).
14209     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
14210         isa<ConstantSDNode>(Cond.getOperand(1)) &&
14211         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
14212         Cond.getOperand(0).getResNo() == 1 &&
14213         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
14214          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
14215          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
14216          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
14217          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
14218          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
14219       Inverted = true;
14220       Cond = Cond.getOperand(0);
14221     } else {
14222       SDValue NewCond = LowerSETCC(Cond, DAG);
14223       if (NewCond.getNode())
14224         Cond = NewCond;
14225     }
14226   }
14227 #if 0
14228   // FIXME: LowerXALUO doesn't handle these!!
14229   else if (Cond.getOpcode() == X86ISD::ADD  ||
14230            Cond.getOpcode() == X86ISD::SUB  ||
14231            Cond.getOpcode() == X86ISD::SMUL ||
14232            Cond.getOpcode() == X86ISD::UMUL)
14233     Cond = LowerXALUO(Cond, DAG);
14234 #endif
14235
14236   // Look pass (and (setcc_carry (cmp ...)), 1).
14237   if (Cond.getOpcode() == ISD::AND &&
14238       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
14239     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
14240     if (C && C->getAPIntValue() == 1)
14241       Cond = Cond.getOperand(0);
14242   }
14243
14244   // If condition flag is set by a X86ISD::CMP, then use it as the condition
14245   // setting operand in place of the X86ISD::SETCC.
14246   unsigned CondOpcode = Cond.getOpcode();
14247   if (CondOpcode == X86ISD::SETCC ||
14248       CondOpcode == X86ISD::SETCC_CARRY) {
14249     CC = Cond.getOperand(0);
14250
14251     SDValue Cmp = Cond.getOperand(1);
14252     unsigned Opc = Cmp.getOpcode();
14253     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
14254     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
14255       Cond = Cmp;
14256       addTest = false;
14257     } else {
14258       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
14259       default: break;
14260       case X86::COND_O:
14261       case X86::COND_B:
14262         // These can only come from an arithmetic instruction with overflow,
14263         // e.g. SADDO, UADDO.
14264         Cond = Cond.getNode()->getOperand(1);
14265         addTest = false;
14266         break;
14267       }
14268     }
14269   }
14270   CondOpcode = Cond.getOpcode();
14271   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
14272       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
14273       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
14274        Cond.getOperand(0).getValueType() != MVT::i8)) {
14275     SDValue LHS = Cond.getOperand(0);
14276     SDValue RHS = Cond.getOperand(1);
14277     unsigned X86Opcode;
14278     unsigned X86Cond;
14279     SDVTList VTs;
14280     // Keep this in sync with LowerXALUO, otherwise we might create redundant
14281     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
14282     // X86ISD::INC).
14283     switch (CondOpcode) {
14284     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
14285     case ISD::SADDO:
14286       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14287         if (C->isOne()) {
14288           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
14289           break;
14290         }
14291       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
14292     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
14293     case ISD::SSUBO:
14294       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14295         if (C->isOne()) {
14296           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
14297           break;
14298         }
14299       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
14300     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
14301     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
14302     default: llvm_unreachable("unexpected overflowing operator");
14303     }
14304     if (Inverted)
14305       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
14306     if (CondOpcode == ISD::UMULO)
14307       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
14308                           MVT::i32);
14309     else
14310       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14311
14312     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
14313
14314     if (CondOpcode == ISD::UMULO)
14315       Cond = X86Op.getValue(2);
14316     else
14317       Cond = X86Op.getValue(1);
14318
14319     CC = DAG.getConstant(X86Cond, dl, MVT::i8);
14320     addTest = false;
14321   } else {
14322     unsigned CondOpc;
14323     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
14324       SDValue Cmp = Cond.getOperand(0).getOperand(1);
14325       if (CondOpc == ISD::OR) {
14326         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
14327         // two branches instead of an explicit OR instruction with a
14328         // separate test.
14329         if (Cmp == Cond.getOperand(1).getOperand(1) &&
14330             isX86LogicalCmp(Cmp)) {
14331           CC = Cond.getOperand(0).getOperand(0);
14332           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14333                               Chain, Dest, CC, Cmp);
14334           CC = Cond.getOperand(1).getOperand(0);
14335           Cond = Cmp;
14336           addTest = false;
14337         }
14338       } else { // ISD::AND
14339         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
14340         // two branches instead of an explicit AND instruction with a
14341         // separate test. However, we only do this if this block doesn't
14342         // have a fall-through edge, because this requires an explicit
14343         // jmp when the condition is false.
14344         if (Cmp == Cond.getOperand(1).getOperand(1) &&
14345             isX86LogicalCmp(Cmp) &&
14346             Op.getNode()->hasOneUse()) {
14347           X86::CondCode CCode =
14348             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
14349           CCode = X86::GetOppositeBranchCondition(CCode);
14350           CC = DAG.getConstant(CCode, dl, MVT::i8);
14351           SDNode *User = *Op.getNode()->use_begin();
14352           // Look for an unconditional branch following this conditional branch.
14353           // We need this because we need to reverse the successors in order
14354           // to implement FCMP_OEQ.
14355           if (User->getOpcode() == ISD::BR) {
14356             SDValue FalseBB = User->getOperand(1);
14357             SDNode *NewBR =
14358               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14359             assert(NewBR == User);
14360             (void)NewBR;
14361             Dest = FalseBB;
14362
14363             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14364                                 Chain, Dest, CC, Cmp);
14365             X86::CondCode CCode =
14366               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
14367             CCode = X86::GetOppositeBranchCondition(CCode);
14368             CC = DAG.getConstant(CCode, dl, MVT::i8);
14369             Cond = Cmp;
14370             addTest = false;
14371           }
14372         }
14373       }
14374     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
14375       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
14376       // It should be transformed during dag combiner except when the condition
14377       // is set by a arithmetics with overflow node.
14378       X86::CondCode CCode =
14379         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
14380       CCode = X86::GetOppositeBranchCondition(CCode);
14381       CC = DAG.getConstant(CCode, dl, MVT::i8);
14382       Cond = Cond.getOperand(0).getOperand(1);
14383       addTest = false;
14384     } else if (Cond.getOpcode() == ISD::SETCC &&
14385                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
14386       // For FCMP_OEQ, we can emit
14387       // two branches instead of an explicit AND instruction with a
14388       // separate test. However, we only do this if this block doesn't
14389       // have a fall-through edge, because this requires an explicit
14390       // jmp when the condition is false.
14391       if (Op.getNode()->hasOneUse()) {
14392         SDNode *User = *Op.getNode()->use_begin();
14393         // Look for an unconditional branch following this conditional branch.
14394         // We need this because we need to reverse the successors in order
14395         // to implement FCMP_OEQ.
14396         if (User->getOpcode() == ISD::BR) {
14397           SDValue FalseBB = User->getOperand(1);
14398           SDNode *NewBR =
14399             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14400           assert(NewBR == User);
14401           (void)NewBR;
14402           Dest = FalseBB;
14403
14404           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14405                                     Cond.getOperand(0), Cond.getOperand(1));
14406           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14407           CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
14408           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14409                               Chain, Dest, CC, Cmp);
14410           CC = DAG.getConstant(X86::COND_P, dl, MVT::i8);
14411           Cond = Cmp;
14412           addTest = false;
14413         }
14414       }
14415     } else if (Cond.getOpcode() == ISD::SETCC &&
14416                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
14417       // For FCMP_UNE, we can emit
14418       // two branches instead of an explicit AND instruction with a
14419       // separate test. However, we only do this if this block doesn't
14420       // have a fall-through edge, because this requires an explicit
14421       // jmp when the condition is false.
14422       if (Op.getNode()->hasOneUse()) {
14423         SDNode *User = *Op.getNode()->use_begin();
14424         // Look for an unconditional branch following this conditional branch.
14425         // We need this because we need to reverse the successors in order
14426         // to implement FCMP_UNE.
14427         if (User->getOpcode() == ISD::BR) {
14428           SDValue FalseBB = User->getOperand(1);
14429           SDNode *NewBR =
14430             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14431           assert(NewBR == User);
14432           (void)NewBR;
14433
14434           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14435                                     Cond.getOperand(0), Cond.getOperand(1));
14436           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14437           CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
14438           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14439                               Chain, Dest, CC, Cmp);
14440           CC = DAG.getConstant(X86::COND_NP, dl, MVT::i8);
14441           Cond = Cmp;
14442           addTest = false;
14443           Dest = FalseBB;
14444         }
14445       }
14446     }
14447   }
14448
14449   if (addTest) {
14450     // Look pass the truncate if the high bits are known zero.
14451     if (isTruncWithZeroHighBitsInput(Cond, DAG))
14452         Cond = Cond.getOperand(0);
14453
14454     // We know the result of AND is compared against zero. Try to match
14455     // it to BT.
14456     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
14457       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
14458       if (NewSetCC.getNode()) {
14459         CC = NewSetCC.getOperand(0);
14460         Cond = NewSetCC.getOperand(1);
14461         addTest = false;
14462       }
14463     }
14464   }
14465
14466   if (addTest) {
14467     X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
14468     CC = DAG.getConstant(X86Cond, dl, MVT::i8);
14469     Cond = EmitTest(Cond, X86Cond, dl, DAG);
14470   }
14471   Cond = ConvertCmpIfNecessary(Cond, DAG);
14472   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14473                      Chain, Dest, CC, Cond);
14474 }
14475
14476 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
14477 // Calls to _alloca are needed to probe the stack when allocating more than 4k
14478 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
14479 // that the guard pages used by the OS virtual memory manager are allocated in
14480 // correct sequence.
14481 SDValue
14482 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
14483                                            SelectionDAG &DAG) const {
14484   MachineFunction &MF = DAG.getMachineFunction();
14485   bool SplitStack = MF.shouldSplitStack();
14486   bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMachO()) ||
14487                SplitStack;
14488   SDLoc dl(Op);
14489
14490   if (!Lower) {
14491     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14492     SDNode* Node = Op.getNode();
14493
14494     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
14495     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
14496         " not tell us which reg is the stack pointer!");
14497     EVT VT = Node->getValueType(0);
14498     SDValue Tmp1 = SDValue(Node, 0);
14499     SDValue Tmp2 = SDValue(Node, 1);
14500     SDValue Tmp3 = Node->getOperand(2);
14501     SDValue Chain = Tmp1.getOperand(0);
14502
14503     // Chain the dynamic stack allocation so that it doesn't modify the stack
14504     // pointer when other instructions are using the stack.
14505     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, dl, true),
14506         SDLoc(Node));
14507
14508     SDValue Size = Tmp2.getOperand(1);
14509     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
14510     Chain = SP.getValue(1);
14511     unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
14512     const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
14513     unsigned StackAlign = TFI.getStackAlignment();
14514     Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
14515     if (Align > StackAlign)
14516       Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
14517           DAG.getConstant(-(uint64_t)Align, dl, VT));
14518     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
14519
14520     Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
14521         DAG.getIntPtrConstant(0, dl, true), SDValue(),
14522         SDLoc(Node));
14523
14524     SDValue Ops[2] = { Tmp1, Tmp2 };
14525     return DAG.getMergeValues(Ops, dl);
14526   }
14527
14528   // Get the inputs.
14529   SDValue Chain = Op.getOperand(0);
14530   SDValue Size  = Op.getOperand(1);
14531   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
14532   EVT VT = Op.getNode()->getValueType(0);
14533
14534   bool Is64Bit = Subtarget->is64Bit();
14535   EVT SPTy = getPointerTy();
14536
14537   if (SplitStack) {
14538     MachineRegisterInfo &MRI = MF.getRegInfo();
14539
14540     if (Is64Bit) {
14541       // The 64 bit implementation of segmented stacks needs to clobber both r10
14542       // r11. This makes it impossible to use it along with nested parameters.
14543       const Function *F = MF.getFunction();
14544
14545       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
14546            I != E; ++I)
14547         if (I->hasNestAttr())
14548           report_fatal_error("Cannot use segmented stacks with functions that "
14549                              "have nested arguments.");
14550     }
14551
14552     const TargetRegisterClass *AddrRegClass =
14553       getRegClassFor(getPointerTy());
14554     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
14555     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
14556     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
14557                                 DAG.getRegister(Vreg, SPTy));
14558     SDValue Ops1[2] = { Value, Chain };
14559     return DAG.getMergeValues(Ops1, dl);
14560   } else {
14561     SDValue Flag;
14562     const unsigned Reg = (Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX);
14563
14564     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
14565     Flag = Chain.getValue(1);
14566     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
14567
14568     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
14569
14570     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
14571     unsigned SPReg = RegInfo->getStackRegister();
14572     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
14573     Chain = SP.getValue(1);
14574
14575     if (Align) {
14576       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
14577                        DAG.getConstant(-(uint64_t)Align, dl, VT));
14578       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
14579     }
14580
14581     SDValue Ops1[2] = { SP, Chain };
14582     return DAG.getMergeValues(Ops1, dl);
14583   }
14584 }
14585
14586 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
14587   MachineFunction &MF = DAG.getMachineFunction();
14588   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
14589
14590   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
14591   SDLoc DL(Op);
14592
14593   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
14594     // vastart just stores the address of the VarArgsFrameIndex slot into the
14595     // memory location argument.
14596     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
14597                                    getPointerTy());
14598     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
14599                         MachinePointerInfo(SV), false, false, 0);
14600   }
14601
14602   // __va_list_tag:
14603   //   gp_offset         (0 - 6 * 8)
14604   //   fp_offset         (48 - 48 + 8 * 16)
14605   //   overflow_arg_area (point to parameters coming in memory).
14606   //   reg_save_area
14607   SmallVector<SDValue, 8> MemOps;
14608   SDValue FIN = Op.getOperand(1);
14609   // Store gp_offset
14610   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
14611                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
14612                                                DL, MVT::i32),
14613                                FIN, MachinePointerInfo(SV), false, false, 0);
14614   MemOps.push_back(Store);
14615
14616   // Store fp_offset
14617   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14618                     FIN, DAG.getIntPtrConstant(4, DL));
14619   Store = DAG.getStore(Op.getOperand(0), DL,
14620                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(), DL,
14621                                        MVT::i32),
14622                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
14623   MemOps.push_back(Store);
14624
14625   // Store ptr to overflow_arg_area
14626   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14627                     FIN, DAG.getIntPtrConstant(4, DL));
14628   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
14629                                     getPointerTy());
14630   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
14631                        MachinePointerInfo(SV, 8),
14632                        false, false, 0);
14633   MemOps.push_back(Store);
14634
14635   // Store ptr to reg_save_area.
14636   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14637                     FIN, DAG.getIntPtrConstant(8, DL));
14638   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
14639                                     getPointerTy());
14640   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
14641                        MachinePointerInfo(SV, 16), false, false, 0);
14642   MemOps.push_back(Store);
14643   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
14644 }
14645
14646 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
14647   assert(Subtarget->is64Bit() &&
14648          "LowerVAARG only handles 64-bit va_arg!");
14649   assert((Subtarget->isTargetLinux() ||
14650           Subtarget->isTargetDarwin()) &&
14651           "Unhandled target in LowerVAARG");
14652   assert(Op.getNode()->getNumOperands() == 4);
14653   SDValue Chain = Op.getOperand(0);
14654   SDValue SrcPtr = Op.getOperand(1);
14655   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
14656   unsigned Align = Op.getConstantOperandVal(3);
14657   SDLoc dl(Op);
14658
14659   EVT ArgVT = Op.getNode()->getValueType(0);
14660   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
14661   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
14662   uint8_t ArgMode;
14663
14664   // Decide which area this value should be read from.
14665   // TODO: Implement the AMD64 ABI in its entirety. This simple
14666   // selection mechanism works only for the basic types.
14667   if (ArgVT == MVT::f80) {
14668     llvm_unreachable("va_arg for f80 not yet implemented");
14669   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
14670     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
14671   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
14672     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
14673   } else {
14674     llvm_unreachable("Unhandled argument type in LowerVAARG");
14675   }
14676
14677   if (ArgMode == 2) {
14678     // Sanity Check: Make sure using fp_offset makes sense.
14679     assert(!Subtarget->useSoftFloat() &&
14680            !(DAG.getMachineFunction().getFunction()->hasFnAttribute(
14681                Attribute::NoImplicitFloat)) &&
14682            Subtarget->hasSSE1());
14683   }
14684
14685   // Insert VAARG_64 node into the DAG
14686   // VAARG_64 returns two values: Variable Argument Address, Chain
14687   SDValue InstOps[] = {Chain, SrcPtr, DAG.getConstant(ArgSize, dl, MVT::i32),
14688                        DAG.getConstant(ArgMode, dl, MVT::i8),
14689                        DAG.getConstant(Align, dl, MVT::i32)};
14690   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
14691   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
14692                                           VTs, InstOps, MVT::i64,
14693                                           MachinePointerInfo(SV),
14694                                           /*Align=*/0,
14695                                           /*Volatile=*/false,
14696                                           /*ReadMem=*/true,
14697                                           /*WriteMem=*/true);
14698   Chain = VAARG.getValue(1);
14699
14700   // Load the next argument and return it
14701   return DAG.getLoad(ArgVT, dl,
14702                      Chain,
14703                      VAARG,
14704                      MachinePointerInfo(),
14705                      false, false, false, 0);
14706 }
14707
14708 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
14709                            SelectionDAG &DAG) {
14710   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
14711   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
14712   SDValue Chain = Op.getOperand(0);
14713   SDValue DstPtr = Op.getOperand(1);
14714   SDValue SrcPtr = Op.getOperand(2);
14715   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
14716   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
14717   SDLoc DL(Op);
14718
14719   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
14720                        DAG.getIntPtrConstant(24, DL), 8, /*isVolatile*/false,
14721                        false, false,
14722                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
14723 }
14724
14725 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
14726 // amount is a constant. Takes immediate version of shift as input.
14727 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
14728                                           SDValue SrcOp, uint64_t ShiftAmt,
14729                                           SelectionDAG &DAG) {
14730   MVT ElementType = VT.getVectorElementType();
14731
14732   // Fold this packed shift into its first operand if ShiftAmt is 0.
14733   if (ShiftAmt == 0)
14734     return SrcOp;
14735
14736   // Check for ShiftAmt >= element width
14737   if (ShiftAmt >= ElementType.getSizeInBits()) {
14738     if (Opc == X86ISD::VSRAI)
14739       ShiftAmt = ElementType.getSizeInBits() - 1;
14740     else
14741       return DAG.getConstant(0, dl, VT);
14742   }
14743
14744   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
14745          && "Unknown target vector shift-by-constant node");
14746
14747   // Fold this packed vector shift into a build vector if SrcOp is a
14748   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
14749   if (VT == SrcOp.getSimpleValueType() &&
14750       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
14751     SmallVector<SDValue, 8> Elts;
14752     unsigned NumElts = SrcOp->getNumOperands();
14753     ConstantSDNode *ND;
14754
14755     switch(Opc) {
14756     default: llvm_unreachable(nullptr);
14757     case X86ISD::VSHLI:
14758       for (unsigned i=0; i!=NumElts; ++i) {
14759         SDValue CurrentOp = SrcOp->getOperand(i);
14760         if (CurrentOp->getOpcode() == ISD::UNDEF) {
14761           Elts.push_back(CurrentOp);
14762           continue;
14763         }
14764         ND = cast<ConstantSDNode>(CurrentOp);
14765         const APInt &C = ND->getAPIntValue();
14766         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), dl, ElementType));
14767       }
14768       break;
14769     case X86ISD::VSRLI:
14770       for (unsigned i=0; i!=NumElts; ++i) {
14771         SDValue CurrentOp = SrcOp->getOperand(i);
14772         if (CurrentOp->getOpcode() == ISD::UNDEF) {
14773           Elts.push_back(CurrentOp);
14774           continue;
14775         }
14776         ND = cast<ConstantSDNode>(CurrentOp);
14777         const APInt &C = ND->getAPIntValue();
14778         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), dl, ElementType));
14779       }
14780       break;
14781     case X86ISD::VSRAI:
14782       for (unsigned i=0; i!=NumElts; ++i) {
14783         SDValue CurrentOp = SrcOp->getOperand(i);
14784         if (CurrentOp->getOpcode() == ISD::UNDEF) {
14785           Elts.push_back(CurrentOp);
14786           continue;
14787         }
14788         ND = cast<ConstantSDNode>(CurrentOp);
14789         const APInt &C = ND->getAPIntValue();
14790         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), dl, ElementType));
14791       }
14792       break;
14793     }
14794
14795     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
14796   }
14797
14798   return DAG.getNode(Opc, dl, VT, SrcOp,
14799                      DAG.getConstant(ShiftAmt, dl, MVT::i8));
14800 }
14801
14802 // getTargetVShiftNode - Handle vector element shifts where the shift amount
14803 // may or may not be a constant. Takes immediate version of shift as input.
14804 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
14805                                    SDValue SrcOp, SDValue ShAmt,
14806                                    SelectionDAG &DAG) {
14807   MVT SVT = ShAmt.getSimpleValueType();
14808   assert((SVT == MVT::i32 || SVT == MVT::i64) && "Unexpected value type!");
14809
14810   // Catch shift-by-constant.
14811   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
14812     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
14813                                       CShAmt->getZExtValue(), DAG);
14814
14815   // Change opcode to non-immediate version
14816   switch (Opc) {
14817     default: llvm_unreachable("Unknown target vector shift node");
14818     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
14819     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
14820     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
14821   }
14822
14823   const X86Subtarget &Subtarget =
14824       static_cast<const X86Subtarget &>(DAG.getSubtarget());
14825   if (Subtarget.hasSSE41() && ShAmt.getOpcode() == ISD::ZERO_EXTEND &&
14826       ShAmt.getOperand(0).getSimpleValueType() == MVT::i16) {
14827     // Let the shuffle legalizer expand this shift amount node.
14828     SDValue Op0 = ShAmt.getOperand(0);
14829     Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(Op0), MVT::v8i16, Op0);
14830     ShAmt = getShuffleVectorZeroOrUndef(Op0, 0, true, &Subtarget, DAG);
14831   } else {
14832     // Need to build a vector containing shift amount.
14833     // SSE/AVX packed shifts only use the lower 64-bit of the shift count.
14834     SmallVector<SDValue, 4> ShOps;
14835     ShOps.push_back(ShAmt);
14836     if (SVT == MVT::i32) {
14837       ShOps.push_back(DAG.getConstant(0, dl, SVT));
14838       ShOps.push_back(DAG.getUNDEF(SVT));
14839     }
14840     ShOps.push_back(DAG.getUNDEF(SVT));
14841
14842     MVT BVT = SVT == MVT::i32 ? MVT::v4i32 : MVT::v2i64;
14843     ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, BVT, ShOps);
14844   }
14845
14846   // The return type has to be a 128-bit type with the same element
14847   // type as the input type.
14848   MVT EltVT = VT.getVectorElementType();
14849   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
14850
14851   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
14852   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
14853 }
14854
14855 /// \brief Return (and \p Op, \p Mask) for compare instructions or
14856 /// (vselect \p Mask, \p Op, \p PreservedSrc) for others along with the
14857 /// necessary casting for \p Mask when lowering masking intrinsics.
14858 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
14859                                     SDValue PreservedSrc,
14860                                     const X86Subtarget *Subtarget,
14861                                     SelectionDAG &DAG) {
14862     EVT VT = Op.getValueType();
14863     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
14864                                   MVT::i1, VT.getVectorNumElements());
14865     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14866                                      Mask.getValueType().getSizeInBits());
14867     SDLoc dl(Op);
14868
14869     assert(MaskVT.isSimple() && "invalid mask type");
14870
14871     if (isAllOnes(Mask))
14872       return Op;
14873
14874     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
14875     // are extracted by EXTRACT_SUBVECTOR.
14876     SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
14877                               DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
14878                               DAG.getIntPtrConstant(0, dl));
14879
14880     switch (Op.getOpcode()) {
14881       default: break;
14882       case X86ISD::PCMPEQM:
14883       case X86ISD::PCMPGTM:
14884       case X86ISD::CMPM:
14885       case X86ISD::CMPMU:
14886         return DAG.getNode(ISD::AND, dl, VT, Op, VMask);
14887     }
14888     if (PreservedSrc.getOpcode() == ISD::UNDEF)
14889       PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
14890     return DAG.getNode(ISD::VSELECT, dl, VT, VMask, Op, PreservedSrc);
14891 }
14892
14893 /// \brief Creates an SDNode for a predicated scalar operation.
14894 /// \returns (X86vselect \p Mask, \p Op, \p PreservedSrc).
14895 /// The mask is comming as MVT::i8 and it should be truncated
14896 /// to MVT::i1 while lowering masking intrinsics.
14897 /// The main difference between ScalarMaskingNode and VectorMaskingNode is using
14898 /// "X86select" instead of "vselect". We just can't create the "vselect" node for
14899 /// a scalar instruction.
14900 static SDValue getScalarMaskingNode(SDValue Op, SDValue Mask,
14901                                     SDValue PreservedSrc,
14902                                     const X86Subtarget *Subtarget,
14903                                     SelectionDAG &DAG) {
14904     if (isAllOnes(Mask))
14905       return Op;
14906
14907     EVT VT = Op.getValueType();
14908     SDLoc dl(Op);
14909     // The mask should be of type MVT::i1
14910     SDValue IMask = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Mask);
14911
14912     if (PreservedSrc.getOpcode() == ISD::UNDEF)
14913       PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
14914     return DAG.getNode(X86ISD::SELECT, dl, VT, IMask, Op, PreservedSrc);
14915 }
14916
14917 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
14918                                        SelectionDAG &DAG) {
14919   SDLoc dl(Op);
14920   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14921   EVT VT = Op.getValueType();
14922   const IntrinsicData* IntrData = getIntrinsicWithoutChain(IntNo);
14923   if (IntrData) {
14924     switch(IntrData->Type) {
14925     case INTR_TYPE_1OP:
14926       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1));
14927     case INTR_TYPE_2OP:
14928       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
14929         Op.getOperand(2));
14930     case INTR_TYPE_3OP:
14931       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
14932         Op.getOperand(2), Op.getOperand(3));
14933     case INTR_TYPE_1OP_MASK_RM: {
14934       SDValue Src = Op.getOperand(1);
14935       SDValue Src0 = Op.getOperand(2);
14936       SDValue Mask = Op.getOperand(3);
14937       SDValue RoundingMode = Op.getOperand(4);
14938       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src,
14939                                               RoundingMode),
14940                                   Mask, Src0, Subtarget, DAG);
14941     }
14942     case INTR_TYPE_SCALAR_MASK_RM: {
14943       SDValue Src1 = Op.getOperand(1);
14944       SDValue Src2 = Op.getOperand(2);
14945       SDValue Src0 = Op.getOperand(3);
14946       SDValue Mask = Op.getOperand(4);
14947       // There are 2 kinds of intrinsics in this group:
14948       // (1) With supress-all-exceptions (sae) or rounding mode- 6 operands
14949       // (2) With rounding mode and sae - 7 operands.
14950       if (Op.getNumOperands() == 6) {
14951         SDValue Sae  = Op.getOperand(5);
14952         unsigned Opc = IntrData->Opc1 ? IntrData->Opc1 : IntrData->Opc0;
14953         return getScalarMaskingNode(DAG.getNode(Opc, dl, VT, Src1, Src2,
14954                                                 Sae),
14955                                     Mask, Src0, Subtarget, DAG);
14956       }
14957       assert(Op.getNumOperands() == 7 && "Unexpected intrinsic form");
14958       SDValue RoundingMode  = Op.getOperand(5);
14959       SDValue Sae  = Op.getOperand(6);
14960       return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
14961                                               RoundingMode, Sae),
14962                                   Mask, Src0, Subtarget, DAG);
14963     }
14964     case INTR_TYPE_2OP_MASK: {
14965       SDValue Src1 = Op.getOperand(1);
14966       SDValue Src2 = Op.getOperand(2);
14967       SDValue PassThru = Op.getOperand(3);
14968       SDValue Mask = Op.getOperand(4);
14969       // We specify 2 possible opcodes for intrinsics with rounding modes.
14970       // First, we check if the intrinsic may have non-default rounding mode,
14971       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
14972       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
14973       if (IntrWithRoundingModeOpcode != 0) {
14974         SDValue Rnd = Op.getOperand(5);
14975         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
14976         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
14977           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
14978                                       dl, Op.getValueType(),
14979                                       Src1, Src2, Rnd),
14980                                       Mask, PassThru, Subtarget, DAG);
14981         }
14982       }
14983       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
14984                                               Src1,Src2),
14985                                   Mask, PassThru, Subtarget, DAG);
14986     }
14987     case FMA_OP_MASK: {
14988       SDValue Src1 = Op.getOperand(1);
14989       SDValue Src2 = Op.getOperand(2);
14990       SDValue Src3 = Op.getOperand(3);
14991       SDValue Mask = Op.getOperand(4);
14992       // We specify 2 possible opcodes for intrinsics with rounding modes.
14993       // First, we check if the intrinsic may have non-default rounding mode,
14994       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
14995       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
14996       if (IntrWithRoundingModeOpcode != 0) {
14997         SDValue Rnd = Op.getOperand(5);
14998         if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
14999             X86::STATIC_ROUNDING::CUR_DIRECTION)
15000           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15001                                                   dl, Op.getValueType(),
15002                                                   Src1, Src2, Src3, Rnd),
15003                                       Mask, Src1, Subtarget, DAG);
15004       }
15005       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0,
15006                                               dl, Op.getValueType(),
15007                                               Src1, Src2, Src3),
15008                                   Mask, Src1, Subtarget, DAG);
15009     }
15010     case CMP_MASK:
15011     case CMP_MASK_CC: {
15012       // Comparison intrinsics with masks.
15013       // Example of transformation:
15014       // (i8 (int_x86_avx512_mask_pcmpeq_q_128
15015       //             (v2i64 %a), (v2i64 %b), (i8 %mask))) ->
15016       // (i8 (bitcast
15017       //   (v8i1 (insert_subvector undef,
15018       //           (v2i1 (and (PCMPEQM %a, %b),
15019       //                      (extract_subvector
15020       //                         (v8i1 (bitcast %mask)), 0))), 0))))
15021       EVT VT = Op.getOperand(1).getValueType();
15022       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15023                                     VT.getVectorNumElements());
15024       SDValue Mask = Op.getOperand((IntrData->Type == CMP_MASK_CC) ? 4 : 3);
15025       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15026                                        Mask.getValueType().getSizeInBits());
15027       SDValue Cmp;
15028       if (IntrData->Type == CMP_MASK_CC) {
15029         SDValue CC = Op.getOperand(3);
15030         CC = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, CC);
15031         // We specify 2 possible opcodes for intrinsics with rounding modes.
15032         // First, we check if the intrinsic may have non-default rounding mode,
15033         // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15034         if (IntrData->Opc1 != 0) {
15035           SDValue Rnd = Op.getOperand(5);
15036           if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
15037               X86::STATIC_ROUNDING::CUR_DIRECTION)
15038             Cmp = DAG.getNode(IntrData->Opc1, dl, MaskVT, Op.getOperand(1),
15039                               Op.getOperand(2), CC, Rnd);
15040         }
15041         //default rounding mode
15042         if(!Cmp.getNode())
15043             Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
15044                               Op.getOperand(2), CC);
15045
15046       } else {
15047         assert(IntrData->Type == CMP_MASK && "Unexpected intrinsic type!");
15048         Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
15049                           Op.getOperand(2));
15050       }
15051       SDValue CmpMask = getVectorMaskingNode(Cmp, Mask,
15052                                              DAG.getTargetConstant(0, dl,
15053                                                                    MaskVT),
15054                                              Subtarget, DAG);
15055       SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
15056                                 DAG.getUNDEF(BitcastVT), CmpMask,
15057                                 DAG.getIntPtrConstant(0, dl));
15058       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
15059     }
15060     case COMI: { // Comparison intrinsics
15061       ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
15062       SDValue LHS = Op.getOperand(1);
15063       SDValue RHS = Op.getOperand(2);
15064       unsigned X86CC = TranslateX86CC(CC, dl, true, LHS, RHS, DAG);
15065       assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
15066       SDValue Cond = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
15067       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15068                                   DAG.getConstant(X86CC, dl, MVT::i8), Cond);
15069       return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15070     }
15071     case VSHIFT:
15072       return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
15073                                  Op.getOperand(1), Op.getOperand(2), DAG);
15074     case VSHIFT_MASK:
15075       return getVectorMaskingNode(getTargetVShiftNode(IntrData->Opc0, dl,
15076                                                       Op.getSimpleValueType(),
15077                                                       Op.getOperand(1),
15078                                                       Op.getOperand(2), DAG),
15079                                   Op.getOperand(4), Op.getOperand(3), Subtarget,
15080                                   DAG);
15081     case COMPRESS_EXPAND_IN_REG: {
15082       SDValue Mask = Op.getOperand(3);
15083       SDValue DataToCompress = Op.getOperand(1);
15084       SDValue PassThru = Op.getOperand(2);
15085       if (isAllOnes(Mask)) // return data as is
15086         return Op.getOperand(1);
15087       EVT VT = Op.getValueType();
15088       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15089                                     VT.getVectorNumElements());
15090       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15091                                        Mask.getValueType().getSizeInBits());
15092       SDLoc dl(Op);
15093       SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15094                                   DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
15095                                   DAG.getIntPtrConstant(0, dl));
15096
15097       return DAG.getNode(IntrData->Opc0, dl, VT, VMask, DataToCompress,
15098                          PassThru);
15099     }
15100     case BLEND: {
15101       SDValue Mask = Op.getOperand(3);
15102       EVT VT = Op.getValueType();
15103       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15104                                     VT.getVectorNumElements());
15105       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15106                                        Mask.getValueType().getSizeInBits());
15107       SDLoc dl(Op);
15108       SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15109                                   DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
15110                                   DAG.getIntPtrConstant(0, dl));
15111       return DAG.getNode(IntrData->Opc0, dl, VT, VMask, Op.getOperand(1),
15112                          Op.getOperand(2));
15113     }
15114     default:
15115       break;
15116     }
15117   }
15118
15119   switch (IntNo) {
15120   default: return SDValue();    // Don't custom lower most intrinsics.
15121
15122   case Intrinsic::x86_avx2_permd:
15123   case Intrinsic::x86_avx2_permps:
15124     // Operands intentionally swapped. Mask is last operand to intrinsic,
15125     // but second operand for node/instruction.
15126     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
15127                        Op.getOperand(2), Op.getOperand(1));
15128
15129   case Intrinsic::x86_avx512_mask_valign_q_512:
15130   case Intrinsic::x86_avx512_mask_valign_d_512:
15131     // Vector source operands are swapped.
15132     return getVectorMaskingNode(DAG.getNode(X86ISD::VALIGN, dl,
15133                                             Op.getValueType(), Op.getOperand(2),
15134                                             Op.getOperand(1),
15135                                             Op.getOperand(3)),
15136                                 Op.getOperand(5), Op.getOperand(4),
15137                                 Subtarget, DAG);
15138
15139   // ptest and testp intrinsics. The intrinsic these come from are designed to
15140   // return an integer value, not just an instruction so lower it to the ptest
15141   // or testp pattern and a setcc for the result.
15142   case Intrinsic::x86_sse41_ptestz:
15143   case Intrinsic::x86_sse41_ptestc:
15144   case Intrinsic::x86_sse41_ptestnzc:
15145   case Intrinsic::x86_avx_ptestz_256:
15146   case Intrinsic::x86_avx_ptestc_256:
15147   case Intrinsic::x86_avx_ptestnzc_256:
15148   case Intrinsic::x86_avx_vtestz_ps:
15149   case Intrinsic::x86_avx_vtestc_ps:
15150   case Intrinsic::x86_avx_vtestnzc_ps:
15151   case Intrinsic::x86_avx_vtestz_pd:
15152   case Intrinsic::x86_avx_vtestc_pd:
15153   case Intrinsic::x86_avx_vtestnzc_pd:
15154   case Intrinsic::x86_avx_vtestz_ps_256:
15155   case Intrinsic::x86_avx_vtestc_ps_256:
15156   case Intrinsic::x86_avx_vtestnzc_ps_256:
15157   case Intrinsic::x86_avx_vtestz_pd_256:
15158   case Intrinsic::x86_avx_vtestc_pd_256:
15159   case Intrinsic::x86_avx_vtestnzc_pd_256: {
15160     bool IsTestPacked = false;
15161     unsigned X86CC;
15162     switch (IntNo) {
15163     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
15164     case Intrinsic::x86_avx_vtestz_ps:
15165     case Intrinsic::x86_avx_vtestz_pd:
15166     case Intrinsic::x86_avx_vtestz_ps_256:
15167     case Intrinsic::x86_avx_vtestz_pd_256:
15168       IsTestPacked = true; // Fallthrough
15169     case Intrinsic::x86_sse41_ptestz:
15170     case Intrinsic::x86_avx_ptestz_256:
15171       // ZF = 1
15172       X86CC = X86::COND_E;
15173       break;
15174     case Intrinsic::x86_avx_vtestc_ps:
15175     case Intrinsic::x86_avx_vtestc_pd:
15176     case Intrinsic::x86_avx_vtestc_ps_256:
15177     case Intrinsic::x86_avx_vtestc_pd_256:
15178       IsTestPacked = true; // Fallthrough
15179     case Intrinsic::x86_sse41_ptestc:
15180     case Intrinsic::x86_avx_ptestc_256:
15181       // CF = 1
15182       X86CC = X86::COND_B;
15183       break;
15184     case Intrinsic::x86_avx_vtestnzc_ps:
15185     case Intrinsic::x86_avx_vtestnzc_pd:
15186     case Intrinsic::x86_avx_vtestnzc_ps_256:
15187     case Intrinsic::x86_avx_vtestnzc_pd_256:
15188       IsTestPacked = true; // Fallthrough
15189     case Intrinsic::x86_sse41_ptestnzc:
15190     case Intrinsic::x86_avx_ptestnzc_256:
15191       // ZF and CF = 0
15192       X86CC = X86::COND_A;
15193       break;
15194     }
15195
15196     SDValue LHS = Op.getOperand(1);
15197     SDValue RHS = Op.getOperand(2);
15198     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
15199     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
15200     SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
15201     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
15202     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15203   }
15204   case Intrinsic::x86_avx512_kortestz_w:
15205   case Intrinsic::x86_avx512_kortestc_w: {
15206     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
15207     SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
15208     SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
15209     SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
15210     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
15211     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
15212     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15213   }
15214
15215   case Intrinsic::x86_sse42_pcmpistria128:
15216   case Intrinsic::x86_sse42_pcmpestria128:
15217   case Intrinsic::x86_sse42_pcmpistric128:
15218   case Intrinsic::x86_sse42_pcmpestric128:
15219   case Intrinsic::x86_sse42_pcmpistrio128:
15220   case Intrinsic::x86_sse42_pcmpestrio128:
15221   case Intrinsic::x86_sse42_pcmpistris128:
15222   case Intrinsic::x86_sse42_pcmpestris128:
15223   case Intrinsic::x86_sse42_pcmpistriz128:
15224   case Intrinsic::x86_sse42_pcmpestriz128: {
15225     unsigned Opcode;
15226     unsigned X86CC;
15227     switch (IntNo) {
15228     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
15229     case Intrinsic::x86_sse42_pcmpistria128:
15230       Opcode = X86ISD::PCMPISTRI;
15231       X86CC = X86::COND_A;
15232       break;
15233     case Intrinsic::x86_sse42_pcmpestria128:
15234       Opcode = X86ISD::PCMPESTRI;
15235       X86CC = X86::COND_A;
15236       break;
15237     case Intrinsic::x86_sse42_pcmpistric128:
15238       Opcode = X86ISD::PCMPISTRI;
15239       X86CC = X86::COND_B;
15240       break;
15241     case Intrinsic::x86_sse42_pcmpestric128:
15242       Opcode = X86ISD::PCMPESTRI;
15243       X86CC = X86::COND_B;
15244       break;
15245     case Intrinsic::x86_sse42_pcmpistrio128:
15246       Opcode = X86ISD::PCMPISTRI;
15247       X86CC = X86::COND_O;
15248       break;
15249     case Intrinsic::x86_sse42_pcmpestrio128:
15250       Opcode = X86ISD::PCMPESTRI;
15251       X86CC = X86::COND_O;
15252       break;
15253     case Intrinsic::x86_sse42_pcmpistris128:
15254       Opcode = X86ISD::PCMPISTRI;
15255       X86CC = X86::COND_S;
15256       break;
15257     case Intrinsic::x86_sse42_pcmpestris128:
15258       Opcode = X86ISD::PCMPESTRI;
15259       X86CC = X86::COND_S;
15260       break;
15261     case Intrinsic::x86_sse42_pcmpistriz128:
15262       Opcode = X86ISD::PCMPISTRI;
15263       X86CC = X86::COND_E;
15264       break;
15265     case Intrinsic::x86_sse42_pcmpestriz128:
15266       Opcode = X86ISD::PCMPESTRI;
15267       X86CC = X86::COND_E;
15268       break;
15269     }
15270     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
15271     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
15272     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
15273     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15274                                 DAG.getConstant(X86CC, dl, MVT::i8),
15275                                 SDValue(PCMP.getNode(), 1));
15276     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15277   }
15278
15279   case Intrinsic::x86_sse42_pcmpistri128:
15280   case Intrinsic::x86_sse42_pcmpestri128: {
15281     unsigned Opcode;
15282     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
15283       Opcode = X86ISD::PCMPISTRI;
15284     else
15285       Opcode = X86ISD::PCMPESTRI;
15286
15287     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
15288     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
15289     return DAG.getNode(Opcode, dl, VTs, NewOps);
15290   }
15291   }
15292 }
15293
15294 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15295                               SDValue Src, SDValue Mask, SDValue Base,
15296                               SDValue Index, SDValue ScaleOp, SDValue Chain,
15297                               const X86Subtarget * Subtarget) {
15298   SDLoc dl(Op);
15299   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15300   assert(C && "Invalid scale type");
15301   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
15302   EVT MaskVT = MVT::getVectorVT(MVT::i1,
15303                              Index.getSimpleValueType().getVectorNumElements());
15304   SDValue MaskInReg;
15305   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15306   if (MaskC)
15307     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
15308   else
15309     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
15310   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
15311   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
15312   SDValue Segment = DAG.getRegister(0, MVT::i32);
15313   if (Src.getOpcode() == ISD::UNDEF)
15314     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
15315   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
15316   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
15317   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
15318   return DAG.getMergeValues(RetOps, dl);
15319 }
15320
15321 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15322                                SDValue Src, SDValue Mask, SDValue Base,
15323                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
15324   SDLoc dl(Op);
15325   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15326   assert(C && "Invalid scale type");
15327   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
15328   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
15329   SDValue Segment = DAG.getRegister(0, MVT::i32);
15330   EVT MaskVT = MVT::getVectorVT(MVT::i1,
15331                              Index.getSimpleValueType().getVectorNumElements());
15332   SDValue MaskInReg;
15333   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15334   if (MaskC)
15335     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
15336   else
15337     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
15338   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
15339   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
15340   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
15341   return SDValue(Res, 1);
15342 }
15343
15344 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15345                                SDValue Mask, SDValue Base, SDValue Index,
15346                                SDValue ScaleOp, SDValue Chain) {
15347   SDLoc dl(Op);
15348   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15349   assert(C && "Invalid scale type");
15350   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
15351   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
15352   SDValue Segment = DAG.getRegister(0, MVT::i32);
15353   EVT MaskVT =
15354     MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
15355   SDValue MaskInReg;
15356   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15357   if (MaskC)
15358     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
15359   else
15360     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
15361   //SDVTList VTs = DAG.getVTList(MVT::Other);
15362   SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
15363   SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
15364   return SDValue(Res, 0);
15365 }
15366
15367 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
15368 // read performance monitor counters (x86_rdpmc).
15369 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
15370                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
15371                               SmallVectorImpl<SDValue> &Results) {
15372   assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
15373   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
15374   SDValue LO, HI;
15375
15376   // The ECX register is used to select the index of the performance counter
15377   // to read.
15378   SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
15379                                    N->getOperand(2));
15380   SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
15381
15382   // Reads the content of a 64-bit performance counter and returns it in the
15383   // registers EDX:EAX.
15384   if (Subtarget->is64Bit()) {
15385     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
15386     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
15387                             LO.getValue(2));
15388   } else {
15389     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
15390     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
15391                             LO.getValue(2));
15392   }
15393   Chain = HI.getValue(1);
15394
15395   if (Subtarget->is64Bit()) {
15396     // The EAX register is loaded with the low-order 32 bits. The EDX register
15397     // is loaded with the supported high-order bits of the counter.
15398     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
15399                               DAG.getConstant(32, DL, MVT::i8));
15400     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
15401     Results.push_back(Chain);
15402     return;
15403   }
15404
15405   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
15406   SDValue Ops[] = { LO, HI };
15407   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
15408   Results.push_back(Pair);
15409   Results.push_back(Chain);
15410 }
15411
15412 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
15413 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
15414 // also used to custom lower READCYCLECOUNTER nodes.
15415 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
15416                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
15417                               SmallVectorImpl<SDValue> &Results) {
15418   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
15419   SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
15420   SDValue LO, HI;
15421
15422   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
15423   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
15424   // and the EAX register is loaded with the low-order 32 bits.
15425   if (Subtarget->is64Bit()) {
15426     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
15427     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
15428                             LO.getValue(2));
15429   } else {
15430     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
15431     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
15432                             LO.getValue(2));
15433   }
15434   SDValue Chain = HI.getValue(1);
15435
15436   if (Opcode == X86ISD::RDTSCP_DAG) {
15437     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
15438
15439     // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
15440     // the ECX register. Add 'ecx' explicitly to the chain.
15441     SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
15442                                      HI.getValue(2));
15443     // Explicitly store the content of ECX at the location passed in input
15444     // to the 'rdtscp' intrinsic.
15445     Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
15446                          MachinePointerInfo(), false, false, 0);
15447   }
15448
15449   if (Subtarget->is64Bit()) {
15450     // The EDX register is loaded with the high-order 32 bits of the MSR, and
15451     // the EAX register is loaded with the low-order 32 bits.
15452     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
15453                               DAG.getConstant(32, DL, MVT::i8));
15454     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
15455     Results.push_back(Chain);
15456     return;
15457   }
15458
15459   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
15460   SDValue Ops[] = { LO, HI };
15461   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
15462   Results.push_back(Pair);
15463   Results.push_back(Chain);
15464 }
15465
15466 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
15467                                      SelectionDAG &DAG) {
15468   SmallVector<SDValue, 2> Results;
15469   SDLoc DL(Op);
15470   getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
15471                           Results);
15472   return DAG.getMergeValues(Results, DL);
15473 }
15474
15475
15476 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
15477                                       SelectionDAG &DAG) {
15478   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
15479
15480   const IntrinsicData* IntrData = getIntrinsicWithChain(IntNo);
15481   if (!IntrData)
15482     return SDValue();
15483
15484   SDLoc dl(Op);
15485   switch(IntrData->Type) {
15486   default:
15487     llvm_unreachable("Unknown Intrinsic Type");
15488     break;
15489   case RDSEED:
15490   case RDRAND: {
15491     // Emit the node with the right value type.
15492     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
15493     SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
15494
15495     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
15496     // Otherwise return the value from Rand, which is always 0, casted to i32.
15497     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
15498                       DAG.getConstant(1, dl, Op->getValueType(1)),
15499                       DAG.getConstant(X86::COND_B, dl, MVT::i32),
15500                       SDValue(Result.getNode(), 1) };
15501     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
15502                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
15503                                   Ops);
15504
15505     // Return { result, isValid, chain }.
15506     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
15507                        SDValue(Result.getNode(), 2));
15508   }
15509   case GATHER: {
15510   //gather(v1, mask, index, base, scale);
15511     SDValue Chain = Op.getOperand(0);
15512     SDValue Src   = Op.getOperand(2);
15513     SDValue Base  = Op.getOperand(3);
15514     SDValue Index = Op.getOperand(4);
15515     SDValue Mask  = Op.getOperand(5);
15516     SDValue Scale = Op.getOperand(6);
15517     return getGatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale,
15518                          Chain, Subtarget);
15519   }
15520   case SCATTER: {
15521   //scatter(base, mask, index, v1, scale);
15522     SDValue Chain = Op.getOperand(0);
15523     SDValue Base  = Op.getOperand(2);
15524     SDValue Mask  = Op.getOperand(3);
15525     SDValue Index = Op.getOperand(4);
15526     SDValue Src   = Op.getOperand(5);
15527     SDValue Scale = Op.getOperand(6);
15528     return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index,
15529                           Scale, Chain);
15530   }
15531   case PREFETCH: {
15532     SDValue Hint = Op.getOperand(6);
15533     unsigned HintVal = cast<ConstantSDNode>(Hint)->getZExtValue();
15534     assert(HintVal < 2 && "Wrong prefetch hint in intrinsic: should be 0 or 1");
15535     unsigned Opcode = (HintVal ? IntrData->Opc1 : IntrData->Opc0);
15536     SDValue Chain = Op.getOperand(0);
15537     SDValue Mask  = Op.getOperand(2);
15538     SDValue Index = Op.getOperand(3);
15539     SDValue Base  = Op.getOperand(4);
15540     SDValue Scale = Op.getOperand(5);
15541     return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
15542   }
15543   // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
15544   case RDTSC: {
15545     SmallVector<SDValue, 2> Results;
15546     getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget,
15547                             Results);
15548     return DAG.getMergeValues(Results, dl);
15549   }
15550   // Read Performance Monitoring Counters.
15551   case RDPMC: {
15552     SmallVector<SDValue, 2> Results;
15553     getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
15554     return DAG.getMergeValues(Results, dl);
15555   }
15556   // XTEST intrinsics.
15557   case XTEST: {
15558     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
15559     SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
15560     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15561                                 DAG.getConstant(X86::COND_NE, dl, MVT::i8),
15562                                 InTrans);
15563     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
15564     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
15565                        Ret, SDValue(InTrans.getNode(), 1));
15566   }
15567   // ADC/ADCX/SBB
15568   case ADX: {
15569     SmallVector<SDValue, 2> Results;
15570     SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
15571     SDVTList VTs = DAG.getVTList(Op.getOperand(3)->getValueType(0), MVT::Other);
15572     SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(2),
15573                                 DAG.getConstant(-1, dl, MVT::i8));
15574     SDValue Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(3),
15575                               Op.getOperand(4), GenCF.getValue(1));
15576     SDValue Store = DAG.getStore(Op.getOperand(0), dl, Res.getValue(0),
15577                                  Op.getOperand(5), MachinePointerInfo(),
15578                                  false, false, 0);
15579     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15580                                 DAG.getConstant(X86::COND_B, dl, MVT::i8),
15581                                 Res.getValue(1));
15582     Results.push_back(SetCC);
15583     Results.push_back(Store);
15584     return DAG.getMergeValues(Results, dl);
15585   }
15586   case COMPRESS_TO_MEM: {
15587     SDLoc dl(Op);
15588     SDValue Mask = Op.getOperand(4);
15589     SDValue DataToCompress = Op.getOperand(3);
15590     SDValue Addr = Op.getOperand(2);
15591     SDValue Chain = Op.getOperand(0);
15592
15593     if (isAllOnes(Mask)) // return just a store
15594       return DAG.getStore(Chain, dl, DataToCompress, Addr,
15595                           MachinePointerInfo(), false, false, 0);
15596
15597     EVT VT = DataToCompress.getValueType();
15598     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15599                                   VT.getVectorNumElements());
15600     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15601                                      Mask.getValueType().getSizeInBits());
15602     SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15603                                 DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
15604                                 DAG.getIntPtrConstant(0, dl));
15605
15606     SDValue Compressed =  DAG.getNode(IntrData->Opc0, dl, VT, VMask,
15607                                       DataToCompress, DAG.getUNDEF(VT));
15608     return DAG.getStore(Chain, dl, Compressed, Addr,
15609                         MachinePointerInfo(), false, false, 0);
15610   }
15611   case EXPAND_FROM_MEM: {
15612     SDLoc dl(Op);
15613     SDValue Mask = Op.getOperand(4);
15614     SDValue PathThru = Op.getOperand(3);
15615     SDValue Addr = Op.getOperand(2);
15616     SDValue Chain = Op.getOperand(0);
15617     EVT VT = Op.getValueType();
15618
15619     if (isAllOnes(Mask)) // return just a load
15620       return DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(), false, false,
15621                          false, 0);
15622     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15623                                   VT.getVectorNumElements());
15624     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15625                                      Mask.getValueType().getSizeInBits());
15626     SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15627                                 DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
15628                                 DAG.getIntPtrConstant(0, dl));
15629
15630     SDValue DataToExpand = DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(),
15631                                    false, false, false, 0);
15632
15633     SDValue Results[] = {
15634         DAG.getNode(IntrData->Opc0, dl, VT, VMask, DataToExpand, PathThru),
15635         Chain};
15636     return DAG.getMergeValues(Results, dl);
15637   }
15638   }
15639 }
15640
15641 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
15642                                            SelectionDAG &DAG) const {
15643   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
15644   MFI->setReturnAddressIsTaken(true);
15645
15646   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
15647     return SDValue();
15648
15649   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15650   SDLoc dl(Op);
15651   EVT PtrVT = getPointerTy();
15652
15653   if (Depth > 0) {
15654     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
15655     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15656     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), dl, PtrVT);
15657     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15658                        DAG.getNode(ISD::ADD, dl, PtrVT,
15659                                    FrameAddr, Offset),
15660                        MachinePointerInfo(), false, false, false, 0);
15661   }
15662
15663   // Just load the return address.
15664   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
15665   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15666                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
15667 }
15668
15669 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
15670   MachineFunction &MF = DAG.getMachineFunction();
15671   MachineFrameInfo *MFI = MF.getFrameInfo();
15672   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
15673   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15674   EVT VT = Op.getValueType();
15675
15676   MFI->setFrameAddressIsTaken(true);
15677
15678   if (MF.getTarget().getMCAsmInfo()->usesWindowsCFI()) {
15679     // Depth > 0 makes no sense on targets which use Windows unwind codes.  It
15680     // is not possible to crawl up the stack without looking at the unwind codes
15681     // simultaneously.
15682     int FrameAddrIndex = FuncInfo->getFAIndex();
15683     if (!FrameAddrIndex) {
15684       // Set up a frame object for the return address.
15685       unsigned SlotSize = RegInfo->getSlotSize();
15686       FrameAddrIndex = MF.getFrameInfo()->CreateFixedObject(
15687           SlotSize, /*Offset=*/0, /*IsImmutable=*/false);
15688       FuncInfo->setFAIndex(FrameAddrIndex);
15689     }
15690     return DAG.getFrameIndex(FrameAddrIndex, VT);
15691   }
15692
15693   unsigned FrameReg =
15694       RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
15695   SDLoc dl(Op);  // FIXME probably not meaningful
15696   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15697   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
15698           (FrameReg == X86::EBP && VT == MVT::i32)) &&
15699          "Invalid Frame Register!");
15700   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
15701   while (Depth--)
15702     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
15703                             MachinePointerInfo(),
15704                             false, false, false, 0);
15705   return FrameAddr;
15706 }
15707
15708 // FIXME? Maybe this could be a TableGen attribute on some registers and
15709 // this table could be generated automatically from RegInfo.
15710 unsigned X86TargetLowering::getRegisterByName(const char* RegName,
15711                                               EVT VT) const {
15712   unsigned Reg = StringSwitch<unsigned>(RegName)
15713                        .Case("esp", X86::ESP)
15714                        .Case("rsp", X86::RSP)
15715                        .Default(0);
15716   if (Reg)
15717     return Reg;
15718   report_fatal_error("Invalid register name global variable");
15719 }
15720
15721 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
15722                                                      SelectionDAG &DAG) const {
15723   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15724   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize(), SDLoc(Op));
15725 }
15726
15727 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
15728   SDValue Chain     = Op.getOperand(0);
15729   SDValue Offset    = Op.getOperand(1);
15730   SDValue Handler   = Op.getOperand(2);
15731   SDLoc dl      (Op);
15732
15733   EVT PtrVT = getPointerTy();
15734   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15735   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
15736   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
15737           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
15738          "Invalid Frame Register!");
15739   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
15740   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
15741
15742   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
15743                                  DAG.getIntPtrConstant(RegInfo->getSlotSize(),
15744                                                        dl));
15745   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
15746   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
15747                        false, false, 0);
15748   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
15749
15750   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
15751                      DAG.getRegister(StoreAddrReg, PtrVT));
15752 }
15753
15754 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
15755                                                SelectionDAG &DAG) const {
15756   SDLoc DL(Op);
15757   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
15758                      DAG.getVTList(MVT::i32, MVT::Other),
15759                      Op.getOperand(0), Op.getOperand(1));
15760 }
15761
15762 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
15763                                                 SelectionDAG &DAG) const {
15764   SDLoc DL(Op);
15765   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
15766                      Op.getOperand(0), Op.getOperand(1));
15767 }
15768
15769 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
15770   return Op.getOperand(0);
15771 }
15772
15773 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
15774                                                 SelectionDAG &DAG) const {
15775   SDValue Root = Op.getOperand(0);
15776   SDValue Trmp = Op.getOperand(1); // trampoline
15777   SDValue FPtr = Op.getOperand(2); // nested function
15778   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
15779   SDLoc dl (Op);
15780
15781   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
15782   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
15783
15784   if (Subtarget->is64Bit()) {
15785     SDValue OutChains[6];
15786
15787     // Large code-model.
15788     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
15789     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
15790
15791     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
15792     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
15793
15794     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
15795
15796     // Load the pointer to the nested function into R11.
15797     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
15798     SDValue Addr = Trmp;
15799     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
15800                                 Addr, MachinePointerInfo(TrmpAddr),
15801                                 false, false, 0);
15802
15803     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15804                        DAG.getConstant(2, dl, MVT::i64));
15805     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
15806                                 MachinePointerInfo(TrmpAddr, 2),
15807                                 false, false, 2);
15808
15809     // Load the 'nest' parameter value into R10.
15810     // R10 is specified in X86CallingConv.td
15811     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
15812     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15813                        DAG.getConstant(10, dl, MVT::i64));
15814     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
15815                                 Addr, MachinePointerInfo(TrmpAddr, 10),
15816                                 false, false, 0);
15817
15818     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15819                        DAG.getConstant(12, dl, MVT::i64));
15820     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
15821                                 MachinePointerInfo(TrmpAddr, 12),
15822                                 false, false, 2);
15823
15824     // Jump to the nested function.
15825     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
15826     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15827                        DAG.getConstant(20, dl, MVT::i64));
15828     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
15829                                 Addr, MachinePointerInfo(TrmpAddr, 20),
15830                                 false, false, 0);
15831
15832     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
15833     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15834                        DAG.getConstant(22, dl, MVT::i64));
15835     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, dl, MVT::i8),
15836                                 Addr, MachinePointerInfo(TrmpAddr, 22),
15837                                 false, false, 0);
15838
15839     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
15840   } else {
15841     const Function *Func =
15842       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
15843     CallingConv::ID CC = Func->getCallingConv();
15844     unsigned NestReg;
15845
15846     switch (CC) {
15847     default:
15848       llvm_unreachable("Unsupported calling convention");
15849     case CallingConv::C:
15850     case CallingConv::X86_StdCall: {
15851       // Pass 'nest' parameter in ECX.
15852       // Must be kept in sync with X86CallingConv.td
15853       NestReg = X86::ECX;
15854
15855       // Check that ECX wasn't needed by an 'inreg' parameter.
15856       FunctionType *FTy = Func->getFunctionType();
15857       const AttributeSet &Attrs = Func->getAttributes();
15858
15859       if (!Attrs.isEmpty() && !Func->isVarArg()) {
15860         unsigned InRegCount = 0;
15861         unsigned Idx = 1;
15862
15863         for (FunctionType::param_iterator I = FTy->param_begin(),
15864              E = FTy->param_end(); I != E; ++I, ++Idx)
15865           if (Attrs.hasAttribute(Idx, Attribute::InReg))
15866             // FIXME: should only count parameters that are lowered to integers.
15867             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
15868
15869         if (InRegCount > 2) {
15870           report_fatal_error("Nest register in use - reduce number of inreg"
15871                              " parameters!");
15872         }
15873       }
15874       break;
15875     }
15876     case CallingConv::X86_FastCall:
15877     case CallingConv::X86_ThisCall:
15878     case CallingConv::Fast:
15879       // Pass 'nest' parameter in EAX.
15880       // Must be kept in sync with X86CallingConv.td
15881       NestReg = X86::EAX;
15882       break;
15883     }
15884
15885     SDValue OutChains[4];
15886     SDValue Addr, Disp;
15887
15888     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15889                        DAG.getConstant(10, dl, MVT::i32));
15890     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
15891
15892     // This is storing the opcode for MOV32ri.
15893     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
15894     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
15895     OutChains[0] = DAG.getStore(Root, dl,
15896                                 DAG.getConstant(MOV32ri|N86Reg, dl, MVT::i8),
15897                                 Trmp, MachinePointerInfo(TrmpAddr),
15898                                 false, false, 0);
15899
15900     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15901                        DAG.getConstant(1, dl, MVT::i32));
15902     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
15903                                 MachinePointerInfo(TrmpAddr, 1),
15904                                 false, false, 1);
15905
15906     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
15907     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15908                        DAG.getConstant(5, dl, MVT::i32));
15909     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, dl, MVT::i8),
15910                                 Addr, MachinePointerInfo(TrmpAddr, 5),
15911                                 false, false, 1);
15912
15913     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15914                        DAG.getConstant(6, dl, MVT::i32));
15915     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
15916                                 MachinePointerInfo(TrmpAddr, 6),
15917                                 false, false, 1);
15918
15919     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
15920   }
15921 }
15922
15923 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
15924                                             SelectionDAG &DAG) const {
15925   /*
15926    The rounding mode is in bits 11:10 of FPSR, and has the following
15927    settings:
15928      00 Round to nearest
15929      01 Round to -inf
15930      10 Round to +inf
15931      11 Round to 0
15932
15933   FLT_ROUNDS, on the other hand, expects the following:
15934     -1 Undefined
15935      0 Round to 0
15936      1 Round to nearest
15937      2 Round to +inf
15938      3 Round to -inf
15939
15940   To perform the conversion, we do:
15941     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
15942   */
15943
15944   MachineFunction &MF = DAG.getMachineFunction();
15945   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
15946   unsigned StackAlignment = TFI.getStackAlignment();
15947   MVT VT = Op.getSimpleValueType();
15948   SDLoc DL(Op);
15949
15950   // Save FP Control Word to stack slot
15951   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
15952   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
15953
15954   MachineMemOperand *MMO =
15955    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
15956                            MachineMemOperand::MOStore, 2, 2);
15957
15958   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
15959   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
15960                                           DAG.getVTList(MVT::Other),
15961                                           Ops, MVT::i16, MMO);
15962
15963   // Load FP Control Word from stack slot
15964   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
15965                             MachinePointerInfo(), false, false, false, 0);
15966
15967   // Transform as necessary
15968   SDValue CWD1 =
15969     DAG.getNode(ISD::SRL, DL, MVT::i16,
15970                 DAG.getNode(ISD::AND, DL, MVT::i16,
15971                             CWD, DAG.getConstant(0x800, DL, MVT::i16)),
15972                 DAG.getConstant(11, DL, MVT::i8));
15973   SDValue CWD2 =
15974     DAG.getNode(ISD::SRL, DL, MVT::i16,
15975                 DAG.getNode(ISD::AND, DL, MVT::i16,
15976                             CWD, DAG.getConstant(0x400, DL, MVT::i16)),
15977                 DAG.getConstant(9, DL, MVT::i8));
15978
15979   SDValue RetVal =
15980     DAG.getNode(ISD::AND, DL, MVT::i16,
15981                 DAG.getNode(ISD::ADD, DL, MVT::i16,
15982                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
15983                             DAG.getConstant(1, DL, MVT::i16)),
15984                 DAG.getConstant(3, DL, MVT::i16));
15985
15986   return DAG.getNode((VT.getSizeInBits() < 16 ?
15987                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
15988 }
15989
15990 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
15991   MVT VT = Op.getSimpleValueType();
15992   EVT OpVT = VT;
15993   unsigned NumBits = VT.getSizeInBits();
15994   SDLoc dl(Op);
15995
15996   Op = Op.getOperand(0);
15997   if (VT == MVT::i8) {
15998     // Zero extend to i32 since there is not an i8 bsr.
15999     OpVT = MVT::i32;
16000     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
16001   }
16002
16003   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
16004   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
16005   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
16006
16007   // If src is zero (i.e. bsr sets ZF), returns NumBits.
16008   SDValue Ops[] = {
16009     Op,
16010     DAG.getConstant(NumBits + NumBits - 1, dl, OpVT),
16011     DAG.getConstant(X86::COND_E, dl, MVT::i8),
16012     Op.getValue(1)
16013   };
16014   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
16015
16016   // Finally xor with NumBits-1.
16017   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
16018                    DAG.getConstant(NumBits - 1, dl, OpVT));
16019
16020   if (VT == MVT::i8)
16021     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
16022   return Op;
16023 }
16024
16025 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
16026   MVT VT = Op.getSimpleValueType();
16027   EVT OpVT = VT;
16028   unsigned NumBits = VT.getSizeInBits();
16029   SDLoc dl(Op);
16030
16031   Op = Op.getOperand(0);
16032   if (VT == MVT::i8) {
16033     // Zero extend to i32 since there is not an i8 bsr.
16034     OpVT = MVT::i32;
16035     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
16036   }
16037
16038   // Issue a bsr (scan bits in reverse).
16039   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
16040   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
16041
16042   // And xor with NumBits-1.
16043   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
16044                    DAG.getConstant(NumBits - 1, dl, OpVT));
16045
16046   if (VT == MVT::i8)
16047     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
16048   return Op;
16049 }
16050
16051 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
16052   MVT VT = Op.getSimpleValueType();
16053   unsigned NumBits = VT.getSizeInBits();
16054   SDLoc dl(Op);
16055   Op = Op.getOperand(0);
16056
16057   // Issue a bsf (scan bits forward) which also sets EFLAGS.
16058   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
16059   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
16060
16061   // If src is zero (i.e. bsf sets ZF), returns NumBits.
16062   SDValue Ops[] = {
16063     Op,
16064     DAG.getConstant(NumBits, dl, VT),
16065     DAG.getConstant(X86::COND_E, dl, MVT::i8),
16066     Op.getValue(1)
16067   };
16068   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
16069 }
16070
16071 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
16072 // ones, and then concatenate the result back.
16073 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
16074   MVT VT = Op.getSimpleValueType();
16075
16076   assert(VT.is256BitVector() && VT.isInteger() &&
16077          "Unsupported value type for operation");
16078
16079   unsigned NumElems = VT.getVectorNumElements();
16080   SDLoc dl(Op);
16081
16082   // Extract the LHS vectors
16083   SDValue LHS = Op.getOperand(0);
16084   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
16085   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
16086
16087   // Extract the RHS vectors
16088   SDValue RHS = Op.getOperand(1);
16089   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
16090   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
16091
16092   MVT EltVT = VT.getVectorElementType();
16093   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16094
16095   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
16096                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
16097                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
16098 }
16099
16100 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
16101   assert(Op.getSimpleValueType().is256BitVector() &&
16102          Op.getSimpleValueType().isInteger() &&
16103          "Only handle AVX 256-bit vector integer operation");
16104   return Lower256IntArith(Op, DAG);
16105 }
16106
16107 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
16108   assert(Op.getSimpleValueType().is256BitVector() &&
16109          Op.getSimpleValueType().isInteger() &&
16110          "Only handle AVX 256-bit vector integer operation");
16111   return Lower256IntArith(Op, DAG);
16112 }
16113
16114 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
16115                         SelectionDAG &DAG) {
16116   SDLoc dl(Op);
16117   MVT VT = Op.getSimpleValueType();
16118
16119   // Decompose 256-bit ops into smaller 128-bit ops.
16120   if (VT.is256BitVector() && !Subtarget->hasInt256())
16121     return Lower256IntArith(Op, DAG);
16122
16123   SDValue A = Op.getOperand(0);
16124   SDValue B = Op.getOperand(1);
16125
16126   // Lower v16i8/v32i8 mul as promotion to v8i16/v16i16 vector
16127   // pairs, multiply and truncate.
16128   if (VT == MVT::v16i8 || VT == MVT::v32i8) {
16129     if (Subtarget->hasInt256()) {
16130       if (VT == MVT::v32i8) {
16131         MVT SubVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() / 2);
16132         SDValue Lo = DAG.getIntPtrConstant(0, dl);
16133         SDValue Hi = DAG.getIntPtrConstant(VT.getVectorNumElements() / 2, dl);
16134         SDValue ALo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Lo);
16135         SDValue BLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Lo);
16136         SDValue AHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Hi);
16137         SDValue BHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Hi);
16138         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
16139                            DAG.getNode(ISD::MUL, dl, SubVT, ALo, BLo),
16140                            DAG.getNode(ISD::MUL, dl, SubVT, AHi, BHi));
16141       }
16142
16143       MVT ExVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements());
16144       return DAG.getNode(
16145           ISD::TRUNCATE, dl, VT,
16146           DAG.getNode(ISD::MUL, dl, ExVT,
16147                       DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, A),
16148                       DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, B)));
16149     }
16150
16151     assert(VT == MVT::v16i8 &&
16152            "Pre-AVX2 support only supports v16i8 multiplication");
16153     MVT ExVT = MVT::v8i16;
16154
16155     // Extract the lo parts and sign extend to i16
16156     SDValue ALo, BLo;
16157     if (Subtarget->hasSSE41()) {
16158       ALo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, A);
16159       BLo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, B);
16160     } else {
16161       const int ShufMask[] = {-1, 0, -1, 1, -1, 2, -1, 3,
16162                               -1, 4, -1, 5, -1, 6, -1, 7};
16163       ALo = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16164       BLo = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16165       ALo = DAG.getNode(ISD::BITCAST, dl, ExVT, ALo);
16166       BLo = DAG.getNode(ISD::BITCAST, dl, ExVT, BLo);
16167       ALo = DAG.getNode(ISD::SRA, dl, ExVT, ALo, DAG.getConstant(8, dl, ExVT));
16168       BLo = DAG.getNode(ISD::SRA, dl, ExVT, BLo, DAG.getConstant(8, dl, ExVT));
16169     }
16170
16171     // Extract the hi parts and sign extend to i16
16172     SDValue AHi, BHi;
16173     if (Subtarget->hasSSE41()) {
16174       const int ShufMask[] = {8,  9,  10, 11, 12, 13, 14, 15,
16175                               -1, -1, -1, -1, -1, -1, -1, -1};
16176       AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16177       BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16178       AHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, AHi);
16179       BHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, BHi);
16180     } else {
16181       const int ShufMask[] = {-1, 8,  -1, 9,  -1, 10, -1, 11,
16182                               -1, 12, -1, 13, -1, 14, -1, 15};
16183       AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16184       BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16185       AHi = DAG.getNode(ISD::BITCAST, dl, ExVT, AHi);
16186       BHi = DAG.getNode(ISD::BITCAST, dl, ExVT, BHi);
16187       AHi = DAG.getNode(ISD::SRA, dl, ExVT, AHi, DAG.getConstant(8, dl, ExVT));
16188       BHi = DAG.getNode(ISD::SRA, dl, ExVT, BHi, DAG.getConstant(8, dl, ExVT));
16189     }
16190
16191     // Multiply, mask the lower 8bits of the lo/hi results and pack
16192     SDValue RLo = DAG.getNode(ISD::MUL, dl, ExVT, ALo, BLo);
16193     SDValue RHi = DAG.getNode(ISD::MUL, dl, ExVT, AHi, BHi);
16194     RLo = DAG.getNode(ISD::AND, dl, ExVT, RLo, DAG.getConstant(255, dl, ExVT));
16195     RHi = DAG.getNode(ISD::AND, dl, ExVT, RHi, DAG.getConstant(255, dl, ExVT));
16196     return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
16197   }
16198
16199   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
16200   if (VT == MVT::v4i32) {
16201     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
16202            "Should not custom lower when pmuldq is available!");
16203
16204     // Extract the odd parts.
16205     static const int UnpackMask[] = { 1, -1, 3, -1 };
16206     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
16207     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
16208
16209     // Multiply the even parts.
16210     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
16211     // Now multiply odd parts.
16212     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
16213
16214     Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
16215     Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
16216
16217     // Merge the two vectors back together with a shuffle. This expands into 2
16218     // shuffles.
16219     static const int ShufMask[] = { 0, 4, 2, 6 };
16220     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
16221   }
16222
16223   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
16224          "Only know how to lower V2I64/V4I64/V8I64 multiply");
16225
16226   //  Ahi = psrlqi(a, 32);
16227   //  Bhi = psrlqi(b, 32);
16228   //
16229   //  AloBlo = pmuludq(a, b);
16230   //  AloBhi = pmuludq(a, Bhi);
16231   //  AhiBlo = pmuludq(Ahi, b);
16232
16233   //  AloBhi = psllqi(AloBhi, 32);
16234   //  AhiBlo = psllqi(AhiBlo, 32);
16235   //  return AloBlo + AloBhi + AhiBlo;
16236
16237   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
16238   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
16239
16240   // Bit cast to 32-bit vectors for MULUDQ
16241   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
16242                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
16243   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
16244   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
16245   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
16246   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
16247
16248   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
16249   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
16250   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
16251
16252   AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
16253   AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
16254
16255   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
16256   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
16257 }
16258
16259 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
16260   assert(Subtarget->isTargetWin64() && "Unexpected target");
16261   EVT VT = Op.getValueType();
16262   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
16263          "Unexpected return type for lowering");
16264
16265   RTLIB::Libcall LC;
16266   bool isSigned;
16267   switch (Op->getOpcode()) {
16268   default: llvm_unreachable("Unexpected request for libcall!");
16269   case ISD::SDIV:      isSigned = true;  LC = RTLIB::SDIV_I128;    break;
16270   case ISD::UDIV:      isSigned = false; LC = RTLIB::UDIV_I128;    break;
16271   case ISD::SREM:      isSigned = true;  LC = RTLIB::SREM_I128;    break;
16272   case ISD::UREM:      isSigned = false; LC = RTLIB::UREM_I128;    break;
16273   case ISD::SDIVREM:   isSigned = true;  LC = RTLIB::SDIVREM_I128; break;
16274   case ISD::UDIVREM:   isSigned = false; LC = RTLIB::UDIVREM_I128; break;
16275   }
16276
16277   SDLoc dl(Op);
16278   SDValue InChain = DAG.getEntryNode();
16279
16280   TargetLowering::ArgListTy Args;
16281   TargetLowering::ArgListEntry Entry;
16282   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
16283     EVT ArgVT = Op->getOperand(i).getValueType();
16284     assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
16285            "Unexpected argument type for lowering");
16286     SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
16287     Entry.Node = StackPtr;
16288     InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
16289                            false, false, 16);
16290     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
16291     Entry.Ty = PointerType::get(ArgTy,0);
16292     Entry.isSExt = false;
16293     Entry.isZExt = false;
16294     Args.push_back(Entry);
16295   }
16296
16297   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
16298                                          getPointerTy());
16299
16300   TargetLowering::CallLoweringInfo CLI(DAG);
16301   CLI.setDebugLoc(dl).setChain(InChain)
16302     .setCallee(getLibcallCallingConv(LC),
16303                static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
16304                Callee, std::move(Args), 0)
16305     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
16306
16307   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
16308   return DAG.getNode(ISD::BITCAST, dl, VT, CallInfo.first);
16309 }
16310
16311 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
16312                              SelectionDAG &DAG) {
16313   SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
16314   EVT VT = Op0.getValueType();
16315   SDLoc dl(Op);
16316
16317   assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
16318          (VT == MVT::v8i32 && Subtarget->hasInt256()));
16319
16320   // PMULxD operations multiply each even value (starting at 0) of LHS with
16321   // the related value of RHS and produce a widen result.
16322   // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
16323   // => <2 x i64> <ae|cg>
16324   //
16325   // In other word, to have all the results, we need to perform two PMULxD:
16326   // 1. one with the even values.
16327   // 2. one with the odd values.
16328   // To achieve #2, with need to place the odd values at an even position.
16329   //
16330   // Place the odd value at an even position (basically, shift all values 1
16331   // step to the left):
16332   const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
16333   // <a|b|c|d> => <b|undef|d|undef>
16334   SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
16335   // <e|f|g|h> => <f|undef|h|undef>
16336   SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
16337
16338   // Emit two multiplies, one for the lower 2 ints and one for the higher 2
16339   // ints.
16340   MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
16341   bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
16342   unsigned Opcode =
16343       (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
16344   // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
16345   // => <2 x i64> <ae|cg>
16346   SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
16347                              DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
16348   // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
16349   // => <2 x i64> <bf|dh>
16350   SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
16351                              DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
16352
16353   // Shuffle it back into the right order.
16354   SDValue Highs, Lows;
16355   if (VT == MVT::v8i32) {
16356     const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
16357     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
16358     const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
16359     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
16360   } else {
16361     const int HighMask[] = {1, 5, 3, 7};
16362     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
16363     const int LowMask[] = {0, 4, 2, 6};
16364     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
16365   }
16366
16367   // If we have a signed multiply but no PMULDQ fix up the high parts of a
16368   // unsigned multiply.
16369   if (IsSigned && !Subtarget->hasSSE41()) {
16370     SDValue ShAmt =
16371         DAG.getConstant(31, dl,
16372                         DAG.getTargetLoweringInfo().getShiftAmountTy(VT));
16373     SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
16374                              DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
16375     SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
16376                              DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
16377
16378     SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
16379     Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
16380   }
16381
16382   // The first result of MUL_LOHI is actually the low value, followed by the
16383   // high value.
16384   SDValue Ops[] = {Lows, Highs};
16385   return DAG.getMergeValues(Ops, dl);
16386 }
16387
16388 // Return true if the requred (according to Opcode) shift-imm form is natively
16389 // supported by the Subtarget
16390 static bool SupportedVectorShiftWithImm(MVT VT, const X86Subtarget *Subtarget, 
16391                                         unsigned Opcode) {
16392   if (VT.getScalarSizeInBits() < 16)
16393     return false;
16394  
16395   if (VT.is512BitVector() &&
16396       (VT.getScalarSizeInBits() > 16 || Subtarget->hasBWI()))
16397     return true;
16398
16399   bool LShift = VT.is128BitVector() || 
16400     (VT.is256BitVector() && Subtarget->hasInt256());
16401
16402   bool AShift = LShift && (Subtarget->hasVLX() ||
16403     (VT != MVT::v2i64 && VT != MVT::v4i64));
16404   return (Opcode == ISD::SRA) ? AShift : LShift;
16405 }
16406
16407 // The shift amount is a variable, but it is the same for all vector lanes.
16408 // These instrcutions are defined together with shift-immediate.
16409 static 
16410 bool SupportedVectorShiftWithBaseAmnt(MVT VT, const X86Subtarget *Subtarget, 
16411                                       unsigned Opcode) {
16412   return SupportedVectorShiftWithImm(VT, Subtarget, Opcode);
16413 }
16414
16415 // Return true if the requred (according to Opcode) variable-shift form is
16416 // natively supported by the Subtarget
16417 static bool SupportedVectorVarShift(MVT VT, const X86Subtarget *Subtarget, 
16418                                     unsigned Opcode) {
16419
16420   if (!Subtarget->hasInt256() || VT.getScalarSizeInBits() < 16)
16421     return false;
16422
16423   // vXi16 supported only on AVX-512, BWI
16424   if (VT.getScalarSizeInBits() == 16 && !Subtarget->hasBWI())
16425     return false;
16426
16427   if (VT.is512BitVector() || Subtarget->hasVLX())
16428     return true;
16429
16430   bool LShift = VT.is128BitVector() || VT.is256BitVector();
16431   bool AShift = LShift &&  VT != MVT::v2i64 && VT != MVT::v4i64;
16432   return (Opcode == ISD::SRA) ? AShift : LShift;
16433 }
16434
16435 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
16436                                          const X86Subtarget *Subtarget) {
16437   MVT VT = Op.getSimpleValueType();
16438   SDLoc dl(Op);
16439   SDValue R = Op.getOperand(0);
16440   SDValue Amt = Op.getOperand(1);
16441
16442   unsigned X86Opc = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
16443     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
16444
16445   // Optimize shl/srl/sra with constant shift amount.
16446   if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
16447     if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
16448       uint64_t ShiftAmt = ShiftConst->getZExtValue();
16449
16450       if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
16451         return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
16452
16453       if (VT == MVT::v16i8 || (Subtarget->hasInt256() && VT == MVT::v32i8)) {
16454         unsigned NumElts = VT.getVectorNumElements();
16455         MVT ShiftVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
16456
16457         if (Op.getOpcode() == ISD::SHL) {
16458           // Make a large shift.
16459           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ShiftVT,
16460                                                    R, ShiftAmt, DAG);
16461           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
16462           // Zero out the rightmost bits.
16463           SmallVector<SDValue, 32> V(
16464               NumElts, DAG.getConstant(uint8_t(-1U << ShiftAmt), dl, MVT::i8));
16465           return DAG.getNode(ISD::AND, dl, VT, SHL,
16466                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
16467         }
16468         if (Op.getOpcode() == ISD::SRL) {
16469           // Make a large shift.
16470           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ShiftVT,
16471                                                    R, ShiftAmt, DAG);
16472           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
16473           // Zero out the leftmost bits.
16474           SmallVector<SDValue, 32> V(
16475               NumElts, DAG.getConstant(uint8_t(-1U) >> ShiftAmt, dl, MVT::i8));
16476           return DAG.getNode(ISD::AND, dl, VT, SRL,
16477                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
16478         }
16479         if (Op.getOpcode() == ISD::SRA) {
16480           if (ShiftAmt == 7) {
16481             // R s>> 7  ===  R s< 0
16482             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
16483             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
16484           }
16485
16486           // R s>> a === ((R u>> a) ^ m) - m
16487           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
16488           SmallVector<SDValue, 32> V(NumElts,
16489                                      DAG.getConstant(128 >> ShiftAmt, dl,
16490                                                      MVT::i8));
16491           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
16492           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
16493           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
16494           return Res;
16495         }
16496         llvm_unreachable("Unknown shift opcode.");
16497       }
16498     }
16499   }
16500
16501   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
16502   if (!Subtarget->is64Bit() &&
16503       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
16504       Amt.getOpcode() == ISD::BITCAST &&
16505       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
16506     Amt = Amt.getOperand(0);
16507     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
16508                      VT.getVectorNumElements();
16509     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
16510     uint64_t ShiftAmt = 0;
16511     for (unsigned i = 0; i != Ratio; ++i) {
16512       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
16513       if (!C)
16514         return SDValue();
16515       // 6 == Log2(64)
16516       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
16517     }
16518     // Check remaining shift amounts.
16519     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
16520       uint64_t ShAmt = 0;
16521       for (unsigned j = 0; j != Ratio; ++j) {
16522         ConstantSDNode *C =
16523           dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
16524         if (!C)
16525           return SDValue();
16526         // 6 == Log2(64)
16527         ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
16528       }
16529       if (ShAmt != ShiftAmt)
16530         return SDValue();
16531     }
16532     return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
16533   }
16534
16535   return SDValue();
16536 }
16537
16538 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
16539                                         const X86Subtarget* Subtarget) {
16540   MVT VT = Op.getSimpleValueType();
16541   SDLoc dl(Op);
16542   SDValue R = Op.getOperand(0);
16543   SDValue Amt = Op.getOperand(1);
16544
16545   unsigned X86OpcI = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
16546     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
16547
16548   unsigned X86OpcV = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHL :
16549     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRL : X86ISD::VSRA;
16550
16551   if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode())) {
16552     SDValue BaseShAmt;
16553     EVT EltVT = VT.getVectorElementType();
16554
16555     if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Amt)) {
16556       // Check if this build_vector node is doing a splat.
16557       // If so, then set BaseShAmt equal to the splat value.
16558       BaseShAmt = BV->getSplatValue();
16559       if (BaseShAmt && BaseShAmt.getOpcode() == ISD::UNDEF)
16560         BaseShAmt = SDValue();
16561     } else {
16562       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
16563         Amt = Amt.getOperand(0);
16564
16565       ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt);
16566       if (SVN && SVN->isSplat()) {
16567         unsigned SplatIdx = (unsigned)SVN->getSplatIndex();
16568         SDValue InVec = Amt.getOperand(0);
16569         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
16570           assert((SplatIdx < InVec.getValueType().getVectorNumElements()) &&
16571                  "Unexpected shuffle index found!");
16572           BaseShAmt = InVec.getOperand(SplatIdx);
16573         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
16574            if (ConstantSDNode *C =
16575                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
16576              if (C->getZExtValue() == SplatIdx)
16577                BaseShAmt = InVec.getOperand(1);
16578            }
16579         }
16580
16581         if (!BaseShAmt)
16582           // Avoid introducing an extract element from a shuffle.
16583           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InVec,
16584                                   DAG.getIntPtrConstant(SplatIdx, dl));
16585       }
16586     }
16587
16588     if (BaseShAmt.getNode()) {
16589       assert(EltVT.bitsLE(MVT::i64) && "Unexpected element type!");
16590       if (EltVT != MVT::i64 && EltVT.bitsGT(MVT::i32))
16591         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, BaseShAmt);
16592       else if (EltVT.bitsLT(MVT::i32))
16593         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
16594
16595       return getTargetVShiftNode(X86OpcI, dl, VT, R, BaseShAmt, DAG);
16596     }
16597   }
16598
16599   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
16600   if (!Subtarget->is64Bit() && VT == MVT::v2i64  &&
16601       Amt.getOpcode() == ISD::BITCAST &&
16602       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
16603     Amt = Amt.getOperand(0);
16604     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
16605                      VT.getVectorNumElements();
16606     std::vector<SDValue> Vals(Ratio);
16607     for (unsigned i = 0; i != Ratio; ++i)
16608       Vals[i] = Amt.getOperand(i);
16609     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
16610       for (unsigned j = 0; j != Ratio; ++j)
16611         if (Vals[j] != Amt.getOperand(i + j))
16612           return SDValue();
16613     }
16614     return DAG.getNode(X86OpcV, dl, VT, R, Op.getOperand(1));
16615   }
16616   return SDValue();
16617 }
16618
16619 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
16620                           SelectionDAG &DAG) {
16621   MVT VT = Op.getSimpleValueType();
16622   SDLoc dl(Op);
16623   SDValue R = Op.getOperand(0);
16624   SDValue Amt = Op.getOperand(1);
16625
16626   assert(VT.isVector() && "Custom lowering only for vector shifts!");
16627   assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
16628
16629   if (SDValue V = LowerScalarImmediateShift(Op, DAG, Subtarget))
16630     return V;
16631
16632   if (SDValue V = LowerScalarVariableShift(Op, DAG, Subtarget))
16633       return V;
16634
16635   if (SupportedVectorVarShift(VT, Subtarget, Op.getOpcode()))
16636     return Op;
16637
16638   // 2i64 vector logical shifts can efficiently avoid scalarization - do the
16639   // shifts per-lane and then shuffle the partial results back together.
16640   if (VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) {
16641     // Splat the shift amounts so the scalar shifts above will catch it.
16642     SDValue Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {0, 0});
16643     SDValue Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {1, 1});
16644     SDValue R0 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt0);
16645     SDValue R1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt1);
16646     return DAG.getVectorShuffle(VT, dl, R0, R1, {0, 3});
16647   }
16648
16649   // If possible, lower this packed shift into a vector multiply instead of
16650   // expanding it into a sequence of scalar shifts.
16651   // Do this only if the vector shift count is a constant build_vector.
16652   if (Op.getOpcode() == ISD::SHL &&
16653       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
16654        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
16655       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
16656     SmallVector<SDValue, 8> Elts;
16657     EVT SVT = VT.getScalarType();
16658     unsigned SVTBits = SVT.getSizeInBits();
16659     const APInt &One = APInt(SVTBits, 1);
16660     unsigned NumElems = VT.getVectorNumElements();
16661
16662     for (unsigned i=0; i !=NumElems; ++i) {
16663       SDValue Op = Amt->getOperand(i);
16664       if (Op->getOpcode() == ISD::UNDEF) {
16665         Elts.push_back(Op);
16666         continue;
16667       }
16668
16669       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
16670       const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
16671       uint64_t ShAmt = C.getZExtValue();
16672       if (ShAmt >= SVTBits) {
16673         Elts.push_back(DAG.getUNDEF(SVT));
16674         continue;
16675       }
16676       Elts.push_back(DAG.getConstant(One.shl(ShAmt), dl, SVT));
16677     }
16678     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
16679     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
16680   }
16681
16682   // Lower SHL with variable shift amount.
16683   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
16684     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, dl, VT));
16685
16686     Op = DAG.getNode(ISD::ADD, dl, VT, Op,
16687                      DAG.getConstant(0x3f800000U, dl, VT));
16688     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
16689     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
16690     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
16691   }
16692
16693   // If possible, lower this shift as a sequence of two shifts by
16694   // constant plus a MOVSS/MOVSD instead of scalarizing it.
16695   // Example:
16696   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
16697   //
16698   // Could be rewritten as:
16699   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
16700   //
16701   // The advantage is that the two shifts from the example would be
16702   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
16703   // the vector shift into four scalar shifts plus four pairs of vector
16704   // insert/extract.
16705   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
16706       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
16707     unsigned TargetOpcode = X86ISD::MOVSS;
16708     bool CanBeSimplified;
16709     // The splat value for the first packed shift (the 'X' from the example).
16710     SDValue Amt1 = Amt->getOperand(0);
16711     // The splat value for the second packed shift (the 'Y' from the example).
16712     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
16713                                         Amt->getOperand(2);
16714
16715     // See if it is possible to replace this node with a sequence of
16716     // two shifts followed by a MOVSS/MOVSD
16717     if (VT == MVT::v4i32) {
16718       // Check if it is legal to use a MOVSS.
16719       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
16720                         Amt2 == Amt->getOperand(3);
16721       if (!CanBeSimplified) {
16722         // Otherwise, check if we can still simplify this node using a MOVSD.
16723         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
16724                           Amt->getOperand(2) == Amt->getOperand(3);
16725         TargetOpcode = X86ISD::MOVSD;
16726         Amt2 = Amt->getOperand(2);
16727       }
16728     } else {
16729       // Do similar checks for the case where the machine value type
16730       // is MVT::v8i16.
16731       CanBeSimplified = Amt1 == Amt->getOperand(1);
16732       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
16733         CanBeSimplified = Amt2 == Amt->getOperand(i);
16734
16735       if (!CanBeSimplified) {
16736         TargetOpcode = X86ISD::MOVSD;
16737         CanBeSimplified = true;
16738         Amt2 = Amt->getOperand(4);
16739         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
16740           CanBeSimplified = Amt1 == Amt->getOperand(i);
16741         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
16742           CanBeSimplified = Amt2 == Amt->getOperand(j);
16743       }
16744     }
16745
16746     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
16747         isa<ConstantSDNode>(Amt2)) {
16748       // Replace this node with two shifts followed by a MOVSS/MOVSD.
16749       EVT CastVT = MVT::v4i32;
16750       SDValue Splat1 =
16751         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), dl, VT);
16752       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
16753       SDValue Splat2 =
16754         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), dl, VT);
16755       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
16756       if (TargetOpcode == X86ISD::MOVSD)
16757         CastVT = MVT::v2i64;
16758       SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
16759       SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
16760       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
16761                                             BitCast1, DAG);
16762       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
16763     }
16764   }
16765
16766   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
16767     // Turn 'a' into a mask suitable for VSELECT: a = a << 5;
16768     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, dl, VT));
16769
16770     SDValue VSelM = DAG.getConstant(0x80, dl, VT);
16771     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16772     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16773
16774     // r = VSELECT(r, shl(r, 4), a);
16775     SDValue M = DAG.getNode(ISD::SHL, dl, VT, R, DAG.getConstant(4, dl, VT));
16776     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
16777
16778     // a += a
16779     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
16780     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16781     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16782
16783     // r = VSELECT(r, shl(r, 2), a);
16784     M = DAG.getNode(ISD::SHL, dl, VT, R, DAG.getConstant(2, dl, VT));
16785     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
16786
16787     // a += a
16788     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
16789     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16790     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16791
16792     // return VSELECT(r, r+r, a);
16793     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
16794                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
16795     return R;
16796   }
16797
16798   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
16799   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
16800   // solution better.
16801   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
16802     MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
16803     unsigned ExtOpc =
16804         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
16805     R = DAG.getNode(ExtOpc, dl, NewVT, R);
16806     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
16807     return DAG.getNode(ISD::TRUNCATE, dl, VT,
16808                        DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
16809   }
16810
16811   // Decompose 256-bit shifts into smaller 128-bit shifts.
16812   if (VT.is256BitVector()) {
16813     unsigned NumElems = VT.getVectorNumElements();
16814     MVT EltVT = VT.getVectorElementType();
16815     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16816
16817     // Extract the two vectors
16818     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
16819     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
16820
16821     // Recreate the shift amount vectors
16822     SDValue Amt1, Amt2;
16823     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
16824       // Constant shift amount
16825       SmallVector<SDValue, 8> Ops(Amt->op_begin(), Amt->op_begin() + NumElems);
16826       ArrayRef<SDValue> Amt1Csts = makeArrayRef(Ops).slice(0, NumElems / 2);
16827       ArrayRef<SDValue> Amt2Csts = makeArrayRef(Ops).slice(NumElems / 2);
16828
16829       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
16830       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
16831     } else {
16832       // Variable shift amount
16833       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
16834       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
16835     }
16836
16837     // Issue new vector shifts for the smaller types
16838     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
16839     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
16840
16841     // Concatenate the result back
16842     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
16843   }
16844
16845   return SDValue();
16846 }
16847
16848 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
16849   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
16850   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
16851   // looks for this combo and may remove the "setcc" instruction if the "setcc"
16852   // has only one use.
16853   SDNode *N = Op.getNode();
16854   SDValue LHS = N->getOperand(0);
16855   SDValue RHS = N->getOperand(1);
16856   unsigned BaseOp = 0;
16857   unsigned Cond = 0;
16858   SDLoc DL(Op);
16859   switch (Op.getOpcode()) {
16860   default: llvm_unreachable("Unknown ovf instruction!");
16861   case ISD::SADDO:
16862     // A subtract of one will be selected as a INC. Note that INC doesn't
16863     // set CF, so we can't do this for UADDO.
16864     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16865       if (C->isOne()) {
16866         BaseOp = X86ISD::INC;
16867         Cond = X86::COND_O;
16868         break;
16869       }
16870     BaseOp = X86ISD::ADD;
16871     Cond = X86::COND_O;
16872     break;
16873   case ISD::UADDO:
16874     BaseOp = X86ISD::ADD;
16875     Cond = X86::COND_B;
16876     break;
16877   case ISD::SSUBO:
16878     // A subtract of one will be selected as a DEC. Note that DEC doesn't
16879     // set CF, so we can't do this for USUBO.
16880     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16881       if (C->isOne()) {
16882         BaseOp = X86ISD::DEC;
16883         Cond = X86::COND_O;
16884         break;
16885       }
16886     BaseOp = X86ISD::SUB;
16887     Cond = X86::COND_O;
16888     break;
16889   case ISD::USUBO:
16890     BaseOp = X86ISD::SUB;
16891     Cond = X86::COND_B;
16892     break;
16893   case ISD::SMULO:
16894     BaseOp = N->getValueType(0) == MVT::i8 ? X86ISD::SMUL8 : X86ISD::SMUL;
16895     Cond = X86::COND_O;
16896     break;
16897   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
16898     if (N->getValueType(0) == MVT::i8) {
16899       BaseOp = X86ISD::UMUL8;
16900       Cond = X86::COND_O;
16901       break;
16902     }
16903     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
16904                                  MVT::i32);
16905     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
16906
16907     SDValue SetCC =
16908       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16909                   DAG.getConstant(X86::COND_O, DL, MVT::i32),
16910                   SDValue(Sum.getNode(), 2));
16911
16912     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
16913   }
16914   }
16915
16916   // Also sets EFLAGS.
16917   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
16918   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
16919
16920   SDValue SetCC =
16921     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
16922                 DAG.getConstant(Cond, DL, MVT::i32),
16923                 SDValue(Sum.getNode(), 1));
16924
16925   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
16926 }
16927
16928 /// Returns true if the operand type is exactly twice the native width, and
16929 /// the corresponding cmpxchg8b or cmpxchg16b instruction is available.
16930 /// Used to know whether to use cmpxchg8/16b when expanding atomic operations
16931 /// (otherwise we leave them alone to become __sync_fetch_and_... calls).
16932 bool X86TargetLowering::needsCmpXchgNb(const Type *MemType) const {
16933   unsigned OpWidth = MemType->getPrimitiveSizeInBits();
16934
16935   if (OpWidth == 64)
16936     return !Subtarget->is64Bit(); // FIXME this should be Subtarget.hasCmpxchg8b
16937   else if (OpWidth == 128)
16938     return Subtarget->hasCmpxchg16b();
16939   else
16940     return false;
16941 }
16942
16943 bool X86TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
16944   return needsCmpXchgNb(SI->getValueOperand()->getType());
16945 }
16946
16947 // Note: this turns large loads into lock cmpxchg8b/16b.
16948 // FIXME: On 32 bits x86, fild/movq might be faster than lock cmpxchg8b.
16949 bool X86TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
16950   auto PTy = cast<PointerType>(LI->getPointerOperand()->getType());
16951   return needsCmpXchgNb(PTy->getElementType());
16952 }
16953
16954 TargetLoweringBase::AtomicRMWExpansionKind
16955 X86TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
16956   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
16957   const Type *MemType = AI->getType();
16958
16959   // If the operand is too big, we must see if cmpxchg8/16b is available
16960   // and default to library calls otherwise.
16961   if (MemType->getPrimitiveSizeInBits() > NativeWidth) {
16962     return needsCmpXchgNb(MemType) ? AtomicRMWExpansionKind::CmpXChg
16963                                    : AtomicRMWExpansionKind::None;
16964   }
16965
16966   AtomicRMWInst::BinOp Op = AI->getOperation();
16967   switch (Op) {
16968   default:
16969     llvm_unreachable("Unknown atomic operation");
16970   case AtomicRMWInst::Xchg:
16971   case AtomicRMWInst::Add:
16972   case AtomicRMWInst::Sub:
16973     // It's better to use xadd, xsub or xchg for these in all cases.
16974     return AtomicRMWExpansionKind::None;
16975   case AtomicRMWInst::Or:
16976   case AtomicRMWInst::And:
16977   case AtomicRMWInst::Xor:
16978     // If the atomicrmw's result isn't actually used, we can just add a "lock"
16979     // prefix to a normal instruction for these operations.
16980     return !AI->use_empty() ? AtomicRMWExpansionKind::CmpXChg
16981                             : AtomicRMWExpansionKind::None;
16982   case AtomicRMWInst::Nand:
16983   case AtomicRMWInst::Max:
16984   case AtomicRMWInst::Min:
16985   case AtomicRMWInst::UMax:
16986   case AtomicRMWInst::UMin:
16987     // These always require a non-trivial set of data operations on x86. We must
16988     // use a cmpxchg loop.
16989     return AtomicRMWExpansionKind::CmpXChg;
16990   }
16991 }
16992
16993 static bool hasMFENCE(const X86Subtarget& Subtarget) {
16994   // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
16995   // no-sse2). There isn't any reason to disable it if the target processor
16996   // supports it.
16997   return Subtarget.hasSSE2() || Subtarget.is64Bit();
16998 }
16999
17000 LoadInst *
17001 X86TargetLowering::lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *AI) const {
17002   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
17003   const Type *MemType = AI->getType();
17004   // Accesses larger than the native width are turned into cmpxchg/libcalls, so
17005   // there is no benefit in turning such RMWs into loads, and it is actually
17006   // harmful as it introduces a mfence.
17007   if (MemType->getPrimitiveSizeInBits() > NativeWidth)
17008     return nullptr;
17009
17010   auto Builder = IRBuilder<>(AI);
17011   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
17012   auto SynchScope = AI->getSynchScope();
17013   // We must restrict the ordering to avoid generating loads with Release or
17014   // ReleaseAcquire orderings.
17015   auto Order = AtomicCmpXchgInst::getStrongestFailureOrdering(AI->getOrdering());
17016   auto Ptr = AI->getPointerOperand();
17017
17018   // Before the load we need a fence. Here is an example lifted from
17019   // http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf showing why a fence
17020   // is required:
17021   // Thread 0:
17022   //   x.store(1, relaxed);
17023   //   r1 = y.fetch_add(0, release);
17024   // Thread 1:
17025   //   y.fetch_add(42, acquire);
17026   //   r2 = x.load(relaxed);
17027   // r1 = r2 = 0 is impossible, but becomes possible if the idempotent rmw is
17028   // lowered to just a load without a fence. A mfence flushes the store buffer,
17029   // making the optimization clearly correct.
17030   // FIXME: it is required if isAtLeastRelease(Order) but it is not clear
17031   // otherwise, we might be able to be more agressive on relaxed idempotent
17032   // rmw. In practice, they do not look useful, so we don't try to be
17033   // especially clever.
17034   if (SynchScope == SingleThread)
17035     // FIXME: we could just insert an X86ISD::MEMBARRIER here, except we are at
17036     // the IR level, so we must wrap it in an intrinsic.
17037     return nullptr;
17038
17039   if (!hasMFENCE(*Subtarget))
17040     // FIXME: it might make sense to use a locked operation here but on a
17041     // different cache-line to prevent cache-line bouncing. In practice it
17042     // is probably a small win, and x86 processors without mfence are rare
17043     // enough that we do not bother.
17044     return nullptr;
17045
17046   Function *MFence =
17047       llvm::Intrinsic::getDeclaration(M, Intrinsic::x86_sse2_mfence);
17048   Builder.CreateCall(MFence, {});
17049
17050   // Finally we can emit the atomic load.
17051   LoadInst *Loaded = Builder.CreateAlignedLoad(Ptr,
17052           AI->getType()->getPrimitiveSizeInBits());
17053   Loaded->setAtomic(Order, SynchScope);
17054   AI->replaceAllUsesWith(Loaded);
17055   AI->eraseFromParent();
17056   return Loaded;
17057 }
17058
17059 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
17060                                  SelectionDAG &DAG) {
17061   SDLoc dl(Op);
17062   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
17063     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
17064   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
17065     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
17066
17067   // The only fence that needs an instruction is a sequentially-consistent
17068   // cross-thread fence.
17069   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
17070     if (hasMFENCE(*Subtarget))
17071       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
17072
17073     SDValue Chain = Op.getOperand(0);
17074     SDValue Zero = DAG.getConstant(0, dl, MVT::i32);
17075     SDValue Ops[] = {
17076       DAG.getRegister(X86::ESP, MVT::i32),     // Base
17077       DAG.getTargetConstant(1, dl, MVT::i8),   // Scale
17078       DAG.getRegister(0, MVT::i32),            // Index
17079       DAG.getTargetConstant(0, dl, MVT::i32),  // Disp
17080       DAG.getRegister(0, MVT::i32),            // Segment.
17081       Zero,
17082       Chain
17083     };
17084     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
17085     return SDValue(Res, 0);
17086   }
17087
17088   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
17089   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
17090 }
17091
17092 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
17093                              SelectionDAG &DAG) {
17094   MVT T = Op.getSimpleValueType();
17095   SDLoc DL(Op);
17096   unsigned Reg = 0;
17097   unsigned size = 0;
17098   switch(T.SimpleTy) {
17099   default: llvm_unreachable("Invalid value type!");
17100   case MVT::i8:  Reg = X86::AL;  size = 1; break;
17101   case MVT::i16: Reg = X86::AX;  size = 2; break;
17102   case MVT::i32: Reg = X86::EAX; size = 4; break;
17103   case MVT::i64:
17104     assert(Subtarget->is64Bit() && "Node not type legal!");
17105     Reg = X86::RAX; size = 8;
17106     break;
17107   }
17108   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
17109                                   Op.getOperand(2), SDValue());
17110   SDValue Ops[] = { cpIn.getValue(0),
17111                     Op.getOperand(1),
17112                     Op.getOperand(3),
17113                     DAG.getTargetConstant(size, DL, MVT::i8),
17114                     cpIn.getValue(1) };
17115   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
17116   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
17117   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
17118                                            Ops, T, MMO);
17119
17120   SDValue cpOut =
17121     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
17122   SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
17123                                       MVT::i32, cpOut.getValue(2));
17124   SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
17125                                 DAG.getConstant(X86::COND_E, DL, MVT::i8),
17126                                 EFLAGS);
17127
17128   DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
17129   DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
17130   DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
17131   return SDValue();
17132 }
17133
17134 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
17135                             SelectionDAG &DAG) {
17136   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
17137   MVT DstVT = Op.getSimpleValueType();
17138
17139   if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
17140     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
17141     if (DstVT != MVT::f64)
17142       // This conversion needs to be expanded.
17143       return SDValue();
17144
17145     SDValue InVec = Op->getOperand(0);
17146     SDLoc dl(Op);
17147     unsigned NumElts = SrcVT.getVectorNumElements();
17148     EVT SVT = SrcVT.getVectorElementType();
17149
17150     // Widen the vector in input in the case of MVT::v2i32.
17151     // Example: from MVT::v2i32 to MVT::v4i32.
17152     SmallVector<SDValue, 16> Elts;
17153     for (unsigned i = 0, e = NumElts; i != e; ++i)
17154       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
17155                                  DAG.getIntPtrConstant(i, dl)));
17156
17157     // Explicitly mark the extra elements as Undef.
17158     Elts.append(NumElts, DAG.getUNDEF(SVT));
17159
17160     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
17161     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
17162     SDValue ToV2F64 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, BV);
17163     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
17164                        DAG.getIntPtrConstant(0, dl));
17165   }
17166
17167   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
17168          Subtarget->hasMMX() && "Unexpected custom BITCAST");
17169   assert((DstVT == MVT::i64 ||
17170           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
17171          "Unexpected custom BITCAST");
17172   // i64 <=> MMX conversions are Legal.
17173   if (SrcVT==MVT::i64 && DstVT.isVector())
17174     return Op;
17175   if (DstVT==MVT::i64 && SrcVT.isVector())
17176     return Op;
17177   // MMX <=> MMX conversions are Legal.
17178   if (SrcVT.isVector() && DstVT.isVector())
17179     return Op;
17180   // All other conversions need to be expanded.
17181   return SDValue();
17182 }
17183
17184 static SDValue LowerCTPOP(SDValue Op, const X86Subtarget *Subtarget,
17185                           SelectionDAG &DAG) {
17186   SDNode *Node = Op.getNode();
17187   SDLoc dl(Node);
17188
17189   Op = Op.getOperand(0);
17190   EVT VT = Op.getValueType();
17191   assert((VT.is128BitVector() || VT.is256BitVector()) &&
17192          "CTPOP lowering only implemented for 128/256-bit wide vector types");
17193
17194   unsigned NumElts = VT.getVectorNumElements();
17195   EVT EltVT = VT.getVectorElementType();
17196   unsigned Len = EltVT.getSizeInBits();
17197
17198   // This is the vectorized version of the "best" algorithm from
17199   // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
17200   // with a minor tweak to use a series of adds + shifts instead of vector
17201   // multiplications. Implemented for the v2i64, v4i64, v4i32, v8i32 types:
17202   //
17203   //  v2i64, v4i64, v4i32 => Only profitable w/ popcnt disabled
17204   //  v8i32 => Always profitable
17205   //
17206   // FIXME: There a couple of possible improvements:
17207   //
17208   // 1) Support for i8 and i16 vectors (needs measurements if popcnt enabled).
17209   // 2) Use strategies from http://wm.ite.pl/articles/sse-popcount.html
17210   //
17211   assert(EltVT.isInteger() && (Len == 32 || Len == 64) && Len % 8 == 0 &&
17212          "CTPOP not implemented for this vector element type.");
17213
17214   // X86 canonicalize ANDs to vXi64, generate the appropriate bitcasts to avoid
17215   // extra legalization.
17216   bool NeedsBitcast = EltVT == MVT::i32;
17217   MVT BitcastVT = VT.is256BitVector() ? MVT::v4i64 : MVT::v2i64;
17218
17219   SDValue Cst55 = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x55)), dl,
17220                                   EltVT);
17221   SDValue Cst33 = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x33)), dl,
17222                                   EltVT);
17223   SDValue Cst0F = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x0F)), dl,
17224                                   EltVT);
17225
17226   // v = v - ((v >> 1) & 0x55555555...)
17227   SmallVector<SDValue, 8> Ones(NumElts, DAG.getConstant(1, dl, EltVT));
17228   SDValue OnesV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ones);
17229   SDValue Srl = DAG.getNode(ISD::SRL, dl, VT, Op, OnesV);
17230   if (NeedsBitcast)
17231     Srl = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Srl);
17232
17233   SmallVector<SDValue, 8> Mask55(NumElts, Cst55);
17234   SDValue M55 = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Mask55);
17235   if (NeedsBitcast)
17236     M55 = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M55);
17237
17238   SDValue And = DAG.getNode(ISD::AND, dl, Srl.getValueType(), Srl, M55);
17239   if (VT != And.getValueType())
17240     And = DAG.getNode(ISD::BITCAST, dl, VT, And);
17241   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, Op, And);
17242
17243   // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
17244   SmallVector<SDValue, 8> Mask33(NumElts, Cst33);
17245   SDValue M33 = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Mask33);
17246   SmallVector<SDValue, 8> Twos(NumElts, DAG.getConstant(2, dl, EltVT));
17247   SDValue TwosV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Twos);
17248
17249   Srl = DAG.getNode(ISD::SRL, dl, VT, Sub, TwosV);
17250   if (NeedsBitcast) {
17251     Srl = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Srl);
17252     M33 = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M33);
17253     Sub = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Sub);
17254   }
17255
17256   SDValue AndRHS = DAG.getNode(ISD::AND, dl, M33.getValueType(), Srl, M33);
17257   SDValue AndLHS = DAG.getNode(ISD::AND, dl, M33.getValueType(), Sub, M33);
17258   if (VT != AndRHS.getValueType()) {
17259     AndRHS = DAG.getNode(ISD::BITCAST, dl, VT, AndRHS);
17260     AndLHS = DAG.getNode(ISD::BITCAST, dl, VT, AndLHS);
17261   }
17262   SDValue Add = DAG.getNode(ISD::ADD, dl, VT, AndLHS, AndRHS);
17263
17264   // v = (v + (v >> 4)) & 0x0F0F0F0F...
17265   SmallVector<SDValue, 8> Fours(NumElts, DAG.getConstant(4, dl, EltVT));
17266   SDValue FoursV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Fours);
17267   Srl = DAG.getNode(ISD::SRL, dl, VT, Add, FoursV);
17268   Add = DAG.getNode(ISD::ADD, dl, VT, Add, Srl);
17269
17270   SmallVector<SDValue, 8> Mask0F(NumElts, Cst0F);
17271   SDValue M0F = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Mask0F);
17272   if (NeedsBitcast) {
17273     Add = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Add);
17274     M0F = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M0F);
17275   }
17276   And = DAG.getNode(ISD::AND, dl, M0F.getValueType(), Add, M0F);
17277   if (VT != And.getValueType())
17278     And = DAG.getNode(ISD::BITCAST, dl, VT, And);
17279
17280   // The algorithm mentioned above uses:
17281   //    v = (v * 0x01010101...) >> (Len - 8)
17282   //
17283   // Change it to use vector adds + vector shifts which yield faster results on
17284   // Haswell than using vector integer multiplication.
17285   //
17286   // For i32 elements:
17287   //    v = v + (v >> 8)
17288   //    v = v + (v >> 16)
17289   //
17290   // For i64 elements:
17291   //    v = v + (v >> 8)
17292   //    v = v + (v >> 16)
17293   //    v = v + (v >> 32)
17294   //
17295   Add = And;
17296   SmallVector<SDValue, 8> Csts;
17297   for (unsigned i = 8; i <= Len/2; i *= 2) {
17298     Csts.assign(NumElts, DAG.getConstant(i, dl, EltVT));
17299     SDValue CstsV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Csts);
17300     Srl = DAG.getNode(ISD::SRL, dl, VT, Add, CstsV);
17301     Add = DAG.getNode(ISD::ADD, dl, VT, Add, Srl);
17302     Csts.clear();
17303   }
17304
17305   // The result is on the least significant 6-bits on i32 and 7-bits on i64.
17306   SDValue Cst3F = DAG.getConstant(APInt(Len, Len == 32 ? 0x3F : 0x7F), dl,
17307                                   EltVT);
17308   SmallVector<SDValue, 8> Cst3FV(NumElts, Cst3F);
17309   SDValue M3F = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Cst3FV);
17310   if (NeedsBitcast) {
17311     Add = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Add);
17312     M3F = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M3F);
17313   }
17314   And = DAG.getNode(ISD::AND, dl, M3F.getValueType(), Add, M3F);
17315   if (VT != And.getValueType())
17316     And = DAG.getNode(ISD::BITCAST, dl, VT, And);
17317
17318   return And;
17319 }
17320
17321 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
17322   SDNode *Node = Op.getNode();
17323   SDLoc dl(Node);
17324   EVT T = Node->getValueType(0);
17325   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
17326                               DAG.getConstant(0, dl, T), Node->getOperand(2));
17327   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
17328                        cast<AtomicSDNode>(Node)->getMemoryVT(),
17329                        Node->getOperand(0),
17330                        Node->getOperand(1), negOp,
17331                        cast<AtomicSDNode>(Node)->getMemOperand(),
17332                        cast<AtomicSDNode>(Node)->getOrdering(),
17333                        cast<AtomicSDNode>(Node)->getSynchScope());
17334 }
17335
17336 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
17337   SDNode *Node = Op.getNode();
17338   SDLoc dl(Node);
17339   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
17340
17341   // Convert seq_cst store -> xchg
17342   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
17343   // FIXME: On 32-bit, store -> fist or movq would be more efficient
17344   //        (The only way to get a 16-byte store is cmpxchg16b)
17345   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
17346   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
17347       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
17348     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
17349                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
17350                                  Node->getOperand(0),
17351                                  Node->getOperand(1), Node->getOperand(2),
17352                                  cast<AtomicSDNode>(Node)->getMemOperand(),
17353                                  cast<AtomicSDNode>(Node)->getOrdering(),
17354                                  cast<AtomicSDNode>(Node)->getSynchScope());
17355     return Swap.getValue(1);
17356   }
17357   // Other atomic stores have a simple pattern.
17358   return Op;
17359 }
17360
17361 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
17362   EVT VT = Op.getNode()->getSimpleValueType(0);
17363
17364   // Let legalize expand this if it isn't a legal type yet.
17365   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
17366     return SDValue();
17367
17368   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
17369
17370   unsigned Opc;
17371   bool ExtraOp = false;
17372   switch (Op.getOpcode()) {
17373   default: llvm_unreachable("Invalid code");
17374   case ISD::ADDC: Opc = X86ISD::ADD; break;
17375   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
17376   case ISD::SUBC: Opc = X86ISD::SUB; break;
17377   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
17378   }
17379
17380   if (!ExtraOp)
17381     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
17382                        Op.getOperand(1));
17383   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
17384                      Op.getOperand(1), Op.getOperand(2));
17385 }
17386
17387 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
17388                             SelectionDAG &DAG) {
17389   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
17390
17391   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
17392   // which returns the values as { float, float } (in XMM0) or
17393   // { double, double } (which is returned in XMM0, XMM1).
17394   SDLoc dl(Op);
17395   SDValue Arg = Op.getOperand(0);
17396   EVT ArgVT = Arg.getValueType();
17397   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
17398
17399   TargetLowering::ArgListTy Args;
17400   TargetLowering::ArgListEntry Entry;
17401
17402   Entry.Node = Arg;
17403   Entry.Ty = ArgTy;
17404   Entry.isSExt = false;
17405   Entry.isZExt = false;
17406   Args.push_back(Entry);
17407
17408   bool isF64 = ArgVT == MVT::f64;
17409   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
17410   // the small struct {f32, f32} is returned in (eax, edx). For f64,
17411   // the results are returned via SRet in memory.
17412   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
17413   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17414   SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
17415
17416   Type *RetTy = isF64
17417     ? (Type*)StructType::get(ArgTy, ArgTy, nullptr)
17418     : (Type*)VectorType::get(ArgTy, 4);
17419
17420   TargetLowering::CallLoweringInfo CLI(DAG);
17421   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
17422     .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
17423
17424   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
17425
17426   if (isF64)
17427     // Returned in xmm0 and xmm1.
17428     return CallResult.first;
17429
17430   // Returned in bits 0:31 and 32:64 xmm0.
17431   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
17432                                CallResult.first, DAG.getIntPtrConstant(0, dl));
17433   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
17434                                CallResult.first, DAG.getIntPtrConstant(1, dl));
17435   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
17436   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
17437 }
17438
17439 static SDValue LowerMSCATTER(SDValue Op, const X86Subtarget *Subtarget,
17440                              SelectionDAG &DAG) {
17441   assert(Subtarget->hasAVX512() &&
17442          "MGATHER/MSCATTER are supported on AVX-512 arch only");
17443
17444   MaskedScatterSDNode *N = cast<MaskedScatterSDNode>(Op.getNode());
17445   EVT VT = N->getValue().getValueType();
17446   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported scatter op");
17447   SDLoc dl(Op);
17448
17449   // X86 scatter kills mask register, so its type should be added to
17450   // the list of return values
17451   if (N->getNumValues() == 1) {
17452     SDValue Index = N->getIndex();
17453     if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
17454         !Index.getValueType().is512BitVector())
17455       Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
17456
17457     SDVTList VTs = DAG.getVTList(N->getMask().getValueType(), MVT::Other);
17458     SDValue Ops[] = { N->getOperand(0), N->getOperand(1),  N->getOperand(2),
17459                       N->getOperand(3), Index };
17460
17461     SDValue NewScatter = DAG.getMaskedScatter(VTs, VT, dl, Ops, N->getMemOperand());
17462     DAG.ReplaceAllUsesWith(Op, SDValue(NewScatter.getNode(), 1));
17463     return SDValue(NewScatter.getNode(), 0);
17464   }
17465   return Op;
17466 }
17467
17468 static SDValue LowerMGATHER(SDValue Op, const X86Subtarget *Subtarget,
17469                             SelectionDAG &DAG) {
17470   assert(Subtarget->hasAVX512() &&
17471          "MGATHER/MSCATTER are supported on AVX-512 arch only");
17472
17473   MaskedGatherSDNode *N = cast<MaskedGatherSDNode>(Op.getNode());
17474   EVT VT = Op.getValueType();
17475   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported gather op");
17476   SDLoc dl(Op);
17477
17478   SDValue Index = N->getIndex();
17479   if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
17480       !Index.getValueType().is512BitVector()) {
17481     Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
17482     SDValue Ops[] = { N->getOperand(0), N->getOperand(1),  N->getOperand(2),
17483                       N->getOperand(3), Index };
17484     DAG.UpdateNodeOperands(N, Ops);
17485   }
17486   return Op;
17487 }
17488
17489 SDValue X86TargetLowering::LowerGC_TRANSITION_START(SDValue Op,
17490                                                     SelectionDAG &DAG) const {
17491   // TODO: Eventually, the lowering of these nodes should be informed by or
17492   // deferred to the GC strategy for the function in which they appear. For
17493   // now, however, they must be lowered to something. Since they are logically
17494   // no-ops in the case of a null GC strategy (or a GC strategy which does not
17495   // require special handling for these nodes), lower them as literal NOOPs for
17496   // the time being.
17497   SmallVector<SDValue, 2> Ops;
17498
17499   Ops.push_back(Op.getOperand(0));
17500   if (Op->getGluedNode())
17501     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
17502
17503   SDLoc OpDL(Op);
17504   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
17505   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
17506
17507   return NOOP;
17508 }
17509
17510 SDValue X86TargetLowering::LowerGC_TRANSITION_END(SDValue Op,
17511                                                   SelectionDAG &DAG) const {
17512   // TODO: Eventually, the lowering of these nodes should be informed by or
17513   // deferred to the GC strategy for the function in which they appear. For
17514   // now, however, they must be lowered to something. Since they are logically
17515   // no-ops in the case of a null GC strategy (or a GC strategy which does not
17516   // require special handling for these nodes), lower them as literal NOOPs for
17517   // the time being.
17518   SmallVector<SDValue, 2> Ops;
17519
17520   Ops.push_back(Op.getOperand(0));
17521   if (Op->getGluedNode())
17522     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
17523
17524   SDLoc OpDL(Op);
17525   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
17526   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
17527
17528   return NOOP;
17529 }
17530
17531 /// LowerOperation - Provide custom lowering hooks for some operations.
17532 ///
17533 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
17534   switch (Op.getOpcode()) {
17535   default: llvm_unreachable("Should not custom lower this!");
17536   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
17537   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
17538     return LowerCMP_SWAP(Op, Subtarget, DAG);
17539   case ISD::CTPOP:              return LowerCTPOP(Op, Subtarget, DAG);
17540   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
17541   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
17542   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
17543   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, Subtarget, DAG);
17544   case ISD::VECTOR_SHUFFLE:     return lowerVectorShuffle(Op, Subtarget, DAG);
17545   case ISD::VSELECT:            return LowerVSELECT(Op, DAG);
17546   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
17547   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
17548   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
17549   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
17550   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
17551   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
17552   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
17553   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
17554   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
17555   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
17556   case ISD::SHL_PARTS:
17557   case ISD::SRA_PARTS:
17558   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
17559   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
17560   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
17561   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
17562   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
17563   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
17564   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
17565   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
17566   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
17567   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
17568   case ISD::LOAD:               return LowerExtendedLoad(Op, Subtarget, DAG);
17569   case ISD::FABS:
17570   case ISD::FNEG:               return LowerFABSorFNEG(Op, DAG);
17571   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
17572   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
17573   case ISD::SETCC:              return LowerSETCC(Op, DAG);
17574   case ISD::SELECT:             return LowerSELECT(Op, DAG);
17575   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
17576   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
17577   case ISD::VASTART:            return LowerVASTART(Op, DAG);
17578   case ISD::VAARG:              return LowerVAARG(Op, DAG);
17579   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
17580   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, Subtarget, DAG);
17581   case ISD::INTRINSIC_VOID:
17582   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
17583   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
17584   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
17585   case ISD::FRAME_TO_ARGS_OFFSET:
17586                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
17587   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
17588   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
17589   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
17590   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
17591   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
17592   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
17593   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
17594   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
17595   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
17596   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
17597   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
17598   case ISD::UMUL_LOHI:
17599   case ISD::SMUL_LOHI:          return LowerMUL_LOHI(Op, Subtarget, DAG);
17600   case ISD::SRA:
17601   case ISD::SRL:
17602   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
17603   case ISD::SADDO:
17604   case ISD::UADDO:
17605   case ISD::SSUBO:
17606   case ISD::USUBO:
17607   case ISD::SMULO:
17608   case ISD::UMULO:              return LowerXALUO(Op, DAG);
17609   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
17610   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
17611   case ISD::ADDC:
17612   case ISD::ADDE:
17613   case ISD::SUBC:
17614   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
17615   case ISD::ADD:                return LowerADD(Op, DAG);
17616   case ISD::SUB:                return LowerSUB(Op, DAG);
17617   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
17618   case ISD::MGATHER:            return LowerMGATHER(Op, Subtarget, DAG);
17619   case ISD::MSCATTER:           return LowerMSCATTER(Op, Subtarget, DAG);
17620   case ISD::GC_TRANSITION_START:
17621                                 return LowerGC_TRANSITION_START(Op, DAG);
17622   case ISD::GC_TRANSITION_END:  return LowerGC_TRANSITION_END(Op, DAG);
17623   }
17624 }
17625
17626 /// ReplaceNodeResults - Replace a node with an illegal result type
17627 /// with a new node built out of custom code.
17628 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
17629                                            SmallVectorImpl<SDValue>&Results,
17630                                            SelectionDAG &DAG) const {
17631   SDLoc dl(N);
17632   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17633   switch (N->getOpcode()) {
17634   default:
17635     llvm_unreachable("Do not know how to custom type legalize this operation!");
17636   // We might have generated v2f32 FMIN/FMAX operations. Widen them to v4f32.
17637   case X86ISD::FMINC:
17638   case X86ISD::FMIN:
17639   case X86ISD::FMAXC:
17640   case X86ISD::FMAX: {
17641     EVT VT = N->getValueType(0);
17642     if (VT != MVT::v2f32)
17643       llvm_unreachable("Unexpected type (!= v2f32) on FMIN/FMAX.");
17644     SDValue UNDEF = DAG.getUNDEF(VT);
17645     SDValue LHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
17646                               N->getOperand(0), UNDEF);
17647     SDValue RHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
17648                               N->getOperand(1), UNDEF);
17649     Results.push_back(DAG.getNode(N->getOpcode(), dl, MVT::v4f32, LHS, RHS));
17650     return;
17651   }
17652   case ISD::SIGN_EXTEND_INREG:
17653   case ISD::ADDC:
17654   case ISD::ADDE:
17655   case ISD::SUBC:
17656   case ISD::SUBE:
17657     // We don't want to expand or promote these.
17658     return;
17659   case ISD::SDIV:
17660   case ISD::UDIV:
17661   case ISD::SREM:
17662   case ISD::UREM:
17663   case ISD::SDIVREM:
17664   case ISD::UDIVREM: {
17665     SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
17666     Results.push_back(V);
17667     return;
17668   }
17669   case ISD::FP_TO_SINT:
17670     // FP_TO_INT*_IN_MEM is not legal for f16 inputs.  Do not convert
17671     // (FP_TO_SINT (load f16)) to FP_TO_INT*.
17672     if (N->getOperand(0).getValueType() == MVT::f16)
17673       break;
17674     // fallthrough
17675   case ISD::FP_TO_UINT: {
17676     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
17677
17678     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
17679       return;
17680
17681     std::pair<SDValue,SDValue> Vals =
17682         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
17683     SDValue FIST = Vals.first, StackSlot = Vals.second;
17684     if (FIST.getNode()) {
17685       EVT VT = N->getValueType(0);
17686       // Return a load from the stack slot.
17687       if (StackSlot.getNode())
17688         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
17689                                       MachinePointerInfo(),
17690                                       false, false, false, 0));
17691       else
17692         Results.push_back(FIST);
17693     }
17694     return;
17695   }
17696   case ISD::UINT_TO_FP: {
17697     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
17698     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
17699         N->getValueType(0) != MVT::v2f32)
17700       return;
17701     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
17702                                  N->getOperand(0));
17703     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
17704                                      MVT::f64);
17705     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
17706     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
17707                              DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
17708     Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
17709     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
17710     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
17711     return;
17712   }
17713   case ISD::FP_ROUND: {
17714     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
17715         return;
17716     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
17717     Results.push_back(V);
17718     return;
17719   }
17720   case ISD::FP_EXTEND: {
17721     // Right now, only MVT::v2f32 has OperationAction for FP_EXTEND.
17722     // No other ValueType for FP_EXTEND should reach this point.
17723     assert(N->getValueType(0) == MVT::v2f32 &&
17724            "Do not know how to legalize this Node");
17725     return;
17726   }
17727   case ISD::INTRINSIC_W_CHAIN: {
17728     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
17729     switch (IntNo) {
17730     default : llvm_unreachable("Do not know how to custom type "
17731                                "legalize this intrinsic operation!");
17732     case Intrinsic::x86_rdtsc:
17733       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
17734                                      Results);
17735     case Intrinsic::x86_rdtscp:
17736       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
17737                                      Results);
17738     case Intrinsic::x86_rdpmc:
17739       return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
17740     }
17741   }
17742   case ISD::READCYCLECOUNTER: {
17743     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
17744                                    Results);
17745   }
17746   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
17747     EVT T = N->getValueType(0);
17748     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
17749     bool Regs64bit = T == MVT::i128;
17750     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
17751     SDValue cpInL, cpInH;
17752     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
17753                         DAG.getConstant(0, dl, HalfT));
17754     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
17755                         DAG.getConstant(1, dl, HalfT));
17756     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
17757                              Regs64bit ? X86::RAX : X86::EAX,
17758                              cpInL, SDValue());
17759     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
17760                              Regs64bit ? X86::RDX : X86::EDX,
17761                              cpInH, cpInL.getValue(1));
17762     SDValue swapInL, swapInH;
17763     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
17764                           DAG.getConstant(0, dl, HalfT));
17765     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
17766                           DAG.getConstant(1, dl, HalfT));
17767     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
17768                                Regs64bit ? X86::RBX : X86::EBX,
17769                                swapInL, cpInH.getValue(1));
17770     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
17771                                Regs64bit ? X86::RCX : X86::ECX,
17772                                swapInH, swapInL.getValue(1));
17773     SDValue Ops[] = { swapInH.getValue(0),
17774                       N->getOperand(1),
17775                       swapInH.getValue(1) };
17776     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
17777     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
17778     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
17779                                   X86ISD::LCMPXCHG8_DAG;
17780     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
17781     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
17782                                         Regs64bit ? X86::RAX : X86::EAX,
17783                                         HalfT, Result.getValue(1));
17784     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
17785                                         Regs64bit ? X86::RDX : X86::EDX,
17786                                         HalfT, cpOutL.getValue(2));
17787     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
17788
17789     SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
17790                                         MVT::i32, cpOutH.getValue(2));
17791     SDValue Success =
17792         DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17793                     DAG.getConstant(X86::COND_E, dl, MVT::i8), EFLAGS);
17794     Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
17795
17796     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
17797     Results.push_back(Success);
17798     Results.push_back(EFLAGS.getValue(1));
17799     return;
17800   }
17801   case ISD::ATOMIC_SWAP:
17802   case ISD::ATOMIC_LOAD_ADD:
17803   case ISD::ATOMIC_LOAD_SUB:
17804   case ISD::ATOMIC_LOAD_AND:
17805   case ISD::ATOMIC_LOAD_OR:
17806   case ISD::ATOMIC_LOAD_XOR:
17807   case ISD::ATOMIC_LOAD_NAND:
17808   case ISD::ATOMIC_LOAD_MIN:
17809   case ISD::ATOMIC_LOAD_MAX:
17810   case ISD::ATOMIC_LOAD_UMIN:
17811   case ISD::ATOMIC_LOAD_UMAX:
17812   case ISD::ATOMIC_LOAD: {
17813     // Delegate to generic TypeLegalization. Situations we can really handle
17814     // should have already been dealt with by AtomicExpandPass.cpp.
17815     break;
17816   }
17817   case ISD::BITCAST: {
17818     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
17819     EVT DstVT = N->getValueType(0);
17820     EVT SrcVT = N->getOperand(0)->getValueType(0);
17821
17822     if (SrcVT != MVT::f64 ||
17823         (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
17824       return;
17825
17826     unsigned NumElts = DstVT.getVectorNumElements();
17827     EVT SVT = DstVT.getVectorElementType();
17828     EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
17829     SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
17830                                    MVT::v2f64, N->getOperand(0));
17831     SDValue ToVecInt = DAG.getNode(ISD::BITCAST, dl, WiderVT, Expanded);
17832
17833     if (ExperimentalVectorWideningLegalization) {
17834       // If we are legalizing vectors by widening, we already have the desired
17835       // legal vector type, just return it.
17836       Results.push_back(ToVecInt);
17837       return;
17838     }
17839
17840     SmallVector<SDValue, 8> Elts;
17841     for (unsigned i = 0, e = NumElts; i != e; ++i)
17842       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
17843                                    ToVecInt, DAG.getIntPtrConstant(i, dl)));
17844
17845     Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
17846   }
17847   }
17848 }
17849
17850 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
17851   switch ((X86ISD::NodeType)Opcode) {
17852   case X86ISD::FIRST_NUMBER:       break;
17853   case X86ISD::BSF:                return "X86ISD::BSF";
17854   case X86ISD::BSR:                return "X86ISD::BSR";
17855   case X86ISD::SHLD:               return "X86ISD::SHLD";
17856   case X86ISD::SHRD:               return "X86ISD::SHRD";
17857   case X86ISD::FAND:               return "X86ISD::FAND";
17858   case X86ISD::FANDN:              return "X86ISD::FANDN";
17859   case X86ISD::FOR:                return "X86ISD::FOR";
17860   case X86ISD::FXOR:               return "X86ISD::FXOR";
17861   case X86ISD::FSRL:               return "X86ISD::FSRL";
17862   case X86ISD::FILD:               return "X86ISD::FILD";
17863   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
17864   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
17865   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
17866   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
17867   case X86ISD::FLD:                return "X86ISD::FLD";
17868   case X86ISD::FST:                return "X86ISD::FST";
17869   case X86ISD::CALL:               return "X86ISD::CALL";
17870   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
17871   case X86ISD::RDTSCP_DAG:         return "X86ISD::RDTSCP_DAG";
17872   case X86ISD::RDPMC_DAG:          return "X86ISD::RDPMC_DAG";
17873   case X86ISD::BT:                 return "X86ISD::BT";
17874   case X86ISD::CMP:                return "X86ISD::CMP";
17875   case X86ISD::COMI:               return "X86ISD::COMI";
17876   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
17877   case X86ISD::CMPM:               return "X86ISD::CMPM";
17878   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
17879   case X86ISD::CMPM_RND:           return "X86ISD::CMPM_RND";
17880   case X86ISD::SETCC:              return "X86ISD::SETCC";
17881   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
17882   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
17883   case X86ISD::FGETSIGNx86:        return "X86ISD::FGETSIGNx86";
17884   case X86ISD::CMOV:               return "X86ISD::CMOV";
17885   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
17886   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
17887   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
17888   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
17889   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
17890   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
17891   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
17892   case X86ISD::MOVDQ2Q:            return "X86ISD::MOVDQ2Q";
17893   case X86ISD::MMX_MOVD2W:         return "X86ISD::MMX_MOVD2W";
17894   case X86ISD::MMX_MOVW2D:         return "X86ISD::MMX_MOVW2D";
17895   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
17896   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
17897   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
17898   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
17899   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
17900   case X86ISD::MMX_PINSRW:         return "X86ISD::MMX_PINSRW";
17901   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
17902   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
17903   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
17904   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
17905   case X86ISD::SHRUNKBLEND:        return "X86ISD::SHRUNKBLEND";
17906   case X86ISD::ADDUS:              return "X86ISD::ADDUS";
17907   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
17908   case X86ISD::HADD:               return "X86ISD::HADD";
17909   case X86ISD::HSUB:               return "X86ISD::HSUB";
17910   case X86ISD::FHADD:              return "X86ISD::FHADD";
17911   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
17912   case X86ISD::UMAX:               return "X86ISD::UMAX";
17913   case X86ISD::UMIN:               return "X86ISD::UMIN";
17914   case X86ISD::SMAX:               return "X86ISD::SMAX";
17915   case X86ISD::SMIN:               return "X86ISD::SMIN";
17916   case X86ISD::FMAX:               return "X86ISD::FMAX";
17917   case X86ISD::FMAX_RND:           return "X86ISD::FMAX_RND";
17918   case X86ISD::FMIN:               return "X86ISD::FMIN";
17919   case X86ISD::FMIN_RND:           return "X86ISD::FMIN_RND";
17920   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
17921   case X86ISD::FMINC:              return "X86ISD::FMINC";
17922   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
17923   case X86ISD::FRCP:               return "X86ISD::FRCP";
17924   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
17925   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
17926   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
17927   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
17928   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
17929   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
17930   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
17931   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
17932   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
17933   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
17934   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
17935   case X86ISD::LCMPXCHG16_DAG:     return "X86ISD::LCMPXCHG16_DAG";
17936   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
17937   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
17938   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
17939   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
17940   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
17941   case X86ISD::VTRUNCM:            return "X86ISD::VTRUNCM";
17942   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
17943   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
17944   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
17945   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
17946   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
17947   case X86ISD::VSHL:               return "X86ISD::VSHL";
17948   case X86ISD::VSRL:               return "X86ISD::VSRL";
17949   case X86ISD::VSRA:               return "X86ISD::VSRA";
17950   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
17951   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
17952   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
17953   case X86ISD::CMPP:               return "X86ISD::CMPP";
17954   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
17955   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
17956   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
17957   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
17958   case X86ISD::ADD:                return "X86ISD::ADD";
17959   case X86ISD::SUB:                return "X86ISD::SUB";
17960   case X86ISD::ADC:                return "X86ISD::ADC";
17961   case X86ISD::SBB:                return "X86ISD::SBB";
17962   case X86ISD::SMUL:               return "X86ISD::SMUL";
17963   case X86ISD::UMUL:               return "X86ISD::UMUL";
17964   case X86ISD::SMUL8:              return "X86ISD::SMUL8";
17965   case X86ISD::UMUL8:              return "X86ISD::UMUL8";
17966   case X86ISD::SDIVREM8_SEXT_HREG: return "X86ISD::SDIVREM8_SEXT_HREG";
17967   case X86ISD::UDIVREM8_ZEXT_HREG: return "X86ISD::UDIVREM8_ZEXT_HREG";
17968   case X86ISD::INC:                return "X86ISD::INC";
17969   case X86ISD::DEC:                return "X86ISD::DEC";
17970   case X86ISD::OR:                 return "X86ISD::OR";
17971   case X86ISD::XOR:                return "X86ISD::XOR";
17972   case X86ISD::AND:                return "X86ISD::AND";
17973   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
17974   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
17975   case X86ISD::PTEST:              return "X86ISD::PTEST";
17976   case X86ISD::TESTP:              return "X86ISD::TESTP";
17977   case X86ISD::TESTM:              return "X86ISD::TESTM";
17978   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
17979   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
17980   case X86ISD::PACKSS:             return "X86ISD::PACKSS";
17981   case X86ISD::PACKUS:             return "X86ISD::PACKUS";
17982   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
17983   case X86ISD::VALIGN:             return "X86ISD::VALIGN";
17984   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
17985   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
17986   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
17987   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
17988   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
17989   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
17990   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
17991   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
17992   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
17993   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
17994   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
17995   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
17996   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
17997   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
17998   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
17999   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
18000   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
18001   case X86ISD::SUBV_BROADCAST:     return "X86ISD::SUBV_BROADCAST";
18002   case X86ISD::VEXTRACT:           return "X86ISD::VEXTRACT";
18003   case X86ISD::VPERMILPV:          return "X86ISD::VPERMILPV";
18004   case X86ISD::VPERMILPI:          return "X86ISD::VPERMILPI";
18005   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
18006   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
18007   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
18008   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
18009   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
18010   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
18011   case X86ISD::PMULDQ:             return "X86ISD::PMULDQ";
18012   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
18013   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
18014   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
18015   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
18016   case X86ISD::MFENCE:             return "X86ISD::MFENCE";
18017   case X86ISD::SFENCE:             return "X86ISD::SFENCE";
18018   case X86ISD::LFENCE:             return "X86ISD::LFENCE";
18019   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
18020   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
18021   case X86ISD::SAHF:               return "X86ISD::SAHF";
18022   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
18023   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
18024   case X86ISD::FMADD:              return "X86ISD::FMADD";
18025   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
18026   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
18027   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
18028   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
18029   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
18030   case X86ISD::FMADD_RND:          return "X86ISD::FMADD_RND";
18031   case X86ISD::FNMADD_RND:         return "X86ISD::FNMADD_RND";
18032   case X86ISD::FMSUB_RND:          return "X86ISD::FMSUB_RND";
18033   case X86ISD::FNMSUB_RND:         return "X86ISD::FNMSUB_RND";
18034   case X86ISD::FMADDSUB_RND:       return "X86ISD::FMADDSUB_RND";
18035   case X86ISD::FMSUBADD_RND:       return "X86ISD::FMSUBADD_RND";
18036   case X86ISD::RNDSCALE:           return "X86ISD::RNDSCALE";
18037   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
18038   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
18039   case X86ISD::XTEST:              return "X86ISD::XTEST";
18040   case X86ISD::COMPRESS:           return "X86ISD::COMPRESS";
18041   case X86ISD::EXPAND:             return "X86ISD::EXPAND";
18042   case X86ISD::SELECT:             return "X86ISD::SELECT";
18043   case X86ISD::ADDSUB:             return "X86ISD::ADDSUB";
18044   case X86ISD::RCP28:              return "X86ISD::RCP28";
18045   case X86ISD::EXP2:               return "X86ISD::EXP2";
18046   case X86ISD::RSQRT28:            return "X86ISD::RSQRT28";
18047   case X86ISD::FADD_RND:           return "X86ISD::FADD_RND";
18048   case X86ISD::FSUB_RND:           return "X86ISD::FSUB_RND";
18049   case X86ISD::FMUL_RND:           return "X86ISD::FMUL_RND";
18050   case X86ISD::FDIV_RND:           return "X86ISD::FDIV_RND";
18051   case X86ISD::ADDS:               return "X86ISD::ADDS";
18052   case X86ISD::SUBS:               return "X86ISD::SUBS";
18053   }
18054   return nullptr;
18055 }
18056
18057 // isLegalAddressingMode - Return true if the addressing mode represented
18058 // by AM is legal for this target, for a load/store of the specified type.
18059 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
18060                                               Type *Ty) const {
18061   // X86 supports extremely general addressing modes.
18062   CodeModel::Model M = getTargetMachine().getCodeModel();
18063   Reloc::Model R = getTargetMachine().getRelocationModel();
18064
18065   // X86 allows a sign-extended 32-bit immediate field as a displacement.
18066   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
18067     return false;
18068
18069   if (AM.BaseGV) {
18070     unsigned GVFlags =
18071       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
18072
18073     // If a reference to this global requires an extra load, we can't fold it.
18074     if (isGlobalStubReference(GVFlags))
18075       return false;
18076
18077     // If BaseGV requires a register for the PIC base, we cannot also have a
18078     // BaseReg specified.
18079     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
18080       return false;
18081
18082     // If lower 4G is not available, then we must use rip-relative addressing.
18083     if ((M != CodeModel::Small || R != Reloc::Static) &&
18084         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
18085       return false;
18086   }
18087
18088   switch (AM.Scale) {
18089   case 0:
18090   case 1:
18091   case 2:
18092   case 4:
18093   case 8:
18094     // These scales always work.
18095     break;
18096   case 3:
18097   case 5:
18098   case 9:
18099     // These scales are formed with basereg+scalereg.  Only accept if there is
18100     // no basereg yet.
18101     if (AM.HasBaseReg)
18102       return false;
18103     break;
18104   default:  // Other stuff never works.
18105     return false;
18106   }
18107
18108   return true;
18109 }
18110
18111 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
18112   unsigned Bits = Ty->getScalarSizeInBits();
18113
18114   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
18115   // particularly cheaper than those without.
18116   if (Bits == 8)
18117     return false;
18118
18119   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
18120   // variable shifts just as cheap as scalar ones.
18121   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
18122     return false;
18123
18124   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
18125   // fully general vector.
18126   return true;
18127 }
18128
18129 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
18130   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
18131     return false;
18132   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
18133   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
18134   return NumBits1 > NumBits2;
18135 }
18136
18137 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
18138   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
18139     return false;
18140
18141   if (!isTypeLegal(EVT::getEVT(Ty1)))
18142     return false;
18143
18144   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
18145
18146   // Assuming the caller doesn't have a zeroext or signext return parameter,
18147   // truncation all the way down to i1 is valid.
18148   return true;
18149 }
18150
18151 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
18152   return isInt<32>(Imm);
18153 }
18154
18155 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
18156   // Can also use sub to handle negated immediates.
18157   return isInt<32>(Imm);
18158 }
18159
18160 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
18161   if (!VT1.isInteger() || !VT2.isInteger())
18162     return false;
18163   unsigned NumBits1 = VT1.getSizeInBits();
18164   unsigned NumBits2 = VT2.getSizeInBits();
18165   return NumBits1 > NumBits2;
18166 }
18167
18168 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
18169   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
18170   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
18171 }
18172
18173 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
18174   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
18175   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
18176 }
18177
18178 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
18179   EVT VT1 = Val.getValueType();
18180   if (isZExtFree(VT1, VT2))
18181     return true;
18182
18183   if (Val.getOpcode() != ISD::LOAD)
18184     return false;
18185
18186   if (!VT1.isSimple() || !VT1.isInteger() ||
18187       !VT2.isSimple() || !VT2.isInteger())
18188     return false;
18189
18190   switch (VT1.getSimpleVT().SimpleTy) {
18191   default: break;
18192   case MVT::i8:
18193   case MVT::i16:
18194   case MVT::i32:
18195     // X86 has 8, 16, and 32-bit zero-extending loads.
18196     return true;
18197   }
18198
18199   return false;
18200 }
18201
18202 bool X86TargetLowering::isVectorLoadExtDesirable(SDValue) const { return true; }
18203
18204 bool
18205 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
18206   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
18207     return false;
18208
18209   VT = VT.getScalarType();
18210
18211   if (!VT.isSimple())
18212     return false;
18213
18214   switch (VT.getSimpleVT().SimpleTy) {
18215   case MVT::f32:
18216   case MVT::f64:
18217     return true;
18218   default:
18219     break;
18220   }
18221
18222   return false;
18223 }
18224
18225 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
18226   // i16 instructions are longer (0x66 prefix) and potentially slower.
18227   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
18228 }
18229
18230 /// isShuffleMaskLegal - Targets can use this to indicate that they only
18231 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
18232 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
18233 /// are assumed to be legal.
18234 bool
18235 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
18236                                       EVT VT) const {
18237   if (!VT.isSimple())
18238     return false;
18239
18240   // Not for i1 vectors
18241   if (VT.getScalarType() == MVT::i1)
18242     return false;
18243
18244   // Very little shuffling can be done for 64-bit vectors right now.
18245   if (VT.getSizeInBits() == 64)
18246     return false;
18247
18248   // We only care that the types being shuffled are legal. The lowering can
18249   // handle any possible shuffle mask that results.
18250   return isTypeLegal(VT.getSimpleVT());
18251 }
18252
18253 bool
18254 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
18255                                           EVT VT) const {
18256   // Just delegate to the generic legality, clear masks aren't special.
18257   return isShuffleMaskLegal(Mask, VT);
18258 }
18259
18260 //===----------------------------------------------------------------------===//
18261 //                           X86 Scheduler Hooks
18262 //===----------------------------------------------------------------------===//
18263
18264 /// Utility function to emit xbegin specifying the start of an RTM region.
18265 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
18266                                      const TargetInstrInfo *TII) {
18267   DebugLoc DL = MI->getDebugLoc();
18268
18269   const BasicBlock *BB = MBB->getBasicBlock();
18270   MachineFunction::iterator I = MBB;
18271   ++I;
18272
18273   // For the v = xbegin(), we generate
18274   //
18275   // thisMBB:
18276   //  xbegin sinkMBB
18277   //
18278   // mainMBB:
18279   //  eax = -1
18280   //
18281   // sinkMBB:
18282   //  v = eax
18283
18284   MachineBasicBlock *thisMBB = MBB;
18285   MachineFunction *MF = MBB->getParent();
18286   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
18287   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
18288   MF->insert(I, mainMBB);
18289   MF->insert(I, sinkMBB);
18290
18291   // Transfer the remainder of BB and its successor edges to sinkMBB.
18292   sinkMBB->splice(sinkMBB->begin(), MBB,
18293                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
18294   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
18295
18296   // thisMBB:
18297   //  xbegin sinkMBB
18298   //  # fallthrough to mainMBB
18299   //  # abortion to sinkMBB
18300   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
18301   thisMBB->addSuccessor(mainMBB);
18302   thisMBB->addSuccessor(sinkMBB);
18303
18304   // mainMBB:
18305   //  EAX = -1
18306   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
18307   mainMBB->addSuccessor(sinkMBB);
18308
18309   // sinkMBB:
18310   // EAX is live into the sinkMBB
18311   sinkMBB->addLiveIn(X86::EAX);
18312   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
18313           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
18314     .addReg(X86::EAX);
18315
18316   MI->eraseFromParent();
18317   return sinkMBB;
18318 }
18319
18320 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
18321 // or XMM0_V32I8 in AVX all of this code can be replaced with that
18322 // in the .td file.
18323 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
18324                                        const TargetInstrInfo *TII) {
18325   unsigned Opc;
18326   switch (MI->getOpcode()) {
18327   default: llvm_unreachable("illegal opcode!");
18328   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
18329   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
18330   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
18331   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
18332   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
18333   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
18334   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
18335   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
18336   }
18337
18338   DebugLoc dl = MI->getDebugLoc();
18339   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
18340
18341   unsigned NumArgs = MI->getNumOperands();
18342   for (unsigned i = 1; i < NumArgs; ++i) {
18343     MachineOperand &Op = MI->getOperand(i);
18344     if (!(Op.isReg() && Op.isImplicit()))
18345       MIB.addOperand(Op);
18346   }
18347   if (MI->hasOneMemOperand())
18348     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
18349
18350   BuildMI(*BB, MI, dl,
18351     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
18352     .addReg(X86::XMM0);
18353
18354   MI->eraseFromParent();
18355   return BB;
18356 }
18357
18358 // FIXME: Custom handling because TableGen doesn't support multiple implicit
18359 // defs in an instruction pattern
18360 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
18361                                        const TargetInstrInfo *TII) {
18362   unsigned Opc;
18363   switch (MI->getOpcode()) {
18364   default: llvm_unreachable("illegal opcode!");
18365   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
18366   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
18367   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
18368   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
18369   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
18370   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
18371   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
18372   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
18373   }
18374
18375   DebugLoc dl = MI->getDebugLoc();
18376   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
18377
18378   unsigned NumArgs = MI->getNumOperands(); // remove the results
18379   for (unsigned i = 1; i < NumArgs; ++i) {
18380     MachineOperand &Op = MI->getOperand(i);
18381     if (!(Op.isReg() && Op.isImplicit()))
18382       MIB.addOperand(Op);
18383   }
18384   if (MI->hasOneMemOperand())
18385     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
18386
18387   BuildMI(*BB, MI, dl,
18388     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
18389     .addReg(X86::ECX);
18390
18391   MI->eraseFromParent();
18392   return BB;
18393 }
18394
18395 static MachineBasicBlock *EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
18396                                       const X86Subtarget *Subtarget) {
18397   DebugLoc dl = MI->getDebugLoc();
18398   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18399   // Address into RAX/EAX, other two args into ECX, EDX.
18400   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
18401   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
18402   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
18403   for (int i = 0; i < X86::AddrNumOperands; ++i)
18404     MIB.addOperand(MI->getOperand(i));
18405
18406   unsigned ValOps = X86::AddrNumOperands;
18407   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
18408     .addReg(MI->getOperand(ValOps).getReg());
18409   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
18410     .addReg(MI->getOperand(ValOps+1).getReg());
18411
18412   // The instruction doesn't actually take any operands though.
18413   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
18414
18415   MI->eraseFromParent(); // The pseudo is gone now.
18416   return BB;
18417 }
18418
18419 MachineBasicBlock *
18420 X86TargetLowering::EmitVAARG64WithCustomInserter(MachineInstr *MI,
18421                                                  MachineBasicBlock *MBB) const {
18422   // Emit va_arg instruction on X86-64.
18423
18424   // Operands to this pseudo-instruction:
18425   // 0  ) Output        : destination address (reg)
18426   // 1-5) Input         : va_list address (addr, i64mem)
18427   // 6  ) ArgSize       : Size (in bytes) of vararg type
18428   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
18429   // 8  ) Align         : Alignment of type
18430   // 9  ) EFLAGS (implicit-def)
18431
18432   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
18433   static_assert(X86::AddrNumOperands == 5,
18434                 "VAARG_64 assumes 5 address operands");
18435
18436   unsigned DestReg = MI->getOperand(0).getReg();
18437   MachineOperand &Base = MI->getOperand(1);
18438   MachineOperand &Scale = MI->getOperand(2);
18439   MachineOperand &Index = MI->getOperand(3);
18440   MachineOperand &Disp = MI->getOperand(4);
18441   MachineOperand &Segment = MI->getOperand(5);
18442   unsigned ArgSize = MI->getOperand(6).getImm();
18443   unsigned ArgMode = MI->getOperand(7).getImm();
18444   unsigned Align = MI->getOperand(8).getImm();
18445
18446   // Memory Reference
18447   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
18448   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
18449   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
18450
18451   // Machine Information
18452   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18453   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
18454   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
18455   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
18456   DebugLoc DL = MI->getDebugLoc();
18457
18458   // struct va_list {
18459   //   i32   gp_offset
18460   //   i32   fp_offset
18461   //   i64   overflow_area (address)
18462   //   i64   reg_save_area (address)
18463   // }
18464   // sizeof(va_list) = 24
18465   // alignment(va_list) = 8
18466
18467   unsigned TotalNumIntRegs = 6;
18468   unsigned TotalNumXMMRegs = 8;
18469   bool UseGPOffset = (ArgMode == 1);
18470   bool UseFPOffset = (ArgMode == 2);
18471   unsigned MaxOffset = TotalNumIntRegs * 8 +
18472                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
18473
18474   /* Align ArgSize to a multiple of 8 */
18475   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
18476   bool NeedsAlign = (Align > 8);
18477
18478   MachineBasicBlock *thisMBB = MBB;
18479   MachineBasicBlock *overflowMBB;
18480   MachineBasicBlock *offsetMBB;
18481   MachineBasicBlock *endMBB;
18482
18483   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
18484   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
18485   unsigned OffsetReg = 0;
18486
18487   if (!UseGPOffset && !UseFPOffset) {
18488     // If we only pull from the overflow region, we don't create a branch.
18489     // We don't need to alter control flow.
18490     OffsetDestReg = 0; // unused
18491     OverflowDestReg = DestReg;
18492
18493     offsetMBB = nullptr;
18494     overflowMBB = thisMBB;
18495     endMBB = thisMBB;
18496   } else {
18497     // First emit code to check if gp_offset (or fp_offset) is below the bound.
18498     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
18499     // If not, pull from overflow_area. (branch to overflowMBB)
18500     //
18501     //       thisMBB
18502     //         |     .
18503     //         |        .
18504     //     offsetMBB   overflowMBB
18505     //         |        .
18506     //         |     .
18507     //        endMBB
18508
18509     // Registers for the PHI in endMBB
18510     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
18511     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
18512
18513     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
18514     MachineFunction *MF = MBB->getParent();
18515     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18516     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18517     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18518
18519     MachineFunction::iterator MBBIter = MBB;
18520     ++MBBIter;
18521
18522     // Insert the new basic blocks
18523     MF->insert(MBBIter, offsetMBB);
18524     MF->insert(MBBIter, overflowMBB);
18525     MF->insert(MBBIter, endMBB);
18526
18527     // Transfer the remainder of MBB and its successor edges to endMBB.
18528     endMBB->splice(endMBB->begin(), thisMBB,
18529                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
18530     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
18531
18532     // Make offsetMBB and overflowMBB successors of thisMBB
18533     thisMBB->addSuccessor(offsetMBB);
18534     thisMBB->addSuccessor(overflowMBB);
18535
18536     // endMBB is a successor of both offsetMBB and overflowMBB
18537     offsetMBB->addSuccessor(endMBB);
18538     overflowMBB->addSuccessor(endMBB);
18539
18540     // Load the offset value into a register
18541     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
18542     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
18543       .addOperand(Base)
18544       .addOperand(Scale)
18545       .addOperand(Index)
18546       .addDisp(Disp, UseFPOffset ? 4 : 0)
18547       .addOperand(Segment)
18548       .setMemRefs(MMOBegin, MMOEnd);
18549
18550     // Check if there is enough room left to pull this argument.
18551     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
18552       .addReg(OffsetReg)
18553       .addImm(MaxOffset + 8 - ArgSizeA8);
18554
18555     // Branch to "overflowMBB" if offset >= max
18556     // Fall through to "offsetMBB" otherwise
18557     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
18558       .addMBB(overflowMBB);
18559   }
18560
18561   // In offsetMBB, emit code to use the reg_save_area.
18562   if (offsetMBB) {
18563     assert(OffsetReg != 0);
18564
18565     // Read the reg_save_area address.
18566     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
18567     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
18568       .addOperand(Base)
18569       .addOperand(Scale)
18570       .addOperand(Index)
18571       .addDisp(Disp, 16)
18572       .addOperand(Segment)
18573       .setMemRefs(MMOBegin, MMOEnd);
18574
18575     // Zero-extend the offset
18576     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
18577       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
18578         .addImm(0)
18579         .addReg(OffsetReg)
18580         .addImm(X86::sub_32bit);
18581
18582     // Add the offset to the reg_save_area to get the final address.
18583     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
18584       .addReg(OffsetReg64)
18585       .addReg(RegSaveReg);
18586
18587     // Compute the offset for the next argument
18588     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
18589     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
18590       .addReg(OffsetReg)
18591       .addImm(UseFPOffset ? 16 : 8);
18592
18593     // Store it back into the va_list.
18594     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
18595       .addOperand(Base)
18596       .addOperand(Scale)
18597       .addOperand(Index)
18598       .addDisp(Disp, UseFPOffset ? 4 : 0)
18599       .addOperand(Segment)
18600       .addReg(NextOffsetReg)
18601       .setMemRefs(MMOBegin, MMOEnd);
18602
18603     // Jump to endMBB
18604     BuildMI(offsetMBB, DL, TII->get(X86::JMP_1))
18605       .addMBB(endMBB);
18606   }
18607
18608   //
18609   // Emit code to use overflow area
18610   //
18611
18612   // Load the overflow_area address into a register.
18613   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
18614   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
18615     .addOperand(Base)
18616     .addOperand(Scale)
18617     .addOperand(Index)
18618     .addDisp(Disp, 8)
18619     .addOperand(Segment)
18620     .setMemRefs(MMOBegin, MMOEnd);
18621
18622   // If we need to align it, do so. Otherwise, just copy the address
18623   // to OverflowDestReg.
18624   if (NeedsAlign) {
18625     // Align the overflow address
18626     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
18627     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
18628
18629     // aligned_addr = (addr + (align-1)) & ~(align-1)
18630     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
18631       .addReg(OverflowAddrReg)
18632       .addImm(Align-1);
18633
18634     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
18635       .addReg(TmpReg)
18636       .addImm(~(uint64_t)(Align-1));
18637   } else {
18638     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
18639       .addReg(OverflowAddrReg);
18640   }
18641
18642   // Compute the next overflow address after this argument.
18643   // (the overflow address should be kept 8-byte aligned)
18644   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
18645   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
18646     .addReg(OverflowDestReg)
18647     .addImm(ArgSizeA8);
18648
18649   // Store the new overflow address.
18650   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
18651     .addOperand(Base)
18652     .addOperand(Scale)
18653     .addOperand(Index)
18654     .addDisp(Disp, 8)
18655     .addOperand(Segment)
18656     .addReg(NextAddrReg)
18657     .setMemRefs(MMOBegin, MMOEnd);
18658
18659   // If we branched, emit the PHI to the front of endMBB.
18660   if (offsetMBB) {
18661     BuildMI(*endMBB, endMBB->begin(), DL,
18662             TII->get(X86::PHI), DestReg)
18663       .addReg(OffsetDestReg).addMBB(offsetMBB)
18664       .addReg(OverflowDestReg).addMBB(overflowMBB);
18665   }
18666
18667   // Erase the pseudo instruction
18668   MI->eraseFromParent();
18669
18670   return endMBB;
18671 }
18672
18673 MachineBasicBlock *
18674 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
18675                                                  MachineInstr *MI,
18676                                                  MachineBasicBlock *MBB) const {
18677   // Emit code to save XMM registers to the stack. The ABI says that the
18678   // number of registers to save is given in %al, so it's theoretically
18679   // possible to do an indirect jump trick to avoid saving all of them,
18680   // however this code takes a simpler approach and just executes all
18681   // of the stores if %al is non-zero. It's less code, and it's probably
18682   // easier on the hardware branch predictor, and stores aren't all that
18683   // expensive anyway.
18684
18685   // Create the new basic blocks. One block contains all the XMM stores,
18686   // and one block is the final destination regardless of whether any
18687   // stores were performed.
18688   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
18689   MachineFunction *F = MBB->getParent();
18690   MachineFunction::iterator MBBIter = MBB;
18691   ++MBBIter;
18692   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
18693   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
18694   F->insert(MBBIter, XMMSaveMBB);
18695   F->insert(MBBIter, EndMBB);
18696
18697   // Transfer the remainder of MBB and its successor edges to EndMBB.
18698   EndMBB->splice(EndMBB->begin(), MBB,
18699                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
18700   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
18701
18702   // The original block will now fall through to the XMM save block.
18703   MBB->addSuccessor(XMMSaveMBB);
18704   // The XMMSaveMBB will fall through to the end block.
18705   XMMSaveMBB->addSuccessor(EndMBB);
18706
18707   // Now add the instructions.
18708   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18709   DebugLoc DL = MI->getDebugLoc();
18710
18711   unsigned CountReg = MI->getOperand(0).getReg();
18712   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
18713   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
18714
18715   if (!Subtarget->isTargetWin64()) {
18716     // If %al is 0, branch around the XMM save block.
18717     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
18718     BuildMI(MBB, DL, TII->get(X86::JE_1)).addMBB(EndMBB);
18719     MBB->addSuccessor(EndMBB);
18720   }
18721
18722   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
18723   // that was just emitted, but clearly shouldn't be "saved".
18724   assert((MI->getNumOperands() <= 3 ||
18725           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
18726           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
18727          && "Expected last argument to be EFLAGS");
18728   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
18729   // In the XMM save block, save all the XMM argument registers.
18730   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
18731     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
18732     MachineMemOperand *MMO =
18733       F->getMachineMemOperand(
18734           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
18735         MachineMemOperand::MOStore,
18736         /*Size=*/16, /*Align=*/16);
18737     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
18738       .addFrameIndex(RegSaveFrameIndex)
18739       .addImm(/*Scale=*/1)
18740       .addReg(/*IndexReg=*/0)
18741       .addImm(/*Disp=*/Offset)
18742       .addReg(/*Segment=*/0)
18743       .addReg(MI->getOperand(i).getReg())
18744       .addMemOperand(MMO);
18745   }
18746
18747   MI->eraseFromParent();   // The pseudo instruction is gone now.
18748
18749   return EndMBB;
18750 }
18751
18752 // The EFLAGS operand of SelectItr might be missing a kill marker
18753 // because there were multiple uses of EFLAGS, and ISel didn't know
18754 // which to mark. Figure out whether SelectItr should have had a
18755 // kill marker, and set it if it should. Returns the correct kill
18756 // marker value.
18757 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
18758                                      MachineBasicBlock* BB,
18759                                      const TargetRegisterInfo* TRI) {
18760   // Scan forward through BB for a use/def of EFLAGS.
18761   MachineBasicBlock::iterator miI(std::next(SelectItr));
18762   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
18763     const MachineInstr& mi = *miI;
18764     if (mi.readsRegister(X86::EFLAGS))
18765       return false;
18766     if (mi.definesRegister(X86::EFLAGS))
18767       break; // Should have kill-flag - update below.
18768   }
18769
18770   // If we hit the end of the block, check whether EFLAGS is live into a
18771   // successor.
18772   if (miI == BB->end()) {
18773     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
18774                                           sEnd = BB->succ_end();
18775          sItr != sEnd; ++sItr) {
18776       MachineBasicBlock* succ = *sItr;
18777       if (succ->isLiveIn(X86::EFLAGS))
18778         return false;
18779     }
18780   }
18781
18782   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
18783   // out. SelectMI should have a kill flag on EFLAGS.
18784   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
18785   return true;
18786 }
18787
18788 MachineBasicBlock *
18789 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
18790                                      MachineBasicBlock *BB) const {
18791   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18792   DebugLoc DL = MI->getDebugLoc();
18793
18794   // To "insert" a SELECT_CC instruction, we actually have to insert the
18795   // diamond control-flow pattern.  The incoming instruction knows the
18796   // destination vreg to set, the condition code register to branch on, the
18797   // true/false values to select between, and a branch opcode to use.
18798   const BasicBlock *LLVM_BB = BB->getBasicBlock();
18799   MachineFunction::iterator It = BB;
18800   ++It;
18801
18802   //  thisMBB:
18803   //  ...
18804   //   TrueVal = ...
18805   //   cmpTY ccX, r1, r2
18806   //   bCC copy1MBB
18807   //   fallthrough --> copy0MBB
18808   MachineBasicBlock *thisMBB = BB;
18809   MachineFunction *F = BB->getParent();
18810
18811   // We also lower double CMOVs:
18812   //   (CMOV (CMOV F, T, cc1), T, cc2)
18813   // to two successives branches.  For that, we look for another CMOV as the
18814   // following instruction.
18815   //
18816   // Without this, we would add a PHI between the two jumps, which ends up
18817   // creating a few copies all around. For instance, for
18818   //
18819   //    (sitofp (zext (fcmp une)))
18820   //
18821   // we would generate:
18822   //
18823   //         ucomiss %xmm1, %xmm0
18824   //         movss  <1.0f>, %xmm0
18825   //         movaps  %xmm0, %xmm1
18826   //         jne     .LBB5_2
18827   //         xorps   %xmm1, %xmm1
18828   // .LBB5_2:
18829   //         jp      .LBB5_4
18830   //         movaps  %xmm1, %xmm0
18831   // .LBB5_4:
18832   //         retq
18833   //
18834   // because this custom-inserter would have generated:
18835   //
18836   //   A
18837   //   | \
18838   //   |  B
18839   //   | /
18840   //   C
18841   //   | \
18842   //   |  D
18843   //   | /
18844   //   E
18845   //
18846   // A: X = ...; Y = ...
18847   // B: empty
18848   // C: Z = PHI [X, A], [Y, B]
18849   // D: empty
18850   // E: PHI [X, C], [Z, D]
18851   //
18852   // If we lower both CMOVs in a single step, we can instead generate:
18853   //
18854   //   A
18855   //   | \
18856   //   |  C
18857   //   | /|
18858   //   |/ |
18859   //   |  |
18860   //   |  D
18861   //   | /
18862   //   E
18863   //
18864   // A: X = ...; Y = ...
18865   // D: empty
18866   // E: PHI [X, A], [X, C], [Y, D]
18867   //
18868   // Which, in our sitofp/fcmp example, gives us something like:
18869   //
18870   //         ucomiss %xmm1, %xmm0
18871   //         movss  <1.0f>, %xmm0
18872   //         jne     .LBB5_4
18873   //         jp      .LBB5_4
18874   //         xorps   %xmm0, %xmm0
18875   // .LBB5_4:
18876   //         retq
18877   //
18878   MachineInstr *NextCMOV = nullptr;
18879   MachineBasicBlock::iterator NextMIIt =
18880       std::next(MachineBasicBlock::iterator(MI));
18881   if (NextMIIt != BB->end() && NextMIIt->getOpcode() == MI->getOpcode() &&
18882       NextMIIt->getOperand(2).getReg() == MI->getOperand(2).getReg() &&
18883       NextMIIt->getOperand(1).getReg() == MI->getOperand(0).getReg())
18884     NextCMOV = &*NextMIIt;
18885
18886   MachineBasicBlock *jcc1MBB = nullptr;
18887
18888   // If we have a double CMOV, we lower it to two successive branches to
18889   // the same block.  EFLAGS is used by both, so mark it as live in the second.
18890   if (NextCMOV) {
18891     jcc1MBB = F->CreateMachineBasicBlock(LLVM_BB);
18892     F->insert(It, jcc1MBB);
18893     jcc1MBB->addLiveIn(X86::EFLAGS);
18894   }
18895
18896   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
18897   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
18898   F->insert(It, copy0MBB);
18899   F->insert(It, sinkMBB);
18900
18901   // If the EFLAGS register isn't dead in the terminator, then claim that it's
18902   // live into the sink and copy blocks.
18903   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
18904
18905   MachineInstr *LastEFLAGSUser = NextCMOV ? NextCMOV : MI;
18906   if (!LastEFLAGSUser->killsRegister(X86::EFLAGS) &&
18907       !checkAndUpdateEFLAGSKill(LastEFLAGSUser, BB, TRI)) {
18908     copy0MBB->addLiveIn(X86::EFLAGS);
18909     sinkMBB->addLiveIn(X86::EFLAGS);
18910   }
18911
18912   // Transfer the remainder of BB and its successor edges to sinkMBB.
18913   sinkMBB->splice(sinkMBB->begin(), BB,
18914                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
18915   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
18916
18917   // Add the true and fallthrough blocks as its successors.
18918   if (NextCMOV) {
18919     // The fallthrough block may be jcc1MBB, if we have a double CMOV.
18920     BB->addSuccessor(jcc1MBB);
18921
18922     // In that case, jcc1MBB will itself fallthrough the copy0MBB, and
18923     // jump to the sinkMBB.
18924     jcc1MBB->addSuccessor(copy0MBB);
18925     jcc1MBB->addSuccessor(sinkMBB);
18926   } else {
18927     BB->addSuccessor(copy0MBB);
18928   }
18929
18930   // The true block target of the first (or only) branch is always sinkMBB.
18931   BB->addSuccessor(sinkMBB);
18932
18933   // Create the conditional branch instruction.
18934   unsigned Opc =
18935     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
18936   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
18937
18938   if (NextCMOV) {
18939     unsigned Opc2 = X86::GetCondBranchFromCond(
18940         (X86::CondCode)NextCMOV->getOperand(3).getImm());
18941     BuildMI(jcc1MBB, DL, TII->get(Opc2)).addMBB(sinkMBB);
18942   }
18943
18944   //  copy0MBB:
18945   //   %FalseValue = ...
18946   //   # fallthrough to sinkMBB
18947   copy0MBB->addSuccessor(sinkMBB);
18948
18949   //  sinkMBB:
18950   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
18951   //  ...
18952   MachineInstrBuilder MIB =
18953       BuildMI(*sinkMBB, sinkMBB->begin(), DL, TII->get(X86::PHI),
18954               MI->getOperand(0).getReg())
18955           .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
18956           .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
18957
18958   // If we have a double CMOV, the second Jcc provides the same incoming
18959   // value as the first Jcc (the True operand of the SELECT_CC/CMOV nodes).
18960   if (NextCMOV) {
18961     MIB.addReg(MI->getOperand(2).getReg()).addMBB(jcc1MBB);
18962     // Copy the PHI result to the register defined by the second CMOV.
18963     BuildMI(*sinkMBB, std::next(MachineBasicBlock::iterator(MIB.getInstr())),
18964             DL, TII->get(TargetOpcode::COPY), NextCMOV->getOperand(0).getReg())
18965         .addReg(MI->getOperand(0).getReg());
18966     NextCMOV->eraseFromParent();
18967   }
18968
18969   MI->eraseFromParent();   // The pseudo instruction is gone now.
18970   return sinkMBB;
18971 }
18972
18973 MachineBasicBlock *
18974 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI,
18975                                         MachineBasicBlock *BB) const {
18976   MachineFunction *MF = BB->getParent();
18977   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18978   DebugLoc DL = MI->getDebugLoc();
18979   const BasicBlock *LLVM_BB = BB->getBasicBlock();
18980
18981   assert(MF->shouldSplitStack());
18982
18983   const bool Is64Bit = Subtarget->is64Bit();
18984   const bool IsLP64 = Subtarget->isTarget64BitLP64();
18985
18986   const unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
18987   const unsigned TlsOffset = IsLP64 ? 0x70 : Is64Bit ? 0x40 : 0x30;
18988
18989   // BB:
18990   //  ... [Till the alloca]
18991   // If stacklet is not large enough, jump to mallocMBB
18992   //
18993   // bumpMBB:
18994   //  Allocate by subtracting from RSP
18995   //  Jump to continueMBB
18996   //
18997   // mallocMBB:
18998   //  Allocate by call to runtime
18999   //
19000   // continueMBB:
19001   //  ...
19002   //  [rest of original BB]
19003   //
19004
19005   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19006   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19007   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19008
19009   MachineRegisterInfo &MRI = MF->getRegInfo();
19010   const TargetRegisterClass *AddrRegClass =
19011     getRegClassFor(getPointerTy());
19012
19013   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
19014     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
19015     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
19016     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
19017     sizeVReg = MI->getOperand(1).getReg(),
19018     physSPReg = IsLP64 || Subtarget->isTargetNaCl64() ? X86::RSP : X86::ESP;
19019
19020   MachineFunction::iterator MBBIter = BB;
19021   ++MBBIter;
19022
19023   MF->insert(MBBIter, bumpMBB);
19024   MF->insert(MBBIter, mallocMBB);
19025   MF->insert(MBBIter, continueMBB);
19026
19027   continueMBB->splice(continueMBB->begin(), BB,
19028                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
19029   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
19030
19031   // Add code to the main basic block to check if the stack limit has been hit,
19032   // and if so, jump to mallocMBB otherwise to bumpMBB.
19033   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
19034   BuildMI(BB, DL, TII->get(IsLP64 ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
19035     .addReg(tmpSPVReg).addReg(sizeVReg);
19036   BuildMI(BB, DL, TII->get(IsLP64 ? X86::CMP64mr:X86::CMP32mr))
19037     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
19038     .addReg(SPLimitVReg);
19039   BuildMI(BB, DL, TII->get(X86::JG_1)).addMBB(mallocMBB);
19040
19041   // bumpMBB simply decreases the stack pointer, since we know the current
19042   // stacklet has enough space.
19043   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
19044     .addReg(SPLimitVReg);
19045   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
19046     .addReg(SPLimitVReg);
19047   BuildMI(bumpMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
19048
19049   // Calls into a routine in libgcc to allocate more space from the heap.
19050   const uint32_t *RegMask =
19051       Subtarget->getRegisterInfo()->getCallPreservedMask(*MF, CallingConv::C);
19052   if (IsLP64) {
19053     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
19054       .addReg(sizeVReg);
19055     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
19056       .addExternalSymbol("__morestack_allocate_stack_space")
19057       .addRegMask(RegMask)
19058       .addReg(X86::RDI, RegState::Implicit)
19059       .addReg(X86::RAX, RegState::ImplicitDefine);
19060   } else if (Is64Bit) {
19061     BuildMI(mallocMBB, DL, TII->get(X86::MOV32rr), X86::EDI)
19062       .addReg(sizeVReg);
19063     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
19064       .addExternalSymbol("__morestack_allocate_stack_space")
19065       .addRegMask(RegMask)
19066       .addReg(X86::EDI, RegState::Implicit)
19067       .addReg(X86::EAX, RegState::ImplicitDefine);
19068   } else {
19069     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
19070       .addImm(12);
19071     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
19072     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
19073       .addExternalSymbol("__morestack_allocate_stack_space")
19074       .addRegMask(RegMask)
19075       .addReg(X86::EAX, RegState::ImplicitDefine);
19076   }
19077
19078   if (!Is64Bit)
19079     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
19080       .addImm(16);
19081
19082   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
19083     .addReg(IsLP64 ? X86::RAX : X86::EAX);
19084   BuildMI(mallocMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
19085
19086   // Set up the CFG correctly.
19087   BB->addSuccessor(bumpMBB);
19088   BB->addSuccessor(mallocMBB);
19089   mallocMBB->addSuccessor(continueMBB);
19090   bumpMBB->addSuccessor(continueMBB);
19091
19092   // Take care of the PHI nodes.
19093   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
19094           MI->getOperand(0).getReg())
19095     .addReg(mallocPtrVReg).addMBB(mallocMBB)
19096     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
19097
19098   // Delete the original pseudo instruction.
19099   MI->eraseFromParent();
19100
19101   // And we're done.
19102   return continueMBB;
19103 }
19104
19105 MachineBasicBlock *
19106 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
19107                                         MachineBasicBlock *BB) const {
19108   DebugLoc DL = MI->getDebugLoc();
19109
19110   assert(!Subtarget->isTargetMachO());
19111
19112   X86FrameLowering::emitStackProbeCall(*BB->getParent(), *BB, MI, DL);
19113
19114   MI->eraseFromParent();   // The pseudo instruction is gone now.
19115   return BB;
19116 }
19117
19118 MachineBasicBlock *
19119 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
19120                                       MachineBasicBlock *BB) const {
19121   // This is pretty easy.  We're taking the value that we received from
19122   // our load from the relocation, sticking it in either RDI (x86-64)
19123   // or EAX and doing an indirect call.  The return value will then
19124   // be in the normal return register.
19125   MachineFunction *F = BB->getParent();
19126   const X86InstrInfo *TII = Subtarget->getInstrInfo();
19127   DebugLoc DL = MI->getDebugLoc();
19128
19129   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
19130   assert(MI->getOperand(3).isGlobal() && "This should be a global");
19131
19132   // Get a register mask for the lowered call.
19133   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
19134   // proper register mask.
19135   const uint32_t *RegMask =
19136       Subtarget->getRegisterInfo()->getCallPreservedMask(*F, CallingConv::C);
19137   if (Subtarget->is64Bit()) {
19138     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
19139                                       TII->get(X86::MOV64rm), X86::RDI)
19140     .addReg(X86::RIP)
19141     .addImm(0).addReg(0)
19142     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
19143                       MI->getOperand(3).getTargetFlags())
19144     .addReg(0);
19145     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
19146     addDirectMem(MIB, X86::RDI);
19147     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
19148   } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
19149     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
19150                                       TII->get(X86::MOV32rm), X86::EAX)
19151     .addReg(0)
19152     .addImm(0).addReg(0)
19153     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
19154                       MI->getOperand(3).getTargetFlags())
19155     .addReg(0);
19156     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
19157     addDirectMem(MIB, X86::EAX);
19158     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
19159   } else {
19160     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
19161                                       TII->get(X86::MOV32rm), X86::EAX)
19162     .addReg(TII->getGlobalBaseReg(F))
19163     .addImm(0).addReg(0)
19164     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
19165                       MI->getOperand(3).getTargetFlags())
19166     .addReg(0);
19167     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
19168     addDirectMem(MIB, X86::EAX);
19169     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
19170   }
19171
19172   MI->eraseFromParent(); // The pseudo instruction is gone now.
19173   return BB;
19174 }
19175
19176 MachineBasicBlock *
19177 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
19178                                     MachineBasicBlock *MBB) const {
19179   DebugLoc DL = MI->getDebugLoc();
19180   MachineFunction *MF = MBB->getParent();
19181   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19182   MachineRegisterInfo &MRI = MF->getRegInfo();
19183
19184   const BasicBlock *BB = MBB->getBasicBlock();
19185   MachineFunction::iterator I = MBB;
19186   ++I;
19187
19188   // Memory Reference
19189   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
19190   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
19191
19192   unsigned DstReg;
19193   unsigned MemOpndSlot = 0;
19194
19195   unsigned CurOp = 0;
19196
19197   DstReg = MI->getOperand(CurOp++).getReg();
19198   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
19199   assert(RC->hasType(MVT::i32) && "Invalid destination!");
19200   unsigned mainDstReg = MRI.createVirtualRegister(RC);
19201   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
19202
19203   MemOpndSlot = CurOp;
19204
19205   MVT PVT = getPointerTy();
19206   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
19207          "Invalid Pointer Size!");
19208
19209   // For v = setjmp(buf), we generate
19210   //
19211   // thisMBB:
19212   //  buf[LabelOffset] = restoreMBB
19213   //  SjLjSetup restoreMBB
19214   //
19215   // mainMBB:
19216   //  v_main = 0
19217   //
19218   // sinkMBB:
19219   //  v = phi(main, restore)
19220   //
19221   // restoreMBB:
19222   //  if base pointer being used, load it from frame
19223   //  v_restore = 1
19224
19225   MachineBasicBlock *thisMBB = MBB;
19226   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
19227   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
19228   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
19229   MF->insert(I, mainMBB);
19230   MF->insert(I, sinkMBB);
19231   MF->push_back(restoreMBB);
19232
19233   MachineInstrBuilder MIB;
19234
19235   // Transfer the remainder of BB and its successor edges to sinkMBB.
19236   sinkMBB->splice(sinkMBB->begin(), MBB,
19237                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
19238   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
19239
19240   // thisMBB:
19241   unsigned PtrStoreOpc = 0;
19242   unsigned LabelReg = 0;
19243   const int64_t LabelOffset = 1 * PVT.getStoreSize();
19244   Reloc::Model RM = MF->getTarget().getRelocationModel();
19245   bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
19246                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
19247
19248   // Prepare IP either in reg or imm.
19249   if (!UseImmLabel) {
19250     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
19251     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
19252     LabelReg = MRI.createVirtualRegister(PtrRC);
19253     if (Subtarget->is64Bit()) {
19254       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
19255               .addReg(X86::RIP)
19256               .addImm(0)
19257               .addReg(0)
19258               .addMBB(restoreMBB)
19259               .addReg(0);
19260     } else {
19261       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
19262       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
19263               .addReg(XII->getGlobalBaseReg(MF))
19264               .addImm(0)
19265               .addReg(0)
19266               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
19267               .addReg(0);
19268     }
19269   } else
19270     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
19271   // Store IP
19272   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
19273   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
19274     if (i == X86::AddrDisp)
19275       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
19276     else
19277       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
19278   }
19279   if (!UseImmLabel)
19280     MIB.addReg(LabelReg);
19281   else
19282     MIB.addMBB(restoreMBB);
19283   MIB.setMemRefs(MMOBegin, MMOEnd);
19284   // Setup
19285   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
19286           .addMBB(restoreMBB);
19287
19288   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
19289   MIB.addRegMask(RegInfo->getNoPreservedMask());
19290   thisMBB->addSuccessor(mainMBB);
19291   thisMBB->addSuccessor(restoreMBB);
19292
19293   // mainMBB:
19294   //  EAX = 0
19295   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
19296   mainMBB->addSuccessor(sinkMBB);
19297
19298   // sinkMBB:
19299   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
19300           TII->get(X86::PHI), DstReg)
19301     .addReg(mainDstReg).addMBB(mainMBB)
19302     .addReg(restoreDstReg).addMBB(restoreMBB);
19303
19304   // restoreMBB:
19305   if (RegInfo->hasBasePointer(*MF)) {
19306     const bool Uses64BitFramePtr =
19307         Subtarget->isTarget64BitLP64() || Subtarget->isTargetNaCl64();
19308     X86MachineFunctionInfo *X86FI = MF->getInfo<X86MachineFunctionInfo>();
19309     X86FI->setRestoreBasePointer(MF);
19310     unsigned FramePtr = RegInfo->getFrameRegister(*MF);
19311     unsigned BasePtr = RegInfo->getBaseRegister();
19312     unsigned Opm = Uses64BitFramePtr ? X86::MOV64rm : X86::MOV32rm;
19313     addRegOffset(BuildMI(restoreMBB, DL, TII->get(Opm), BasePtr),
19314                  FramePtr, true, X86FI->getRestoreBasePointerOffset())
19315       .setMIFlag(MachineInstr::FrameSetup);
19316   }
19317   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
19318   BuildMI(restoreMBB, DL, TII->get(X86::JMP_1)).addMBB(sinkMBB);
19319   restoreMBB->addSuccessor(sinkMBB);
19320
19321   MI->eraseFromParent();
19322   return sinkMBB;
19323 }
19324
19325 MachineBasicBlock *
19326 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
19327                                      MachineBasicBlock *MBB) const {
19328   DebugLoc DL = MI->getDebugLoc();
19329   MachineFunction *MF = MBB->getParent();
19330   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19331   MachineRegisterInfo &MRI = MF->getRegInfo();
19332
19333   // Memory Reference
19334   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
19335   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
19336
19337   MVT PVT = getPointerTy();
19338   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
19339          "Invalid Pointer Size!");
19340
19341   const TargetRegisterClass *RC =
19342     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
19343   unsigned Tmp = MRI.createVirtualRegister(RC);
19344   // Since FP is only updated here but NOT referenced, it's treated as GPR.
19345   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
19346   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
19347   unsigned SP = RegInfo->getStackRegister();
19348
19349   MachineInstrBuilder MIB;
19350
19351   const int64_t LabelOffset = 1 * PVT.getStoreSize();
19352   const int64_t SPOffset = 2 * PVT.getStoreSize();
19353
19354   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
19355   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
19356
19357   // Reload FP
19358   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
19359   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
19360     MIB.addOperand(MI->getOperand(i));
19361   MIB.setMemRefs(MMOBegin, MMOEnd);
19362   // Reload IP
19363   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
19364   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
19365     if (i == X86::AddrDisp)
19366       MIB.addDisp(MI->getOperand(i), LabelOffset);
19367     else
19368       MIB.addOperand(MI->getOperand(i));
19369   }
19370   MIB.setMemRefs(MMOBegin, MMOEnd);
19371   // Reload SP
19372   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
19373   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
19374     if (i == X86::AddrDisp)
19375       MIB.addDisp(MI->getOperand(i), SPOffset);
19376     else
19377       MIB.addOperand(MI->getOperand(i));
19378   }
19379   MIB.setMemRefs(MMOBegin, MMOEnd);
19380   // Jump
19381   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
19382
19383   MI->eraseFromParent();
19384   return MBB;
19385 }
19386
19387 // Replace 213-type (isel default) FMA3 instructions with 231-type for
19388 // accumulator loops. Writing back to the accumulator allows the coalescer
19389 // to remove extra copies in the loop.
19390 MachineBasicBlock *
19391 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
19392                                  MachineBasicBlock *MBB) const {
19393   MachineOperand &AddendOp = MI->getOperand(3);
19394
19395   // Bail out early if the addend isn't a register - we can't switch these.
19396   if (!AddendOp.isReg())
19397     return MBB;
19398
19399   MachineFunction &MF = *MBB->getParent();
19400   MachineRegisterInfo &MRI = MF.getRegInfo();
19401
19402   // Check whether the addend is defined by a PHI:
19403   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
19404   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
19405   if (!AddendDef.isPHI())
19406     return MBB;
19407
19408   // Look for the following pattern:
19409   // loop:
19410   //   %addend = phi [%entry, 0], [%loop, %result]
19411   //   ...
19412   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
19413
19414   // Replace with:
19415   //   loop:
19416   //   %addend = phi [%entry, 0], [%loop, %result]
19417   //   ...
19418   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
19419
19420   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
19421     assert(AddendDef.getOperand(i).isReg());
19422     MachineOperand PHISrcOp = AddendDef.getOperand(i);
19423     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
19424     if (&PHISrcInst == MI) {
19425       // Found a matching instruction.
19426       unsigned NewFMAOpc = 0;
19427       switch (MI->getOpcode()) {
19428         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
19429         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
19430         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
19431         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
19432         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
19433         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
19434         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
19435         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
19436         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
19437         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
19438         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
19439         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
19440         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
19441         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
19442         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
19443         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
19444         case X86::VFMADDSUBPDr213r: NewFMAOpc = X86::VFMADDSUBPDr231r; break;
19445         case X86::VFMADDSUBPSr213r: NewFMAOpc = X86::VFMADDSUBPSr231r; break;
19446         case X86::VFMSUBADDPDr213r: NewFMAOpc = X86::VFMSUBADDPDr231r; break;
19447         case X86::VFMSUBADDPSr213r: NewFMAOpc = X86::VFMSUBADDPSr231r; break;
19448
19449         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
19450         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
19451         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
19452         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
19453         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
19454         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
19455         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
19456         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
19457         case X86::VFMADDSUBPDr213rY: NewFMAOpc = X86::VFMADDSUBPDr231rY; break;
19458         case X86::VFMADDSUBPSr213rY: NewFMAOpc = X86::VFMADDSUBPSr231rY; break;
19459         case X86::VFMSUBADDPDr213rY: NewFMAOpc = X86::VFMSUBADDPDr231rY; break;
19460         case X86::VFMSUBADDPSr213rY: NewFMAOpc = X86::VFMSUBADDPSr231rY; break;
19461         default: llvm_unreachable("Unrecognized FMA variant.");
19462       }
19463
19464       const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
19465       MachineInstrBuilder MIB =
19466         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
19467         .addOperand(MI->getOperand(0))
19468         .addOperand(MI->getOperand(3))
19469         .addOperand(MI->getOperand(2))
19470         .addOperand(MI->getOperand(1));
19471       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
19472       MI->eraseFromParent();
19473     }
19474   }
19475
19476   return MBB;
19477 }
19478
19479 MachineBasicBlock *
19480 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
19481                                                MachineBasicBlock *BB) const {
19482   switch (MI->getOpcode()) {
19483   default: llvm_unreachable("Unexpected instr type to insert");
19484   case X86::TAILJMPd64:
19485   case X86::TAILJMPr64:
19486   case X86::TAILJMPm64:
19487   case X86::TAILJMPd64_REX:
19488   case X86::TAILJMPr64_REX:
19489   case X86::TAILJMPm64_REX:
19490     llvm_unreachable("TAILJMP64 would not be touched here.");
19491   case X86::TCRETURNdi64:
19492   case X86::TCRETURNri64:
19493   case X86::TCRETURNmi64:
19494     return BB;
19495   case X86::WIN_ALLOCA:
19496     return EmitLoweredWinAlloca(MI, BB);
19497   case X86::SEG_ALLOCA_32:
19498   case X86::SEG_ALLOCA_64:
19499     return EmitLoweredSegAlloca(MI, BB);
19500   case X86::TLSCall_32:
19501   case X86::TLSCall_64:
19502     return EmitLoweredTLSCall(MI, BB);
19503   case X86::CMOV_GR8:
19504   case X86::CMOV_FR32:
19505   case X86::CMOV_FR64:
19506   case X86::CMOV_V4F32:
19507   case X86::CMOV_V2F64:
19508   case X86::CMOV_V2I64:
19509   case X86::CMOV_V8F32:
19510   case X86::CMOV_V4F64:
19511   case X86::CMOV_V4I64:
19512   case X86::CMOV_V16F32:
19513   case X86::CMOV_V8F64:
19514   case X86::CMOV_V8I64:
19515   case X86::CMOV_GR16:
19516   case X86::CMOV_GR32:
19517   case X86::CMOV_RFP32:
19518   case X86::CMOV_RFP64:
19519   case X86::CMOV_RFP80:
19520   case X86::CMOV_V8I1:
19521   case X86::CMOV_V16I1:
19522   case X86::CMOV_V32I1:
19523   case X86::CMOV_V64I1:
19524     return EmitLoweredSelect(MI, BB);
19525
19526   case X86::FP32_TO_INT16_IN_MEM:
19527   case X86::FP32_TO_INT32_IN_MEM:
19528   case X86::FP32_TO_INT64_IN_MEM:
19529   case X86::FP64_TO_INT16_IN_MEM:
19530   case X86::FP64_TO_INT32_IN_MEM:
19531   case X86::FP64_TO_INT64_IN_MEM:
19532   case X86::FP80_TO_INT16_IN_MEM:
19533   case X86::FP80_TO_INT32_IN_MEM:
19534   case X86::FP80_TO_INT64_IN_MEM: {
19535     MachineFunction *F = BB->getParent();
19536     const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19537     DebugLoc DL = MI->getDebugLoc();
19538
19539     // Change the floating point control register to use "round towards zero"
19540     // mode when truncating to an integer value.
19541     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
19542     addFrameReference(BuildMI(*BB, MI, DL,
19543                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
19544
19545     // Load the old value of the high byte of the control word...
19546     unsigned OldCW =
19547       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
19548     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
19549                       CWFrameIdx);
19550
19551     // Set the high part to be round to zero...
19552     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
19553       .addImm(0xC7F);
19554
19555     // Reload the modified control word now...
19556     addFrameReference(BuildMI(*BB, MI, DL,
19557                               TII->get(X86::FLDCW16m)), CWFrameIdx);
19558
19559     // Restore the memory image of control word to original value
19560     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
19561       .addReg(OldCW);
19562
19563     // Get the X86 opcode to use.
19564     unsigned Opc;
19565     switch (MI->getOpcode()) {
19566     default: llvm_unreachable("illegal opcode!");
19567     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
19568     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
19569     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
19570     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
19571     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
19572     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
19573     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
19574     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
19575     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
19576     }
19577
19578     X86AddressMode AM;
19579     MachineOperand &Op = MI->getOperand(0);
19580     if (Op.isReg()) {
19581       AM.BaseType = X86AddressMode::RegBase;
19582       AM.Base.Reg = Op.getReg();
19583     } else {
19584       AM.BaseType = X86AddressMode::FrameIndexBase;
19585       AM.Base.FrameIndex = Op.getIndex();
19586     }
19587     Op = MI->getOperand(1);
19588     if (Op.isImm())
19589       AM.Scale = Op.getImm();
19590     Op = MI->getOperand(2);
19591     if (Op.isImm())
19592       AM.IndexReg = Op.getImm();
19593     Op = MI->getOperand(3);
19594     if (Op.isGlobal()) {
19595       AM.GV = Op.getGlobal();
19596     } else {
19597       AM.Disp = Op.getImm();
19598     }
19599     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
19600                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
19601
19602     // Reload the original control word now.
19603     addFrameReference(BuildMI(*BB, MI, DL,
19604                               TII->get(X86::FLDCW16m)), CWFrameIdx);
19605
19606     MI->eraseFromParent();   // The pseudo instruction is gone now.
19607     return BB;
19608   }
19609     // String/text processing lowering.
19610   case X86::PCMPISTRM128REG:
19611   case X86::VPCMPISTRM128REG:
19612   case X86::PCMPISTRM128MEM:
19613   case X86::VPCMPISTRM128MEM:
19614   case X86::PCMPESTRM128REG:
19615   case X86::VPCMPESTRM128REG:
19616   case X86::PCMPESTRM128MEM:
19617   case X86::VPCMPESTRM128MEM:
19618     assert(Subtarget->hasSSE42() &&
19619            "Target must have SSE4.2 or AVX features enabled");
19620     return EmitPCMPSTRM(MI, BB, Subtarget->getInstrInfo());
19621
19622   // String/text processing lowering.
19623   case X86::PCMPISTRIREG:
19624   case X86::VPCMPISTRIREG:
19625   case X86::PCMPISTRIMEM:
19626   case X86::VPCMPISTRIMEM:
19627   case X86::PCMPESTRIREG:
19628   case X86::VPCMPESTRIREG:
19629   case X86::PCMPESTRIMEM:
19630   case X86::VPCMPESTRIMEM:
19631     assert(Subtarget->hasSSE42() &&
19632            "Target must have SSE4.2 or AVX features enabled");
19633     return EmitPCMPSTRI(MI, BB, Subtarget->getInstrInfo());
19634
19635   // Thread synchronization.
19636   case X86::MONITOR:
19637     return EmitMonitor(MI, BB, Subtarget);
19638
19639   // xbegin
19640   case X86::XBEGIN:
19641     return EmitXBegin(MI, BB, Subtarget->getInstrInfo());
19642
19643   case X86::VASTART_SAVE_XMM_REGS:
19644     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
19645
19646   case X86::VAARG_64:
19647     return EmitVAARG64WithCustomInserter(MI, BB);
19648
19649   case X86::EH_SjLj_SetJmp32:
19650   case X86::EH_SjLj_SetJmp64:
19651     return emitEHSjLjSetJmp(MI, BB);
19652
19653   case X86::EH_SjLj_LongJmp32:
19654   case X86::EH_SjLj_LongJmp64:
19655     return emitEHSjLjLongJmp(MI, BB);
19656
19657   case TargetOpcode::STATEPOINT:
19658     // As an implementation detail, STATEPOINT shares the STACKMAP format at
19659     // this point in the process.  We diverge later.
19660     return emitPatchPoint(MI, BB);
19661
19662   case TargetOpcode::STACKMAP:
19663   case TargetOpcode::PATCHPOINT:
19664     return emitPatchPoint(MI, BB);
19665
19666   case X86::VFMADDPDr213r:
19667   case X86::VFMADDPSr213r:
19668   case X86::VFMADDSDr213r:
19669   case X86::VFMADDSSr213r:
19670   case X86::VFMSUBPDr213r:
19671   case X86::VFMSUBPSr213r:
19672   case X86::VFMSUBSDr213r:
19673   case X86::VFMSUBSSr213r:
19674   case X86::VFNMADDPDr213r:
19675   case X86::VFNMADDPSr213r:
19676   case X86::VFNMADDSDr213r:
19677   case X86::VFNMADDSSr213r:
19678   case X86::VFNMSUBPDr213r:
19679   case X86::VFNMSUBPSr213r:
19680   case X86::VFNMSUBSDr213r:
19681   case X86::VFNMSUBSSr213r:
19682   case X86::VFMADDSUBPDr213r:
19683   case X86::VFMADDSUBPSr213r:
19684   case X86::VFMSUBADDPDr213r:
19685   case X86::VFMSUBADDPSr213r:
19686   case X86::VFMADDPDr213rY:
19687   case X86::VFMADDPSr213rY:
19688   case X86::VFMSUBPDr213rY:
19689   case X86::VFMSUBPSr213rY:
19690   case X86::VFNMADDPDr213rY:
19691   case X86::VFNMADDPSr213rY:
19692   case X86::VFNMSUBPDr213rY:
19693   case X86::VFNMSUBPSr213rY:
19694   case X86::VFMADDSUBPDr213rY:
19695   case X86::VFMADDSUBPSr213rY:
19696   case X86::VFMSUBADDPDr213rY:
19697   case X86::VFMSUBADDPSr213rY:
19698     return emitFMA3Instr(MI, BB);
19699   }
19700 }
19701
19702 //===----------------------------------------------------------------------===//
19703 //                           X86 Optimization Hooks
19704 //===----------------------------------------------------------------------===//
19705
19706 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
19707                                                       APInt &KnownZero,
19708                                                       APInt &KnownOne,
19709                                                       const SelectionDAG &DAG,
19710                                                       unsigned Depth) const {
19711   unsigned BitWidth = KnownZero.getBitWidth();
19712   unsigned Opc = Op.getOpcode();
19713   assert((Opc >= ISD::BUILTIN_OP_END ||
19714           Opc == ISD::INTRINSIC_WO_CHAIN ||
19715           Opc == ISD::INTRINSIC_W_CHAIN ||
19716           Opc == ISD::INTRINSIC_VOID) &&
19717          "Should use MaskedValueIsZero if you don't know whether Op"
19718          " is a target node!");
19719
19720   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
19721   switch (Opc) {
19722   default: break;
19723   case X86ISD::ADD:
19724   case X86ISD::SUB:
19725   case X86ISD::ADC:
19726   case X86ISD::SBB:
19727   case X86ISD::SMUL:
19728   case X86ISD::UMUL:
19729   case X86ISD::INC:
19730   case X86ISD::DEC:
19731   case X86ISD::OR:
19732   case X86ISD::XOR:
19733   case X86ISD::AND:
19734     // These nodes' second result is a boolean.
19735     if (Op.getResNo() == 0)
19736       break;
19737     // Fallthrough
19738   case X86ISD::SETCC:
19739     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
19740     break;
19741   case ISD::INTRINSIC_WO_CHAIN: {
19742     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
19743     unsigned NumLoBits = 0;
19744     switch (IntId) {
19745     default: break;
19746     case Intrinsic::x86_sse_movmsk_ps:
19747     case Intrinsic::x86_avx_movmsk_ps_256:
19748     case Intrinsic::x86_sse2_movmsk_pd:
19749     case Intrinsic::x86_avx_movmsk_pd_256:
19750     case Intrinsic::x86_mmx_pmovmskb:
19751     case Intrinsic::x86_sse2_pmovmskb_128:
19752     case Intrinsic::x86_avx2_pmovmskb: {
19753       // High bits of movmskp{s|d}, pmovmskb are known zero.
19754       switch (IntId) {
19755         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
19756         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
19757         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
19758         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
19759         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
19760         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
19761         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
19762         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
19763       }
19764       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
19765       break;
19766     }
19767     }
19768     break;
19769   }
19770   }
19771 }
19772
19773 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
19774   SDValue Op,
19775   const SelectionDAG &,
19776   unsigned Depth) const {
19777   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
19778   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
19779     return Op.getValueType().getScalarType().getSizeInBits();
19780
19781   // Fallback case.
19782   return 1;
19783 }
19784
19785 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
19786 /// node is a GlobalAddress + offset.
19787 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
19788                                        const GlobalValue* &GA,
19789                                        int64_t &Offset) const {
19790   if (N->getOpcode() == X86ISD::Wrapper) {
19791     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
19792       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
19793       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
19794       return true;
19795     }
19796   }
19797   return TargetLowering::isGAPlusOffset(N, GA, Offset);
19798 }
19799
19800 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
19801 /// same as extracting the high 128-bit part of 256-bit vector and then
19802 /// inserting the result into the low part of a new 256-bit vector
19803 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
19804   EVT VT = SVOp->getValueType(0);
19805   unsigned NumElems = VT.getVectorNumElements();
19806
19807   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
19808   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
19809     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
19810         SVOp->getMaskElt(j) >= 0)
19811       return false;
19812
19813   return true;
19814 }
19815
19816 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
19817 /// same as extracting the low 128-bit part of 256-bit vector and then
19818 /// inserting the result into the high part of a new 256-bit vector
19819 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
19820   EVT VT = SVOp->getValueType(0);
19821   unsigned NumElems = VT.getVectorNumElements();
19822
19823   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
19824   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
19825     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
19826         SVOp->getMaskElt(j) >= 0)
19827       return false;
19828
19829   return true;
19830 }
19831
19832 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
19833 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
19834                                         TargetLowering::DAGCombinerInfo &DCI,
19835                                         const X86Subtarget* Subtarget) {
19836   SDLoc dl(N);
19837   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
19838   SDValue V1 = SVOp->getOperand(0);
19839   SDValue V2 = SVOp->getOperand(1);
19840   EVT VT = SVOp->getValueType(0);
19841   unsigned NumElems = VT.getVectorNumElements();
19842
19843   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
19844       V2.getOpcode() == ISD::CONCAT_VECTORS) {
19845     //
19846     //                   0,0,0,...
19847     //                      |
19848     //    V      UNDEF    BUILD_VECTOR    UNDEF
19849     //     \      /           \           /
19850     //  CONCAT_VECTOR         CONCAT_VECTOR
19851     //         \                  /
19852     //          \                /
19853     //          RESULT: V + zero extended
19854     //
19855     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
19856         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
19857         V1.getOperand(1).getOpcode() != ISD::UNDEF)
19858       return SDValue();
19859
19860     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
19861       return SDValue();
19862
19863     // To match the shuffle mask, the first half of the mask should
19864     // be exactly the first vector, and all the rest a splat with the
19865     // first element of the second one.
19866     for (unsigned i = 0; i != NumElems/2; ++i)
19867       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
19868           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
19869         return SDValue();
19870
19871     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
19872     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
19873       if (Ld->hasNUsesOfValue(1, 0)) {
19874         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
19875         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
19876         SDValue ResNode =
19877           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
19878                                   Ld->getMemoryVT(),
19879                                   Ld->getPointerInfo(),
19880                                   Ld->getAlignment(),
19881                                   false/*isVolatile*/, true/*ReadMem*/,
19882                                   false/*WriteMem*/);
19883
19884         // Make sure the newly-created LOAD is in the same position as Ld in
19885         // terms of dependency. We create a TokenFactor for Ld and ResNode,
19886         // and update uses of Ld's output chain to use the TokenFactor.
19887         if (Ld->hasAnyUseOfValue(1)) {
19888           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
19889                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
19890           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
19891           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
19892                                  SDValue(ResNode.getNode(), 1));
19893         }
19894
19895         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
19896       }
19897     }
19898
19899     // Emit a zeroed vector and insert the desired subvector on its
19900     // first half.
19901     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
19902     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
19903     return DCI.CombineTo(N, InsV);
19904   }
19905
19906   //===--------------------------------------------------------------------===//
19907   // Combine some shuffles into subvector extracts and inserts:
19908   //
19909
19910   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
19911   if (isShuffleHigh128VectorInsertLow(SVOp)) {
19912     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
19913     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
19914     return DCI.CombineTo(N, InsV);
19915   }
19916
19917   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
19918   if (isShuffleLow128VectorInsertHigh(SVOp)) {
19919     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
19920     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
19921     return DCI.CombineTo(N, InsV);
19922   }
19923
19924   return SDValue();
19925 }
19926
19927 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
19928 /// possible.
19929 ///
19930 /// This is the leaf of the recursive combinine below. When we have found some
19931 /// chain of single-use x86 shuffle instructions and accumulated the combined
19932 /// shuffle mask represented by them, this will try to pattern match that mask
19933 /// into either a single instruction if there is a special purpose instruction
19934 /// for this operation, or into a PSHUFB instruction which is a fully general
19935 /// instruction but should only be used to replace chains over a certain depth.
19936 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
19937                                    int Depth, bool HasPSHUFB, SelectionDAG &DAG,
19938                                    TargetLowering::DAGCombinerInfo &DCI,
19939                                    const X86Subtarget *Subtarget) {
19940   assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
19941
19942   // Find the operand that enters the chain. Note that multiple uses are OK
19943   // here, we're not going to remove the operand we find.
19944   SDValue Input = Op.getOperand(0);
19945   while (Input.getOpcode() == ISD::BITCAST)
19946     Input = Input.getOperand(0);
19947
19948   MVT VT = Input.getSimpleValueType();
19949   MVT RootVT = Root.getSimpleValueType();
19950   SDLoc DL(Root);
19951
19952   // Just remove no-op shuffle masks.
19953   if (Mask.size() == 1) {
19954     DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Input),
19955                   /*AddTo*/ true);
19956     return true;
19957   }
19958
19959   // Use the float domain if the operand type is a floating point type.
19960   bool FloatDomain = VT.isFloatingPoint();
19961
19962   // For floating point shuffles, we don't have free copies in the shuffle
19963   // instructions or the ability to load as part of the instruction, so
19964   // canonicalize their shuffles to UNPCK or MOV variants.
19965   //
19966   // Note that even with AVX we prefer the PSHUFD form of shuffle for integer
19967   // vectors because it can have a load folded into it that UNPCK cannot. This
19968   // doesn't preclude something switching to the shorter encoding post-RA.
19969   //
19970   // FIXME: Should teach these routines about AVX vector widths.
19971   if (FloatDomain && VT.getSizeInBits() == 128) {
19972     if (Mask.equals({0, 0}) || Mask.equals({1, 1})) {
19973       bool Lo = Mask.equals({0, 0});
19974       unsigned Shuffle;
19975       MVT ShuffleVT;
19976       // Check if we have SSE3 which will let us use MOVDDUP. That instruction
19977       // is no slower than UNPCKLPD but has the option to fold the input operand
19978       // into even an unaligned memory load.
19979       if (Lo && Subtarget->hasSSE3()) {
19980         Shuffle = X86ISD::MOVDDUP;
19981         ShuffleVT = MVT::v2f64;
19982       } else {
19983         // We have MOVLHPS and MOVHLPS throughout SSE and they encode smaller
19984         // than the UNPCK variants.
19985         Shuffle = Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS;
19986         ShuffleVT = MVT::v4f32;
19987       }
19988       if (Depth == 1 && Root->getOpcode() == Shuffle)
19989         return false; // Nothing to do!
19990       Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19991       DCI.AddToWorklist(Op.getNode());
19992       if (Shuffle == X86ISD::MOVDDUP)
19993         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
19994       else
19995         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
19996       DCI.AddToWorklist(Op.getNode());
19997       DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19998                     /*AddTo*/ true);
19999       return true;
20000     }
20001     if (Subtarget->hasSSE3() &&
20002         (Mask.equals({0, 0, 2, 2}) || Mask.equals({1, 1, 3, 3}))) {
20003       bool Lo = Mask.equals({0, 0, 2, 2});
20004       unsigned Shuffle = Lo ? X86ISD::MOVSLDUP : X86ISD::MOVSHDUP;
20005       MVT ShuffleVT = MVT::v4f32;
20006       if (Depth == 1 && Root->getOpcode() == Shuffle)
20007         return false; // Nothing to do!
20008       Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
20009       DCI.AddToWorklist(Op.getNode());
20010       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
20011       DCI.AddToWorklist(Op.getNode());
20012       DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
20013                     /*AddTo*/ true);
20014       return true;
20015     }
20016     if (Mask.equals({0, 0, 1, 1}) || Mask.equals({2, 2, 3, 3})) {
20017       bool Lo = Mask.equals({0, 0, 1, 1});
20018       unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
20019       MVT ShuffleVT = MVT::v4f32;
20020       if (Depth == 1 && Root->getOpcode() == Shuffle)
20021         return false; // Nothing to do!
20022       Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
20023       DCI.AddToWorklist(Op.getNode());
20024       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
20025       DCI.AddToWorklist(Op.getNode());
20026       DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
20027                     /*AddTo*/ true);
20028       return true;
20029     }
20030   }
20031
20032   // We always canonicalize the 8 x i16 and 16 x i8 shuffles into their UNPCK
20033   // variants as none of these have single-instruction variants that are
20034   // superior to the UNPCK formulation.
20035   if (!FloatDomain && VT.getSizeInBits() == 128 &&
20036       (Mask.equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
20037        Mask.equals({4, 4, 5, 5, 6, 6, 7, 7}) ||
20038        Mask.equals({0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7}) ||
20039        Mask.equals(
20040            {8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15}))) {
20041     bool Lo = Mask[0] == 0;
20042     unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
20043     if (Depth == 1 && Root->getOpcode() == Shuffle)
20044       return false; // Nothing to do!
20045     MVT ShuffleVT;
20046     switch (Mask.size()) {
20047     case 8:
20048       ShuffleVT = MVT::v8i16;
20049       break;
20050     case 16:
20051       ShuffleVT = MVT::v16i8;
20052       break;
20053     default:
20054       llvm_unreachable("Impossible mask size!");
20055     };
20056     Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
20057     DCI.AddToWorklist(Op.getNode());
20058     Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
20059     DCI.AddToWorklist(Op.getNode());
20060     DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
20061                   /*AddTo*/ true);
20062     return true;
20063   }
20064
20065   // Don't try to re-form single instruction chains under any circumstances now
20066   // that we've done encoding canonicalization for them.
20067   if (Depth < 2)
20068     return false;
20069
20070   // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
20071   // can replace them with a single PSHUFB instruction profitably. Intel's
20072   // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
20073   // in practice PSHUFB tends to be *very* fast so we're more aggressive.
20074   if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
20075     SmallVector<SDValue, 16> PSHUFBMask;
20076     int NumBytes = VT.getSizeInBits() / 8;
20077     int Ratio = NumBytes / Mask.size();
20078     for (int i = 0; i < NumBytes; ++i) {
20079       if (Mask[i / Ratio] == SM_SentinelUndef) {
20080         PSHUFBMask.push_back(DAG.getUNDEF(MVT::i8));
20081         continue;
20082       }
20083       int M = Mask[i / Ratio] != SM_SentinelZero
20084                   ? Ratio * Mask[i / Ratio] + i % Ratio
20085                   : 255;
20086       PSHUFBMask.push_back(DAG.getConstant(M, DL, MVT::i8));
20087     }
20088     MVT ByteVT = MVT::getVectorVT(MVT::i8, NumBytes);
20089     Op = DAG.getNode(ISD::BITCAST, DL, ByteVT, Input);
20090     DCI.AddToWorklist(Op.getNode());
20091     SDValue PSHUFBMaskOp =
20092         DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVT, PSHUFBMask);
20093     DCI.AddToWorklist(PSHUFBMaskOp.getNode());
20094     Op = DAG.getNode(X86ISD::PSHUFB, DL, ByteVT, Op, PSHUFBMaskOp);
20095     DCI.AddToWorklist(Op.getNode());
20096     DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
20097                   /*AddTo*/ true);
20098     return true;
20099   }
20100
20101   // Failed to find any combines.
20102   return false;
20103 }
20104
20105 /// \brief Fully generic combining of x86 shuffle instructions.
20106 ///
20107 /// This should be the last combine run over the x86 shuffle instructions. Once
20108 /// they have been fully optimized, this will recursively consider all chains
20109 /// of single-use shuffle instructions, build a generic model of the cumulative
20110 /// shuffle operation, and check for simpler instructions which implement this
20111 /// operation. We use this primarily for two purposes:
20112 ///
20113 /// 1) Collapse generic shuffles to specialized single instructions when
20114 ///    equivalent. In most cases, this is just an encoding size win, but
20115 ///    sometimes we will collapse multiple generic shuffles into a single
20116 ///    special-purpose shuffle.
20117 /// 2) Look for sequences of shuffle instructions with 3 or more total
20118 ///    instructions, and replace them with the slightly more expensive SSSE3
20119 ///    PSHUFB instruction if available. We do this as the last combining step
20120 ///    to ensure we avoid using PSHUFB if we can implement the shuffle with
20121 ///    a suitable short sequence of other instructions. The PHUFB will either
20122 ///    use a register or have to read from memory and so is slightly (but only
20123 ///    slightly) more expensive than the other shuffle instructions.
20124 ///
20125 /// Because this is inherently a quadratic operation (for each shuffle in
20126 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
20127 /// This should never be an issue in practice as the shuffle lowering doesn't
20128 /// produce sequences of more than 8 instructions.
20129 ///
20130 /// FIXME: We will currently miss some cases where the redundant shuffling
20131 /// would simplify under the threshold for PSHUFB formation because of
20132 /// combine-ordering. To fix this, we should do the redundant instruction
20133 /// combining in this recursive walk.
20134 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
20135                                           ArrayRef<int> RootMask,
20136                                           int Depth, bool HasPSHUFB,
20137                                           SelectionDAG &DAG,
20138                                           TargetLowering::DAGCombinerInfo &DCI,
20139                                           const X86Subtarget *Subtarget) {
20140   // Bound the depth of our recursive combine because this is ultimately
20141   // quadratic in nature.
20142   if (Depth > 8)
20143     return false;
20144
20145   // Directly rip through bitcasts to find the underlying operand.
20146   while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
20147     Op = Op.getOperand(0);
20148
20149   MVT VT = Op.getSimpleValueType();
20150   if (!VT.isVector())
20151     return false; // Bail if we hit a non-vector.
20152
20153   assert(Root.getSimpleValueType().isVector() &&
20154          "Shuffles operate on vector types!");
20155   assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
20156          "Can only combine shuffles of the same vector register size.");
20157
20158   if (!isTargetShuffle(Op.getOpcode()))
20159     return false;
20160   SmallVector<int, 16> OpMask;
20161   bool IsUnary;
20162   bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, OpMask, IsUnary);
20163   // We only can combine unary shuffles which we can decode the mask for.
20164   if (!HaveMask || !IsUnary)
20165     return false;
20166
20167   assert(VT.getVectorNumElements() == OpMask.size() &&
20168          "Different mask size from vector size!");
20169   assert(((RootMask.size() > OpMask.size() &&
20170            RootMask.size() % OpMask.size() == 0) ||
20171           (OpMask.size() > RootMask.size() &&
20172            OpMask.size() % RootMask.size() == 0) ||
20173           OpMask.size() == RootMask.size()) &&
20174          "The smaller number of elements must divide the larger.");
20175   int RootRatio = std::max<int>(1, OpMask.size() / RootMask.size());
20176   int OpRatio = std::max<int>(1, RootMask.size() / OpMask.size());
20177   assert(((RootRatio == 1 && OpRatio == 1) ||
20178           (RootRatio == 1) != (OpRatio == 1)) &&
20179          "Must not have a ratio for both incoming and op masks!");
20180
20181   SmallVector<int, 16> Mask;
20182   Mask.reserve(std::max(OpMask.size(), RootMask.size()));
20183
20184   // Merge this shuffle operation's mask into our accumulated mask. Note that
20185   // this shuffle's mask will be the first applied to the input, followed by the
20186   // root mask to get us all the way to the root value arrangement. The reason
20187   // for this order is that we are recursing up the operation chain.
20188   for (int i = 0, e = std::max(OpMask.size(), RootMask.size()); i < e; ++i) {
20189     int RootIdx = i / RootRatio;
20190     if (RootMask[RootIdx] < 0) {
20191       // This is a zero or undef lane, we're done.
20192       Mask.push_back(RootMask[RootIdx]);
20193       continue;
20194     }
20195
20196     int RootMaskedIdx = RootMask[RootIdx] * RootRatio + i % RootRatio;
20197     int OpIdx = RootMaskedIdx / OpRatio;
20198     if (OpMask[OpIdx] < 0) {
20199       // The incoming lanes are zero or undef, it doesn't matter which ones we
20200       // are using.
20201       Mask.push_back(OpMask[OpIdx]);
20202       continue;
20203     }
20204
20205     // Ok, we have non-zero lanes, map them through.
20206     Mask.push_back(OpMask[OpIdx] * OpRatio +
20207                    RootMaskedIdx % OpRatio);
20208   }
20209
20210   // See if we can recurse into the operand to combine more things.
20211   switch (Op.getOpcode()) {
20212     case X86ISD::PSHUFB:
20213       HasPSHUFB = true;
20214     case X86ISD::PSHUFD:
20215     case X86ISD::PSHUFHW:
20216     case X86ISD::PSHUFLW:
20217       if (Op.getOperand(0).hasOneUse() &&
20218           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
20219                                         HasPSHUFB, DAG, DCI, Subtarget))
20220         return true;
20221       break;
20222
20223     case X86ISD::UNPCKL:
20224     case X86ISD::UNPCKH:
20225       assert(Op.getOperand(0) == Op.getOperand(1) && "We only combine unary shuffles!");
20226       // We can't check for single use, we have to check that this shuffle is the only user.
20227       if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
20228           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
20229                                         HasPSHUFB, DAG, DCI, Subtarget))
20230           return true;
20231       break;
20232   }
20233
20234   // Minor canonicalization of the accumulated shuffle mask to make it easier
20235   // to match below. All this does is detect masks with squential pairs of
20236   // elements, and shrink them to the half-width mask. It does this in a loop
20237   // so it will reduce the size of the mask to the minimal width mask which
20238   // performs an equivalent shuffle.
20239   SmallVector<int, 16> WidenedMask;
20240   while (Mask.size() > 1 && canWidenShuffleElements(Mask, WidenedMask)) {
20241     Mask = std::move(WidenedMask);
20242     WidenedMask.clear();
20243   }
20244
20245   return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
20246                                 Subtarget);
20247 }
20248
20249 /// \brief Get the PSHUF-style mask from PSHUF node.
20250 ///
20251 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
20252 /// PSHUF-style masks that can be reused with such instructions.
20253 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
20254   MVT VT = N.getSimpleValueType();
20255   SmallVector<int, 4> Mask;
20256   bool IsUnary;
20257   bool HaveMask = getTargetShuffleMask(N.getNode(), VT, Mask, IsUnary);
20258   (void)HaveMask;
20259   assert(HaveMask);
20260
20261   // If we have more than 128-bits, only the low 128-bits of shuffle mask
20262   // matter. Check that the upper masks are repeats and remove them.
20263   if (VT.getSizeInBits() > 128) {
20264     int LaneElts = 128 / VT.getScalarSizeInBits();
20265 #ifndef NDEBUG
20266     for (int i = 1, NumLanes = VT.getSizeInBits() / 128; i < NumLanes; ++i)
20267       for (int j = 0; j < LaneElts; ++j)
20268         assert(Mask[j] == Mask[i * LaneElts + j] - LaneElts &&
20269                "Mask doesn't repeat in high 128-bit lanes!");
20270 #endif
20271     Mask.resize(LaneElts);
20272   }
20273
20274   switch (N.getOpcode()) {
20275   case X86ISD::PSHUFD:
20276     return Mask;
20277   case X86ISD::PSHUFLW:
20278     Mask.resize(4);
20279     return Mask;
20280   case X86ISD::PSHUFHW:
20281     Mask.erase(Mask.begin(), Mask.begin() + 4);
20282     for (int &M : Mask)
20283       M -= 4;
20284     return Mask;
20285   default:
20286     llvm_unreachable("No valid shuffle instruction found!");
20287   }
20288 }
20289
20290 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
20291 ///
20292 /// We walk up the chain and look for a combinable shuffle, skipping over
20293 /// shuffles that we could hoist this shuffle's transformation past without
20294 /// altering anything.
20295 static SDValue
20296 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
20297                              SelectionDAG &DAG,
20298                              TargetLowering::DAGCombinerInfo &DCI) {
20299   assert(N.getOpcode() == X86ISD::PSHUFD &&
20300          "Called with something other than an x86 128-bit half shuffle!");
20301   SDLoc DL(N);
20302
20303   // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
20304   // of the shuffles in the chain so that we can form a fresh chain to replace
20305   // this one.
20306   SmallVector<SDValue, 8> Chain;
20307   SDValue V = N.getOperand(0);
20308   for (; V.hasOneUse(); V = V.getOperand(0)) {
20309     switch (V.getOpcode()) {
20310     default:
20311       return SDValue(); // Nothing combined!
20312
20313     case ISD::BITCAST:
20314       // Skip bitcasts as we always know the type for the target specific
20315       // instructions.
20316       continue;
20317
20318     case X86ISD::PSHUFD:
20319       // Found another dword shuffle.
20320       break;
20321
20322     case X86ISD::PSHUFLW:
20323       // Check that the low words (being shuffled) are the identity in the
20324       // dword shuffle, and the high words are self-contained.
20325       if (Mask[0] != 0 || Mask[1] != 1 ||
20326           !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
20327         return SDValue();
20328
20329       Chain.push_back(V);
20330       continue;
20331
20332     case X86ISD::PSHUFHW:
20333       // Check that the high words (being shuffled) are the identity in the
20334       // dword shuffle, and the low words are self-contained.
20335       if (Mask[2] != 2 || Mask[3] != 3 ||
20336           !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
20337         return SDValue();
20338
20339       Chain.push_back(V);
20340       continue;
20341
20342     case X86ISD::UNPCKL:
20343     case X86ISD::UNPCKH:
20344       // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
20345       // shuffle into a preceding word shuffle.
20346       if (V.getSimpleValueType().getScalarType() != MVT::i8 &&
20347           V.getSimpleValueType().getScalarType() != MVT::i16)
20348         return SDValue();
20349
20350       // Search for a half-shuffle which we can combine with.
20351       unsigned CombineOp =
20352           V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
20353       if (V.getOperand(0) != V.getOperand(1) ||
20354           !V->isOnlyUserOf(V.getOperand(0).getNode()))
20355         return SDValue();
20356       Chain.push_back(V);
20357       V = V.getOperand(0);
20358       do {
20359         switch (V.getOpcode()) {
20360         default:
20361           return SDValue(); // Nothing to combine.
20362
20363         case X86ISD::PSHUFLW:
20364         case X86ISD::PSHUFHW:
20365           if (V.getOpcode() == CombineOp)
20366             break;
20367
20368           Chain.push_back(V);
20369
20370           // Fallthrough!
20371         case ISD::BITCAST:
20372           V = V.getOperand(0);
20373           continue;
20374         }
20375         break;
20376       } while (V.hasOneUse());
20377       break;
20378     }
20379     // Break out of the loop if we break out of the switch.
20380     break;
20381   }
20382
20383   if (!V.hasOneUse())
20384     // We fell out of the loop without finding a viable combining instruction.
20385     return SDValue();
20386
20387   // Merge this node's mask and our incoming mask.
20388   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
20389   for (int &M : Mask)
20390     M = VMask[M];
20391   V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
20392                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
20393
20394   // Rebuild the chain around this new shuffle.
20395   while (!Chain.empty()) {
20396     SDValue W = Chain.pop_back_val();
20397
20398     if (V.getValueType() != W.getOperand(0).getValueType())
20399       V = DAG.getNode(ISD::BITCAST, DL, W.getOperand(0).getValueType(), V);
20400
20401     switch (W.getOpcode()) {
20402     default:
20403       llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
20404
20405     case X86ISD::UNPCKL:
20406     case X86ISD::UNPCKH:
20407       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
20408       break;
20409
20410     case X86ISD::PSHUFD:
20411     case X86ISD::PSHUFLW:
20412     case X86ISD::PSHUFHW:
20413       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
20414       break;
20415     }
20416   }
20417   if (V.getValueType() != N.getValueType())
20418     V = DAG.getNode(ISD::BITCAST, DL, N.getValueType(), V);
20419
20420   // Return the new chain to replace N.
20421   return V;
20422 }
20423
20424 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or pshufhw.
20425 ///
20426 /// We walk up the chain, skipping shuffles of the other half and looking
20427 /// through shuffles which switch halves trying to find a shuffle of the same
20428 /// pair of dwords.
20429 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
20430                                         SelectionDAG &DAG,
20431                                         TargetLowering::DAGCombinerInfo &DCI) {
20432   assert(
20433       (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
20434       "Called with something other than an x86 128-bit half shuffle!");
20435   SDLoc DL(N);
20436   unsigned CombineOpcode = N.getOpcode();
20437
20438   // Walk up a single-use chain looking for a combinable shuffle.
20439   SDValue V = N.getOperand(0);
20440   for (; V.hasOneUse(); V = V.getOperand(0)) {
20441     switch (V.getOpcode()) {
20442     default:
20443       return false; // Nothing combined!
20444
20445     case ISD::BITCAST:
20446       // Skip bitcasts as we always know the type for the target specific
20447       // instructions.
20448       continue;
20449
20450     case X86ISD::PSHUFLW:
20451     case X86ISD::PSHUFHW:
20452       if (V.getOpcode() == CombineOpcode)
20453         break;
20454
20455       // Other-half shuffles are no-ops.
20456       continue;
20457     }
20458     // Break out of the loop if we break out of the switch.
20459     break;
20460   }
20461
20462   if (!V.hasOneUse())
20463     // We fell out of the loop without finding a viable combining instruction.
20464     return false;
20465
20466   // Combine away the bottom node as its shuffle will be accumulated into
20467   // a preceding shuffle.
20468   DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
20469
20470   // Record the old value.
20471   SDValue Old = V;
20472
20473   // Merge this node's mask and our incoming mask (adjusted to account for all
20474   // the pshufd instructions encountered).
20475   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
20476   for (int &M : Mask)
20477     M = VMask[M];
20478   V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
20479                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
20480
20481   // Check that the shuffles didn't cancel each other out. If not, we need to
20482   // combine to the new one.
20483   if (Old != V)
20484     // Replace the combinable shuffle with the combined one, updating all users
20485     // so that we re-evaluate the chain here.
20486     DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
20487
20488   return true;
20489 }
20490
20491 /// \brief Try to combine x86 target specific shuffles.
20492 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
20493                                            TargetLowering::DAGCombinerInfo &DCI,
20494                                            const X86Subtarget *Subtarget) {
20495   SDLoc DL(N);
20496   MVT VT = N.getSimpleValueType();
20497   SmallVector<int, 4> Mask;
20498
20499   switch (N.getOpcode()) {
20500   case X86ISD::PSHUFD:
20501   case X86ISD::PSHUFLW:
20502   case X86ISD::PSHUFHW:
20503     Mask = getPSHUFShuffleMask(N);
20504     assert(Mask.size() == 4);
20505     break;
20506   default:
20507     return SDValue();
20508   }
20509
20510   // Nuke no-op shuffles that show up after combining.
20511   if (isNoopShuffleMask(Mask))
20512     return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
20513
20514   // Look for simplifications involving one or two shuffle instructions.
20515   SDValue V = N.getOperand(0);
20516   switch (N.getOpcode()) {
20517   default:
20518     break;
20519   case X86ISD::PSHUFLW:
20520   case X86ISD::PSHUFHW:
20521     assert(VT.getScalarType() == MVT::i16 && "Bad word shuffle type!");
20522
20523     if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
20524       return SDValue(); // We combined away this shuffle, so we're done.
20525
20526     // See if this reduces to a PSHUFD which is no more expensive and can
20527     // combine with more operations. Note that it has to at least flip the
20528     // dwords as otherwise it would have been removed as a no-op.
20529     if (makeArrayRef(Mask).equals({2, 3, 0, 1})) {
20530       int DMask[] = {0, 1, 2, 3};
20531       int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
20532       DMask[DOffset + 0] = DOffset + 1;
20533       DMask[DOffset + 1] = DOffset + 0;
20534       MVT DVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
20535       V = DAG.getNode(ISD::BITCAST, DL, DVT, V);
20536       DCI.AddToWorklist(V.getNode());
20537       V = DAG.getNode(X86ISD::PSHUFD, DL, DVT, V,
20538                       getV4X86ShuffleImm8ForMask(DMask, DL, DAG));
20539       DCI.AddToWorklist(V.getNode());
20540       return DAG.getNode(ISD::BITCAST, DL, VT, V);
20541     }
20542
20543     // Look for shuffle patterns which can be implemented as a single unpack.
20544     // FIXME: This doesn't handle the location of the PSHUFD generically, and
20545     // only works when we have a PSHUFD followed by two half-shuffles.
20546     if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
20547         (V.getOpcode() == X86ISD::PSHUFLW ||
20548          V.getOpcode() == X86ISD::PSHUFHW) &&
20549         V.getOpcode() != N.getOpcode() &&
20550         V.hasOneUse()) {
20551       SDValue D = V.getOperand(0);
20552       while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
20553         D = D.getOperand(0);
20554       if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
20555         SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
20556         SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
20557         int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
20558         int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
20559         int WordMask[8];
20560         for (int i = 0; i < 4; ++i) {
20561           WordMask[i + NOffset] = Mask[i] + NOffset;
20562           WordMask[i + VOffset] = VMask[i] + VOffset;
20563         }
20564         // Map the word mask through the DWord mask.
20565         int MappedMask[8];
20566         for (int i = 0; i < 8; ++i)
20567           MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
20568         if (makeArrayRef(MappedMask).equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
20569             makeArrayRef(MappedMask).equals({4, 4, 5, 5, 6, 6, 7, 7})) {
20570           // We can replace all three shuffles with an unpack.
20571           V = DAG.getNode(ISD::BITCAST, DL, VT, D.getOperand(0));
20572           DCI.AddToWorklist(V.getNode());
20573           return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
20574                                                 : X86ISD::UNPCKH,
20575                              DL, VT, V, V);
20576         }
20577       }
20578     }
20579
20580     break;
20581
20582   case X86ISD::PSHUFD:
20583     if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG, DCI))
20584       return NewN;
20585
20586     break;
20587   }
20588
20589   return SDValue();
20590 }
20591
20592 /// \brief Try to combine a shuffle into a target-specific add-sub node.
20593 ///
20594 /// We combine this directly on the abstract vector shuffle nodes so it is
20595 /// easier to generically match. We also insert dummy vector shuffle nodes for
20596 /// the operands which explicitly discard the lanes which are unused by this
20597 /// operation to try to flow through the rest of the combiner the fact that
20598 /// they're unused.
20599 static SDValue combineShuffleToAddSub(SDNode *N, SelectionDAG &DAG) {
20600   SDLoc DL(N);
20601   EVT VT = N->getValueType(0);
20602
20603   // We only handle target-independent shuffles.
20604   // FIXME: It would be easy and harmless to use the target shuffle mask
20605   // extraction tool to support more.
20606   if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
20607     return SDValue();
20608
20609   auto *SVN = cast<ShuffleVectorSDNode>(N);
20610   ArrayRef<int> Mask = SVN->getMask();
20611   SDValue V1 = N->getOperand(0);
20612   SDValue V2 = N->getOperand(1);
20613
20614   // We require the first shuffle operand to be the SUB node, and the second to
20615   // be the ADD node.
20616   // FIXME: We should support the commuted patterns.
20617   if (V1->getOpcode() != ISD::FSUB || V2->getOpcode() != ISD::FADD)
20618     return SDValue();
20619
20620   // If there are other uses of these operations we can't fold them.
20621   if (!V1->hasOneUse() || !V2->hasOneUse())
20622     return SDValue();
20623
20624   // Ensure that both operations have the same operands. Note that we can
20625   // commute the FADD operands.
20626   SDValue LHS = V1->getOperand(0), RHS = V1->getOperand(1);
20627   if ((V2->getOperand(0) != LHS || V2->getOperand(1) != RHS) &&
20628       (V2->getOperand(0) != RHS || V2->getOperand(1) != LHS))
20629     return SDValue();
20630
20631   // We're looking for blends between FADD and FSUB nodes. We insist on these
20632   // nodes being lined up in a specific expected pattern.
20633   if (!(isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
20634         isShuffleEquivalent(V1, V2, Mask, {0, 5, 2, 7}) ||
20635         isShuffleEquivalent(V1, V2, Mask, {0, 9, 2, 11, 4, 13, 6, 15})))
20636     return SDValue();
20637
20638   // Only specific types are legal at this point, assert so we notice if and
20639   // when these change.
20640   assert((VT == MVT::v4f32 || VT == MVT::v2f64 || VT == MVT::v8f32 ||
20641           VT == MVT::v4f64) &&
20642          "Unknown vector type encountered!");
20643
20644   return DAG.getNode(X86ISD::ADDSUB, DL, VT, LHS, RHS);
20645 }
20646
20647 /// PerformShuffleCombine - Performs several different shuffle combines.
20648 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
20649                                      TargetLowering::DAGCombinerInfo &DCI,
20650                                      const X86Subtarget *Subtarget) {
20651   SDLoc dl(N);
20652   SDValue N0 = N->getOperand(0);
20653   SDValue N1 = N->getOperand(1);
20654   EVT VT = N->getValueType(0);
20655
20656   // Don't create instructions with illegal types after legalize types has run.
20657   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20658   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
20659     return SDValue();
20660
20661   // If we have legalized the vector types, look for blends of FADD and FSUB
20662   // nodes that we can fuse into an ADDSUB node.
20663   if (TLI.isTypeLegal(VT) && Subtarget->hasSSE3())
20664     if (SDValue AddSub = combineShuffleToAddSub(N, DAG))
20665       return AddSub;
20666
20667   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
20668   if (Subtarget->hasFp256() && VT.is256BitVector() &&
20669       N->getOpcode() == ISD::VECTOR_SHUFFLE)
20670     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
20671
20672   // During Type Legalization, when promoting illegal vector types,
20673   // the backend might introduce new shuffle dag nodes and bitcasts.
20674   //
20675   // This code performs the following transformation:
20676   // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
20677   //       (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
20678   //
20679   // We do this only if both the bitcast and the BINOP dag nodes have
20680   // one use. Also, perform this transformation only if the new binary
20681   // operation is legal. This is to avoid introducing dag nodes that
20682   // potentially need to be further expanded (or custom lowered) into a
20683   // less optimal sequence of dag nodes.
20684   if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
20685       N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
20686       N0.getOpcode() == ISD::BITCAST) {
20687     SDValue BC0 = N0.getOperand(0);
20688     EVT SVT = BC0.getValueType();
20689     unsigned Opcode = BC0.getOpcode();
20690     unsigned NumElts = VT.getVectorNumElements();
20691
20692     if (BC0.hasOneUse() && SVT.isVector() &&
20693         SVT.getVectorNumElements() * 2 == NumElts &&
20694         TLI.isOperationLegal(Opcode, VT)) {
20695       bool CanFold = false;
20696       switch (Opcode) {
20697       default : break;
20698       case ISD::ADD :
20699       case ISD::FADD :
20700       case ISD::SUB :
20701       case ISD::FSUB :
20702       case ISD::MUL :
20703       case ISD::FMUL :
20704         CanFold = true;
20705       }
20706
20707       unsigned SVTNumElts = SVT.getVectorNumElements();
20708       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
20709       for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
20710         CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
20711       for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
20712         CanFold = SVOp->getMaskElt(i) < 0;
20713
20714       if (CanFold) {
20715         SDValue BC00 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(0));
20716         SDValue BC01 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(1));
20717         SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
20718         return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
20719       }
20720     }
20721   }
20722
20723   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
20724   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
20725   // consecutive, non-overlapping, and in the right order.
20726   SmallVector<SDValue, 16> Elts;
20727   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
20728     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
20729
20730   SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
20731   if (LD.getNode())
20732     return LD;
20733
20734   if (isTargetShuffle(N->getOpcode())) {
20735     SDValue Shuffle =
20736         PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
20737     if (Shuffle.getNode())
20738       return Shuffle;
20739
20740     // Try recursively combining arbitrary sequences of x86 shuffle
20741     // instructions into higher-order shuffles. We do this after combining
20742     // specific PSHUF instruction sequences into their minimal form so that we
20743     // can evaluate how many specialized shuffle instructions are involved in
20744     // a particular chain.
20745     SmallVector<int, 1> NonceMask; // Just a placeholder.
20746     NonceMask.push_back(0);
20747     if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
20748                                       /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
20749                                       DCI, Subtarget))
20750       return SDValue(); // This routine will use CombineTo to replace N.
20751   }
20752
20753   return SDValue();
20754 }
20755
20756 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
20757 /// specific shuffle of a load can be folded into a single element load.
20758 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
20759 /// shuffles have been custom lowered so we need to handle those here.
20760 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
20761                                          TargetLowering::DAGCombinerInfo &DCI) {
20762   if (DCI.isBeforeLegalizeOps())
20763     return SDValue();
20764
20765   SDValue InVec = N->getOperand(0);
20766   SDValue EltNo = N->getOperand(1);
20767
20768   if (!isa<ConstantSDNode>(EltNo))
20769     return SDValue();
20770
20771   EVT OriginalVT = InVec.getValueType();
20772
20773   if (InVec.getOpcode() == ISD::BITCAST) {
20774     // Don't duplicate a load with other uses.
20775     if (!InVec.hasOneUse())
20776       return SDValue();
20777     EVT BCVT = InVec.getOperand(0).getValueType();
20778     if (!BCVT.isVector() || 
20779         BCVT.getVectorNumElements() != OriginalVT.getVectorNumElements())
20780       return SDValue();
20781     InVec = InVec.getOperand(0);
20782   }
20783
20784   EVT CurrentVT = InVec.getValueType();
20785
20786   if (!isTargetShuffle(InVec.getOpcode()))
20787     return SDValue();
20788
20789   // Don't duplicate a load with other uses.
20790   if (!InVec.hasOneUse())
20791     return SDValue();
20792
20793   SmallVector<int, 16> ShuffleMask;
20794   bool UnaryShuffle;
20795   if (!getTargetShuffleMask(InVec.getNode(), CurrentVT.getSimpleVT(),
20796                             ShuffleMask, UnaryShuffle))
20797     return SDValue();
20798
20799   // Select the input vector, guarding against out of range extract vector.
20800   unsigned NumElems = CurrentVT.getVectorNumElements();
20801   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
20802   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
20803   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
20804                                          : InVec.getOperand(1);
20805
20806   // If inputs to shuffle are the same for both ops, then allow 2 uses
20807   unsigned AllowedUses = InVec.getNumOperands() > 1 &&
20808                          InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
20809
20810   if (LdNode.getOpcode() == ISD::BITCAST) {
20811     // Don't duplicate a load with other uses.
20812     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
20813       return SDValue();
20814
20815     AllowedUses = 1; // only allow 1 load use if we have a bitcast
20816     LdNode = LdNode.getOperand(0);
20817   }
20818
20819   if (!ISD::isNormalLoad(LdNode.getNode()))
20820     return SDValue();
20821
20822   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
20823
20824   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
20825     return SDValue();
20826
20827   EVT EltVT = N->getValueType(0);
20828   // If there's a bitcast before the shuffle, check if the load type and
20829   // alignment is valid.
20830   unsigned Align = LN0->getAlignment();
20831   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20832   unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
20833       EltVT.getTypeForEVT(*DAG.getContext()));
20834
20835   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, EltVT))
20836     return SDValue();
20837
20838   // All checks match so transform back to vector_shuffle so that DAG combiner
20839   // can finish the job
20840   SDLoc dl(N);
20841
20842   // Create shuffle node taking into account the case that its a unary shuffle
20843   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(CurrentVT)
20844                                    : InVec.getOperand(1);
20845   Shuffle = DAG.getVectorShuffle(CurrentVT, dl,
20846                                  InVec.getOperand(0), Shuffle,
20847                                  &ShuffleMask[0]);
20848   Shuffle = DAG.getNode(ISD::BITCAST, dl, OriginalVT, Shuffle);
20849   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
20850                      EltNo);
20851 }
20852
20853 /// \brief Detect bitcasts between i32 to x86mmx low word. Since MMX types are
20854 /// special and don't usually play with other vector types, it's better to
20855 /// handle them early to be sure we emit efficient code by avoiding
20856 /// store-load conversions.
20857 static SDValue PerformBITCASTCombine(SDNode *N, SelectionDAG &DAG) {
20858   if (N->getValueType(0) != MVT::x86mmx ||
20859       N->getOperand(0)->getOpcode() != ISD::BUILD_VECTOR ||
20860       N->getOperand(0)->getValueType(0) != MVT::v2i32)
20861     return SDValue();
20862
20863   SDValue V = N->getOperand(0);
20864   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V.getOperand(1));
20865   if (C && C->getZExtValue() == 0 && V.getOperand(0).getValueType() == MVT::i32)
20866     return DAG.getNode(X86ISD::MMX_MOVW2D, SDLoc(V.getOperand(0)),
20867                        N->getValueType(0), V.getOperand(0));
20868
20869   return SDValue();
20870 }
20871
20872 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
20873 /// generation and convert it from being a bunch of shuffles and extracts
20874 /// into a somewhat faster sequence. For i686, the best sequence is apparently
20875 /// storing the value and loading scalars back, while for x64 we should
20876 /// use 64-bit extracts and shifts.
20877 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
20878                                          TargetLowering::DAGCombinerInfo &DCI) {
20879   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
20880   if (NewOp.getNode())
20881     return NewOp;
20882
20883   SDValue InputVector = N->getOperand(0);
20884   SDLoc dl(InputVector);
20885   // Detect mmx to i32 conversion through a v2i32 elt extract.
20886   if (InputVector.getOpcode() == ISD::BITCAST && InputVector.hasOneUse() &&
20887       N->getValueType(0) == MVT::i32 &&
20888       InputVector.getValueType() == MVT::v2i32) {
20889
20890     // The bitcast source is a direct mmx result.
20891     SDValue MMXSrc = InputVector.getNode()->getOperand(0);
20892     if (MMXSrc.getValueType() == MVT::x86mmx)
20893       return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
20894                          N->getValueType(0),
20895                          InputVector.getNode()->getOperand(0));
20896
20897     // The mmx is indirect: (i64 extract_elt (v1i64 bitcast (x86mmx ...))).
20898     SDValue MMXSrcOp = MMXSrc.getOperand(0);
20899     if (MMXSrc.getOpcode() == ISD::EXTRACT_VECTOR_ELT && MMXSrc.hasOneUse() &&
20900         MMXSrc.getValueType() == MVT::i64 && MMXSrcOp.hasOneUse() &&
20901         MMXSrcOp.getOpcode() == ISD::BITCAST &&
20902         MMXSrcOp.getValueType() == MVT::v1i64 &&
20903         MMXSrcOp.getOperand(0).getValueType() == MVT::x86mmx)
20904       return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
20905                          N->getValueType(0),
20906                          MMXSrcOp.getOperand(0));
20907   }
20908
20909   EVT VT = N->getValueType(0);
20910   
20911   if (VT == MVT::i1 && dyn_cast<ConstantSDNode>(N->getOperand(1)) &&
20912       InputVector.getOpcode() == ISD::BITCAST &&
20913       dyn_cast<ConstantSDNode>(InputVector.getOperand(0))) {
20914     uint64_t ExtractedElt =
20915           cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
20916     uint64_t InputValue =
20917           cast<ConstantSDNode>(InputVector.getOperand(0))->getZExtValue();
20918     uint64_t Res = (InputValue >> ExtractedElt) & 1;
20919     return DAG.getConstant(Res, dl, MVT::i1);
20920   }
20921   // Only operate on vectors of 4 elements, where the alternative shuffling
20922   // gets to be more expensive.
20923   if (InputVector.getValueType() != MVT::v4i32)
20924     return SDValue();
20925
20926   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
20927   // single use which is a sign-extend or zero-extend, and all elements are
20928   // used.
20929   SmallVector<SDNode *, 4> Uses;
20930   unsigned ExtractedElements = 0;
20931   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
20932        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
20933     if (UI.getUse().getResNo() != InputVector.getResNo())
20934       return SDValue();
20935
20936     SDNode *Extract = *UI;
20937     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
20938       return SDValue();
20939
20940     if (Extract->getValueType(0) != MVT::i32)
20941       return SDValue();
20942     if (!Extract->hasOneUse())
20943       return SDValue();
20944     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
20945         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
20946       return SDValue();
20947     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
20948       return SDValue();
20949
20950     // Record which element was extracted.
20951     ExtractedElements |=
20952       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
20953
20954     Uses.push_back(Extract);
20955   }
20956
20957   // If not all the elements were used, this may not be worthwhile.
20958   if (ExtractedElements != 15)
20959     return SDValue();
20960
20961   // Ok, we've now decided to do the transformation.
20962   // If 64-bit shifts are legal, use the extract-shift sequence,
20963   // otherwise bounce the vector off the cache.
20964   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20965   SDValue Vals[4];
20966
20967   if (TLI.isOperationLegal(ISD::SRA, MVT::i64)) {
20968     SDValue Cst = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, InputVector);
20969     EVT VecIdxTy = DAG.getTargetLoweringInfo().getVectorIdxTy();
20970     SDValue BottomHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
20971       DAG.getConstant(0, dl, VecIdxTy));
20972     SDValue TopHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
20973       DAG.getConstant(1, dl, VecIdxTy));
20974
20975     SDValue ShAmt = DAG.getConstant(32, dl,
20976       DAG.getTargetLoweringInfo().getShiftAmountTy(MVT::i64));
20977     Vals[0] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BottomHalf);
20978     Vals[1] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
20979       DAG.getNode(ISD::SRA, dl, MVT::i64, BottomHalf, ShAmt));
20980     Vals[2] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, TopHalf);
20981     Vals[3] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
20982       DAG.getNode(ISD::SRA, dl, MVT::i64, TopHalf, ShAmt));
20983   } else {
20984     // Store the value to a temporary stack slot.
20985     SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
20986     SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
20987       MachinePointerInfo(), false, false, 0);
20988
20989     EVT ElementType = InputVector.getValueType().getVectorElementType();
20990     unsigned EltSize = ElementType.getSizeInBits() / 8;
20991
20992     // Replace each use (extract) with a load of the appropriate element.
20993     for (unsigned i = 0; i < 4; ++i) {
20994       uint64_t Offset = EltSize * i;
20995       SDValue OffsetVal = DAG.getConstant(Offset, dl, TLI.getPointerTy());
20996
20997       SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
20998                                        StackPtr, OffsetVal);
20999
21000       // Load the scalar.
21001       Vals[i] = DAG.getLoad(ElementType, dl, Ch,
21002                             ScalarAddr, MachinePointerInfo(),
21003                             false, false, false, 0);
21004
21005     }
21006   }
21007
21008   // Replace the extracts
21009   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
21010     UE = Uses.end(); UI != UE; ++UI) {
21011     SDNode *Extract = *UI;
21012
21013     SDValue Idx = Extract->getOperand(1);
21014     uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
21015     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), Vals[IdxVal]);
21016   }
21017
21018   // The replacement was made in place; don't return anything.
21019   return SDValue();
21020 }
21021
21022 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
21023 static std::pair<unsigned, bool>
21024 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
21025                    SelectionDAG &DAG, const X86Subtarget *Subtarget) {
21026   if (!VT.isVector())
21027     return std::make_pair(0, false);
21028
21029   bool NeedSplit = false;
21030   switch (VT.getSimpleVT().SimpleTy) {
21031   default: return std::make_pair(0, false);
21032   case MVT::v4i64:
21033   case MVT::v2i64:
21034     if (!Subtarget->hasVLX())
21035       return std::make_pair(0, false);
21036     break;
21037   case MVT::v64i8:
21038   case MVT::v32i16:
21039     if (!Subtarget->hasBWI())
21040       return std::make_pair(0, false);
21041     break;
21042   case MVT::v16i32:
21043   case MVT::v8i64:
21044     if (!Subtarget->hasAVX512())
21045       return std::make_pair(0, false);
21046     break;
21047   case MVT::v32i8:
21048   case MVT::v16i16:
21049   case MVT::v8i32:
21050     if (!Subtarget->hasAVX2())
21051       NeedSplit = true;
21052     if (!Subtarget->hasAVX())
21053       return std::make_pair(0, false);
21054     break;
21055   case MVT::v16i8:
21056   case MVT::v8i16:
21057   case MVT::v4i32:
21058     if (!Subtarget->hasSSE2())
21059       return std::make_pair(0, false);
21060   }
21061
21062   // SSE2 has only a small subset of the operations.
21063   bool hasUnsigned = Subtarget->hasSSE41() ||
21064                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
21065   bool hasSigned = Subtarget->hasSSE41() ||
21066                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
21067
21068   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
21069
21070   unsigned Opc = 0;
21071   // Check for x CC y ? x : y.
21072   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
21073       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
21074     switch (CC) {
21075     default: break;
21076     case ISD::SETULT:
21077     case ISD::SETULE:
21078       Opc = hasUnsigned ? X86ISD::UMIN : 0u; break;
21079     case ISD::SETUGT:
21080     case ISD::SETUGE:
21081       Opc = hasUnsigned ? X86ISD::UMAX : 0u; break;
21082     case ISD::SETLT:
21083     case ISD::SETLE:
21084       Opc = hasSigned ? X86ISD::SMIN : 0u; break;
21085     case ISD::SETGT:
21086     case ISD::SETGE:
21087       Opc = hasSigned ? X86ISD::SMAX : 0u; break;
21088     }
21089   // Check for x CC y ? y : x -- a min/max with reversed arms.
21090   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
21091              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
21092     switch (CC) {
21093     default: break;
21094     case ISD::SETULT:
21095     case ISD::SETULE:
21096       Opc = hasUnsigned ? X86ISD::UMAX : 0u; break;
21097     case ISD::SETUGT:
21098     case ISD::SETUGE:
21099       Opc = hasUnsigned ? X86ISD::UMIN : 0u; break;
21100     case ISD::SETLT:
21101     case ISD::SETLE:
21102       Opc = hasSigned ? X86ISD::SMAX : 0u; break;
21103     case ISD::SETGT:
21104     case ISD::SETGE:
21105       Opc = hasSigned ? X86ISD::SMIN : 0u; break;
21106     }
21107   }
21108
21109   return std::make_pair(Opc, NeedSplit);
21110 }
21111
21112 static SDValue
21113 transformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
21114                                       const X86Subtarget *Subtarget) {
21115   SDLoc dl(N);
21116   SDValue Cond = N->getOperand(0);
21117   SDValue LHS = N->getOperand(1);
21118   SDValue RHS = N->getOperand(2);
21119
21120   if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
21121     SDValue CondSrc = Cond->getOperand(0);
21122     if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
21123       Cond = CondSrc->getOperand(0);
21124   }
21125
21126   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
21127     return SDValue();
21128
21129   // A vselect where all conditions and data are constants can be optimized into
21130   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
21131   if (ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
21132       ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
21133     return SDValue();
21134
21135   unsigned MaskValue = 0;
21136   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
21137     return SDValue();
21138
21139   MVT VT = N->getSimpleValueType(0);
21140   unsigned NumElems = VT.getVectorNumElements();
21141   SmallVector<int, 8> ShuffleMask(NumElems, -1);
21142   for (unsigned i = 0; i < NumElems; ++i) {
21143     // Be sure we emit undef where we can.
21144     if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
21145       ShuffleMask[i] = -1;
21146     else
21147       ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
21148   }
21149
21150   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21151   if (!TLI.isShuffleMaskLegal(ShuffleMask, VT))
21152     return SDValue();
21153   return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
21154 }
21155
21156 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
21157 /// nodes.
21158 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
21159                                     TargetLowering::DAGCombinerInfo &DCI,
21160                                     const X86Subtarget *Subtarget) {
21161   SDLoc DL(N);
21162   SDValue Cond = N->getOperand(0);
21163   // Get the LHS/RHS of the select.
21164   SDValue LHS = N->getOperand(1);
21165   SDValue RHS = N->getOperand(2);
21166   EVT VT = LHS.getValueType();
21167   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21168
21169   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
21170   // instructions match the semantics of the common C idiom x<y?x:y but not
21171   // x<=y?x:y, because of how they handle negative zero (which can be
21172   // ignored in unsafe-math mode).
21173   // We also try to create v2f32 min/max nodes, which we later widen to v4f32.
21174   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
21175       VT != MVT::f80 && (TLI.isTypeLegal(VT) || VT == MVT::v2f32) &&
21176       (Subtarget->hasSSE2() ||
21177        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
21178     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
21179
21180     unsigned Opcode = 0;
21181     // Check for x CC y ? x : y.
21182     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
21183         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
21184       switch (CC) {
21185       default: break;
21186       case ISD::SETULT:
21187         // Converting this to a min would handle NaNs incorrectly, and swapping
21188         // the operands would cause it to handle comparisons between positive
21189         // and negative zero incorrectly.
21190         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
21191           if (!DAG.getTarget().Options.UnsafeFPMath &&
21192               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
21193             break;
21194           std::swap(LHS, RHS);
21195         }
21196         Opcode = X86ISD::FMIN;
21197         break;
21198       case ISD::SETOLE:
21199         // Converting this to a min would handle comparisons between positive
21200         // and negative zero incorrectly.
21201         if (!DAG.getTarget().Options.UnsafeFPMath &&
21202             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
21203           break;
21204         Opcode = X86ISD::FMIN;
21205         break;
21206       case ISD::SETULE:
21207         // Converting this to a min would handle both negative zeros and NaNs
21208         // incorrectly, but we can swap the operands to fix both.
21209         std::swap(LHS, RHS);
21210       case ISD::SETOLT:
21211       case ISD::SETLT:
21212       case ISD::SETLE:
21213         Opcode = X86ISD::FMIN;
21214         break;
21215
21216       case ISD::SETOGE:
21217         // Converting this to a max would handle comparisons between positive
21218         // and negative zero incorrectly.
21219         if (!DAG.getTarget().Options.UnsafeFPMath &&
21220             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
21221           break;
21222         Opcode = X86ISD::FMAX;
21223         break;
21224       case ISD::SETUGT:
21225         // Converting this to a max would handle NaNs incorrectly, and swapping
21226         // the operands would cause it to handle comparisons between positive
21227         // and negative zero incorrectly.
21228         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
21229           if (!DAG.getTarget().Options.UnsafeFPMath &&
21230               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
21231             break;
21232           std::swap(LHS, RHS);
21233         }
21234         Opcode = X86ISD::FMAX;
21235         break;
21236       case ISD::SETUGE:
21237         // Converting this to a max would handle both negative zeros and NaNs
21238         // incorrectly, but we can swap the operands to fix both.
21239         std::swap(LHS, RHS);
21240       case ISD::SETOGT:
21241       case ISD::SETGT:
21242       case ISD::SETGE:
21243         Opcode = X86ISD::FMAX;
21244         break;
21245       }
21246     // Check for x CC y ? y : x -- a min/max with reversed arms.
21247     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
21248                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
21249       switch (CC) {
21250       default: break;
21251       case ISD::SETOGE:
21252         // Converting this to a min would handle comparisons between positive
21253         // and negative zero incorrectly, and swapping the operands would
21254         // cause it to handle NaNs incorrectly.
21255         if (!DAG.getTarget().Options.UnsafeFPMath &&
21256             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
21257           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
21258             break;
21259           std::swap(LHS, RHS);
21260         }
21261         Opcode = X86ISD::FMIN;
21262         break;
21263       case ISD::SETUGT:
21264         // Converting this to a min would handle NaNs incorrectly.
21265         if (!DAG.getTarget().Options.UnsafeFPMath &&
21266             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
21267           break;
21268         Opcode = X86ISD::FMIN;
21269         break;
21270       case ISD::SETUGE:
21271         // Converting this to a min would handle both negative zeros and NaNs
21272         // incorrectly, but we can swap the operands to fix both.
21273         std::swap(LHS, RHS);
21274       case ISD::SETOGT:
21275       case ISD::SETGT:
21276       case ISD::SETGE:
21277         Opcode = X86ISD::FMIN;
21278         break;
21279
21280       case ISD::SETULT:
21281         // Converting this to a max would handle NaNs incorrectly.
21282         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
21283           break;
21284         Opcode = X86ISD::FMAX;
21285         break;
21286       case ISD::SETOLE:
21287         // Converting this to a max would handle comparisons between positive
21288         // and negative zero incorrectly, and swapping the operands would
21289         // cause it to handle NaNs incorrectly.
21290         if (!DAG.getTarget().Options.UnsafeFPMath &&
21291             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
21292           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
21293             break;
21294           std::swap(LHS, RHS);
21295         }
21296         Opcode = X86ISD::FMAX;
21297         break;
21298       case ISD::SETULE:
21299         // Converting this to a max would handle both negative zeros and NaNs
21300         // incorrectly, but we can swap the operands to fix both.
21301         std::swap(LHS, RHS);
21302       case ISD::SETOLT:
21303       case ISD::SETLT:
21304       case ISD::SETLE:
21305         Opcode = X86ISD::FMAX;
21306         break;
21307       }
21308     }
21309
21310     if (Opcode)
21311       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
21312   }
21313
21314   EVT CondVT = Cond.getValueType();
21315   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
21316       CondVT.getVectorElementType() == MVT::i1) {
21317     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
21318     // lowering on KNL. In this case we convert it to
21319     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
21320     // The same situation for all 128 and 256-bit vectors of i8 and i16.
21321     // Since SKX these selects have a proper lowering.
21322     EVT OpVT = LHS.getValueType();
21323     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
21324         (OpVT.getVectorElementType() == MVT::i8 ||
21325          OpVT.getVectorElementType() == MVT::i16) &&
21326         !(Subtarget->hasBWI() && Subtarget->hasVLX())) {
21327       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
21328       DCI.AddToWorklist(Cond.getNode());
21329       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
21330     }
21331   }
21332   // If this is a select between two integer constants, try to do some
21333   // optimizations.
21334   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
21335     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
21336       // Don't do this for crazy integer types.
21337       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
21338         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
21339         // so that TrueC (the true value) is larger than FalseC.
21340         bool NeedsCondInvert = false;
21341
21342         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
21343             // Efficiently invertible.
21344             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
21345              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
21346               isa<ConstantSDNode>(Cond.getOperand(1))))) {
21347           NeedsCondInvert = true;
21348           std::swap(TrueC, FalseC);
21349         }
21350
21351         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
21352         if (FalseC->getAPIntValue() == 0 &&
21353             TrueC->getAPIntValue().isPowerOf2()) {
21354           if (NeedsCondInvert) // Invert the condition if needed.
21355             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
21356                                DAG.getConstant(1, DL, Cond.getValueType()));
21357
21358           // Zero extend the condition if needed.
21359           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
21360
21361           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
21362           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
21363                              DAG.getConstant(ShAmt, DL, MVT::i8));
21364         }
21365
21366         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
21367         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
21368           if (NeedsCondInvert) // Invert the condition if needed.
21369             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
21370                                DAG.getConstant(1, DL, Cond.getValueType()));
21371
21372           // Zero extend the condition if needed.
21373           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
21374                              FalseC->getValueType(0), Cond);
21375           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
21376                              SDValue(FalseC, 0));
21377         }
21378
21379         // Optimize cases that will turn into an LEA instruction.  This requires
21380         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
21381         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
21382           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
21383           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
21384
21385           bool isFastMultiplier = false;
21386           if (Diff < 10) {
21387             switch ((unsigned char)Diff) {
21388               default: break;
21389               case 1:  // result = add base, cond
21390               case 2:  // result = lea base(    , cond*2)
21391               case 3:  // result = lea base(cond, cond*2)
21392               case 4:  // result = lea base(    , cond*4)
21393               case 5:  // result = lea base(cond, cond*4)
21394               case 8:  // result = lea base(    , cond*8)
21395               case 9:  // result = lea base(cond, cond*8)
21396                 isFastMultiplier = true;
21397                 break;
21398             }
21399           }
21400
21401           if (isFastMultiplier) {
21402             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
21403             if (NeedsCondInvert) // Invert the condition if needed.
21404               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
21405                                  DAG.getConstant(1, DL, Cond.getValueType()));
21406
21407             // Zero extend the condition if needed.
21408             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
21409                                Cond);
21410             // Scale the condition by the difference.
21411             if (Diff != 1)
21412               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
21413                                  DAG.getConstant(Diff, DL,
21414                                                  Cond.getValueType()));
21415
21416             // Add the base if non-zero.
21417             if (FalseC->getAPIntValue() != 0)
21418               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
21419                                  SDValue(FalseC, 0));
21420             return Cond;
21421           }
21422         }
21423       }
21424   }
21425
21426   // Canonicalize max and min:
21427   // (x > y) ? x : y -> (x >= y) ? x : y
21428   // (x < y) ? x : y -> (x <= y) ? x : y
21429   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
21430   // the need for an extra compare
21431   // against zero. e.g.
21432   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
21433   // subl   %esi, %edi
21434   // testl  %edi, %edi
21435   // movl   $0, %eax
21436   // cmovgl %edi, %eax
21437   // =>
21438   // xorl   %eax, %eax
21439   // subl   %esi, $edi
21440   // cmovsl %eax, %edi
21441   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
21442       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
21443       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
21444     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
21445     switch (CC) {
21446     default: break;
21447     case ISD::SETLT:
21448     case ISD::SETGT: {
21449       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
21450       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
21451                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
21452       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
21453     }
21454     }
21455   }
21456
21457   // Early exit check
21458   if (!TLI.isTypeLegal(VT))
21459     return SDValue();
21460
21461   // Match VSELECTs into subs with unsigned saturation.
21462   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
21463       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
21464       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
21465        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
21466     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
21467
21468     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
21469     // left side invert the predicate to simplify logic below.
21470     SDValue Other;
21471     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
21472       Other = RHS;
21473       CC = ISD::getSetCCInverse(CC, true);
21474     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
21475       Other = LHS;
21476     }
21477
21478     if (Other.getNode() && Other->getNumOperands() == 2 &&
21479         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
21480       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
21481       SDValue CondRHS = Cond->getOperand(1);
21482
21483       // Look for a general sub with unsigned saturation first.
21484       // x >= y ? x-y : 0 --> subus x, y
21485       // x >  y ? x-y : 0 --> subus x, y
21486       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
21487           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
21488         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
21489
21490       if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
21491         if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
21492           if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
21493             if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
21494               // If the RHS is a constant we have to reverse the const
21495               // canonicalization.
21496               // x > C-1 ? x+-C : 0 --> subus x, C
21497               if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
21498                   CondRHSConst->getAPIntValue() ==
21499                       (-OpRHSConst->getAPIntValue() - 1))
21500                 return DAG.getNode(
21501                     X86ISD::SUBUS, DL, VT, OpLHS,
21502                     DAG.getConstant(-OpRHSConst->getAPIntValue(), DL, VT));
21503
21504           // Another special case: If C was a sign bit, the sub has been
21505           // canonicalized into a xor.
21506           // FIXME: Would it be better to use computeKnownBits to determine
21507           //        whether it's safe to decanonicalize the xor?
21508           // x s< 0 ? x^C : 0 --> subus x, C
21509           if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
21510               ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
21511               OpRHSConst->getAPIntValue().isSignBit())
21512             // Note that we have to rebuild the RHS constant here to ensure we
21513             // don't rely on particular values of undef lanes.
21514             return DAG.getNode(
21515                 X86ISD::SUBUS, DL, VT, OpLHS,
21516                 DAG.getConstant(OpRHSConst->getAPIntValue(), DL, VT));
21517         }
21518     }
21519   }
21520
21521   // Try to match a min/max vector operation.
21522   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
21523     std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
21524     unsigned Opc = ret.first;
21525     bool NeedSplit = ret.second;
21526
21527     if (Opc && NeedSplit) {
21528       unsigned NumElems = VT.getVectorNumElements();
21529       // Extract the LHS vectors
21530       SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
21531       SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
21532
21533       // Extract the RHS vectors
21534       SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
21535       SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
21536
21537       // Create min/max for each subvector
21538       LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
21539       RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
21540
21541       // Merge the result
21542       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
21543     } else if (Opc)
21544       return DAG.getNode(Opc, DL, VT, LHS, RHS);
21545   }
21546
21547   // Simplify vector selection if condition value type matches vselect
21548   // operand type
21549   if (N->getOpcode() == ISD::VSELECT && CondVT == VT) {
21550     assert(Cond.getValueType().isVector() &&
21551            "vector select expects a vector selector!");
21552
21553     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
21554     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
21555
21556     // Try invert the condition if true value is not all 1s and false value
21557     // is not all 0s.
21558     if (!TValIsAllOnes && !FValIsAllZeros &&
21559         // Check if the selector will be produced by CMPP*/PCMP*
21560         Cond.getOpcode() == ISD::SETCC &&
21561         // Check if SETCC has already been promoted
21562         TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT) {
21563       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
21564       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
21565
21566       if (TValIsAllZeros || FValIsAllOnes) {
21567         SDValue CC = Cond.getOperand(2);
21568         ISD::CondCode NewCC =
21569           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
21570                                Cond.getOperand(0).getValueType().isInteger());
21571         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
21572         std::swap(LHS, RHS);
21573         TValIsAllOnes = FValIsAllOnes;
21574         FValIsAllZeros = TValIsAllZeros;
21575       }
21576     }
21577
21578     if (TValIsAllOnes || FValIsAllZeros) {
21579       SDValue Ret;
21580
21581       if (TValIsAllOnes && FValIsAllZeros)
21582         Ret = Cond;
21583       else if (TValIsAllOnes)
21584         Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
21585                           DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
21586       else if (FValIsAllZeros)
21587         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
21588                           DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
21589
21590       return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
21591     }
21592   }
21593
21594   // We should generate an X86ISD::BLENDI from a vselect if its argument
21595   // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
21596   // constants. This specific pattern gets generated when we split a
21597   // selector for a 512 bit vector in a machine without AVX512 (but with
21598   // 256-bit vectors), during legalization:
21599   //
21600   // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
21601   //
21602   // Iff we find this pattern and the build_vectors are built from
21603   // constants, we translate the vselect into a shuffle_vector that we
21604   // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
21605   if ((N->getOpcode() == ISD::VSELECT ||
21606        N->getOpcode() == X86ISD::SHRUNKBLEND) &&
21607       !DCI.isBeforeLegalize()) {
21608     SDValue Shuffle = transformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
21609     if (Shuffle.getNode())
21610       return Shuffle;
21611   }
21612
21613   // If this is a *dynamic* select (non-constant condition) and we can match
21614   // this node with one of the variable blend instructions, restructure the
21615   // condition so that the blends can use the high bit of each element and use
21616   // SimplifyDemandedBits to simplify the condition operand.
21617   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
21618       !DCI.isBeforeLegalize() &&
21619       !ISD::isBuildVectorOfConstantSDNodes(Cond.getNode())) {
21620     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
21621
21622     // Don't optimize vector selects that map to mask-registers.
21623     if (BitWidth == 1)
21624       return SDValue();
21625
21626     // We can only handle the cases where VSELECT is directly legal on the
21627     // subtarget. We custom lower VSELECT nodes with constant conditions and
21628     // this makes it hard to see whether a dynamic VSELECT will correctly
21629     // lower, so we both check the operation's status and explicitly handle the
21630     // cases where a *dynamic* blend will fail even though a constant-condition
21631     // blend could be custom lowered.
21632     // FIXME: We should find a better way to handle this class of problems.
21633     // Potentially, we should combine constant-condition vselect nodes
21634     // pre-legalization into shuffles and not mark as many types as custom
21635     // lowered.
21636     if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
21637       return SDValue();
21638     // FIXME: We don't support i16-element blends currently. We could and
21639     // should support them by making *all* the bits in the condition be set
21640     // rather than just the high bit and using an i8-element blend.
21641     if (VT.getScalarType() == MVT::i16)
21642       return SDValue();
21643     // Dynamic blending was only available from SSE4.1 onward.
21644     if (VT.getSizeInBits() == 128 && !Subtarget->hasSSE41())
21645       return SDValue();
21646     // Byte blends are only available in AVX2
21647     if (VT.getSizeInBits() == 256 && VT.getScalarType() == MVT::i8 &&
21648         !Subtarget->hasAVX2())
21649       return SDValue();
21650
21651     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
21652     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
21653
21654     APInt KnownZero, KnownOne;
21655     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
21656                                           DCI.isBeforeLegalizeOps());
21657     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
21658         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne,
21659                                  TLO)) {
21660       // If we changed the computation somewhere in the DAG, this change
21661       // will affect all users of Cond.
21662       // Make sure it is fine and update all the nodes so that we do not
21663       // use the generic VSELECT anymore. Otherwise, we may perform
21664       // wrong optimizations as we messed up with the actual expectation
21665       // for the vector boolean values.
21666       if (Cond != TLO.Old) {
21667         // Check all uses of that condition operand to check whether it will be
21668         // consumed by non-BLEND instructions, which may depend on all bits are
21669         // set properly.
21670         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
21671              I != E; ++I)
21672           if (I->getOpcode() != ISD::VSELECT)
21673             // TODO: Add other opcodes eventually lowered into BLEND.
21674             return SDValue();
21675
21676         // Update all the users of the condition, before committing the change,
21677         // so that the VSELECT optimizations that expect the correct vector
21678         // boolean value will not be triggered.
21679         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
21680              I != E; ++I)
21681           DAG.ReplaceAllUsesOfValueWith(
21682               SDValue(*I, 0),
21683               DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(*I), I->getValueType(0),
21684                           Cond, I->getOperand(1), I->getOperand(2)));
21685         DCI.CommitTargetLoweringOpt(TLO);
21686         return SDValue();
21687       }
21688       // At this point, only Cond is changed. Change the condition
21689       // just for N to keep the opportunity to optimize all other
21690       // users their own way.
21691       DAG.ReplaceAllUsesOfValueWith(
21692           SDValue(N, 0),
21693           DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(N), N->getValueType(0),
21694                       TLO.New, N->getOperand(1), N->getOperand(2)));
21695       return SDValue();
21696     }
21697   }
21698
21699   return SDValue();
21700 }
21701
21702 // Check whether a boolean test is testing a boolean value generated by
21703 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
21704 // code.
21705 //
21706 // Simplify the following patterns:
21707 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
21708 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
21709 // to (Op EFLAGS Cond)
21710 //
21711 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
21712 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
21713 // to (Op EFLAGS !Cond)
21714 //
21715 // where Op could be BRCOND or CMOV.
21716 //
21717 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
21718   // Quit if not CMP and SUB with its value result used.
21719   if (Cmp.getOpcode() != X86ISD::CMP &&
21720       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
21721       return SDValue();
21722
21723   // Quit if not used as a boolean value.
21724   if (CC != X86::COND_E && CC != X86::COND_NE)
21725     return SDValue();
21726
21727   // Check CMP operands. One of them should be 0 or 1 and the other should be
21728   // an SetCC or extended from it.
21729   SDValue Op1 = Cmp.getOperand(0);
21730   SDValue Op2 = Cmp.getOperand(1);
21731
21732   SDValue SetCC;
21733   const ConstantSDNode* C = nullptr;
21734   bool needOppositeCond = (CC == X86::COND_E);
21735   bool checkAgainstTrue = false; // Is it a comparison against 1?
21736
21737   if ((C = dyn_cast<ConstantSDNode>(Op1)))
21738     SetCC = Op2;
21739   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
21740     SetCC = Op1;
21741   else // Quit if all operands are not constants.
21742     return SDValue();
21743
21744   if (C->getZExtValue() == 1) {
21745     needOppositeCond = !needOppositeCond;
21746     checkAgainstTrue = true;
21747   } else if (C->getZExtValue() != 0)
21748     // Quit if the constant is neither 0 or 1.
21749     return SDValue();
21750
21751   bool truncatedToBoolWithAnd = false;
21752   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
21753   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
21754          SetCC.getOpcode() == ISD::TRUNCATE ||
21755          SetCC.getOpcode() == ISD::AND) {
21756     if (SetCC.getOpcode() == ISD::AND) {
21757       int OpIdx = -1;
21758       ConstantSDNode *CS;
21759       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
21760           CS->getZExtValue() == 1)
21761         OpIdx = 1;
21762       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
21763           CS->getZExtValue() == 1)
21764         OpIdx = 0;
21765       if (OpIdx == -1)
21766         break;
21767       SetCC = SetCC.getOperand(OpIdx);
21768       truncatedToBoolWithAnd = true;
21769     } else
21770       SetCC = SetCC.getOperand(0);
21771   }
21772
21773   switch (SetCC.getOpcode()) {
21774   case X86ISD::SETCC_CARRY:
21775     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
21776     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
21777     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
21778     // truncated to i1 using 'and'.
21779     if (checkAgainstTrue && !truncatedToBoolWithAnd)
21780       break;
21781     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
21782            "Invalid use of SETCC_CARRY!");
21783     // FALL THROUGH
21784   case X86ISD::SETCC:
21785     // Set the condition code or opposite one if necessary.
21786     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
21787     if (needOppositeCond)
21788       CC = X86::GetOppositeBranchCondition(CC);
21789     return SetCC.getOperand(1);
21790   case X86ISD::CMOV: {
21791     // Check whether false/true value has canonical one, i.e. 0 or 1.
21792     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
21793     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
21794     // Quit if true value is not a constant.
21795     if (!TVal)
21796       return SDValue();
21797     // Quit if false value is not a constant.
21798     if (!FVal) {
21799       SDValue Op = SetCC.getOperand(0);
21800       // Skip 'zext' or 'trunc' node.
21801       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
21802           Op.getOpcode() == ISD::TRUNCATE)
21803         Op = Op.getOperand(0);
21804       // A special case for rdrand/rdseed, where 0 is set if false cond is
21805       // found.
21806       if ((Op.getOpcode() != X86ISD::RDRAND &&
21807            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
21808         return SDValue();
21809     }
21810     // Quit if false value is not the constant 0 or 1.
21811     bool FValIsFalse = true;
21812     if (FVal && FVal->getZExtValue() != 0) {
21813       if (FVal->getZExtValue() != 1)
21814         return SDValue();
21815       // If FVal is 1, opposite cond is needed.
21816       needOppositeCond = !needOppositeCond;
21817       FValIsFalse = false;
21818     }
21819     // Quit if TVal is not the constant opposite of FVal.
21820     if (FValIsFalse && TVal->getZExtValue() != 1)
21821       return SDValue();
21822     if (!FValIsFalse && TVal->getZExtValue() != 0)
21823       return SDValue();
21824     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
21825     if (needOppositeCond)
21826       CC = X86::GetOppositeBranchCondition(CC);
21827     return SetCC.getOperand(3);
21828   }
21829   }
21830
21831   return SDValue();
21832 }
21833
21834 /// Check whether Cond is an AND/OR of SETCCs off of the same EFLAGS.
21835 /// Match:
21836 ///   (X86or (X86setcc) (X86setcc))
21837 ///   (X86cmp (and (X86setcc) (X86setcc)), 0)
21838 static bool checkBoolTestAndOrSetCCCombine(SDValue Cond, X86::CondCode &CC0,
21839                                            X86::CondCode &CC1, SDValue &Flags,
21840                                            bool &isAnd) {
21841   if (Cond->getOpcode() == X86ISD::CMP) {
21842     ConstantSDNode *CondOp1C = dyn_cast<ConstantSDNode>(Cond->getOperand(1));
21843     if (!CondOp1C || !CondOp1C->isNullValue())
21844       return false;
21845
21846     Cond = Cond->getOperand(0);
21847   }
21848
21849   isAnd = false;
21850
21851   SDValue SetCC0, SetCC1;
21852   switch (Cond->getOpcode()) {
21853   default: return false;
21854   case ISD::AND:
21855   case X86ISD::AND:
21856     isAnd = true;
21857     // fallthru
21858   case ISD::OR:
21859   case X86ISD::OR:
21860     SetCC0 = Cond->getOperand(0);
21861     SetCC1 = Cond->getOperand(1);
21862     break;
21863   };
21864
21865   // Make sure we have SETCC nodes, using the same flags value.
21866   if (SetCC0.getOpcode() != X86ISD::SETCC ||
21867       SetCC1.getOpcode() != X86ISD::SETCC ||
21868       SetCC0->getOperand(1) != SetCC1->getOperand(1))
21869     return false;
21870
21871   CC0 = (X86::CondCode)SetCC0->getConstantOperandVal(0);
21872   CC1 = (X86::CondCode)SetCC1->getConstantOperandVal(0);
21873   Flags = SetCC0->getOperand(1);
21874   return true;
21875 }
21876
21877 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
21878 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
21879                                   TargetLowering::DAGCombinerInfo &DCI,
21880                                   const X86Subtarget *Subtarget) {
21881   SDLoc DL(N);
21882
21883   // If the flag operand isn't dead, don't touch this CMOV.
21884   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
21885     return SDValue();
21886
21887   SDValue FalseOp = N->getOperand(0);
21888   SDValue TrueOp = N->getOperand(1);
21889   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
21890   SDValue Cond = N->getOperand(3);
21891
21892   if (CC == X86::COND_E || CC == X86::COND_NE) {
21893     switch (Cond.getOpcode()) {
21894     default: break;
21895     case X86ISD::BSR:
21896     case X86ISD::BSF:
21897       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
21898       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
21899         return (CC == X86::COND_E) ? FalseOp : TrueOp;
21900     }
21901   }
21902
21903   SDValue Flags;
21904
21905   Flags = checkBoolTestSetCCCombine(Cond, CC);
21906   if (Flags.getNode() &&
21907       // Extra check as FCMOV only supports a subset of X86 cond.
21908       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
21909     SDValue Ops[] = { FalseOp, TrueOp,
21910                       DAG.getConstant(CC, DL, MVT::i8), Flags };
21911     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
21912   }
21913
21914   // If this is a select between two integer constants, try to do some
21915   // optimizations.  Note that the operands are ordered the opposite of SELECT
21916   // operands.
21917   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
21918     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
21919       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
21920       // larger than FalseC (the false value).
21921       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
21922         CC = X86::GetOppositeBranchCondition(CC);
21923         std::swap(TrueC, FalseC);
21924         std::swap(TrueOp, FalseOp);
21925       }
21926
21927       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
21928       // This is efficient for any integer data type (including i8/i16) and
21929       // shift amount.
21930       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
21931         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
21932                            DAG.getConstant(CC, DL, MVT::i8), Cond);
21933
21934         // Zero extend the condition if needed.
21935         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
21936
21937         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
21938         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
21939                            DAG.getConstant(ShAmt, DL, MVT::i8));
21940         if (N->getNumValues() == 2)  // Dead flag value?
21941           return DCI.CombineTo(N, Cond, SDValue());
21942         return Cond;
21943       }
21944
21945       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
21946       // for any integer data type, including i8/i16.
21947       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
21948         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
21949                            DAG.getConstant(CC, DL, MVT::i8), Cond);
21950
21951         // Zero extend the condition if needed.
21952         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
21953                            FalseC->getValueType(0), Cond);
21954         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
21955                            SDValue(FalseC, 0));
21956
21957         if (N->getNumValues() == 2)  // Dead flag value?
21958           return DCI.CombineTo(N, Cond, SDValue());
21959         return Cond;
21960       }
21961
21962       // Optimize cases that will turn into an LEA instruction.  This requires
21963       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
21964       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
21965         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
21966         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
21967
21968         bool isFastMultiplier = false;
21969         if (Diff < 10) {
21970           switch ((unsigned char)Diff) {
21971           default: break;
21972           case 1:  // result = add base, cond
21973           case 2:  // result = lea base(    , cond*2)
21974           case 3:  // result = lea base(cond, cond*2)
21975           case 4:  // result = lea base(    , cond*4)
21976           case 5:  // result = lea base(cond, cond*4)
21977           case 8:  // result = lea base(    , cond*8)
21978           case 9:  // result = lea base(cond, cond*8)
21979             isFastMultiplier = true;
21980             break;
21981           }
21982         }
21983
21984         if (isFastMultiplier) {
21985           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
21986           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
21987                              DAG.getConstant(CC, DL, MVT::i8), Cond);
21988           // Zero extend the condition if needed.
21989           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
21990                              Cond);
21991           // Scale the condition by the difference.
21992           if (Diff != 1)
21993             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
21994                                DAG.getConstant(Diff, DL, Cond.getValueType()));
21995
21996           // Add the base if non-zero.
21997           if (FalseC->getAPIntValue() != 0)
21998             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
21999                                SDValue(FalseC, 0));
22000           if (N->getNumValues() == 2)  // Dead flag value?
22001             return DCI.CombineTo(N, Cond, SDValue());
22002           return Cond;
22003         }
22004       }
22005     }
22006   }
22007
22008   // Handle these cases:
22009   //   (select (x != c), e, c) -> select (x != c), e, x),
22010   //   (select (x == c), c, e) -> select (x == c), x, e)
22011   // where the c is an integer constant, and the "select" is the combination
22012   // of CMOV and CMP.
22013   //
22014   // The rationale for this change is that the conditional-move from a constant
22015   // needs two instructions, however, conditional-move from a register needs
22016   // only one instruction.
22017   //
22018   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
22019   //  some instruction-combining opportunities. This opt needs to be
22020   //  postponed as late as possible.
22021   //
22022   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
22023     // the DCI.xxxx conditions are provided to postpone the optimization as
22024     // late as possible.
22025
22026     ConstantSDNode *CmpAgainst = nullptr;
22027     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
22028         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
22029         !isa<ConstantSDNode>(Cond.getOperand(0))) {
22030
22031       if (CC == X86::COND_NE &&
22032           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
22033         CC = X86::GetOppositeBranchCondition(CC);
22034         std::swap(TrueOp, FalseOp);
22035       }
22036
22037       if (CC == X86::COND_E &&
22038           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
22039         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
22040                           DAG.getConstant(CC, DL, MVT::i8), Cond };
22041         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
22042       }
22043     }
22044   }
22045
22046   // Fold and/or of setcc's to double CMOV:
22047   //   (CMOV F, T, ((cc1 | cc2) != 0)) -> (CMOV (CMOV F, T, cc1), T, cc2)
22048   //   (CMOV F, T, ((cc1 & cc2) != 0)) -> (CMOV (CMOV T, F, !cc1), F, !cc2)
22049   //
22050   // This combine lets us generate:
22051   //   cmovcc1 (jcc1 if we don't have CMOV)
22052   //   cmovcc2 (same)
22053   // instead of:
22054   //   setcc1
22055   //   setcc2
22056   //   and/or
22057   //   cmovne (jne if we don't have CMOV)
22058   // When we can't use the CMOV instruction, it might increase branch
22059   // mispredicts.
22060   // When we can use CMOV, or when there is no mispredict, this improves
22061   // throughput and reduces register pressure.
22062   //
22063   if (CC == X86::COND_NE) {
22064     SDValue Flags;
22065     X86::CondCode CC0, CC1;
22066     bool isAndSetCC;
22067     if (checkBoolTestAndOrSetCCCombine(Cond, CC0, CC1, Flags, isAndSetCC)) {
22068       if (isAndSetCC) {
22069         std::swap(FalseOp, TrueOp);
22070         CC0 = X86::GetOppositeBranchCondition(CC0);
22071         CC1 = X86::GetOppositeBranchCondition(CC1);
22072       }
22073
22074       SDValue LOps[] = {FalseOp, TrueOp, DAG.getConstant(CC0, DL, MVT::i8),
22075         Flags};
22076       SDValue LCMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), LOps);
22077       SDValue Ops[] = {LCMOV, TrueOp, DAG.getConstant(CC1, DL, MVT::i8), Flags};
22078       SDValue CMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
22079       DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SDValue(CMOV.getNode(), 1));
22080       return CMOV;
22081     }
22082   }
22083
22084   return SDValue();
22085 }
22086
22087 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
22088                                                 const X86Subtarget *Subtarget) {
22089   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
22090   switch (IntNo) {
22091   default: return SDValue();
22092   // SSE/AVX/AVX2 blend intrinsics.
22093   case Intrinsic::x86_avx2_pblendvb:
22094     // Don't try to simplify this intrinsic if we don't have AVX2.
22095     if (!Subtarget->hasAVX2())
22096       return SDValue();
22097     // FALL-THROUGH
22098   case Intrinsic::x86_avx_blendv_pd_256:
22099   case Intrinsic::x86_avx_blendv_ps_256:
22100     // Don't try to simplify this intrinsic if we don't have AVX.
22101     if (!Subtarget->hasAVX())
22102       return SDValue();
22103     // FALL-THROUGH
22104   case Intrinsic::x86_sse41_blendvps:
22105   case Intrinsic::x86_sse41_blendvpd:
22106   case Intrinsic::x86_sse41_pblendvb: {
22107     SDValue Op0 = N->getOperand(1);
22108     SDValue Op1 = N->getOperand(2);
22109     SDValue Mask = N->getOperand(3);
22110
22111     // Don't try to simplify this intrinsic if we don't have SSE4.1.
22112     if (!Subtarget->hasSSE41())
22113       return SDValue();
22114
22115     // fold (blend A, A, Mask) -> A
22116     if (Op0 == Op1)
22117       return Op0;
22118     // fold (blend A, B, allZeros) -> A
22119     if (ISD::isBuildVectorAllZeros(Mask.getNode()))
22120       return Op0;
22121     // fold (blend A, B, allOnes) -> B
22122     if (ISD::isBuildVectorAllOnes(Mask.getNode()))
22123       return Op1;
22124
22125     // Simplify the case where the mask is a constant i32 value.
22126     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
22127       if (C->isNullValue())
22128         return Op0;
22129       if (C->isAllOnesValue())
22130         return Op1;
22131     }
22132
22133     return SDValue();
22134   }
22135
22136   // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
22137   case Intrinsic::x86_sse2_psrai_w:
22138   case Intrinsic::x86_sse2_psrai_d:
22139   case Intrinsic::x86_avx2_psrai_w:
22140   case Intrinsic::x86_avx2_psrai_d:
22141   case Intrinsic::x86_sse2_psra_w:
22142   case Intrinsic::x86_sse2_psra_d:
22143   case Intrinsic::x86_avx2_psra_w:
22144   case Intrinsic::x86_avx2_psra_d: {
22145     SDValue Op0 = N->getOperand(1);
22146     SDValue Op1 = N->getOperand(2);
22147     EVT VT = Op0.getValueType();
22148     assert(VT.isVector() && "Expected a vector type!");
22149
22150     if (isa<BuildVectorSDNode>(Op1))
22151       Op1 = Op1.getOperand(0);
22152
22153     if (!isa<ConstantSDNode>(Op1))
22154       return SDValue();
22155
22156     EVT SVT = VT.getVectorElementType();
22157     unsigned SVTBits = SVT.getSizeInBits();
22158
22159     ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
22160     const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
22161     uint64_t ShAmt = C.getZExtValue();
22162
22163     // Don't try to convert this shift into a ISD::SRA if the shift
22164     // count is bigger than or equal to the element size.
22165     if (ShAmt >= SVTBits)
22166       return SDValue();
22167
22168     // Trivial case: if the shift count is zero, then fold this
22169     // into the first operand.
22170     if (ShAmt == 0)
22171       return Op0;
22172
22173     // Replace this packed shift intrinsic with a target independent
22174     // shift dag node.
22175     SDLoc DL(N);
22176     SDValue Splat = DAG.getConstant(C, DL, VT);
22177     return DAG.getNode(ISD::SRA, DL, VT, Op0, Splat);
22178   }
22179   }
22180 }
22181
22182 /// PerformMulCombine - Optimize a single multiply with constant into two
22183 /// in order to implement it with two cheaper instructions, e.g.
22184 /// LEA + SHL, LEA + LEA.
22185 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
22186                                  TargetLowering::DAGCombinerInfo &DCI) {
22187   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
22188     return SDValue();
22189
22190   EVT VT = N->getValueType(0);
22191   if (VT != MVT::i64 && VT != MVT::i32)
22192     return SDValue();
22193
22194   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
22195   if (!C)
22196     return SDValue();
22197   uint64_t MulAmt = C->getZExtValue();
22198   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
22199     return SDValue();
22200
22201   uint64_t MulAmt1 = 0;
22202   uint64_t MulAmt2 = 0;
22203   if ((MulAmt % 9) == 0) {
22204     MulAmt1 = 9;
22205     MulAmt2 = MulAmt / 9;
22206   } else if ((MulAmt % 5) == 0) {
22207     MulAmt1 = 5;
22208     MulAmt2 = MulAmt / 5;
22209   } else if ((MulAmt % 3) == 0) {
22210     MulAmt1 = 3;
22211     MulAmt2 = MulAmt / 3;
22212   }
22213   if (MulAmt2 &&
22214       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
22215     SDLoc DL(N);
22216
22217     if (isPowerOf2_64(MulAmt2) &&
22218         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
22219       // If second multiplifer is pow2, issue it first. We want the multiply by
22220       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
22221       // is an add.
22222       std::swap(MulAmt1, MulAmt2);
22223
22224     SDValue NewMul;
22225     if (isPowerOf2_64(MulAmt1))
22226       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
22227                            DAG.getConstant(Log2_64(MulAmt1), DL, MVT::i8));
22228     else
22229       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
22230                            DAG.getConstant(MulAmt1, DL, VT));
22231
22232     if (isPowerOf2_64(MulAmt2))
22233       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
22234                            DAG.getConstant(Log2_64(MulAmt2), DL, MVT::i8));
22235     else
22236       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
22237                            DAG.getConstant(MulAmt2, DL, VT));
22238
22239     // Do not add new nodes to DAG combiner worklist.
22240     DCI.CombineTo(N, NewMul, false);
22241   }
22242   return SDValue();
22243 }
22244
22245 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
22246   SDValue N0 = N->getOperand(0);
22247   SDValue N1 = N->getOperand(1);
22248   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
22249   EVT VT = N0.getValueType();
22250
22251   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
22252   // since the result of setcc_c is all zero's or all ones.
22253   if (VT.isInteger() && !VT.isVector() &&
22254       N1C && N0.getOpcode() == ISD::AND &&
22255       N0.getOperand(1).getOpcode() == ISD::Constant) {
22256     SDValue N00 = N0.getOperand(0);
22257     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
22258         ((N00.getOpcode() == ISD::ANY_EXTEND ||
22259           N00.getOpcode() == ISD::ZERO_EXTEND) &&
22260          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
22261       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
22262       APInt ShAmt = N1C->getAPIntValue();
22263       Mask = Mask.shl(ShAmt);
22264       if (Mask != 0) {
22265         SDLoc DL(N);
22266         return DAG.getNode(ISD::AND, DL, VT,
22267                            N00, DAG.getConstant(Mask, DL, VT));
22268       }
22269     }
22270   }
22271
22272   // Hardware support for vector shifts is sparse which makes us scalarize the
22273   // vector operations in many cases. Also, on sandybridge ADD is faster than
22274   // shl.
22275   // (shl V, 1) -> add V,V
22276   if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
22277     if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
22278       assert(N0.getValueType().isVector() && "Invalid vector shift type");
22279       // We shift all of the values by one. In many cases we do not have
22280       // hardware support for this operation. This is better expressed as an ADD
22281       // of two values.
22282       if (N1SplatC->getZExtValue() == 1)
22283         return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
22284     }
22285
22286   return SDValue();
22287 }
22288
22289 /// \brief Returns a vector of 0s if the node in input is a vector logical
22290 /// shift by a constant amount which is known to be bigger than or equal
22291 /// to the vector element size in bits.
22292 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
22293                                       const X86Subtarget *Subtarget) {
22294   EVT VT = N->getValueType(0);
22295
22296   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
22297       (!Subtarget->hasInt256() ||
22298        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
22299     return SDValue();
22300
22301   SDValue Amt = N->getOperand(1);
22302   SDLoc DL(N);
22303   if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
22304     if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
22305       APInt ShiftAmt = AmtSplat->getAPIntValue();
22306       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
22307
22308       // SSE2/AVX2 logical shifts always return a vector of 0s
22309       // if the shift amount is bigger than or equal to
22310       // the element size. The constant shift amount will be
22311       // encoded as a 8-bit immediate.
22312       if (ShiftAmt.trunc(8).uge(MaxAmount))
22313         return getZeroVector(VT, Subtarget, DAG, DL);
22314     }
22315
22316   return SDValue();
22317 }
22318
22319 /// PerformShiftCombine - Combine shifts.
22320 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
22321                                    TargetLowering::DAGCombinerInfo &DCI,
22322                                    const X86Subtarget *Subtarget) {
22323   if (N->getOpcode() == ISD::SHL) {
22324     SDValue V = PerformSHLCombine(N, DAG);
22325     if (V.getNode()) return V;
22326   }
22327
22328   if (N->getOpcode() != ISD::SRA) {
22329     // Try to fold this logical shift into a zero vector.
22330     SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
22331     if (V.getNode()) return V;
22332   }
22333
22334   return SDValue();
22335 }
22336
22337 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
22338 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
22339 // and friends.  Likewise for OR -> CMPNEQSS.
22340 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
22341                             TargetLowering::DAGCombinerInfo &DCI,
22342                             const X86Subtarget *Subtarget) {
22343   unsigned opcode;
22344
22345   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
22346   // we're requiring SSE2 for both.
22347   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
22348     SDValue N0 = N->getOperand(0);
22349     SDValue N1 = N->getOperand(1);
22350     SDValue CMP0 = N0->getOperand(1);
22351     SDValue CMP1 = N1->getOperand(1);
22352     SDLoc DL(N);
22353
22354     // The SETCCs should both refer to the same CMP.
22355     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
22356       return SDValue();
22357
22358     SDValue CMP00 = CMP0->getOperand(0);
22359     SDValue CMP01 = CMP0->getOperand(1);
22360     EVT     VT    = CMP00.getValueType();
22361
22362     if (VT == MVT::f32 || VT == MVT::f64) {
22363       bool ExpectingFlags = false;
22364       // Check for any users that want flags:
22365       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
22366            !ExpectingFlags && UI != UE; ++UI)
22367         switch (UI->getOpcode()) {
22368         default:
22369         case ISD::BR_CC:
22370         case ISD::BRCOND:
22371         case ISD::SELECT:
22372           ExpectingFlags = true;
22373           break;
22374         case ISD::CopyToReg:
22375         case ISD::SIGN_EXTEND:
22376         case ISD::ZERO_EXTEND:
22377         case ISD::ANY_EXTEND:
22378           break;
22379         }
22380
22381       if (!ExpectingFlags) {
22382         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
22383         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
22384
22385         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
22386           X86::CondCode tmp = cc0;
22387           cc0 = cc1;
22388           cc1 = tmp;
22389         }
22390
22391         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
22392             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
22393           // FIXME: need symbolic constants for these magic numbers.
22394           // See X86ATTInstPrinter.cpp:printSSECC().
22395           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
22396           if (Subtarget->hasAVX512()) {
22397             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
22398                                          CMP01,
22399                                          DAG.getConstant(x86cc, DL, MVT::i8));
22400             if (N->getValueType(0) != MVT::i1)
22401               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
22402                                  FSetCC);
22403             return FSetCC;
22404           }
22405           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
22406                                               CMP00.getValueType(), CMP00, CMP01,
22407                                               DAG.getConstant(x86cc, DL,
22408                                                               MVT::i8));
22409
22410           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
22411           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
22412
22413           if (is64BitFP && !Subtarget->is64Bit()) {
22414             // On a 32-bit target, we cannot bitcast the 64-bit float to a
22415             // 64-bit integer, since that's not a legal type. Since
22416             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
22417             // bits, but can do this little dance to extract the lowest 32 bits
22418             // and work with those going forward.
22419             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
22420                                            OnesOrZeroesF);
22421             SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
22422                                            Vector64);
22423             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
22424                                         Vector32, DAG.getIntPtrConstant(0, DL));
22425             IntVT = MVT::i32;
22426           }
22427
22428           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT,
22429                                               OnesOrZeroesF);
22430           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
22431                                       DAG.getConstant(1, DL, IntVT));
22432           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8,
22433                                               ANDed);
22434           return OneBitOfTruth;
22435         }
22436       }
22437     }
22438   }
22439   return SDValue();
22440 }
22441
22442 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
22443 /// so it can be folded inside ANDNP.
22444 static bool CanFoldXORWithAllOnes(const SDNode *N) {
22445   EVT VT = N->getValueType(0);
22446
22447   // Match direct AllOnes for 128 and 256-bit vectors
22448   if (ISD::isBuildVectorAllOnes(N))
22449     return true;
22450
22451   // Look through a bit convert.
22452   if (N->getOpcode() == ISD::BITCAST)
22453     N = N->getOperand(0).getNode();
22454
22455   // Sometimes the operand may come from a insert_subvector building a 256-bit
22456   // allones vector
22457   if (VT.is256BitVector() &&
22458       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
22459     SDValue V1 = N->getOperand(0);
22460     SDValue V2 = N->getOperand(1);
22461
22462     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
22463         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
22464         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
22465         ISD::isBuildVectorAllOnes(V2.getNode()))
22466       return true;
22467   }
22468
22469   return false;
22470 }
22471
22472 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
22473 // register. In most cases we actually compare or select YMM-sized registers
22474 // and mixing the two types creates horrible code. This method optimizes
22475 // some of the transition sequences.
22476 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
22477                                  TargetLowering::DAGCombinerInfo &DCI,
22478                                  const X86Subtarget *Subtarget) {
22479   EVT VT = N->getValueType(0);
22480   if (!VT.is256BitVector())
22481     return SDValue();
22482
22483   assert((N->getOpcode() == ISD::ANY_EXTEND ||
22484           N->getOpcode() == ISD::ZERO_EXTEND ||
22485           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
22486
22487   SDValue Narrow = N->getOperand(0);
22488   EVT NarrowVT = Narrow->getValueType(0);
22489   if (!NarrowVT.is128BitVector())
22490     return SDValue();
22491
22492   if (Narrow->getOpcode() != ISD::XOR &&
22493       Narrow->getOpcode() != ISD::AND &&
22494       Narrow->getOpcode() != ISD::OR)
22495     return SDValue();
22496
22497   SDValue N0  = Narrow->getOperand(0);
22498   SDValue N1  = Narrow->getOperand(1);
22499   SDLoc DL(Narrow);
22500
22501   // The Left side has to be a trunc.
22502   if (N0.getOpcode() != ISD::TRUNCATE)
22503     return SDValue();
22504
22505   // The type of the truncated inputs.
22506   EVT WideVT = N0->getOperand(0)->getValueType(0);
22507   if (WideVT != VT)
22508     return SDValue();
22509
22510   // The right side has to be a 'trunc' or a constant vector.
22511   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
22512   ConstantSDNode *RHSConstSplat = nullptr;
22513   if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
22514     RHSConstSplat = RHSBV->getConstantSplatNode();
22515   if (!RHSTrunc && !RHSConstSplat)
22516     return SDValue();
22517
22518   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22519
22520   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
22521     return SDValue();
22522
22523   // Set N0 and N1 to hold the inputs to the new wide operation.
22524   N0 = N0->getOperand(0);
22525   if (RHSConstSplat) {
22526     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
22527                      SDValue(RHSConstSplat, 0));
22528     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
22529     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
22530   } else if (RHSTrunc) {
22531     N1 = N1->getOperand(0);
22532   }
22533
22534   // Generate the wide operation.
22535   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
22536   unsigned Opcode = N->getOpcode();
22537   switch (Opcode) {
22538   case ISD::ANY_EXTEND:
22539     return Op;
22540   case ISD::ZERO_EXTEND: {
22541     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
22542     APInt Mask = APInt::getAllOnesValue(InBits);
22543     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
22544     return DAG.getNode(ISD::AND, DL, VT,
22545                        Op, DAG.getConstant(Mask, DL, VT));
22546   }
22547   case ISD::SIGN_EXTEND:
22548     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
22549                        Op, DAG.getValueType(NarrowVT));
22550   default:
22551     llvm_unreachable("Unexpected opcode");
22552   }
22553 }
22554
22555 static SDValue VectorZextCombine(SDNode *N, SelectionDAG &DAG,
22556                                  TargetLowering::DAGCombinerInfo &DCI,
22557                                  const X86Subtarget *Subtarget) {
22558   SDValue N0 = N->getOperand(0);
22559   SDValue N1 = N->getOperand(1);
22560   SDLoc DL(N);
22561
22562   // A vector zext_in_reg may be represented as a shuffle,
22563   // feeding into a bitcast (this represents anyext) feeding into
22564   // an and with a mask.
22565   // We'd like to try to combine that into a shuffle with zero
22566   // plus a bitcast, removing the and.
22567   if (N0.getOpcode() != ISD::BITCAST ||
22568       N0.getOperand(0).getOpcode() != ISD::VECTOR_SHUFFLE)
22569     return SDValue();
22570
22571   // The other side of the AND should be a splat of 2^C, where C
22572   // is the number of bits in the source type.
22573   if (N1.getOpcode() == ISD::BITCAST)
22574     N1 = N1.getOperand(0);
22575   if (N1.getOpcode() != ISD::BUILD_VECTOR)
22576     return SDValue();
22577   BuildVectorSDNode *Vector = cast<BuildVectorSDNode>(N1);
22578
22579   ShuffleVectorSDNode *Shuffle = cast<ShuffleVectorSDNode>(N0.getOperand(0));
22580   EVT SrcType = Shuffle->getValueType(0);
22581
22582   // We expect a single-source shuffle
22583   if (Shuffle->getOperand(1)->getOpcode() != ISD::UNDEF)
22584     return SDValue();
22585
22586   unsigned SrcSize = SrcType.getScalarSizeInBits();
22587
22588   APInt SplatValue, SplatUndef;
22589   unsigned SplatBitSize;
22590   bool HasAnyUndefs;
22591   if (!Vector->isConstantSplat(SplatValue, SplatUndef,
22592                                 SplatBitSize, HasAnyUndefs))
22593     return SDValue();
22594
22595   unsigned ResSize = N1.getValueType().getScalarSizeInBits();
22596   // Make sure the splat matches the mask we expect
22597   if (SplatBitSize > ResSize ||
22598       (SplatValue + 1).exactLogBase2() != (int)SrcSize)
22599     return SDValue();
22600
22601   // Make sure the input and output size make sense
22602   if (SrcSize >= ResSize || ResSize % SrcSize)
22603     return SDValue();
22604
22605   // We expect a shuffle of the form <0, u, u, u, 1, u, u, u...>
22606   // The number of u's between each two values depends on the ratio between
22607   // the source and dest type.
22608   unsigned ZextRatio = ResSize / SrcSize;
22609   bool IsZext = true;
22610   for (unsigned i = 0; i < SrcType.getVectorNumElements(); ++i) {
22611     if (i % ZextRatio) {
22612       if (Shuffle->getMaskElt(i) > 0) {
22613         // Expected undef
22614         IsZext = false;
22615         break;
22616       }
22617     } else {
22618       if (Shuffle->getMaskElt(i) != (int)(i / ZextRatio)) {
22619         // Expected element number
22620         IsZext = false;
22621         break;
22622       }
22623     }
22624   }
22625
22626   if (!IsZext)
22627     return SDValue();
22628
22629   // Ok, perform the transformation - replace the shuffle with
22630   // a shuffle of the form <0, k, k, k, 1, k, k, k> with zero
22631   // (instead of undef) where the k elements come from the zero vector.
22632   SmallVector<int, 8> Mask;
22633   unsigned NumElems = SrcType.getVectorNumElements();
22634   for (unsigned i = 0; i < NumElems; ++i)
22635     if (i % ZextRatio)
22636       Mask.push_back(NumElems);
22637     else
22638       Mask.push_back(i / ZextRatio);
22639
22640   SDValue NewShuffle = DAG.getVectorShuffle(Shuffle->getValueType(0), DL,
22641     Shuffle->getOperand(0), DAG.getConstant(0, DL, SrcType), Mask);
22642   return DAG.getNode(ISD::BITCAST, DL, N0.getValueType(), NewShuffle);
22643 }
22644
22645 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
22646                                  TargetLowering::DAGCombinerInfo &DCI,
22647                                  const X86Subtarget *Subtarget) {
22648   if (DCI.isBeforeLegalizeOps())
22649     return SDValue();
22650
22651   if (SDValue Zext = VectorZextCombine(N, DAG, DCI, Subtarget))
22652     return Zext;
22653
22654   if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
22655     return R;
22656
22657   EVT VT = N->getValueType(0);
22658   SDValue N0 = N->getOperand(0);
22659   SDValue N1 = N->getOperand(1);
22660   SDLoc DL(N);
22661
22662   // Create BEXTR instructions
22663   // BEXTR is ((X >> imm) & (2**size-1))
22664   if (VT == MVT::i32 || VT == MVT::i64) {
22665     // Check for BEXTR.
22666     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
22667         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
22668       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
22669       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
22670       if (MaskNode && ShiftNode) {
22671         uint64_t Mask = MaskNode->getZExtValue();
22672         uint64_t Shift = ShiftNode->getZExtValue();
22673         if (isMask_64(Mask)) {
22674           uint64_t MaskSize = countPopulation(Mask);
22675           if (Shift + MaskSize <= VT.getSizeInBits())
22676             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
22677                                DAG.getConstant(Shift | (MaskSize << 8), DL,
22678                                                VT));
22679         }
22680       }
22681     } // BEXTR
22682
22683     return SDValue();
22684   }
22685
22686   // Want to form ANDNP nodes:
22687   // 1) In the hopes of then easily combining them with OR and AND nodes
22688   //    to form PBLEND/PSIGN.
22689   // 2) To match ANDN packed intrinsics
22690   if (VT != MVT::v2i64 && VT != MVT::v4i64)
22691     return SDValue();
22692
22693   // Check LHS for vnot
22694   if (N0.getOpcode() == ISD::XOR &&
22695       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
22696       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
22697     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
22698
22699   // Check RHS for vnot
22700   if (N1.getOpcode() == ISD::XOR &&
22701       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
22702       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
22703     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
22704
22705   return SDValue();
22706 }
22707
22708 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
22709                                 TargetLowering::DAGCombinerInfo &DCI,
22710                                 const X86Subtarget *Subtarget) {
22711   if (DCI.isBeforeLegalizeOps())
22712     return SDValue();
22713
22714   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
22715   if (R.getNode())
22716     return R;
22717
22718   SDValue N0 = N->getOperand(0);
22719   SDValue N1 = N->getOperand(1);
22720   EVT VT = N->getValueType(0);
22721
22722   // look for psign/blend
22723   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
22724     if (!Subtarget->hasSSSE3() ||
22725         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
22726       return SDValue();
22727
22728     // Canonicalize pandn to RHS
22729     if (N0.getOpcode() == X86ISD::ANDNP)
22730       std::swap(N0, N1);
22731     // or (and (m, y), (pandn m, x))
22732     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
22733       SDValue Mask = N1.getOperand(0);
22734       SDValue X    = N1.getOperand(1);
22735       SDValue Y;
22736       if (N0.getOperand(0) == Mask)
22737         Y = N0.getOperand(1);
22738       if (N0.getOperand(1) == Mask)
22739         Y = N0.getOperand(0);
22740
22741       // Check to see if the mask appeared in both the AND and ANDNP and
22742       if (!Y.getNode())
22743         return SDValue();
22744
22745       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
22746       // Look through mask bitcast.
22747       if (Mask.getOpcode() == ISD::BITCAST)
22748         Mask = Mask.getOperand(0);
22749       if (X.getOpcode() == ISD::BITCAST)
22750         X = X.getOperand(0);
22751       if (Y.getOpcode() == ISD::BITCAST)
22752         Y = Y.getOperand(0);
22753
22754       EVT MaskVT = Mask.getValueType();
22755
22756       // Validate that the Mask operand is a vector sra node.
22757       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
22758       // there is no psrai.b
22759       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
22760       unsigned SraAmt = ~0;
22761       if (Mask.getOpcode() == ISD::SRA) {
22762         if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
22763           if (auto *AmtConst = AmtBV->getConstantSplatNode())
22764             SraAmt = AmtConst->getZExtValue();
22765       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
22766         SDValue SraC = Mask.getOperand(1);
22767         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
22768       }
22769       if ((SraAmt + 1) != EltBits)
22770         return SDValue();
22771
22772       SDLoc DL(N);
22773
22774       // Now we know we at least have a plendvb with the mask val.  See if
22775       // we can form a psignb/w/d.
22776       // psign = x.type == y.type == mask.type && y = sub(0, x);
22777       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
22778           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
22779           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
22780         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
22781                "Unsupported VT for PSIGN");
22782         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
22783         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
22784       }
22785       // PBLENDVB only available on SSE 4.1
22786       if (!Subtarget->hasSSE41())
22787         return SDValue();
22788
22789       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
22790
22791       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
22792       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
22793       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
22794       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
22795       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
22796     }
22797   }
22798
22799   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
22800     return SDValue();
22801
22802   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
22803   MachineFunction &MF = DAG.getMachineFunction();
22804   bool OptForSize =
22805       MF.getFunction()->hasFnAttribute(Attribute::OptimizeForSize);
22806
22807   // SHLD/SHRD instructions have lower register pressure, but on some
22808   // platforms they have higher latency than the equivalent
22809   // series of shifts/or that would otherwise be generated.
22810   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
22811   // have higher latencies and we are not optimizing for size.
22812   if (!OptForSize && Subtarget->isSHLDSlow())
22813     return SDValue();
22814
22815   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
22816     std::swap(N0, N1);
22817   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
22818     return SDValue();
22819   if (!N0.hasOneUse() || !N1.hasOneUse())
22820     return SDValue();
22821
22822   SDValue ShAmt0 = N0.getOperand(1);
22823   if (ShAmt0.getValueType() != MVT::i8)
22824     return SDValue();
22825   SDValue ShAmt1 = N1.getOperand(1);
22826   if (ShAmt1.getValueType() != MVT::i8)
22827     return SDValue();
22828   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
22829     ShAmt0 = ShAmt0.getOperand(0);
22830   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
22831     ShAmt1 = ShAmt1.getOperand(0);
22832
22833   SDLoc DL(N);
22834   unsigned Opc = X86ISD::SHLD;
22835   SDValue Op0 = N0.getOperand(0);
22836   SDValue Op1 = N1.getOperand(0);
22837   if (ShAmt0.getOpcode() == ISD::SUB) {
22838     Opc = X86ISD::SHRD;
22839     std::swap(Op0, Op1);
22840     std::swap(ShAmt0, ShAmt1);
22841   }
22842
22843   unsigned Bits = VT.getSizeInBits();
22844   if (ShAmt1.getOpcode() == ISD::SUB) {
22845     SDValue Sum = ShAmt1.getOperand(0);
22846     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
22847       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
22848       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
22849         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
22850       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
22851         return DAG.getNode(Opc, DL, VT,
22852                            Op0, Op1,
22853                            DAG.getNode(ISD::TRUNCATE, DL,
22854                                        MVT::i8, ShAmt0));
22855     }
22856   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
22857     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
22858     if (ShAmt0C &&
22859         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
22860       return DAG.getNode(Opc, DL, VT,
22861                          N0.getOperand(0), N1.getOperand(0),
22862                          DAG.getNode(ISD::TRUNCATE, DL,
22863                                        MVT::i8, ShAmt0));
22864   }
22865
22866   return SDValue();
22867 }
22868
22869 // Generate NEG and CMOV for integer abs.
22870 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
22871   EVT VT = N->getValueType(0);
22872
22873   // Since X86 does not have CMOV for 8-bit integer, we don't convert
22874   // 8-bit integer abs to NEG and CMOV.
22875   if (VT.isInteger() && VT.getSizeInBits() == 8)
22876     return SDValue();
22877
22878   SDValue N0 = N->getOperand(0);
22879   SDValue N1 = N->getOperand(1);
22880   SDLoc DL(N);
22881
22882   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
22883   // and change it to SUB and CMOV.
22884   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
22885       N0.getOpcode() == ISD::ADD &&
22886       N0.getOperand(1) == N1 &&
22887       N1.getOpcode() == ISD::SRA &&
22888       N1.getOperand(0) == N0.getOperand(0))
22889     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
22890       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
22891         // Generate SUB & CMOV.
22892         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
22893                                   DAG.getConstant(0, DL, VT), N0.getOperand(0));
22894
22895         SDValue Ops[] = { N0.getOperand(0), Neg,
22896                           DAG.getConstant(X86::COND_GE, DL, MVT::i8),
22897                           SDValue(Neg.getNode(), 1) };
22898         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
22899       }
22900   return SDValue();
22901 }
22902
22903 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
22904 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
22905                                  TargetLowering::DAGCombinerInfo &DCI,
22906                                  const X86Subtarget *Subtarget) {
22907   if (DCI.isBeforeLegalizeOps())
22908     return SDValue();
22909
22910   if (Subtarget->hasCMov()) {
22911     SDValue RV = performIntegerAbsCombine(N, DAG);
22912     if (RV.getNode())
22913       return RV;
22914   }
22915
22916   return SDValue();
22917 }
22918
22919 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
22920 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
22921                                   TargetLowering::DAGCombinerInfo &DCI,
22922                                   const X86Subtarget *Subtarget) {
22923   LoadSDNode *Ld = cast<LoadSDNode>(N);
22924   EVT RegVT = Ld->getValueType(0);
22925   EVT MemVT = Ld->getMemoryVT();
22926   SDLoc dl(Ld);
22927   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22928
22929   // For chips with slow 32-byte unaligned loads, break the 32-byte operation
22930   // into two 16-byte operations.
22931   ISD::LoadExtType Ext = Ld->getExtensionType();
22932   unsigned Alignment = Ld->getAlignment();
22933   bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
22934   if (RegVT.is256BitVector() && Subtarget->isUnalignedMem32Slow() &&
22935       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
22936     unsigned NumElems = RegVT.getVectorNumElements();
22937     if (NumElems < 2)
22938       return SDValue();
22939
22940     SDValue Ptr = Ld->getBasePtr();
22941     SDValue Increment = DAG.getConstant(16, dl, TLI.getPointerTy());
22942
22943     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
22944                                   NumElems/2);
22945     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
22946                                 Ld->getPointerInfo(), Ld->isVolatile(),
22947                                 Ld->isNonTemporal(), Ld->isInvariant(),
22948                                 Alignment);
22949     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
22950     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
22951                                 Ld->getPointerInfo(), Ld->isVolatile(),
22952                                 Ld->isNonTemporal(), Ld->isInvariant(),
22953                                 std::min(16U, Alignment));
22954     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
22955                              Load1.getValue(1),
22956                              Load2.getValue(1));
22957
22958     SDValue NewVec = DAG.getUNDEF(RegVT);
22959     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
22960     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
22961     return DCI.CombineTo(N, NewVec, TF, true);
22962   }
22963
22964   return SDValue();
22965 }
22966
22967 /// PerformMLOADCombine - Resolve extending loads
22968 static SDValue PerformMLOADCombine(SDNode *N, SelectionDAG &DAG,
22969                                    TargetLowering::DAGCombinerInfo &DCI,
22970                                    const X86Subtarget *Subtarget) {
22971   MaskedLoadSDNode *Mld = cast<MaskedLoadSDNode>(N);
22972   if (Mld->getExtensionType() != ISD::SEXTLOAD)
22973     return SDValue();
22974
22975   EVT VT = Mld->getValueType(0);
22976   unsigned NumElems = VT.getVectorNumElements();
22977   EVT LdVT = Mld->getMemoryVT();
22978   SDLoc dl(Mld);
22979
22980   assert(LdVT != VT && "Cannot extend to the same type");
22981   unsigned ToSz = VT.getVectorElementType().getSizeInBits();
22982   unsigned FromSz = LdVT.getVectorElementType().getSizeInBits();
22983   // From, To sizes and ElemCount must be pow of two
22984   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
22985     "Unexpected size for extending masked load");
22986
22987   unsigned SizeRatio  = ToSz / FromSz;
22988   assert(SizeRatio * NumElems * FromSz == VT.getSizeInBits());
22989
22990   // Create a type on which we perform the shuffle
22991   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
22992           LdVT.getScalarType(), NumElems*SizeRatio);
22993   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
22994
22995   // Convert Src0 value
22996   SDValue WideSrc0 = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mld->getSrc0());
22997   if (Mld->getSrc0().getOpcode() != ISD::UNDEF) {
22998     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
22999     for (unsigned i = 0; i != NumElems; ++i)
23000       ShuffleVec[i] = i * SizeRatio;
23001
23002     // Can't shuffle using an illegal type.
23003     assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
23004             && "WideVecVT should be legal");
23005     WideSrc0 = DAG.getVectorShuffle(WideVecVT, dl, WideSrc0,
23006                                     DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
23007   }
23008   // Prepare the new mask
23009   SDValue NewMask;
23010   SDValue Mask = Mld->getMask();
23011   if (Mask.getValueType() == VT) {
23012     // Mask and original value have the same type
23013     NewMask = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mask);
23014     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
23015     for (unsigned i = 0; i != NumElems; ++i)
23016       ShuffleVec[i] = i * SizeRatio;
23017     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
23018       ShuffleVec[i] = NumElems*SizeRatio;
23019     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
23020                                    DAG.getConstant(0, dl, WideVecVT),
23021                                    &ShuffleVec[0]);
23022   }
23023   else {
23024     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
23025     unsigned WidenNumElts = NumElems*SizeRatio;
23026     unsigned MaskNumElts = VT.getVectorNumElements();
23027     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
23028                                      WidenNumElts);
23029
23030     unsigned NumConcat = WidenNumElts / MaskNumElts;
23031     SmallVector<SDValue, 16> Ops(NumConcat);
23032     SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
23033     Ops[0] = Mask;
23034     for (unsigned i = 1; i != NumConcat; ++i)
23035       Ops[i] = ZeroVal;
23036
23037     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
23038   }
23039
23040   SDValue WideLd = DAG.getMaskedLoad(WideVecVT, dl, Mld->getChain(),
23041                                      Mld->getBasePtr(), NewMask, WideSrc0,
23042                                      Mld->getMemoryVT(), Mld->getMemOperand(),
23043                                      ISD::NON_EXTLOAD);
23044   SDValue NewVec = DAG.getNode(X86ISD::VSEXT, dl, VT, WideLd);
23045   return DCI.CombineTo(N, NewVec, WideLd.getValue(1), true);
23046
23047 }
23048 /// PerformMSTORECombine - Resolve truncating stores
23049 static SDValue PerformMSTORECombine(SDNode *N, SelectionDAG &DAG,
23050                                     const X86Subtarget *Subtarget) {
23051   MaskedStoreSDNode *Mst = cast<MaskedStoreSDNode>(N);
23052   if (!Mst->isTruncatingStore())
23053     return SDValue();
23054
23055   EVT VT = Mst->getValue().getValueType();
23056   unsigned NumElems = VT.getVectorNumElements();
23057   EVT StVT = Mst->getMemoryVT();
23058   SDLoc dl(Mst);
23059
23060   assert(StVT != VT && "Cannot truncate to the same type");
23061   unsigned FromSz = VT.getVectorElementType().getSizeInBits();
23062   unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
23063
23064   // From, To sizes and ElemCount must be pow of two
23065   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
23066     "Unexpected size for truncating masked store");
23067   // We are going to use the original vector elt for storing.
23068   // Accumulated smaller vector elements must be a multiple of the store size.
23069   assert (((NumElems * FromSz) % ToSz) == 0 &&
23070           "Unexpected ratio for truncating masked store");
23071
23072   unsigned SizeRatio  = FromSz / ToSz;
23073   assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
23074
23075   // Create a type on which we perform the shuffle
23076   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
23077           StVT.getScalarType(), NumElems*SizeRatio);
23078
23079   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
23080
23081   SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mst->getValue());
23082   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
23083   for (unsigned i = 0; i != NumElems; ++i)
23084     ShuffleVec[i] = i * SizeRatio;
23085
23086   // Can't shuffle using an illegal type.
23087   assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
23088           && "WideVecVT should be legal");
23089
23090   SDValue TruncatedVal = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
23091                                         DAG.getUNDEF(WideVecVT),
23092                                         &ShuffleVec[0]);
23093
23094   SDValue NewMask;
23095   SDValue Mask = Mst->getMask();
23096   if (Mask.getValueType() == VT) {
23097     // Mask and original value have the same type
23098     NewMask = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mask);
23099     for (unsigned i = 0; i != NumElems; ++i)
23100       ShuffleVec[i] = i * SizeRatio;
23101     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
23102       ShuffleVec[i] = NumElems*SizeRatio;
23103     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
23104                                    DAG.getConstant(0, dl, WideVecVT),
23105                                    &ShuffleVec[0]);
23106   }
23107   else {
23108     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
23109     unsigned WidenNumElts = NumElems*SizeRatio;
23110     unsigned MaskNumElts = VT.getVectorNumElements();
23111     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
23112                                      WidenNumElts);
23113
23114     unsigned NumConcat = WidenNumElts / MaskNumElts;
23115     SmallVector<SDValue, 16> Ops(NumConcat);
23116     SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
23117     Ops[0] = Mask;
23118     for (unsigned i = 1; i != NumConcat; ++i)
23119       Ops[i] = ZeroVal;
23120
23121     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
23122   }
23123
23124   return DAG.getMaskedStore(Mst->getChain(), dl, TruncatedVal, Mst->getBasePtr(),
23125                             NewMask, StVT, Mst->getMemOperand(), false);
23126 }
23127 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
23128 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
23129                                    const X86Subtarget *Subtarget) {
23130   StoreSDNode *St = cast<StoreSDNode>(N);
23131   EVT VT = St->getValue().getValueType();
23132   EVT StVT = St->getMemoryVT();
23133   SDLoc dl(St);
23134   SDValue StoredVal = St->getOperand(1);
23135   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23136
23137   // If we are saving a concatenation of two XMM registers and 32-byte stores
23138   // are slow, such as on Sandy Bridge, perform two 16-byte stores.
23139   unsigned Alignment = St->getAlignment();
23140   bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
23141   if (VT.is256BitVector() && Subtarget->isUnalignedMem32Slow() &&
23142       StVT == VT && !IsAligned) {
23143     unsigned NumElems = VT.getVectorNumElements();
23144     if (NumElems < 2)
23145       return SDValue();
23146
23147     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
23148     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
23149
23150     SDValue Stride = DAG.getConstant(16, dl, TLI.getPointerTy());
23151     SDValue Ptr0 = St->getBasePtr();
23152     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
23153
23154     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
23155                                 St->getPointerInfo(), St->isVolatile(),
23156                                 St->isNonTemporal(), Alignment);
23157     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
23158                                 St->getPointerInfo(), St->isVolatile(),
23159                                 St->isNonTemporal(),
23160                                 std::min(16U, Alignment));
23161     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
23162   }
23163
23164   // Optimize trunc store (of multiple scalars) to shuffle and store.
23165   // First, pack all of the elements in one place. Next, store to memory
23166   // in fewer chunks.
23167   if (St->isTruncatingStore() && VT.isVector()) {
23168     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23169     unsigned NumElems = VT.getVectorNumElements();
23170     assert(StVT != VT && "Cannot truncate to the same type");
23171     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
23172     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
23173
23174     // From, To sizes and ElemCount must be pow of two
23175     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
23176     // We are going to use the original vector elt for storing.
23177     // Accumulated smaller vector elements must be a multiple of the store size.
23178     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
23179
23180     unsigned SizeRatio  = FromSz / ToSz;
23181
23182     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
23183
23184     // Create a type on which we perform the shuffle
23185     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
23186             StVT.getScalarType(), NumElems*SizeRatio);
23187
23188     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
23189
23190     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
23191     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
23192     for (unsigned i = 0; i != NumElems; ++i)
23193       ShuffleVec[i] = i * SizeRatio;
23194
23195     // Can't shuffle using an illegal type.
23196     if (!TLI.isTypeLegal(WideVecVT))
23197       return SDValue();
23198
23199     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
23200                                          DAG.getUNDEF(WideVecVT),
23201                                          &ShuffleVec[0]);
23202     // At this point all of the data is stored at the bottom of the
23203     // register. We now need to save it to mem.
23204
23205     // Find the largest store unit
23206     MVT StoreType = MVT::i8;
23207     for (MVT Tp : MVT::integer_valuetypes()) {
23208       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
23209         StoreType = Tp;
23210     }
23211
23212     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
23213     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
23214         (64 <= NumElems * ToSz))
23215       StoreType = MVT::f64;
23216
23217     // Bitcast the original vector into a vector of store-size units
23218     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
23219             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
23220     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
23221     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
23222     SmallVector<SDValue, 8> Chains;
23223     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8, dl,
23224                                         TLI.getPointerTy());
23225     SDValue Ptr = St->getBasePtr();
23226
23227     // Perform one or more big stores into memory.
23228     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
23229       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
23230                                    StoreType, ShuffWide,
23231                                    DAG.getIntPtrConstant(i, dl));
23232       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
23233                                 St->getPointerInfo(), St->isVolatile(),
23234                                 St->isNonTemporal(), St->getAlignment());
23235       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
23236       Chains.push_back(Ch);
23237     }
23238
23239     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
23240   }
23241
23242   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
23243   // the FP state in cases where an emms may be missing.
23244   // A preferable solution to the general problem is to figure out the right
23245   // places to insert EMMS.  This qualifies as a quick hack.
23246
23247   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
23248   if (VT.getSizeInBits() != 64)
23249     return SDValue();
23250
23251   const Function *F = DAG.getMachineFunction().getFunction();
23252   bool NoImplicitFloatOps = F->hasFnAttribute(Attribute::NoImplicitFloat);
23253   bool F64IsLegal =
23254       !Subtarget->useSoftFloat() && !NoImplicitFloatOps && Subtarget->hasSSE2();
23255   if ((VT.isVector() ||
23256        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
23257       isa<LoadSDNode>(St->getValue()) &&
23258       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
23259       St->getChain().hasOneUse() && !St->isVolatile()) {
23260     SDNode* LdVal = St->getValue().getNode();
23261     LoadSDNode *Ld = nullptr;
23262     int TokenFactorIndex = -1;
23263     SmallVector<SDValue, 8> Ops;
23264     SDNode* ChainVal = St->getChain().getNode();
23265     // Must be a store of a load.  We currently handle two cases:  the load
23266     // is a direct child, and it's under an intervening TokenFactor.  It is
23267     // possible to dig deeper under nested TokenFactors.
23268     if (ChainVal == LdVal)
23269       Ld = cast<LoadSDNode>(St->getChain());
23270     else if (St->getValue().hasOneUse() &&
23271              ChainVal->getOpcode() == ISD::TokenFactor) {
23272       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
23273         if (ChainVal->getOperand(i).getNode() == LdVal) {
23274           TokenFactorIndex = i;
23275           Ld = cast<LoadSDNode>(St->getValue());
23276         } else
23277           Ops.push_back(ChainVal->getOperand(i));
23278       }
23279     }
23280
23281     if (!Ld || !ISD::isNormalLoad(Ld))
23282       return SDValue();
23283
23284     // If this is not the MMX case, i.e. we are just turning i64 load/store
23285     // into f64 load/store, avoid the transformation if there are multiple
23286     // uses of the loaded value.
23287     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
23288       return SDValue();
23289
23290     SDLoc LdDL(Ld);
23291     SDLoc StDL(N);
23292     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
23293     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
23294     // pair instead.
23295     if (Subtarget->is64Bit() || F64IsLegal) {
23296       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
23297       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
23298                                   Ld->getPointerInfo(), Ld->isVolatile(),
23299                                   Ld->isNonTemporal(), Ld->isInvariant(),
23300                                   Ld->getAlignment());
23301       SDValue NewChain = NewLd.getValue(1);
23302       if (TokenFactorIndex != -1) {
23303         Ops.push_back(NewChain);
23304         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
23305       }
23306       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
23307                           St->getPointerInfo(),
23308                           St->isVolatile(), St->isNonTemporal(),
23309                           St->getAlignment());
23310     }
23311
23312     // Otherwise, lower to two pairs of 32-bit loads / stores.
23313     SDValue LoAddr = Ld->getBasePtr();
23314     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
23315                                  DAG.getConstant(4, LdDL, MVT::i32));
23316
23317     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
23318                                Ld->getPointerInfo(),
23319                                Ld->isVolatile(), Ld->isNonTemporal(),
23320                                Ld->isInvariant(), Ld->getAlignment());
23321     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
23322                                Ld->getPointerInfo().getWithOffset(4),
23323                                Ld->isVolatile(), Ld->isNonTemporal(),
23324                                Ld->isInvariant(),
23325                                MinAlign(Ld->getAlignment(), 4));
23326
23327     SDValue NewChain = LoLd.getValue(1);
23328     if (TokenFactorIndex != -1) {
23329       Ops.push_back(LoLd);
23330       Ops.push_back(HiLd);
23331       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
23332     }
23333
23334     LoAddr = St->getBasePtr();
23335     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
23336                          DAG.getConstant(4, StDL, MVT::i32));
23337
23338     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
23339                                 St->getPointerInfo(),
23340                                 St->isVolatile(), St->isNonTemporal(),
23341                                 St->getAlignment());
23342     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
23343                                 St->getPointerInfo().getWithOffset(4),
23344                                 St->isVolatile(),
23345                                 St->isNonTemporal(),
23346                                 MinAlign(St->getAlignment(), 4));
23347     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
23348   }
23349
23350   // This is similar to the above case, but here we handle a scalar 64-bit
23351   // integer store that is extracted from a vector on a 32-bit target.
23352   // If we have SSE2, then we can treat it like a floating-point double
23353   // to get past legalization. The execution dependencies fixup pass will
23354   // choose the optimal machine instruction for the store if this really is
23355   // an integer or v2f32 rather than an f64.
23356   if (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit() &&
23357       St->getOperand(1).getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
23358     SDValue OldExtract = St->getOperand(1);
23359     SDValue ExtOp0 = OldExtract.getOperand(0);
23360     unsigned VecSize = ExtOp0.getValueSizeInBits();
23361     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, VecSize / 64);
23362     SDValue BitCast = DAG.getNode(ISD::BITCAST, dl, VecVT, ExtOp0);
23363     SDValue NewExtract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
23364                                      BitCast, OldExtract.getOperand(1));
23365     return DAG.getStore(St->getChain(), dl, NewExtract, St->getBasePtr(),
23366                         St->getPointerInfo(), St->isVolatile(),
23367                         St->isNonTemporal(), St->getAlignment());
23368   }
23369
23370   return SDValue();
23371 }
23372
23373 /// Return 'true' if this vector operation is "horizontal"
23374 /// and return the operands for the horizontal operation in LHS and RHS.  A
23375 /// horizontal operation performs the binary operation on successive elements
23376 /// of its first operand, then on successive elements of its second operand,
23377 /// returning the resulting values in a vector.  For example, if
23378 ///   A = < float a0, float a1, float a2, float a3 >
23379 /// and
23380 ///   B = < float b0, float b1, float b2, float b3 >
23381 /// then the result of doing a horizontal operation on A and B is
23382 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
23383 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
23384 /// A horizontal-op B, for some already available A and B, and if so then LHS is
23385 /// set to A, RHS to B, and the routine returns 'true'.
23386 /// Note that the binary operation should have the property that if one of the
23387 /// operands is UNDEF then the result is UNDEF.
23388 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
23389   // Look for the following pattern: if
23390   //   A = < float a0, float a1, float a2, float a3 >
23391   //   B = < float b0, float b1, float b2, float b3 >
23392   // and
23393   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
23394   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
23395   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
23396   // which is A horizontal-op B.
23397
23398   // At least one of the operands should be a vector shuffle.
23399   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
23400       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
23401     return false;
23402
23403   MVT VT = LHS.getSimpleValueType();
23404
23405   assert((VT.is128BitVector() || VT.is256BitVector()) &&
23406          "Unsupported vector type for horizontal add/sub");
23407
23408   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
23409   // operate independently on 128-bit lanes.
23410   unsigned NumElts = VT.getVectorNumElements();
23411   unsigned NumLanes = VT.getSizeInBits()/128;
23412   unsigned NumLaneElts = NumElts / NumLanes;
23413   assert((NumLaneElts % 2 == 0) &&
23414          "Vector type should have an even number of elements in each lane");
23415   unsigned HalfLaneElts = NumLaneElts/2;
23416
23417   // View LHS in the form
23418   //   LHS = VECTOR_SHUFFLE A, B, LMask
23419   // If LHS is not a shuffle then pretend it is the shuffle
23420   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
23421   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
23422   // type VT.
23423   SDValue A, B;
23424   SmallVector<int, 16> LMask(NumElts);
23425   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
23426     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
23427       A = LHS.getOperand(0);
23428     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
23429       B = LHS.getOperand(1);
23430     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
23431     std::copy(Mask.begin(), Mask.end(), LMask.begin());
23432   } else {
23433     if (LHS.getOpcode() != ISD::UNDEF)
23434       A = LHS;
23435     for (unsigned i = 0; i != NumElts; ++i)
23436       LMask[i] = i;
23437   }
23438
23439   // Likewise, view RHS in the form
23440   //   RHS = VECTOR_SHUFFLE C, D, RMask
23441   SDValue C, D;
23442   SmallVector<int, 16> RMask(NumElts);
23443   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
23444     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
23445       C = RHS.getOperand(0);
23446     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
23447       D = RHS.getOperand(1);
23448     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
23449     std::copy(Mask.begin(), Mask.end(), RMask.begin());
23450   } else {
23451     if (RHS.getOpcode() != ISD::UNDEF)
23452       C = RHS;
23453     for (unsigned i = 0; i != NumElts; ++i)
23454       RMask[i] = i;
23455   }
23456
23457   // Check that the shuffles are both shuffling the same vectors.
23458   if (!(A == C && B == D) && !(A == D && B == C))
23459     return false;
23460
23461   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
23462   if (!A.getNode() && !B.getNode())
23463     return false;
23464
23465   // If A and B occur in reverse order in RHS, then "swap" them (which means
23466   // rewriting the mask).
23467   if (A != C)
23468     ShuffleVectorSDNode::commuteMask(RMask);
23469
23470   // At this point LHS and RHS are equivalent to
23471   //   LHS = VECTOR_SHUFFLE A, B, LMask
23472   //   RHS = VECTOR_SHUFFLE A, B, RMask
23473   // Check that the masks correspond to performing a horizontal operation.
23474   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
23475     for (unsigned i = 0; i != NumLaneElts; ++i) {
23476       int LIdx = LMask[i+l], RIdx = RMask[i+l];
23477
23478       // Ignore any UNDEF components.
23479       if (LIdx < 0 || RIdx < 0 ||
23480           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
23481           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
23482         continue;
23483
23484       // Check that successive elements are being operated on.  If not, this is
23485       // not a horizontal operation.
23486       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
23487       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
23488       if (!(LIdx == Index && RIdx == Index + 1) &&
23489           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
23490         return false;
23491     }
23492   }
23493
23494   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
23495   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
23496   return true;
23497 }
23498
23499 /// Do target-specific dag combines on floating point adds.
23500 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
23501                                   const X86Subtarget *Subtarget) {
23502   EVT VT = N->getValueType(0);
23503   SDValue LHS = N->getOperand(0);
23504   SDValue RHS = N->getOperand(1);
23505
23506   // Try to synthesize horizontal adds from adds of shuffles.
23507   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
23508        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
23509       isHorizontalBinOp(LHS, RHS, true))
23510     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
23511   return SDValue();
23512 }
23513
23514 /// Do target-specific dag combines on floating point subs.
23515 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
23516                                   const X86Subtarget *Subtarget) {
23517   EVT VT = N->getValueType(0);
23518   SDValue LHS = N->getOperand(0);
23519   SDValue RHS = N->getOperand(1);
23520
23521   // Try to synthesize horizontal subs from subs of shuffles.
23522   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
23523        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
23524       isHorizontalBinOp(LHS, RHS, false))
23525     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
23526   return SDValue();
23527 }
23528
23529 /// Do target-specific dag combines on X86ISD::FOR and X86ISD::FXOR nodes.
23530 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
23531   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
23532
23533   // F[X]OR(0.0, x) -> x
23534   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
23535     if (C->getValueAPF().isPosZero())
23536       return N->getOperand(1);
23537
23538   // F[X]OR(x, 0.0) -> x
23539   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
23540     if (C->getValueAPF().isPosZero())
23541       return N->getOperand(0);
23542   return SDValue();
23543 }
23544
23545 /// Do target-specific dag combines on X86ISD::FMIN and X86ISD::FMAX nodes.
23546 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
23547   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
23548
23549   // Only perform optimizations if UnsafeMath is used.
23550   if (!DAG.getTarget().Options.UnsafeFPMath)
23551     return SDValue();
23552
23553   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
23554   // into FMINC and FMAXC, which are Commutative operations.
23555   unsigned NewOp = 0;
23556   switch (N->getOpcode()) {
23557     default: llvm_unreachable("unknown opcode");
23558     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
23559     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
23560   }
23561
23562   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
23563                      N->getOperand(0), N->getOperand(1));
23564 }
23565
23566 /// Do target-specific dag combines on X86ISD::FAND nodes.
23567 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
23568   // FAND(0.0, x) -> 0.0
23569   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
23570     if (C->getValueAPF().isPosZero())
23571       return N->getOperand(0);
23572
23573   // FAND(x, 0.0) -> 0.0
23574   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
23575     if (C->getValueAPF().isPosZero())
23576       return N->getOperand(1);
23577
23578   return SDValue();
23579 }
23580
23581 /// Do target-specific dag combines on X86ISD::FANDN nodes
23582 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
23583   // FANDN(0.0, x) -> x
23584   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
23585     if (C->getValueAPF().isPosZero())
23586       return N->getOperand(1);
23587
23588   // FANDN(x, 0.0) -> 0.0
23589   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
23590     if (C->getValueAPF().isPosZero())
23591       return N->getOperand(1);
23592
23593   return SDValue();
23594 }
23595
23596 static SDValue PerformBTCombine(SDNode *N,
23597                                 SelectionDAG &DAG,
23598                                 TargetLowering::DAGCombinerInfo &DCI) {
23599   // BT ignores high bits in the bit index operand.
23600   SDValue Op1 = N->getOperand(1);
23601   if (Op1.hasOneUse()) {
23602     unsigned BitWidth = Op1.getValueSizeInBits();
23603     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
23604     APInt KnownZero, KnownOne;
23605     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
23606                                           !DCI.isBeforeLegalizeOps());
23607     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23608     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
23609         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
23610       DCI.CommitTargetLoweringOpt(TLO);
23611   }
23612   return SDValue();
23613 }
23614
23615 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
23616   SDValue Op = N->getOperand(0);
23617   if (Op.getOpcode() == ISD::BITCAST)
23618     Op = Op.getOperand(0);
23619   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
23620   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
23621       VT.getVectorElementType().getSizeInBits() ==
23622       OpVT.getVectorElementType().getSizeInBits()) {
23623     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
23624   }
23625   return SDValue();
23626 }
23627
23628 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
23629                                                const X86Subtarget *Subtarget) {
23630   EVT VT = N->getValueType(0);
23631   if (!VT.isVector())
23632     return SDValue();
23633
23634   SDValue N0 = N->getOperand(0);
23635   SDValue N1 = N->getOperand(1);
23636   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
23637   SDLoc dl(N);
23638
23639   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
23640   // both SSE and AVX2 since there is no sign-extended shift right
23641   // operation on a vector with 64-bit elements.
23642   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
23643   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
23644   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
23645       N0.getOpcode() == ISD::SIGN_EXTEND)) {
23646     SDValue N00 = N0.getOperand(0);
23647
23648     // EXTLOAD has a better solution on AVX2,
23649     // it may be replaced with X86ISD::VSEXT node.
23650     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
23651       if (!ISD::isNormalLoad(N00.getNode()))
23652         return SDValue();
23653
23654     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
23655         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
23656                                   N00, N1);
23657       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
23658     }
23659   }
23660   return SDValue();
23661 }
23662
23663 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
23664                                   TargetLowering::DAGCombinerInfo &DCI,
23665                                   const X86Subtarget *Subtarget) {
23666   SDValue N0 = N->getOperand(0);
23667   EVT VT = N->getValueType(0);
23668   SDLoc dl(N);
23669
23670   // (i8,i32 sext (sdivrem (i8 x, i8 y)) ->
23671   // (i8,i32 (sdivrem_sext_hreg (i8 x, i8 y)
23672   // This exposes the sext to the sdivrem lowering, so that it directly extends
23673   // from AH (which we otherwise need to do contortions to access).
23674   if (N0.getOpcode() == ISD::SDIVREM && N0.getResNo() == 1 &&
23675       N0.getValueType() == MVT::i8 && VT == MVT::i32) {
23676     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
23677     SDValue R = DAG.getNode(X86ISD::SDIVREM8_SEXT_HREG, dl, NodeTys,
23678                             N0.getOperand(0), N0.getOperand(1));
23679     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
23680     return R.getValue(1);
23681   }
23682
23683   if (!DCI.isBeforeLegalizeOps()) {
23684     if (N0.getValueType() == MVT::i1) {
23685       SDValue Zero = DAG.getConstant(0, dl, VT);
23686       SDValue AllOnes =
23687         DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl, VT);
23688       return DAG.getNode(ISD::SELECT, dl, VT, N0, AllOnes, Zero);
23689     }
23690     return SDValue();
23691   }
23692
23693   if (!Subtarget->hasFp256())
23694     return SDValue();
23695
23696   if (VT.isVector() && VT.getSizeInBits() == 256) {
23697     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
23698     if (R.getNode())
23699       return R;
23700   }
23701
23702   return SDValue();
23703 }
23704
23705 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
23706                                  const X86Subtarget* Subtarget) {
23707   SDLoc dl(N);
23708   EVT VT = N->getValueType(0);
23709
23710   // Let legalize expand this if it isn't a legal type yet.
23711   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
23712     return SDValue();
23713
23714   EVT ScalarVT = VT.getScalarType();
23715   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
23716       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
23717     return SDValue();
23718
23719   SDValue A = N->getOperand(0);
23720   SDValue B = N->getOperand(1);
23721   SDValue C = N->getOperand(2);
23722
23723   bool NegA = (A.getOpcode() == ISD::FNEG);
23724   bool NegB = (B.getOpcode() == ISD::FNEG);
23725   bool NegC = (C.getOpcode() == ISD::FNEG);
23726
23727   // Negative multiplication when NegA xor NegB
23728   bool NegMul = (NegA != NegB);
23729   if (NegA)
23730     A = A.getOperand(0);
23731   if (NegB)
23732     B = B.getOperand(0);
23733   if (NegC)
23734     C = C.getOperand(0);
23735
23736   unsigned Opcode;
23737   if (!NegMul)
23738     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
23739   else
23740     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
23741
23742   return DAG.getNode(Opcode, dl, VT, A, B, C);
23743 }
23744
23745 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
23746                                   TargetLowering::DAGCombinerInfo &DCI,
23747                                   const X86Subtarget *Subtarget) {
23748   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
23749   //           (and (i32 x86isd::setcc_carry), 1)
23750   // This eliminates the zext. This transformation is necessary because
23751   // ISD::SETCC is always legalized to i8.
23752   SDLoc dl(N);
23753   SDValue N0 = N->getOperand(0);
23754   EVT VT = N->getValueType(0);
23755
23756   if (N0.getOpcode() == ISD::AND &&
23757       N0.hasOneUse() &&
23758       N0.getOperand(0).hasOneUse()) {
23759     SDValue N00 = N0.getOperand(0);
23760     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
23761       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
23762       if (!C || C->getZExtValue() != 1)
23763         return SDValue();
23764       return DAG.getNode(ISD::AND, dl, VT,
23765                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
23766                                      N00.getOperand(0), N00.getOperand(1)),
23767                          DAG.getConstant(1, dl, VT));
23768     }
23769   }
23770
23771   if (N0.getOpcode() == ISD::TRUNCATE &&
23772       N0.hasOneUse() &&
23773       N0.getOperand(0).hasOneUse()) {
23774     SDValue N00 = N0.getOperand(0);
23775     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
23776       return DAG.getNode(ISD::AND, dl, VT,
23777                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
23778                                      N00.getOperand(0), N00.getOperand(1)),
23779                          DAG.getConstant(1, dl, VT));
23780     }
23781   }
23782   if (VT.is256BitVector()) {
23783     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
23784     if (R.getNode())
23785       return R;
23786   }
23787
23788   // (i8,i32 zext (udivrem (i8 x, i8 y)) ->
23789   // (i8,i32 (udivrem_zext_hreg (i8 x, i8 y)
23790   // This exposes the zext to the udivrem lowering, so that it directly extends
23791   // from AH (which we otherwise need to do contortions to access).
23792   if (N0.getOpcode() == ISD::UDIVREM &&
23793       N0.getResNo() == 1 && N0.getValueType() == MVT::i8 &&
23794       (VT == MVT::i32 || VT == MVT::i64)) {
23795     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
23796     SDValue R = DAG.getNode(X86ISD::UDIVREM8_ZEXT_HREG, dl, NodeTys,
23797                             N0.getOperand(0), N0.getOperand(1));
23798     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
23799     return R.getValue(1);
23800   }
23801
23802   return SDValue();
23803 }
23804
23805 // Optimize x == -y --> x+y == 0
23806 //          x != -y --> x+y != 0
23807 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
23808                                       const X86Subtarget* Subtarget) {
23809   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
23810   SDValue LHS = N->getOperand(0);
23811   SDValue RHS = N->getOperand(1);
23812   EVT VT = N->getValueType(0);
23813   SDLoc DL(N);
23814
23815   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
23816     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
23817       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
23818         SDValue addV = DAG.getNode(ISD::ADD, DL, LHS.getValueType(), RHS,
23819                                    LHS.getOperand(1));
23820         return DAG.getSetCC(DL, N->getValueType(0), addV,
23821                             DAG.getConstant(0, DL, addV.getValueType()), CC);
23822       }
23823   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
23824     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
23825       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
23826         SDValue addV = DAG.getNode(ISD::ADD, DL, RHS.getValueType(), LHS,
23827                                    RHS.getOperand(1));
23828         return DAG.getSetCC(DL, N->getValueType(0), addV,
23829                             DAG.getConstant(0, DL, addV.getValueType()), CC);
23830       }
23831
23832   if (VT.getScalarType() == MVT::i1 &&
23833       (CC == ISD::SETNE || CC == ISD::SETEQ || ISD::isSignedIntSetCC(CC))) {
23834     bool IsSEXT0 =
23835         (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
23836         (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
23837     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
23838
23839     if (!IsSEXT0 || !IsVZero1) {
23840       // Swap the operands and update the condition code.
23841       std::swap(LHS, RHS);
23842       CC = ISD::getSetCCSwappedOperands(CC);
23843
23844       IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
23845                 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
23846       IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
23847     }
23848
23849     if (IsSEXT0 && IsVZero1) {
23850       assert(VT == LHS.getOperand(0).getValueType() &&
23851              "Uexpected operand type");
23852       if (CC == ISD::SETGT)
23853         return DAG.getConstant(0, DL, VT);
23854       if (CC == ISD::SETLE)
23855         return DAG.getConstant(1, DL, VT);
23856       if (CC == ISD::SETEQ || CC == ISD::SETGE)
23857         return DAG.getNOT(DL, LHS.getOperand(0), VT);
23858
23859       assert((CC == ISD::SETNE || CC == ISD::SETLT) &&
23860              "Unexpected condition code!");
23861       return LHS.getOperand(0);
23862     }
23863   }
23864
23865   return SDValue();
23866 }
23867
23868 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
23869                                          SelectionDAG &DAG) {
23870   SDLoc dl(Load);
23871   MVT VT = Load->getSimpleValueType(0);
23872   MVT EVT = VT.getVectorElementType();
23873   SDValue Addr = Load->getOperand(1);
23874   SDValue NewAddr = DAG.getNode(
23875       ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
23876       DAG.getConstant(Index * EVT.getStoreSize(), dl,
23877                       Addr.getSimpleValueType()));
23878
23879   SDValue NewLoad =
23880       DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
23881                   DAG.getMachineFunction().getMachineMemOperand(
23882                       Load->getMemOperand(), 0, EVT.getStoreSize()));
23883   return NewLoad;
23884 }
23885
23886 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
23887                                       const X86Subtarget *Subtarget) {
23888   SDLoc dl(N);
23889   MVT VT = N->getOperand(1)->getSimpleValueType(0);
23890   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
23891          "X86insertps is only defined for v4x32");
23892
23893   SDValue Ld = N->getOperand(1);
23894   if (MayFoldLoad(Ld)) {
23895     // Extract the countS bits from the immediate so we can get the proper
23896     // address when narrowing the vector load to a specific element.
23897     // When the second source op is a memory address, insertps doesn't use
23898     // countS and just gets an f32 from that address.
23899     unsigned DestIndex =
23900         cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
23901
23902     Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
23903
23904     // Create this as a scalar to vector to match the instruction pattern.
23905     SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
23906     // countS bits are ignored when loading from memory on insertps, which
23907     // means we don't need to explicitly set them to 0.
23908     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
23909                        LoadScalarToVector, N->getOperand(2));
23910   }
23911   return SDValue();
23912 }
23913
23914 static SDValue PerformBLENDICombine(SDNode *N, SelectionDAG &DAG) {
23915   SDValue V0 = N->getOperand(0);
23916   SDValue V1 = N->getOperand(1);
23917   SDLoc DL(N);
23918   EVT VT = N->getValueType(0);
23919
23920   // Canonicalize a v2f64 blend with a mask of 2 by swapping the vector
23921   // operands and changing the mask to 1. This saves us a bunch of
23922   // pattern-matching possibilities related to scalar math ops in SSE/AVX.
23923   // x86InstrInfo knows how to commute this back after instruction selection
23924   // if it would help register allocation.
23925
23926   // TODO: If optimizing for size or a processor that doesn't suffer from
23927   // partial register update stalls, this should be transformed into a MOVSD
23928   // instruction because a MOVSD is 1-2 bytes smaller than a BLENDPD.
23929
23930   if (VT == MVT::v2f64)
23931     if (auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(2)))
23932       if (Mask->getZExtValue() == 2 && !isShuffleFoldableLoad(V0)) {
23933         SDValue NewMask = DAG.getConstant(1, DL, MVT::i8);
23934         return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V0, NewMask);
23935       }
23936
23937   return SDValue();
23938 }
23939
23940 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
23941 // as "sbb reg,reg", since it can be extended without zext and produces
23942 // an all-ones bit which is more useful than 0/1 in some cases.
23943 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
23944                                MVT VT) {
23945   if (VT == MVT::i8)
23946     return DAG.getNode(ISD::AND, DL, VT,
23947                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
23948                                    DAG.getConstant(X86::COND_B, DL, MVT::i8),
23949                                    EFLAGS),
23950                        DAG.getConstant(1, DL, VT));
23951   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
23952   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
23953                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
23954                                  DAG.getConstant(X86::COND_B, DL, MVT::i8),
23955                                  EFLAGS));
23956 }
23957
23958 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
23959 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
23960                                    TargetLowering::DAGCombinerInfo &DCI,
23961                                    const X86Subtarget *Subtarget) {
23962   SDLoc DL(N);
23963   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
23964   SDValue EFLAGS = N->getOperand(1);
23965
23966   if (CC == X86::COND_A) {
23967     // Try to convert COND_A into COND_B in an attempt to facilitate
23968     // materializing "setb reg".
23969     //
23970     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
23971     // cannot take an immediate as its first operand.
23972     //
23973     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
23974         EFLAGS.getValueType().isInteger() &&
23975         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
23976       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
23977                                    EFLAGS.getNode()->getVTList(),
23978                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
23979       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
23980       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
23981     }
23982   }
23983
23984   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
23985   // a zext and produces an all-ones bit which is more useful than 0/1 in some
23986   // cases.
23987   if (CC == X86::COND_B)
23988     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
23989
23990   SDValue Flags;
23991
23992   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
23993   if (Flags.getNode()) {
23994     SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
23995     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
23996   }
23997
23998   return SDValue();
23999 }
24000
24001 // Optimize branch condition evaluation.
24002 //
24003 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
24004                                     TargetLowering::DAGCombinerInfo &DCI,
24005                                     const X86Subtarget *Subtarget) {
24006   SDLoc DL(N);
24007   SDValue Chain = N->getOperand(0);
24008   SDValue Dest = N->getOperand(1);
24009   SDValue EFLAGS = N->getOperand(3);
24010   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
24011
24012   SDValue Flags;
24013
24014   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
24015   if (Flags.getNode()) {
24016     SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
24017     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
24018                        Flags);
24019   }
24020
24021   return SDValue();
24022 }
24023
24024 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
24025                                                          SelectionDAG &DAG) {
24026   // Take advantage of vector comparisons producing 0 or -1 in each lane to
24027   // optimize away operation when it's from a constant.
24028   //
24029   // The general transformation is:
24030   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
24031   //       AND(VECTOR_CMP(x,y), constant2)
24032   //    constant2 = UNARYOP(constant)
24033
24034   // Early exit if this isn't a vector operation, the operand of the
24035   // unary operation isn't a bitwise AND, or if the sizes of the operations
24036   // aren't the same.
24037   EVT VT = N->getValueType(0);
24038   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
24039       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
24040       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
24041     return SDValue();
24042
24043   // Now check that the other operand of the AND is a constant. We could
24044   // make the transformation for non-constant splats as well, but it's unclear
24045   // that would be a benefit as it would not eliminate any operations, just
24046   // perform one more step in scalar code before moving to the vector unit.
24047   if (BuildVectorSDNode *BV =
24048           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
24049     // Bail out if the vector isn't a constant.
24050     if (!BV->isConstant())
24051       return SDValue();
24052
24053     // Everything checks out. Build up the new and improved node.
24054     SDLoc DL(N);
24055     EVT IntVT = BV->getValueType(0);
24056     // Create a new constant of the appropriate type for the transformed
24057     // DAG.
24058     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
24059     // The AND node needs bitcasts to/from an integer vector type around it.
24060     SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
24061     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
24062                                  N->getOperand(0)->getOperand(0), MaskConst);
24063     SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
24064     return Res;
24065   }
24066
24067   return SDValue();
24068 }
24069
24070 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
24071                                         const X86Subtarget *Subtarget) {
24072   // First try to optimize away the conversion entirely when it's
24073   // conditionally from a constant. Vectors only.
24074   SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG);
24075   if (Res != SDValue())
24076     return Res;
24077
24078   // Now move on to more general possibilities.
24079   SDValue Op0 = N->getOperand(0);
24080   EVT InVT = Op0->getValueType(0);
24081
24082   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
24083   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
24084     SDLoc dl(N);
24085     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
24086     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
24087     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
24088   }
24089
24090   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
24091   // a 32-bit target where SSE doesn't support i64->FP operations.
24092   if (Op0.getOpcode() == ISD::LOAD) {
24093     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
24094     EVT VT = Ld->getValueType(0);
24095
24096     // This transformation is not supported if the result type is f16
24097     if (N->getValueType(0) == MVT::f16)
24098       return SDValue();
24099
24100     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
24101         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
24102         !Subtarget->is64Bit() && VT == MVT::i64) {
24103       SDValue FILDChain = Subtarget->getTargetLowering()->BuildFILD(
24104           SDValue(N, 0), Ld->getValueType(0), Ld->getChain(), Op0, DAG);
24105       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
24106       return FILDChain;
24107     }
24108   }
24109   return SDValue();
24110 }
24111
24112 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
24113 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
24114                                  X86TargetLowering::DAGCombinerInfo &DCI) {
24115   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
24116   // the result is either zero or one (depending on the input carry bit).
24117   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
24118   if (X86::isZeroNode(N->getOperand(0)) &&
24119       X86::isZeroNode(N->getOperand(1)) &&
24120       // We don't have a good way to replace an EFLAGS use, so only do this when
24121       // dead right now.
24122       SDValue(N, 1).use_empty()) {
24123     SDLoc DL(N);
24124     EVT VT = N->getValueType(0);
24125     SDValue CarryOut = DAG.getConstant(0, DL, N->getValueType(1));
24126     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
24127                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
24128                                            DAG.getConstant(X86::COND_B, DL,
24129                                                            MVT::i8),
24130                                            N->getOperand(2)),
24131                                DAG.getConstant(1, DL, VT));
24132     return DCI.CombineTo(N, Res1, CarryOut);
24133   }
24134
24135   return SDValue();
24136 }
24137
24138 // fold (add Y, (sete  X, 0)) -> adc  0, Y
24139 //      (add Y, (setne X, 0)) -> sbb -1, Y
24140 //      (sub (sete  X, 0), Y) -> sbb  0, Y
24141 //      (sub (setne X, 0), Y) -> adc -1, Y
24142 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
24143   SDLoc DL(N);
24144
24145   // Look through ZExts.
24146   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
24147   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
24148     return SDValue();
24149
24150   SDValue SetCC = Ext.getOperand(0);
24151   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
24152     return SDValue();
24153
24154   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
24155   if (CC != X86::COND_E && CC != X86::COND_NE)
24156     return SDValue();
24157
24158   SDValue Cmp = SetCC.getOperand(1);
24159   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
24160       !X86::isZeroNode(Cmp.getOperand(1)) ||
24161       !Cmp.getOperand(0).getValueType().isInteger())
24162     return SDValue();
24163
24164   SDValue CmpOp0 = Cmp.getOperand(0);
24165   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
24166                                DAG.getConstant(1, DL, CmpOp0.getValueType()));
24167
24168   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
24169   if (CC == X86::COND_NE)
24170     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
24171                        DL, OtherVal.getValueType(), OtherVal,
24172                        DAG.getConstant(-1ULL, DL, OtherVal.getValueType()),
24173                        NewCmp);
24174   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
24175                      DL, OtherVal.getValueType(), OtherVal,
24176                      DAG.getConstant(0, DL, OtherVal.getValueType()), NewCmp);
24177 }
24178
24179 /// PerformADDCombine - Do target-specific dag combines on integer adds.
24180 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
24181                                  const X86Subtarget *Subtarget) {
24182   EVT VT = N->getValueType(0);
24183   SDValue Op0 = N->getOperand(0);
24184   SDValue Op1 = N->getOperand(1);
24185
24186   // Try to synthesize horizontal adds from adds of shuffles.
24187   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
24188        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
24189       isHorizontalBinOp(Op0, Op1, true))
24190     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
24191
24192   return OptimizeConditionalInDecrement(N, DAG);
24193 }
24194
24195 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
24196                                  const X86Subtarget *Subtarget) {
24197   SDValue Op0 = N->getOperand(0);
24198   SDValue Op1 = N->getOperand(1);
24199
24200   // X86 can't encode an immediate LHS of a sub. See if we can push the
24201   // negation into a preceding instruction.
24202   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
24203     // If the RHS of the sub is a XOR with one use and a constant, invert the
24204     // immediate. Then add one to the LHS of the sub so we can turn
24205     // X-Y -> X+~Y+1, saving one register.
24206     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
24207         isa<ConstantSDNode>(Op1.getOperand(1))) {
24208       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
24209       EVT VT = Op0.getValueType();
24210       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
24211                                    Op1.getOperand(0),
24212                                    DAG.getConstant(~XorC, SDLoc(Op1), VT));
24213       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
24214                          DAG.getConstant(C->getAPIntValue() + 1, SDLoc(N), VT));
24215     }
24216   }
24217
24218   // Try to synthesize horizontal adds from adds of shuffles.
24219   EVT VT = N->getValueType(0);
24220   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
24221        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
24222       isHorizontalBinOp(Op0, Op1, true))
24223     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
24224
24225   return OptimizeConditionalInDecrement(N, DAG);
24226 }
24227
24228 /// performVZEXTCombine - Performs build vector combines
24229 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
24230                                    TargetLowering::DAGCombinerInfo &DCI,
24231                                    const X86Subtarget *Subtarget) {
24232   SDLoc DL(N);
24233   MVT VT = N->getSimpleValueType(0);
24234   SDValue Op = N->getOperand(0);
24235   MVT OpVT = Op.getSimpleValueType();
24236   MVT OpEltVT = OpVT.getVectorElementType();
24237   unsigned InputBits = OpEltVT.getSizeInBits() * VT.getVectorNumElements();
24238
24239   // (vzext (bitcast (vzext (x)) -> (vzext x)
24240   SDValue V = Op;
24241   while (V.getOpcode() == ISD::BITCAST)
24242     V = V.getOperand(0);
24243
24244   if (V != Op && V.getOpcode() == X86ISD::VZEXT) {
24245     MVT InnerVT = V.getSimpleValueType();
24246     MVT InnerEltVT = InnerVT.getVectorElementType();
24247
24248     // If the element sizes match exactly, we can just do one larger vzext. This
24249     // is always an exact type match as vzext operates on integer types.
24250     if (OpEltVT == InnerEltVT) {
24251       assert(OpVT == InnerVT && "Types must match for vzext!");
24252       return DAG.getNode(X86ISD::VZEXT, DL, VT, V.getOperand(0));
24253     }
24254
24255     // The only other way we can combine them is if only a single element of the
24256     // inner vzext is used in the input to the outer vzext.
24257     if (InnerEltVT.getSizeInBits() < InputBits)
24258       return SDValue();
24259
24260     // In this case, the inner vzext is completely dead because we're going to
24261     // only look at bits inside of the low element. Just do the outer vzext on
24262     // a bitcast of the input to the inner.
24263     return DAG.getNode(X86ISD::VZEXT, DL, VT,
24264                        DAG.getNode(ISD::BITCAST, DL, OpVT, V));
24265   }
24266
24267   // Check if we can bypass extracting and re-inserting an element of an input
24268   // vector. Essentialy:
24269   // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
24270   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR &&
24271       V.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
24272       V.getOperand(0).getSimpleValueType().getSizeInBits() == InputBits) {
24273     SDValue ExtractedV = V.getOperand(0);
24274     SDValue OrigV = ExtractedV.getOperand(0);
24275     if (auto *ExtractIdx = dyn_cast<ConstantSDNode>(ExtractedV.getOperand(1)))
24276       if (ExtractIdx->getZExtValue() == 0) {
24277         MVT OrigVT = OrigV.getSimpleValueType();
24278         // Extract a subvector if necessary...
24279         if (OrigVT.getSizeInBits() > OpVT.getSizeInBits()) {
24280           int Ratio = OrigVT.getSizeInBits() / OpVT.getSizeInBits();
24281           OrigVT = MVT::getVectorVT(OrigVT.getVectorElementType(),
24282                                     OrigVT.getVectorNumElements() / Ratio);
24283           OrigV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigVT, OrigV,
24284                               DAG.getIntPtrConstant(0, DL));
24285         }
24286         Op = DAG.getNode(ISD::BITCAST, DL, OpVT, OrigV);
24287         return DAG.getNode(X86ISD::VZEXT, DL, VT, Op);
24288       }
24289   }
24290
24291   return SDValue();
24292 }
24293
24294 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
24295                                              DAGCombinerInfo &DCI) const {
24296   SelectionDAG &DAG = DCI.DAG;
24297   switch (N->getOpcode()) {
24298   default: break;
24299   case ISD::EXTRACT_VECTOR_ELT:
24300     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
24301   case ISD::VSELECT:
24302   case ISD::SELECT:
24303   case X86ISD::SHRUNKBLEND:
24304     return PerformSELECTCombine(N, DAG, DCI, Subtarget);
24305   case ISD::BITCAST:        return PerformBITCASTCombine(N, DAG);
24306   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
24307   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
24308   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
24309   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
24310   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
24311   case ISD::SHL:
24312   case ISD::SRA:
24313   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
24314   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
24315   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
24316   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
24317   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
24318   case ISD::MLOAD:          return PerformMLOADCombine(N, DAG, DCI, Subtarget);
24319   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
24320   case ISD::MSTORE:         return PerformMSTORECombine(N, DAG, Subtarget);
24321   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, Subtarget);
24322   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
24323   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
24324   case X86ISD::FXOR:
24325   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
24326   case X86ISD::FMIN:
24327   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
24328   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
24329   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
24330   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
24331   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
24332   case ISD::ANY_EXTEND:
24333   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
24334   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
24335   case ISD::SIGN_EXTEND_INREG:
24336     return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
24337   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
24338   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
24339   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
24340   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
24341   case X86ISD::SHUFP:       // Handle all target specific shuffles
24342   case X86ISD::PALIGNR:
24343   case X86ISD::UNPCKH:
24344   case X86ISD::UNPCKL:
24345   case X86ISD::MOVHLPS:
24346   case X86ISD::MOVLHPS:
24347   case X86ISD::PSHUFB:
24348   case X86ISD::PSHUFD:
24349   case X86ISD::PSHUFHW:
24350   case X86ISD::PSHUFLW:
24351   case X86ISD::MOVSS:
24352   case X86ISD::MOVSD:
24353   case X86ISD::VPERMILPI:
24354   case X86ISD::VPERM2X128:
24355   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
24356   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
24357   case ISD::INTRINSIC_WO_CHAIN:
24358     return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
24359   case X86ISD::INSERTPS: {
24360     if (getTargetMachine().getOptLevel() > CodeGenOpt::None)
24361       return PerformINSERTPSCombine(N, DAG, Subtarget);
24362     break;
24363   }
24364   case X86ISD::BLENDI:    return PerformBLENDICombine(N, DAG);
24365   }
24366
24367   return SDValue();
24368 }
24369
24370 /// isTypeDesirableForOp - Return true if the target has native support for
24371 /// the specified value type and it is 'desirable' to use the type for the
24372 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
24373 /// instruction encodings are longer and some i16 instructions are slow.
24374 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
24375   if (!isTypeLegal(VT))
24376     return false;
24377   if (VT != MVT::i16)
24378     return true;
24379
24380   switch (Opc) {
24381   default:
24382     return true;
24383   case ISD::LOAD:
24384   case ISD::SIGN_EXTEND:
24385   case ISD::ZERO_EXTEND:
24386   case ISD::ANY_EXTEND:
24387   case ISD::SHL:
24388   case ISD::SRL:
24389   case ISD::SUB:
24390   case ISD::ADD:
24391   case ISD::MUL:
24392   case ISD::AND:
24393   case ISD::OR:
24394   case ISD::XOR:
24395     return false;
24396   }
24397 }
24398
24399 /// IsDesirableToPromoteOp - This method query the target whether it is
24400 /// beneficial for dag combiner to promote the specified node. If true, it
24401 /// should return the desired promotion type by reference.
24402 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
24403   EVT VT = Op.getValueType();
24404   if (VT != MVT::i16)
24405     return false;
24406
24407   bool Promote = false;
24408   bool Commute = false;
24409   switch (Op.getOpcode()) {
24410   default: break;
24411   case ISD::LOAD: {
24412     LoadSDNode *LD = cast<LoadSDNode>(Op);
24413     // If the non-extending load has a single use and it's not live out, then it
24414     // might be folded.
24415     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
24416                                                      Op.hasOneUse()*/) {
24417       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
24418              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
24419         // The only case where we'd want to promote LOAD (rather then it being
24420         // promoted as an operand is when it's only use is liveout.
24421         if (UI->getOpcode() != ISD::CopyToReg)
24422           return false;
24423       }
24424     }
24425     Promote = true;
24426     break;
24427   }
24428   case ISD::SIGN_EXTEND:
24429   case ISD::ZERO_EXTEND:
24430   case ISD::ANY_EXTEND:
24431     Promote = true;
24432     break;
24433   case ISD::SHL:
24434   case ISD::SRL: {
24435     SDValue N0 = Op.getOperand(0);
24436     // Look out for (store (shl (load), x)).
24437     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
24438       return false;
24439     Promote = true;
24440     break;
24441   }
24442   case ISD::ADD:
24443   case ISD::MUL:
24444   case ISD::AND:
24445   case ISD::OR:
24446   case ISD::XOR:
24447     Commute = true;
24448     // fallthrough
24449   case ISD::SUB: {
24450     SDValue N0 = Op.getOperand(0);
24451     SDValue N1 = Op.getOperand(1);
24452     if (!Commute && MayFoldLoad(N1))
24453       return false;
24454     // Avoid disabling potential load folding opportunities.
24455     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
24456       return false;
24457     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
24458       return false;
24459     Promote = true;
24460   }
24461   }
24462
24463   PVT = MVT::i32;
24464   return Promote;
24465 }
24466
24467 //===----------------------------------------------------------------------===//
24468 //                           X86 Inline Assembly Support
24469 //===----------------------------------------------------------------------===//
24470
24471 // Helper to match a string separated by whitespace.
24472 static bool matchAsm(StringRef S, ArrayRef<const char *> Pieces) {
24473   S = S.substr(S.find_first_not_of(" \t")); // Skip leading whitespace.
24474
24475   for (StringRef Piece : Pieces) {
24476     if (!S.startswith(Piece)) // Check if the piece matches.
24477       return false;
24478
24479     S = S.substr(Piece.size());
24480     StringRef::size_type Pos = S.find_first_not_of(" \t");
24481     if (Pos == 0) // We matched a prefix.
24482       return false;
24483
24484     S = S.substr(Pos);
24485   }
24486
24487   return S.empty();
24488 }
24489
24490 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
24491
24492   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
24493     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
24494         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
24495         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
24496
24497       if (AsmPieces.size() == 3)
24498         return true;
24499       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
24500         return true;
24501     }
24502   }
24503   return false;
24504 }
24505
24506 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
24507   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
24508
24509   std::string AsmStr = IA->getAsmString();
24510
24511   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
24512   if (!Ty || Ty->getBitWidth() % 16 != 0)
24513     return false;
24514
24515   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
24516   SmallVector<StringRef, 4> AsmPieces;
24517   SplitString(AsmStr, AsmPieces, ";\n");
24518
24519   switch (AsmPieces.size()) {
24520   default: return false;
24521   case 1:
24522     // FIXME: this should verify that we are targeting a 486 or better.  If not,
24523     // we will turn this bswap into something that will be lowered to logical
24524     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
24525     // lower so don't worry about this.
24526     // bswap $0
24527     if (matchAsm(AsmPieces[0], {"bswap", "$0"}) ||
24528         matchAsm(AsmPieces[0], {"bswapl", "$0"}) ||
24529         matchAsm(AsmPieces[0], {"bswapq", "$0"}) ||
24530         matchAsm(AsmPieces[0], {"bswap", "${0:q}"}) ||
24531         matchAsm(AsmPieces[0], {"bswapl", "${0:q}"}) ||
24532         matchAsm(AsmPieces[0], {"bswapq", "${0:q}"})) {
24533       // No need to check constraints, nothing other than the equivalent of
24534       // "=r,0" would be valid here.
24535       return IntrinsicLowering::LowerToByteSwap(CI);
24536     }
24537
24538     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
24539     if (CI->getType()->isIntegerTy(16) &&
24540         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
24541         (matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) ||
24542          matchAsm(AsmPieces[0], {"rolw", "$$8,", "${0:w}"}))) {
24543       AsmPieces.clear();
24544       const std::string &ConstraintsStr = IA->getConstraintString();
24545       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
24546       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
24547       if (clobbersFlagRegisters(AsmPieces))
24548         return IntrinsicLowering::LowerToByteSwap(CI);
24549     }
24550     break;
24551   case 3:
24552     if (CI->getType()->isIntegerTy(32) &&
24553         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
24554         matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) &&
24555         matchAsm(AsmPieces[1], {"rorl", "$$16,", "$0"}) &&
24556         matchAsm(AsmPieces[2], {"rorw", "$$8,", "${0:w}"})) {
24557       AsmPieces.clear();
24558       const std::string &ConstraintsStr = IA->getConstraintString();
24559       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
24560       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
24561       if (clobbersFlagRegisters(AsmPieces))
24562         return IntrinsicLowering::LowerToByteSwap(CI);
24563     }
24564
24565     if (CI->getType()->isIntegerTy(64)) {
24566       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
24567       if (Constraints.size() >= 2 &&
24568           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
24569           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
24570         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
24571         if (matchAsm(AsmPieces[0], {"bswap", "%eax"}) &&
24572             matchAsm(AsmPieces[1], {"bswap", "%edx"}) &&
24573             matchAsm(AsmPieces[2], {"xchgl", "%eax,", "%edx"}))
24574           return IntrinsicLowering::LowerToByteSwap(CI);
24575       }
24576     }
24577     break;
24578   }
24579   return false;
24580 }
24581
24582 /// getConstraintType - Given a constraint letter, return the type of
24583 /// constraint it is for this target.
24584 X86TargetLowering::ConstraintType
24585 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
24586   if (Constraint.size() == 1) {
24587     switch (Constraint[0]) {
24588     case 'R':
24589     case 'q':
24590     case 'Q':
24591     case 'f':
24592     case 't':
24593     case 'u':
24594     case 'y':
24595     case 'x':
24596     case 'Y':
24597     case 'l':
24598       return C_RegisterClass;
24599     case 'a':
24600     case 'b':
24601     case 'c':
24602     case 'd':
24603     case 'S':
24604     case 'D':
24605     case 'A':
24606       return C_Register;
24607     case 'I':
24608     case 'J':
24609     case 'K':
24610     case 'L':
24611     case 'M':
24612     case 'N':
24613     case 'G':
24614     case 'C':
24615     case 'e':
24616     case 'Z':
24617       return C_Other;
24618     default:
24619       break;
24620     }
24621   }
24622   return TargetLowering::getConstraintType(Constraint);
24623 }
24624
24625 /// Examine constraint type and operand type and determine a weight value.
24626 /// This object must already have been set up with the operand type
24627 /// and the current alternative constraint selected.
24628 TargetLowering::ConstraintWeight
24629   X86TargetLowering::getSingleConstraintMatchWeight(
24630     AsmOperandInfo &info, const char *constraint) const {
24631   ConstraintWeight weight = CW_Invalid;
24632   Value *CallOperandVal = info.CallOperandVal;
24633     // If we don't have a value, we can't do a match,
24634     // but allow it at the lowest weight.
24635   if (!CallOperandVal)
24636     return CW_Default;
24637   Type *type = CallOperandVal->getType();
24638   // Look at the constraint type.
24639   switch (*constraint) {
24640   default:
24641     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
24642   case 'R':
24643   case 'q':
24644   case 'Q':
24645   case 'a':
24646   case 'b':
24647   case 'c':
24648   case 'd':
24649   case 'S':
24650   case 'D':
24651   case 'A':
24652     if (CallOperandVal->getType()->isIntegerTy())
24653       weight = CW_SpecificReg;
24654     break;
24655   case 'f':
24656   case 't':
24657   case 'u':
24658     if (type->isFloatingPointTy())
24659       weight = CW_SpecificReg;
24660     break;
24661   case 'y':
24662     if (type->isX86_MMXTy() && Subtarget->hasMMX())
24663       weight = CW_SpecificReg;
24664     break;
24665   case 'x':
24666   case 'Y':
24667     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
24668         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
24669       weight = CW_Register;
24670     break;
24671   case 'I':
24672     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
24673       if (C->getZExtValue() <= 31)
24674         weight = CW_Constant;
24675     }
24676     break;
24677   case 'J':
24678     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24679       if (C->getZExtValue() <= 63)
24680         weight = CW_Constant;
24681     }
24682     break;
24683   case 'K':
24684     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24685       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
24686         weight = CW_Constant;
24687     }
24688     break;
24689   case 'L':
24690     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24691       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
24692         weight = CW_Constant;
24693     }
24694     break;
24695   case 'M':
24696     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24697       if (C->getZExtValue() <= 3)
24698         weight = CW_Constant;
24699     }
24700     break;
24701   case 'N':
24702     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24703       if (C->getZExtValue() <= 0xff)
24704         weight = CW_Constant;
24705     }
24706     break;
24707   case 'G':
24708   case 'C':
24709     if (isa<ConstantFP>(CallOperandVal)) {
24710       weight = CW_Constant;
24711     }
24712     break;
24713   case 'e':
24714     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24715       if ((C->getSExtValue() >= -0x80000000LL) &&
24716           (C->getSExtValue() <= 0x7fffffffLL))
24717         weight = CW_Constant;
24718     }
24719     break;
24720   case 'Z':
24721     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24722       if (C->getZExtValue() <= 0xffffffff)
24723         weight = CW_Constant;
24724     }
24725     break;
24726   }
24727   return weight;
24728 }
24729
24730 /// LowerXConstraint - try to replace an X constraint, which matches anything,
24731 /// with another that has more specific requirements based on the type of the
24732 /// corresponding operand.
24733 const char *X86TargetLowering::
24734 LowerXConstraint(EVT ConstraintVT) const {
24735   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
24736   // 'f' like normal targets.
24737   if (ConstraintVT.isFloatingPoint()) {
24738     if (Subtarget->hasSSE2())
24739       return "Y";
24740     if (Subtarget->hasSSE1())
24741       return "x";
24742   }
24743
24744   return TargetLowering::LowerXConstraint(ConstraintVT);
24745 }
24746
24747 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
24748 /// vector.  If it is invalid, don't add anything to Ops.
24749 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
24750                                                      std::string &Constraint,
24751                                                      std::vector<SDValue>&Ops,
24752                                                      SelectionDAG &DAG) const {
24753   SDValue Result;
24754
24755   // Only support length 1 constraints for now.
24756   if (Constraint.length() > 1) return;
24757
24758   char ConstraintLetter = Constraint[0];
24759   switch (ConstraintLetter) {
24760   default: break;
24761   case 'I':
24762     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24763       if (C->getZExtValue() <= 31) {
24764         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24765                                        Op.getValueType());
24766         break;
24767       }
24768     }
24769     return;
24770   case 'J':
24771     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24772       if (C->getZExtValue() <= 63) {
24773         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24774                                        Op.getValueType());
24775         break;
24776       }
24777     }
24778     return;
24779   case 'K':
24780     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24781       if (isInt<8>(C->getSExtValue())) {
24782         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24783                                        Op.getValueType());
24784         break;
24785       }
24786     }
24787     return;
24788   case 'L':
24789     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24790       if (C->getZExtValue() == 0xff || C->getZExtValue() == 0xffff ||
24791           (Subtarget->is64Bit() && C->getZExtValue() == 0xffffffff)) {
24792         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op),
24793                                        Op.getValueType());
24794         break;
24795       }
24796     }
24797     return;
24798   case 'M':
24799     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24800       if (C->getZExtValue() <= 3) {
24801         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24802                                        Op.getValueType());
24803         break;
24804       }
24805     }
24806     return;
24807   case 'N':
24808     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24809       if (C->getZExtValue() <= 255) {
24810         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24811                                        Op.getValueType());
24812         break;
24813       }
24814     }
24815     return;
24816   case 'O':
24817     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24818       if (C->getZExtValue() <= 127) {
24819         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24820                                        Op.getValueType());
24821         break;
24822       }
24823     }
24824     return;
24825   case 'e': {
24826     // 32-bit signed value
24827     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24828       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
24829                                            C->getSExtValue())) {
24830         // Widen to 64 bits here to get it sign extended.
24831         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op), MVT::i64);
24832         break;
24833       }
24834     // FIXME gcc accepts some relocatable values here too, but only in certain
24835     // memory models; it's complicated.
24836     }
24837     return;
24838   }
24839   case 'Z': {
24840     // 32-bit unsigned value
24841     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24842       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
24843                                            C->getZExtValue())) {
24844         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24845                                        Op.getValueType());
24846         break;
24847       }
24848     }
24849     // FIXME gcc accepts some relocatable values here too, but only in certain
24850     // memory models; it's complicated.
24851     return;
24852   }
24853   case 'i': {
24854     // Literal immediates are always ok.
24855     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
24856       // Widen to 64 bits here to get it sign extended.
24857       Result = DAG.getTargetConstant(CST->getSExtValue(), SDLoc(Op), MVT::i64);
24858       break;
24859     }
24860
24861     // In any sort of PIC mode addresses need to be computed at runtime by
24862     // adding in a register or some sort of table lookup.  These can't
24863     // be used as immediates.
24864     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
24865       return;
24866
24867     // If we are in non-pic codegen mode, we allow the address of a global (with
24868     // an optional displacement) to be used with 'i'.
24869     GlobalAddressSDNode *GA = nullptr;
24870     int64_t Offset = 0;
24871
24872     // Match either (GA), (GA+C), (GA+C1+C2), etc.
24873     while (1) {
24874       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
24875         Offset += GA->getOffset();
24876         break;
24877       } else if (Op.getOpcode() == ISD::ADD) {
24878         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
24879           Offset += C->getZExtValue();
24880           Op = Op.getOperand(0);
24881           continue;
24882         }
24883       } else if (Op.getOpcode() == ISD::SUB) {
24884         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
24885           Offset += -C->getZExtValue();
24886           Op = Op.getOperand(0);
24887           continue;
24888         }
24889       }
24890
24891       // Otherwise, this isn't something we can handle, reject it.
24892       return;
24893     }
24894
24895     const GlobalValue *GV = GA->getGlobal();
24896     // If we require an extra load to get this address, as in PIC mode, we
24897     // can't accept it.
24898     if (isGlobalStubReference(
24899             Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
24900       return;
24901
24902     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
24903                                         GA->getValueType(0), Offset);
24904     break;
24905   }
24906   }
24907
24908   if (Result.getNode()) {
24909     Ops.push_back(Result);
24910     return;
24911   }
24912   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
24913 }
24914
24915 std::pair<unsigned, const TargetRegisterClass *>
24916 X86TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
24917                                                 const std::string &Constraint,
24918                                                 MVT VT) const {
24919   // First, see if this is a constraint that directly corresponds to an LLVM
24920   // register class.
24921   if (Constraint.size() == 1) {
24922     // GCC Constraint Letters
24923     switch (Constraint[0]) {
24924     default: break;
24925       // TODO: Slight differences here in allocation order and leaving
24926       // RIP in the class. Do they matter any more here than they do
24927       // in the normal allocation?
24928     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
24929       if (Subtarget->is64Bit()) {
24930         if (VT == MVT::i32 || VT == MVT::f32)
24931           return std::make_pair(0U, &X86::GR32RegClass);
24932         if (VT == MVT::i16)
24933           return std::make_pair(0U, &X86::GR16RegClass);
24934         if (VT == MVT::i8 || VT == MVT::i1)
24935           return std::make_pair(0U, &X86::GR8RegClass);
24936         if (VT == MVT::i64 || VT == MVT::f64)
24937           return std::make_pair(0U, &X86::GR64RegClass);
24938         break;
24939       }
24940       // 32-bit fallthrough
24941     case 'Q':   // Q_REGS
24942       if (VT == MVT::i32 || VT == MVT::f32)
24943         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
24944       if (VT == MVT::i16)
24945         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
24946       if (VT == MVT::i8 || VT == MVT::i1)
24947         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
24948       if (VT == MVT::i64)
24949         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
24950       break;
24951     case 'r':   // GENERAL_REGS
24952     case 'l':   // INDEX_REGS
24953       if (VT == MVT::i8 || VT == MVT::i1)
24954         return std::make_pair(0U, &X86::GR8RegClass);
24955       if (VT == MVT::i16)
24956         return std::make_pair(0U, &X86::GR16RegClass);
24957       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
24958         return std::make_pair(0U, &X86::GR32RegClass);
24959       return std::make_pair(0U, &X86::GR64RegClass);
24960     case 'R':   // LEGACY_REGS
24961       if (VT == MVT::i8 || VT == MVT::i1)
24962         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
24963       if (VT == MVT::i16)
24964         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
24965       if (VT == MVT::i32 || !Subtarget->is64Bit())
24966         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
24967       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
24968     case 'f':  // FP Stack registers.
24969       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
24970       // value to the correct fpstack register class.
24971       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
24972         return std::make_pair(0U, &X86::RFP32RegClass);
24973       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
24974         return std::make_pair(0U, &X86::RFP64RegClass);
24975       return std::make_pair(0U, &X86::RFP80RegClass);
24976     case 'y':   // MMX_REGS if MMX allowed.
24977       if (!Subtarget->hasMMX()) break;
24978       return std::make_pair(0U, &X86::VR64RegClass);
24979     case 'Y':   // SSE_REGS if SSE2 allowed
24980       if (!Subtarget->hasSSE2()) break;
24981       // FALL THROUGH.
24982     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
24983       if (!Subtarget->hasSSE1()) break;
24984
24985       switch (VT.SimpleTy) {
24986       default: break;
24987       // Scalar SSE types.
24988       case MVT::f32:
24989       case MVT::i32:
24990         return std::make_pair(0U, &X86::FR32RegClass);
24991       case MVT::f64:
24992       case MVT::i64:
24993         return std::make_pair(0U, &X86::FR64RegClass);
24994       // Vector types.
24995       case MVT::v16i8:
24996       case MVT::v8i16:
24997       case MVT::v4i32:
24998       case MVT::v2i64:
24999       case MVT::v4f32:
25000       case MVT::v2f64:
25001         return std::make_pair(0U, &X86::VR128RegClass);
25002       // AVX types.
25003       case MVT::v32i8:
25004       case MVT::v16i16:
25005       case MVT::v8i32:
25006       case MVT::v4i64:
25007       case MVT::v8f32:
25008       case MVT::v4f64:
25009         return std::make_pair(0U, &X86::VR256RegClass);
25010       case MVT::v8f64:
25011       case MVT::v16f32:
25012       case MVT::v16i32:
25013       case MVT::v8i64:
25014         return std::make_pair(0U, &X86::VR512RegClass);
25015       }
25016       break;
25017     }
25018   }
25019
25020   // Use the default implementation in TargetLowering to convert the register
25021   // constraint into a member of a register class.
25022   std::pair<unsigned, const TargetRegisterClass*> Res;
25023   Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
25024
25025   // Not found as a standard register?
25026   if (!Res.second) {
25027     // Map st(0) -> st(7) -> ST0
25028     if (Constraint.size() == 7 && Constraint[0] == '{' &&
25029         tolower(Constraint[1]) == 's' &&
25030         tolower(Constraint[2]) == 't' &&
25031         Constraint[3] == '(' &&
25032         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
25033         Constraint[5] == ')' &&
25034         Constraint[6] == '}') {
25035
25036       Res.first = X86::FP0+Constraint[4]-'0';
25037       Res.second = &X86::RFP80RegClass;
25038       return Res;
25039     }
25040
25041     // GCC allows "st(0)" to be called just plain "st".
25042     if (StringRef("{st}").equals_lower(Constraint)) {
25043       Res.first = X86::FP0;
25044       Res.second = &X86::RFP80RegClass;
25045       return Res;
25046     }
25047
25048     // flags -> EFLAGS
25049     if (StringRef("{flags}").equals_lower(Constraint)) {
25050       Res.first = X86::EFLAGS;
25051       Res.second = &X86::CCRRegClass;
25052       return Res;
25053     }
25054
25055     // 'A' means EAX + EDX.
25056     if (Constraint == "A") {
25057       Res.first = X86::EAX;
25058       Res.second = &X86::GR32_ADRegClass;
25059       return Res;
25060     }
25061     return Res;
25062   }
25063
25064   // Otherwise, check to see if this is a register class of the wrong value
25065   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
25066   // turn into {ax},{dx}.
25067   if (Res.second->hasType(VT))
25068     return Res;   // Correct type already, nothing to do.
25069
25070   // All of the single-register GCC register classes map their values onto
25071   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
25072   // really want an 8-bit or 32-bit register, map to the appropriate register
25073   // class and return the appropriate register.
25074   if (Res.second == &X86::GR16RegClass) {
25075     if (VT == MVT::i8 || VT == MVT::i1) {
25076       unsigned DestReg = 0;
25077       switch (Res.first) {
25078       default: break;
25079       case X86::AX: DestReg = X86::AL; break;
25080       case X86::DX: DestReg = X86::DL; break;
25081       case X86::CX: DestReg = X86::CL; break;
25082       case X86::BX: DestReg = X86::BL; break;
25083       }
25084       if (DestReg) {
25085         Res.first = DestReg;
25086         Res.second = &X86::GR8RegClass;
25087       }
25088     } else if (VT == MVT::i32 || VT == MVT::f32) {
25089       unsigned DestReg = 0;
25090       switch (Res.first) {
25091       default: break;
25092       case X86::AX: DestReg = X86::EAX; break;
25093       case X86::DX: DestReg = X86::EDX; break;
25094       case X86::CX: DestReg = X86::ECX; break;
25095       case X86::BX: DestReg = X86::EBX; break;
25096       case X86::SI: DestReg = X86::ESI; break;
25097       case X86::DI: DestReg = X86::EDI; break;
25098       case X86::BP: DestReg = X86::EBP; break;
25099       case X86::SP: DestReg = X86::ESP; break;
25100       }
25101       if (DestReg) {
25102         Res.first = DestReg;
25103         Res.second = &X86::GR32RegClass;
25104       }
25105     } else if (VT == MVT::i64 || VT == MVT::f64) {
25106       unsigned DestReg = 0;
25107       switch (Res.first) {
25108       default: break;
25109       case X86::AX: DestReg = X86::RAX; break;
25110       case X86::DX: DestReg = X86::RDX; break;
25111       case X86::CX: DestReg = X86::RCX; break;
25112       case X86::BX: DestReg = X86::RBX; break;
25113       case X86::SI: DestReg = X86::RSI; break;
25114       case X86::DI: DestReg = X86::RDI; break;
25115       case X86::BP: DestReg = X86::RBP; break;
25116       case X86::SP: DestReg = X86::RSP; break;
25117       }
25118       if (DestReg) {
25119         Res.first = DestReg;
25120         Res.second = &X86::GR64RegClass;
25121       }
25122     }
25123   } else if (Res.second == &X86::FR32RegClass ||
25124              Res.second == &X86::FR64RegClass ||
25125              Res.second == &X86::VR128RegClass ||
25126              Res.second == &X86::VR256RegClass ||
25127              Res.second == &X86::FR32XRegClass ||
25128              Res.second == &X86::FR64XRegClass ||
25129              Res.second == &X86::VR128XRegClass ||
25130              Res.second == &X86::VR256XRegClass ||
25131              Res.second == &X86::VR512RegClass) {
25132     // Handle references to XMM physical registers that got mapped into the
25133     // wrong class.  This can happen with constraints like {xmm0} where the
25134     // target independent register mapper will just pick the first match it can
25135     // find, ignoring the required type.
25136
25137     if (VT == MVT::f32 || VT == MVT::i32)
25138       Res.second = &X86::FR32RegClass;
25139     else if (VT == MVT::f64 || VT == MVT::i64)
25140       Res.second = &X86::FR64RegClass;
25141     else if (X86::VR128RegClass.hasType(VT))
25142       Res.second = &X86::VR128RegClass;
25143     else if (X86::VR256RegClass.hasType(VT))
25144       Res.second = &X86::VR256RegClass;
25145     else if (X86::VR512RegClass.hasType(VT))
25146       Res.second = &X86::VR512RegClass;
25147   }
25148
25149   return Res;
25150 }
25151
25152 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
25153                                             Type *Ty) const {
25154   // Scaling factors are not free at all.
25155   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
25156   // will take 2 allocations in the out of order engine instead of 1
25157   // for plain addressing mode, i.e. inst (reg1).
25158   // E.g.,
25159   // vaddps (%rsi,%drx), %ymm0, %ymm1
25160   // Requires two allocations (one for the load, one for the computation)
25161   // whereas:
25162   // vaddps (%rsi), %ymm0, %ymm1
25163   // Requires just 1 allocation, i.e., freeing allocations for other operations
25164   // and having less micro operations to execute.
25165   //
25166   // For some X86 architectures, this is even worse because for instance for
25167   // stores, the complex addressing mode forces the instruction to use the
25168   // "load" ports instead of the dedicated "store" port.
25169   // E.g., on Haswell:
25170   // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
25171   // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
25172   if (isLegalAddressingMode(AM, Ty))
25173     // Scale represents reg2 * scale, thus account for 1
25174     // as soon as we use a second register.
25175     return AM.Scale != 0;
25176   return -1;
25177 }
25178
25179 bool X86TargetLowering::isTargetFTOL() const {
25180   return Subtarget->isTargetKnownWindowsMSVC() && !Subtarget->is64Bit();
25181 }